4 * Copyright (C) 1991, 1992 Linus Torvalds
7 /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
9 * Wirzenius wrote this portably, Torvalds fucked it up :-)
13 * Fri Jul 13 2001 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
14 * - changed to provide snprintf and vsnprintf functions
15 * So Feb 1 16:51:32 CET 2004 Juergen Quade <quade@hsnr.de>
16 * - scnprintf and vscnprintf
20 #include <linux/clk.h>
21 #include <linux/clk-provider.h>
22 #include <linux/module.h> /* for KSYM_SYMBOL_LEN */
23 #include <linux/types.h>
24 #include <linux/string.h>
25 #include <linux/ctype.h>
26 #include <linux/kernel.h>
27 #include <linux/kallsyms.h>
28 #include <linux/math64.h>
29 #include <linux/uaccess.h>
30 #include <linux/ioport.h>
31 #include <linux/dcache.h>
32 #include <linux/cred.h>
33 #include <linux/uuid.h>
35 #include <net/addrconf.h>
37 #include <linux/blkdev.h>
40 #include "../mm/internal.h" /* For the trace_print_flags arrays */
42 #include <asm/page.h> /* for PAGE_SIZE */
43 #include <asm/sections.h> /* for dereference_function_descriptor() */
44 #include <asm/byteorder.h> /* cpu_to_le16 */
46 #include <linux/string_helpers.h>
49 static unsigned long long simple_strntoull(const char *startp, size_t max_chars,
50 char **endp, unsigned int base)
53 unsigned long long result = 0ULL;
57 cp = _parse_integer_fixup_radix(startp, &base);
58 prefix_chars = cp - startp;
59 if (prefix_chars < max_chars) {
60 rv = _parse_integer_limit(cp, base, &result, max_chars - prefix_chars);
62 cp += (rv & ~KSTRTOX_OVERFLOW);
64 /* Field too short for prefix + digit, skip over without converting */
65 cp = startp + max_chars;
75 * simple_strtoull - convert a string to an unsigned long long
76 * @cp: The start of the string
77 * @endp: A pointer to the end of the parsed string will be placed here
78 * @base: The number base to use
80 * This function is obsolete. Please use kstrtoull instead.
82 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
84 return simple_strntoull(cp, INT_MAX, endp, base);
86 EXPORT_SYMBOL(simple_strtoull);
89 * simple_strtoul - convert a string to an unsigned long
90 * @cp: The start of the string
91 * @endp: A pointer to the end of the parsed string will be placed here
92 * @base: The number base to use
94 * This function is obsolete. Please use kstrtoul instead.
96 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
98 return simple_strtoull(cp, endp, base);
100 EXPORT_SYMBOL(simple_strtoul);
103 * simple_strtol - convert a string to a signed long
104 * @cp: The start of the string
105 * @endp: A pointer to the end of the parsed string will be placed here
106 * @base: The number base to use
108 * This function is obsolete. Please use kstrtol instead.
110 long simple_strtol(const char *cp, char **endp, unsigned int base)
113 return -simple_strtoul(cp + 1, endp, base);
115 return simple_strtoul(cp, endp, base);
117 EXPORT_SYMBOL(simple_strtol);
119 static long long simple_strntoll(const char *cp, size_t max_chars, char **endp,
123 * simple_strntoull() safely handles receiving max_chars==0 in the
124 * case cp[0] == '-' && max_chars == 1.
125 * If max_chars == 0 we can drop through and pass it to simple_strntoull()
126 * and the content of *cp is irrelevant.
128 if (*cp == '-' && max_chars > 0)
129 return -simple_strntoull(cp + 1, max_chars - 1, endp, base);
131 return simple_strntoull(cp, max_chars, endp, base);
135 * simple_strtoll - convert a string to a signed long long
136 * @cp: The start of the string
137 * @endp: A pointer to the end of the parsed string will be placed here
138 * @base: The number base to use
140 * This function is obsolete. Please use kstrtoll instead.
142 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
144 return simple_strntoll(cp, INT_MAX, endp, base);
146 EXPORT_SYMBOL(simple_strtoll);
148 static noinline_for_stack
149 int skip_atoi(const char **s)
154 i = i*10 + *((*s)++) - '0';
155 } while (isdigit(**s));
161 * Decimal conversion is by far the most typical, and is used for
162 * /proc and /sys data. This directly impacts e.g. top performance
163 * with many processes running. We optimize it for speed by emitting
164 * two characters at a time, using a 200 byte lookup table. This
165 * roughly halves the number of multiplications compared to computing
166 * the digits one at a time. Implementation strongly inspired by the
167 * previous version, which in turn used ideas described at
168 * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
169 * from the author, Douglas W. Jones).
171 * It turns out there is precisely one 26 bit fixed-point
172 * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
173 * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
174 * range happens to be somewhat larger (x <= 1073741898), but that's
175 * irrelevant for our purpose.
177 * For dividing a number in the range [10^4, 10^6-1] by 100, we still
178 * need a 32x32->64 bit multiply, so we simply use the same constant.
180 * For dividing a number in the range [100, 10^4-1] by 100, there are
181 * several options. The simplest is (x * 0x147b) >> 19, which is valid
182 * for all x <= 43698.
185 static const u16 decpair[100] = {
186 #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
187 _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
188 _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
189 _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
190 _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
191 _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
192 _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
193 _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
194 _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
195 _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
196 _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
201 * This will print a single '0' even if r == 0, since we would
202 * immediately jump to out_r where two 0s would be written but only
203 * one of them accounted for in buf. This is needed by ip4_string
204 * below. All other callers pass a non-zero value of r.
206 static noinline_for_stack
207 char *put_dec_trunc8(char *buf, unsigned r)
215 /* 100 <= r < 10^8 */
216 q = (r * (u64)0x28f5c29) >> 32;
217 *((u16 *)buf) = decpair[r - 100*q];
224 /* 100 <= q < 10^6 */
225 r = (q * (u64)0x28f5c29) >> 32;
226 *((u16 *)buf) = decpair[q - 100*r];
233 /* 100 <= r < 10^4 */
234 q = (r * 0x147b) >> 19;
235 *((u16 *)buf) = decpair[r - 100*q];
242 *((u16 *)buf) = decpair[r];
243 buf += r < 10 ? 1 : 2;
247 #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
248 static noinline_for_stack
249 char *put_dec_full8(char *buf, unsigned r)
254 q = (r * (u64)0x28f5c29) >> 32;
255 *((u16 *)buf) = decpair[r - 100*q];
259 r = (q * (u64)0x28f5c29) >> 32;
260 *((u16 *)buf) = decpair[q - 100*r];
264 q = (r * 0x147b) >> 19;
265 *((u16 *)buf) = decpair[r - 100*q];
269 *((u16 *)buf) = decpair[q];
274 static noinline_for_stack
275 char *put_dec(char *buf, unsigned long long n)
277 if (n >= 100*1000*1000)
278 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
279 /* 1 <= n <= 1.6e11 */
280 if (n >= 100*1000*1000)
281 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
283 return put_dec_trunc8(buf, n);
286 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
289 put_dec_full4(char *buf, unsigned r)
294 q = (r * 0x147b) >> 19;
295 *((u16 *)buf) = decpair[r - 100*q];
298 *((u16 *)buf) = decpair[q];
302 * Call put_dec_full4 on x % 10000, return x / 10000.
303 * The approximation x/10000 == (x * 0x346DC5D7) >> 43
304 * holds for all x < 1,128,869,999. The largest value this
305 * helper will ever be asked to convert is 1,125,520,955.
306 * (second call in the put_dec code, assuming n is all-ones).
308 static noinline_for_stack
309 unsigned put_dec_helper4(char *buf, unsigned x)
311 uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
313 put_dec_full4(buf, x - q * 10000);
317 /* Based on code by Douglas W. Jones found at
318 * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
319 * (with permission from the author).
320 * Performs no 64-bit division and hence should be fast on 32-bit machines.
323 char *put_dec(char *buf, unsigned long long n)
325 uint32_t d3, d2, d1, q, h;
327 if (n < 100*1000*1000)
328 return put_dec_trunc8(buf, n);
330 d1 = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
333 d3 = (h >> 16); /* implicit "& 0xffff" */
335 /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
336 = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
337 q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
338 q = put_dec_helper4(buf, q);
340 q += 7671 * d3 + 9496 * d2 + 6 * d1;
341 q = put_dec_helper4(buf+4, q);
343 q += 4749 * d3 + 42 * d2;
344 q = put_dec_helper4(buf+8, q);
349 buf = put_dec_trunc8(buf, q);
350 else while (buf[-1] == '0')
359 * Convert passed number to decimal string.
360 * Returns the length of string. On buffer overflow, returns 0.
362 * If speed is not important, use snprintf(). It's easy to read the code.
364 int num_to_str(char *buf, int size, unsigned long long num)
366 /* put_dec requires 2-byte alignment of the buffer. */
367 char tmp[sizeof(num) * 3] __aligned(2);
370 /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
375 len = put_dec(tmp, num) - tmp;
380 for (idx = 0; idx < len; ++idx)
381 buf[idx] = tmp[len - idx - 1];
385 #define SIGN 1 /* unsigned/signed, must be 1 */
386 #define LEFT 2 /* left justified */
387 #define PLUS 4 /* show plus */
388 #define SPACE 8 /* space if plus */
389 #define ZEROPAD 16 /* pad with zero, must be 16 == '0' - ' ' */
390 #define SMALL 32 /* use lowercase in hex (must be 32 == 0x20) */
391 #define SPECIAL 64 /* prefix hex with "0x", octal with "0" */
394 FORMAT_TYPE_NONE, /* Just a string part */
396 FORMAT_TYPE_PRECISION,
400 FORMAT_TYPE_PERCENT_CHAR,
402 FORMAT_TYPE_LONG_LONG,
416 unsigned int type:8; /* format_type enum */
417 signed int field_width:24; /* width of output field */
418 unsigned int flags:8; /* flags to number() */
419 unsigned int base:8; /* number base, 8, 10 or 16 only */
420 signed int precision:16; /* # of digits/chars */
422 #define FIELD_WIDTH_MAX ((1 << 23) - 1)
423 #define PRECISION_MAX ((1 << 15) - 1)
425 static noinline_for_stack
426 char *number(char *buf, char *end, unsigned long long num,
427 struct printf_spec spec)
429 /* put_dec requires 2-byte alignment of the buffer. */
430 char tmp[3 * sizeof(num)] __aligned(2);
433 int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
435 bool is_zero = num == 0LL;
436 int field_width = spec.field_width;
437 int precision = spec.precision;
439 BUILD_BUG_ON(sizeof(struct printf_spec) != 8);
441 /* locase = 0 or 0x20. ORing digits or letters with 'locase'
442 * produces same digits or (maybe lowercased) letters */
443 locase = (spec.flags & SMALL);
444 if (spec.flags & LEFT)
445 spec.flags &= ~ZEROPAD;
447 if (spec.flags & SIGN) {
448 if ((signed long long)num < 0) {
450 num = -(signed long long)num;
452 } else if (spec.flags & PLUS) {
455 } else if (spec.flags & SPACE) {
467 /* generate full string in tmp[], in reverse order */
470 tmp[i++] = hex_asc_upper[num] | locase;
471 else if (spec.base != 10) { /* 8 or 16 */
472 int mask = spec.base - 1;
478 tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
481 } else { /* base 10 */
482 i = put_dec(tmp, num) - tmp;
485 /* printing 100 using %2d gives "100", not "00" */
488 /* leading space padding */
489 field_width -= precision;
490 if (!(spec.flags & (ZEROPAD | LEFT))) {
491 while (--field_width >= 0) {
503 /* "0x" / "0" prefix */
505 if (spec.base == 16 || !is_zero) {
510 if (spec.base == 16) {
512 *buf = ('X' | locase);
516 /* zero or space padding */
517 if (!(spec.flags & LEFT)) {
518 char c = ' ' + (spec.flags & ZEROPAD);
519 BUILD_BUG_ON(' ' + ZEROPAD != '0');
520 while (--field_width >= 0) {
526 /* hmm even more zero padding? */
527 while (i <= --precision) {
532 /* actual digits of result */
538 /* trailing space padding */
539 while (--field_width >= 0) {
548 static noinline_for_stack
549 char *special_hex_number(char *buf, char *end, unsigned long long num, int size)
551 struct printf_spec spec;
553 spec.type = FORMAT_TYPE_PTR;
554 spec.field_width = 2 + 2 * size; /* 0x + hex */
555 spec.flags = SPECIAL | SMALL | ZEROPAD;
559 return number(buf, end, num, spec);
562 static void move_right(char *buf, char *end, unsigned len, unsigned spaces)
565 if (buf >= end) /* nowhere to put anything */
568 if (size <= spaces) {
569 memset(buf, ' ', size);
573 if (len > size - spaces)
575 memmove(buf + spaces, buf, len);
577 memset(buf, ' ', spaces);
581 * Handle field width padding for a string.
582 * @buf: current buffer position
583 * @n: length of string
584 * @end: end of output buffer
585 * @spec: for field width and flags
586 * Returns: new buffer position after padding.
588 static noinline_for_stack
589 char *widen_string(char *buf, int n, char *end, struct printf_spec spec)
593 if (likely(n >= spec.field_width))
595 /* we want to pad the sucker */
596 spaces = spec.field_width - n;
597 if (!(spec.flags & LEFT)) {
598 move_right(buf - n, end, n, spaces);
609 static noinline_for_stack
610 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
613 size_t lim = spec.precision;
615 if ((unsigned long)s < PAGE_SIZE)
627 return widen_string(buf, len, end, spec);
630 static noinline_for_stack
631 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
634 const char *array[4], *s;
635 const struct dentry *p;
640 case '2': case '3': case '4':
641 depth = fmt[1] - '0';
648 for (i = 0; i < depth; i++, d = p) {
649 p = ACCESS_ONCE(d->d_parent);
650 array[i] = ACCESS_ONCE(d->d_name.name);
659 for (n = 0; n != spec.precision; n++, buf++) {
671 return widen_string(buf, n, end, spec);
675 static noinline_for_stack
676 char *bdev_name(char *buf, char *end, struct block_device *bdev,
677 struct printf_spec spec, const char *fmt)
679 struct gendisk *hd = bdev->bd_disk;
681 buf = string(buf, end, hd->disk_name, spec);
682 if (bdev->bd_part->partno) {
683 if (isdigit(hd->disk_name[strlen(hd->disk_name)-1])) {
688 buf = number(buf, end, bdev->bd_part->partno, spec);
694 static noinline_for_stack
695 char *symbol_string(char *buf, char *end, void *ptr,
696 struct printf_spec spec, const char *fmt)
699 #ifdef CONFIG_KALLSYMS
700 char sym[KSYM_SYMBOL_LEN];
704 ptr = __builtin_extract_return_addr(ptr);
705 value = (unsigned long)ptr;
707 #ifdef CONFIG_KALLSYMS
709 sprint_backtrace(sym, value);
710 else if (*fmt != 'f' && *fmt != 's')
711 sprint_symbol(sym, value);
713 sprint_symbol_no_offset(sym, value);
715 return string(buf, end, sym, spec);
717 return special_hex_number(buf, end, value, sizeof(void *));
721 static noinline_for_stack
722 char *resource_string(char *buf, char *end, struct resource *res,
723 struct printf_spec spec, const char *fmt)
725 #ifndef IO_RSRC_PRINTK_SIZE
726 #define IO_RSRC_PRINTK_SIZE 6
729 #ifndef MEM_RSRC_PRINTK_SIZE
730 #define MEM_RSRC_PRINTK_SIZE 10
732 static const struct printf_spec io_spec = {
734 .field_width = IO_RSRC_PRINTK_SIZE,
736 .flags = SPECIAL | SMALL | ZEROPAD,
738 static const struct printf_spec mem_spec = {
740 .field_width = MEM_RSRC_PRINTK_SIZE,
742 .flags = SPECIAL | SMALL | ZEROPAD,
744 static const struct printf_spec bus_spec = {
748 .flags = SMALL | ZEROPAD,
750 static const struct printf_spec dec_spec = {
755 static const struct printf_spec str_spec = {
760 static const struct printf_spec flag_spec = {
763 .flags = SPECIAL | SMALL,
766 /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
767 * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
768 #define RSRC_BUF_SIZE ((2 * sizeof(resource_size_t)) + 4)
769 #define FLAG_BUF_SIZE (2 * sizeof(res->flags))
770 #define DECODED_BUF_SIZE sizeof("[mem - 64bit pref window disabled]")
771 #define RAW_BUF_SIZE sizeof("[mem - flags 0x]")
772 char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
773 2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
775 char *p = sym, *pend = sym + sizeof(sym);
776 int decode = (fmt[0] == 'R') ? 1 : 0;
777 const struct printf_spec *specp;
780 if (res->flags & IORESOURCE_IO) {
781 p = string(p, pend, "io ", str_spec);
783 } else if (res->flags & IORESOURCE_MEM) {
784 p = string(p, pend, "mem ", str_spec);
786 } else if (res->flags & IORESOURCE_IRQ) {
787 p = string(p, pend, "irq ", str_spec);
789 } else if (res->flags & IORESOURCE_DMA) {
790 p = string(p, pend, "dma ", str_spec);
792 } else if (res->flags & IORESOURCE_BUS) {
793 p = string(p, pend, "bus ", str_spec);
796 p = string(p, pend, "??? ", str_spec);
800 if (decode && res->flags & IORESOURCE_UNSET) {
801 p = string(p, pend, "size ", str_spec);
802 p = number(p, pend, resource_size(res), *specp);
804 p = number(p, pend, res->start, *specp);
805 if (res->start != res->end) {
807 p = number(p, pend, res->end, *specp);
811 if (res->flags & IORESOURCE_MEM_64)
812 p = string(p, pend, " 64bit", str_spec);
813 if (res->flags & IORESOURCE_PREFETCH)
814 p = string(p, pend, " pref", str_spec);
815 if (res->flags & IORESOURCE_WINDOW)
816 p = string(p, pend, " window", str_spec);
817 if (res->flags & IORESOURCE_DISABLED)
818 p = string(p, pend, " disabled", str_spec);
820 p = string(p, pend, " flags ", str_spec);
821 p = number(p, pend, res->flags, flag_spec);
826 return string(buf, end, sym, spec);
829 static noinline_for_stack
830 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
833 int i, len = 1; /* if we pass '%ph[CDN]', field width remains
834 negative value, fallback to the default */
837 if (spec.field_width == 0)
838 /* nothing to print */
841 if (ZERO_OR_NULL_PTR(addr))
843 return string(buf, end, NULL, spec);
860 if (spec.field_width > 0)
861 len = min_t(int, spec.field_width, 64);
863 for (i = 0; i < len; ++i) {
865 *buf = hex_asc_hi(addr[i]);
868 *buf = hex_asc_lo(addr[i]);
871 if (separator && i != len - 1) {
881 static noinline_for_stack
882 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
883 struct printf_spec spec, const char *fmt)
885 const int CHUNKSZ = 32;
886 int nr_bits = max_t(int, spec.field_width, 0);
890 /* reused to print numbers */
891 spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
893 chunksz = nr_bits & (CHUNKSZ - 1);
897 i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
898 for (; i >= 0; i -= CHUNKSZ) {
902 chunkmask = ((1ULL << chunksz) - 1);
903 word = i / BITS_PER_LONG;
904 bit = i % BITS_PER_LONG;
905 val = (bitmap[word] >> bit) & chunkmask;
914 spec.field_width = DIV_ROUND_UP(chunksz, 4);
915 buf = number(buf, end, val, spec);
922 static noinline_for_stack
923 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
924 struct printf_spec spec, const char *fmt)
926 int nr_bits = max_t(int, spec.field_width, 0);
927 /* current bit is 'cur', most recently seen range is [rbot, rtop] */
931 /* reused to print numbers */
932 spec = (struct printf_spec){ .base = 10 };
934 rbot = cur = find_first_bit(bitmap, nr_bits);
935 while (cur < nr_bits) {
937 cur = find_next_bit(bitmap, nr_bits, cur + 1);
938 if (cur < nr_bits && cur <= rtop + 1)
948 buf = number(buf, end, rbot, spec);
954 buf = number(buf, end, rtop, spec);
962 static noinline_for_stack
963 char *mac_address_string(char *buf, char *end, u8 *addr,
964 struct printf_spec spec, const char *fmt)
966 char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
970 bool reversed = false;
986 for (i = 0; i < 6; i++) {
988 p = hex_byte_pack(p, addr[5 - i]);
990 p = hex_byte_pack(p, addr[i]);
992 if (fmt[0] == 'M' && i != 5)
997 return string(buf, end, mac_addr, spec);
1000 static noinline_for_stack
1001 char *ip4_string(char *p, const u8 *addr, const char *fmt)
1004 bool leading_zeros = (fmt[0] == 'i');
1029 for (i = 0; i < 4; i++) {
1030 char temp[4] __aligned(2); /* hold each IP quad in reverse order */
1031 int digits = put_dec_trunc8(temp, addr[index]) - temp;
1032 if (leading_zeros) {
1038 /* reverse the digits in the quad */
1040 *p++ = temp[digits];
1050 static noinline_for_stack
1051 char *ip6_compressed_string(char *p, const char *addr)
1054 unsigned char zerolength[8];
1059 bool needcolon = false;
1061 struct in6_addr in6;
1063 memcpy(&in6, addr, sizeof(struct in6_addr));
1065 useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
1067 memset(zerolength, 0, sizeof(zerolength));
1074 /* find position of longest 0 run */
1075 for (i = 0; i < range; i++) {
1076 for (j = i; j < range; j++) {
1077 if (in6.s6_addr16[j] != 0)
1082 for (i = 0; i < range; i++) {
1083 if (zerolength[i] > longest) {
1084 longest = zerolength[i];
1088 if (longest == 1) /* don't compress a single 0 */
1092 for (i = 0; i < range; i++) {
1093 if (i == colonpos) {
1094 if (needcolon || i == 0)
1105 /* hex u16 without leading 0s */
1106 word = ntohs(in6.s6_addr16[i]);
1111 p = hex_byte_pack(p, hi);
1113 *p++ = hex_asc_lo(hi);
1114 p = hex_byte_pack(p, lo);
1117 p = hex_byte_pack(p, lo);
1119 *p++ = hex_asc_lo(lo);
1126 p = ip4_string(p, &in6.s6_addr[12], "I4");
1133 static noinline_for_stack
1134 char *ip6_string(char *p, const char *addr, const char *fmt)
1138 for (i = 0; i < 8; i++) {
1139 p = hex_byte_pack(p, *addr++);
1140 p = hex_byte_pack(p, *addr++);
1141 if (fmt[0] == 'I' && i != 7)
1149 static noinline_for_stack
1150 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1151 struct printf_spec spec, const char *fmt)
1153 char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1155 if (fmt[0] == 'I' && fmt[2] == 'c')
1156 ip6_compressed_string(ip6_addr, addr);
1158 ip6_string(ip6_addr, addr, fmt);
1160 return string(buf, end, ip6_addr, spec);
1163 static noinline_for_stack
1164 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1165 struct printf_spec spec, const char *fmt)
1167 char ip4_addr[sizeof("255.255.255.255")];
1169 ip4_string(ip4_addr, addr, fmt);
1171 return string(buf, end, ip4_addr, spec);
1174 static noinline_for_stack
1175 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1176 struct printf_spec spec, const char *fmt)
1178 bool have_p = false, have_s = false, have_f = false, have_c = false;
1179 char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1180 sizeof(":12345") + sizeof("/123456789") +
1181 sizeof("%1234567890")];
1182 char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1183 const u8 *addr = (const u8 *) &sa->sin6_addr;
1184 char fmt6[2] = { fmt[0], '6' };
1188 while (isalpha(*++fmt)) {
1205 if (have_p || have_s || have_f) {
1210 if (fmt6[0] == 'I' && have_c)
1211 p = ip6_compressed_string(ip6_addr + off, addr);
1213 p = ip6_string(ip6_addr + off, addr, fmt6);
1215 if (have_p || have_s || have_f)
1220 p = number(p, pend, ntohs(sa->sin6_port), spec);
1224 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1225 IPV6_FLOWINFO_MASK), spec);
1229 p = number(p, pend, sa->sin6_scope_id, spec);
1233 return string(buf, end, ip6_addr, spec);
1236 static noinline_for_stack
1237 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1238 struct printf_spec spec, const char *fmt)
1240 bool have_p = false;
1241 char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1242 char *pend = ip4_addr + sizeof(ip4_addr);
1243 const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1244 char fmt4[3] = { fmt[0], '4', 0 };
1247 while (isalpha(*++fmt)) {
1261 p = ip4_string(ip4_addr, addr, fmt4);
1264 p = number(p, pend, ntohs(sa->sin_port), spec);
1268 return string(buf, end, ip4_addr, spec);
1271 static noinline_for_stack
1272 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1277 unsigned int flags = 0;
1280 if (spec.field_width == 0)
1281 return buf; /* nothing to print */
1283 if (ZERO_OR_NULL_PTR(addr))
1284 return string(buf, end, NULL, spec); /* NULL pointer */
1288 switch (fmt[count++]) {
1290 flags |= ESCAPE_ANY;
1293 flags |= ESCAPE_SPECIAL;
1296 flags |= ESCAPE_HEX;
1299 flags |= ESCAPE_NULL;
1302 flags |= ESCAPE_OCTAL;
1308 flags |= ESCAPE_SPACE;
1317 flags = ESCAPE_ANY_NP;
1319 len = spec.field_width < 0 ? 1 : spec.field_width;
1322 * string_escape_mem() writes as many characters as it can to
1323 * the given buffer, and returns the total size of the output
1324 * had the buffer been big enough.
1326 buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1331 static noinline_for_stack
1332 char *uuid_string(char *buf, char *end, const u8 *addr,
1333 struct printf_spec spec, const char *fmt)
1335 char uuid[UUID_STRING_LEN + 1];
1338 const u8 *index = uuid_index;
1343 uc = true; /* fall-through */
1352 for (i = 0; i < 16; i++) {
1354 p = hex_byte_pack_upper(p, addr[index[i]]);
1356 p = hex_byte_pack(p, addr[index[i]]);
1369 return string(buf, end, uuid, spec);
1372 static noinline_for_stack
1373 char *netdev_bits(char *buf, char *end, const void *addr, const char *fmt)
1375 unsigned long long num;
1380 num = *(const netdev_features_t *)addr;
1381 size = sizeof(netdev_features_t);
1384 num = (unsigned long)addr;
1385 size = sizeof(unsigned long);
1389 return special_hex_number(buf, end, num, size);
1392 static noinline_for_stack
1393 char *address_val(char *buf, char *end, const void *addr, const char *fmt)
1395 unsigned long long num;
1400 num = *(const dma_addr_t *)addr;
1401 size = sizeof(dma_addr_t);
1405 num = *(const phys_addr_t *)addr;
1406 size = sizeof(phys_addr_t);
1410 return special_hex_number(buf, end, num, size);
1413 static noinline_for_stack
1414 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1417 if (!IS_ENABLED(CONFIG_HAVE_CLK) || !clk)
1418 return string(buf, end, NULL, spec);
1423 #ifdef CONFIG_COMMON_CLK
1424 return string(buf, end, __clk_get_name(clk), spec);
1426 return special_hex_number(buf, end, (unsigned long)clk, sizeof(unsigned long));
1432 char *format_flags(char *buf, char *end, unsigned long flags,
1433 const struct trace_print_flags *names)
1436 const struct printf_spec strspec = {
1440 const struct printf_spec numspec = {
1441 .flags = SPECIAL|SMALL,
1447 for ( ; flags && names->name; names++) {
1449 if ((flags & mask) != mask)
1452 buf = string(buf, end, names->name, strspec);
1463 buf = number(buf, end, flags, numspec);
1468 static noinline_for_stack
1469 char *flags_string(char *buf, char *end, void *flags_ptr, const char *fmt)
1471 unsigned long flags;
1472 const struct trace_print_flags *names;
1476 flags = *(unsigned long *)flags_ptr;
1477 /* Remove zone id */
1478 flags &= (1UL << NR_PAGEFLAGS) - 1;
1479 names = pageflag_names;
1482 flags = *(unsigned long *)flags_ptr;
1483 names = vmaflag_names;
1486 flags = *(gfp_t *)flags_ptr;
1487 names = gfpflag_names;
1490 WARN_ONCE(1, "Unsupported flags modifier: %c\n", fmt[1]);
1494 return format_flags(buf, end, flags, names);
1497 static const char *device_node_name_for_depth(const struct device_node *np, int depth)
1499 for ( ; np && depth; depth--)
1502 return kbasename(np->full_name);
1505 static noinline_for_stack
1506 char *device_node_gen_full_name(const struct device_node *np, char *buf, char *end)
1509 const struct device_node *parent = np->parent;
1510 static const struct printf_spec strspec = {
1515 /* special case for root node */
1517 return string(buf, end, "/", strspec);
1519 for (depth = 0; parent->parent; depth++)
1520 parent = parent->parent;
1522 for ( ; depth >= 0; depth--) {
1523 buf = string(buf, end, "/", strspec);
1524 buf = string(buf, end, device_node_name_for_depth(np, depth),
1530 static noinline_for_stack
1531 char *device_node_string(char *buf, char *end, struct device_node *dn,
1532 struct printf_spec spec, const char *fmt)
1534 char tbuf[sizeof("xxxx") + 1];
1537 char *buf_start = buf;
1538 struct property *prop;
1539 bool has_mult, pass;
1540 static const struct printf_spec num_spec = {
1547 struct printf_spec str_spec = spec;
1548 str_spec.field_width = -1;
1550 if (!IS_ENABLED(CONFIG_OF))
1551 return string(buf, end, "(!OF)", spec);
1553 if ((unsigned long)dn < PAGE_SIZE)
1554 return string(buf, end, "(null)", spec);
1556 /* simple case without anything any more format specifiers */
1558 if (fmt[0] == '\0' || strcspn(fmt,"fnpPFcC") > 0)
1561 for (pass = false; strspn(fmt,"fnpPFcC"); fmt++, pass = true) {
1569 case 'f': /* full_name */
1570 buf = device_node_gen_full_name(dn, buf, end);
1572 case 'n': /* name */
1573 buf = string(buf, end, dn->name, str_spec);
1575 case 'p': /* phandle */
1576 buf = number(buf, end, (unsigned int)dn->phandle, num_spec);
1578 case 'P': /* path-spec */
1579 p = kbasename(of_node_full_name(dn));
1582 buf = string(buf, end, p, str_spec);
1584 case 'F': /* flags */
1585 tbuf[0] = of_node_check_flag(dn, OF_DYNAMIC) ? 'D' : '-';
1586 tbuf[1] = of_node_check_flag(dn, OF_DETACHED) ? 'd' : '-';
1587 tbuf[2] = of_node_check_flag(dn, OF_POPULATED) ? 'P' : '-';
1588 tbuf[3] = of_node_check_flag(dn, OF_POPULATED_BUS) ? 'B' : '-';
1590 buf = string(buf, end, tbuf, str_spec);
1592 case 'c': /* major compatible string */
1593 ret = of_property_read_string(dn, "compatible", &p);
1595 buf = string(buf, end, p, str_spec);
1597 case 'C': /* full compatible string */
1599 of_property_for_each_string(dn, "compatible", prop, p) {
1601 buf = string(buf, end, ",", str_spec);
1602 buf = string(buf, end, "\"", str_spec);
1603 buf = string(buf, end, p, str_spec);
1604 buf = string(buf, end, "\"", str_spec);
1614 return widen_string(buf, buf - buf_start, end, spec);
1617 int kptr_restrict __read_mostly;
1620 * Show a '%p' thing. A kernel extension is that the '%p' is followed
1621 * by an extra set of alphanumeric characters that are extended format
1624 * Please update scripts/checkpatch.pl when adding/removing conversion
1625 * characters. (Search for "check for vsprintf extension").
1627 * Right now we handle:
1629 * - 'F' For symbolic function descriptor pointers with offset
1630 * - 'f' For simple symbolic function names without offset
1631 * - 'S' For symbolic direct pointers with offset
1632 * - 's' For symbolic direct pointers without offset
1633 * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1634 * - 'B' For backtraced symbolic direct pointers with offset
1635 * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1636 * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
1637 * - 'b[l]' For a bitmap, the number of bits is determined by the field
1638 * width which must be explicitly specified either as part of the
1639 * format string '%32b[l]' or through '%*b[l]', [l] selects
1640 * range-list format instead of hex format
1641 * - 'M' For a 6-byte MAC address, it prints the address in the
1642 * usual colon-separated hex notation
1643 * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1644 * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1645 * with a dash-separated hex notation
1646 * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1647 * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1648 * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1649 * IPv6 uses colon separated network-order 16 bit hex with leading 0's
1651 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1652 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1653 * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1654 * IPv6 omits the colons (01020304...0f)
1655 * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
1657 * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1658 * [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1659 * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1660 * - 'I[6S]c' for IPv6 addresses printed as specified by
1661 * http://tools.ietf.org/html/rfc5952
1662 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1663 * of the following flags (see string_escape_mem() for the
1666 * c - ESCAPE_SPECIAL
1672 * By default ESCAPE_ANY_NP is used.
1673 * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1674 * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1675 * Options for %pU are:
1676 * b big endian lower case hex (default)
1677 * B big endian UPPER case hex
1678 * l little endian lower case hex
1679 * L little endian UPPER case hex
1680 * big endian output byte order is:
1681 * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1682 * little endian output byte order is:
1683 * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1684 * - 'V' For a struct va_format which contains a format string * and va_list *,
1685 * call vsnprintf(->format, *->va_list).
1686 * Implements a "recursive vsnprintf".
1687 * Do not use this feature without some mechanism to verify the
1688 * correctness of the format string and va_list arguments.
1689 * - 'K' For a kernel pointer that should be hidden from unprivileged users
1690 * - 'NF' For a netdev_features_t
1691 * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1692 * a certain separator (' ' by default):
1696 * The maximum supported length is 64 bytes of the input. Consider
1697 * to use print_hex_dump() for the larger input.
1698 * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1699 * (default assumed to be phys_addr_t, passed by reference)
1700 * - 'd[234]' For a dentry name (optionally 2-4 last components)
1701 * - 'D[234]' Same as 'd' but for a struct file
1702 * - 'g' For block_device name (gendisk + partition number)
1703 * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1704 * (legacy clock framework) of the clock
1705 * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1706 * (legacy clock framework) of the clock
1707 * - 'Cr' For a clock, it prints the current rate of the clock
1708 * - 'G' For flags to be printed as a collection of symbolic strings that would
1709 * construct the specific value. Supported flags given by option:
1710 * p page flags (see struct page) given as pointer to unsigned long
1711 * g gfp flags (GFP_* and __GFP_*) given as pointer to gfp_t
1712 * v vma flags (VM_*) given as pointer to unsigned long
1713 * - 'O' For a kobject based struct. Must be one of the following:
1714 * - 'OF[fnpPcCF]' For a device tree object
1715 * Without any optional arguments prints the full_name
1716 * f device node full_name
1717 * n device node name
1718 * p device node phandle
1719 * P device node path spec (name + @unit)
1720 * F device node flags
1721 * c major compatible string
1722 * C full compatible string
1724 * ** Please update also Documentation/printk-formats.txt when making changes **
1726 * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
1727 * function pointers are really function descriptors, which contain a
1728 * pointer to the real address.
1730 static noinline_for_stack
1731 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1732 struct printf_spec spec)
1734 const int default_width = 2 * sizeof(void *);
1736 if (!ptr && *fmt != 'K') {
1738 * Print (null) with the same width as a pointer so it makes
1739 * tabular output look nice.
1741 if (spec.field_width == -1)
1742 spec.field_width = default_width;
1743 return string(buf, end, "(null)", spec);
1749 ptr = dereference_function_descriptor(ptr);
1754 return symbol_string(buf, end, ptr, spec, fmt);
1757 return resource_string(buf, end, ptr, spec, fmt);
1759 return hex_string(buf, end, ptr, spec, fmt);
1763 return bitmap_list_string(buf, end, ptr, spec, fmt);
1765 return bitmap_string(buf, end, ptr, spec, fmt);
1767 case 'M': /* Colon separated: 00:01:02:03:04:05 */
1768 case 'm': /* Contiguous: 000102030405 */
1770 /* [mM]R (Reverse order; Bluetooth) */
1771 return mac_address_string(buf, end, ptr, spec, fmt);
1772 case 'I': /* Formatted IP supported
1774 * 6: 0001:0203:...:0708
1775 * 6c: 1::708 or 1::1.2.3.4
1777 case 'i': /* Contiguous:
1778 * 4: 001.002.003.004
1783 return ip6_addr_string(buf, end, ptr, spec, fmt);
1785 return ip4_addr_string(buf, end, ptr, spec, fmt);
1788 struct sockaddr raw;
1789 struct sockaddr_in v4;
1790 struct sockaddr_in6 v6;
1793 switch (sa->raw.sa_family) {
1795 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1797 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1799 return string(buf, end, "(invalid address)", spec);
1804 return escaped_string(buf, end, ptr, spec, fmt);
1806 return uuid_string(buf, end, ptr, spec, fmt);
1811 va_copy(va, *((struct va_format *)ptr)->va);
1812 buf += vsnprintf(buf, end > buf ? end - buf : 0,
1813 ((struct va_format *)ptr)->fmt, va);
1818 switch (kptr_restrict) {
1820 /* Always print %pK values */
1823 const struct cred *cred;
1826 * kptr_restrict==1 cannot be used in IRQ context
1827 * because its test for CAP_SYSLOG would be meaningless.
1829 if (in_irq() || in_serving_softirq() || in_nmi()) {
1830 if (spec.field_width == -1)
1831 spec.field_width = default_width;
1832 return string(buf, end, "pK-error", spec);
1836 * Only print the real pointer value if the current
1837 * process has CAP_SYSLOG and is running with the
1838 * same credentials it started with. This is because
1839 * access to files is checked at open() time, but %pK
1840 * checks permission at read() time. We don't want to
1841 * leak pointer values if a binary opens a file using
1842 * %pK and then elevates privileges before reading it.
1844 cred = current_cred();
1845 if (!has_capability_noaudit(current, CAP_SYSLOG) ||
1846 !uid_eq(cred->euid, cred->uid) ||
1847 !gid_eq(cred->egid, cred->gid))
1853 /* Always print 0's for %pK */
1860 return netdev_bits(buf, end, ptr, fmt);
1862 return address_val(buf, end, ptr, fmt);
1864 return dentry_name(buf, end, ptr, spec, fmt);
1866 return clock(buf, end, ptr, spec, fmt);
1868 return dentry_name(buf, end,
1869 ((const struct file *)ptr)->f_path.dentry,
1873 return bdev_name(buf, end, ptr, spec, fmt);
1877 return flags_string(buf, end, ptr, fmt);
1881 return device_node_string(buf, end, ptr, spec, fmt + 1);
1884 spec.flags |= SMALL;
1885 if (spec.field_width == -1) {
1886 spec.field_width = default_width;
1887 spec.flags |= ZEROPAD;
1891 return number(buf, end, (unsigned long) ptr, spec);
1895 * Helper function to decode printf style format.
1896 * Each call decode a token from the format and return the
1897 * number of characters read (or likely the delta where it wants
1898 * to go on the next call).
1899 * The decoded token is returned through the parameters
1901 * 'h', 'l', or 'L' for integer fields
1902 * 'z' support added 23/7/1999 S.H.
1903 * 'z' changed to 'Z' --davidm 1/25/99
1904 * 'Z' changed to 'z' --adobriyan 2017-01-25
1905 * 't' added for ptrdiff_t
1907 * @fmt: the format string
1908 * @type of the token returned
1909 * @flags: various flags such as +, -, # tokens..
1910 * @field_width: overwritten width
1911 * @base: base of the number (octal, hex, ...)
1912 * @precision: precision of a number
1913 * @qualifier: qualifier of a number (long, size_t, ...)
1915 static noinline_for_stack
1916 int format_decode(const char *fmt, struct printf_spec *spec)
1918 const char *start = fmt;
1921 /* we finished early by reading the field width */
1922 if (spec->type == FORMAT_TYPE_WIDTH) {
1923 if (spec->field_width < 0) {
1924 spec->field_width = -spec->field_width;
1925 spec->flags |= LEFT;
1927 spec->type = FORMAT_TYPE_NONE;
1931 /* we finished early by reading the precision */
1932 if (spec->type == FORMAT_TYPE_PRECISION) {
1933 if (spec->precision < 0)
1934 spec->precision = 0;
1936 spec->type = FORMAT_TYPE_NONE;
1941 spec->type = FORMAT_TYPE_NONE;
1943 for (; *fmt ; ++fmt) {
1948 /* Return the current non-format string */
1949 if (fmt != start || !*fmt)
1955 while (1) { /* this also skips first '%' */
1961 case '-': spec->flags |= LEFT; break;
1962 case '+': spec->flags |= PLUS; break;
1963 case ' ': spec->flags |= SPACE; break;
1964 case '#': spec->flags |= SPECIAL; break;
1965 case '0': spec->flags |= ZEROPAD; break;
1966 default: found = false;
1973 /* get field width */
1974 spec->field_width = -1;
1977 spec->field_width = skip_atoi(&fmt);
1978 else if (*fmt == '*') {
1979 /* it's the next argument */
1980 spec->type = FORMAT_TYPE_WIDTH;
1981 return ++fmt - start;
1985 /* get the precision */
1986 spec->precision = -1;
1989 if (isdigit(*fmt)) {
1990 spec->precision = skip_atoi(&fmt);
1991 if (spec->precision < 0)
1992 spec->precision = 0;
1993 } else if (*fmt == '*') {
1994 /* it's the next argument */
1995 spec->type = FORMAT_TYPE_PRECISION;
1996 return ++fmt - start;
2001 /* get the conversion qualifier */
2003 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2004 *fmt == 'z' || *fmt == 't') {
2006 if (unlikely(qualifier == *fmt)) {
2007 if (qualifier == 'l') {
2010 } else if (qualifier == 'h') {
2021 spec->type = FORMAT_TYPE_CHAR;
2022 return ++fmt - start;
2025 spec->type = FORMAT_TYPE_STR;
2026 return ++fmt - start;
2029 spec->type = FORMAT_TYPE_PTR;
2030 return ++fmt - start;
2033 spec->type = FORMAT_TYPE_PERCENT_CHAR;
2034 return ++fmt - start;
2036 /* integer number formats - set up the flags and "break" */
2042 spec->flags |= SMALL;
2050 spec->flags |= SIGN;
2056 * Since %n poses a greater security risk than
2057 * utility, treat it as any other invalid or
2058 * unsupported format specifier.
2063 WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt);
2064 spec->type = FORMAT_TYPE_INVALID;
2068 if (qualifier == 'L')
2069 spec->type = FORMAT_TYPE_LONG_LONG;
2070 else if (qualifier == 'l') {
2071 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
2072 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
2073 } else if (qualifier == 'z') {
2074 spec->type = FORMAT_TYPE_SIZE_T;
2075 } else if (qualifier == 't') {
2076 spec->type = FORMAT_TYPE_PTRDIFF;
2077 } else if (qualifier == 'H') {
2078 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
2079 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
2080 } else if (qualifier == 'h') {
2081 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
2082 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
2084 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
2085 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
2088 return ++fmt - start;
2092 set_field_width(struct printf_spec *spec, int width)
2094 spec->field_width = width;
2095 if (WARN_ONCE(spec->field_width != width, "field width %d too large", width)) {
2096 spec->field_width = clamp(width, -FIELD_WIDTH_MAX, FIELD_WIDTH_MAX);
2101 set_precision(struct printf_spec *spec, int prec)
2103 spec->precision = prec;
2104 if (WARN_ONCE(spec->precision != prec, "precision %d too large", prec)) {
2105 spec->precision = clamp(prec, 0, PRECISION_MAX);
2110 * vsnprintf - Format a string and place it in a buffer
2111 * @buf: The buffer to place the result into
2112 * @size: The size of the buffer, including the trailing null space
2113 * @fmt: The format string to use
2114 * @args: Arguments for the format string
2116 * This function generally follows C99 vsnprintf, but has some
2117 * extensions and a few limitations:
2119 * - ``%n`` is unsupported
2120 * - ``%p*`` is handled by pointer()
2122 * See pointer() or Documentation/printk-formats.txt for more
2123 * extensive description.
2125 * **Please update the documentation in both places when making changes**
2127 * The return value is the number of characters which would
2128 * be generated for the given input, excluding the trailing
2129 * '\0', as per ISO C99. If you want to have the exact
2130 * number of characters written into @buf as return value
2131 * (not including the trailing '\0'), use vscnprintf(). If the
2132 * return is greater than or equal to @size, the resulting
2133 * string is truncated.
2135 * If you're not already dealing with a va_list consider using snprintf().
2137 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
2139 unsigned long long num;
2141 struct printf_spec spec = {0};
2143 /* Reject out-of-range values early. Large positive sizes are
2144 used for unknown buffer sizes. */
2145 if (WARN_ON_ONCE(size > INT_MAX))
2151 /* Make sure end is always >= buf */
2158 const char *old_fmt = fmt;
2159 int read = format_decode(fmt, &spec);
2163 switch (spec.type) {
2164 case FORMAT_TYPE_NONE: {
2167 if (copy > end - str)
2169 memcpy(str, old_fmt, copy);
2175 case FORMAT_TYPE_WIDTH:
2176 set_field_width(&spec, va_arg(args, int));
2179 case FORMAT_TYPE_PRECISION:
2180 set_precision(&spec, va_arg(args, int));
2183 case FORMAT_TYPE_CHAR: {
2186 if (!(spec.flags & LEFT)) {
2187 while (--spec.field_width > 0) {
2194 c = (unsigned char) va_arg(args, int);
2198 while (--spec.field_width > 0) {
2206 case FORMAT_TYPE_STR:
2207 str = string(str, end, va_arg(args, char *), spec);
2210 case FORMAT_TYPE_PTR:
2211 str = pointer(fmt, str, end, va_arg(args, void *),
2213 while (isalnum(*fmt))
2217 case FORMAT_TYPE_PERCENT_CHAR:
2223 case FORMAT_TYPE_INVALID:
2225 * Presumably the arguments passed gcc's type
2226 * checking, but there is no safe or sane way
2227 * for us to continue parsing the format and
2228 * fetching from the va_list; the remaining
2229 * specifiers and arguments would be out of
2235 switch (spec.type) {
2236 case FORMAT_TYPE_LONG_LONG:
2237 num = va_arg(args, long long);
2239 case FORMAT_TYPE_ULONG:
2240 num = va_arg(args, unsigned long);
2242 case FORMAT_TYPE_LONG:
2243 num = va_arg(args, long);
2245 case FORMAT_TYPE_SIZE_T:
2246 if (spec.flags & SIGN)
2247 num = va_arg(args, ssize_t);
2249 num = va_arg(args, size_t);
2251 case FORMAT_TYPE_PTRDIFF:
2252 num = va_arg(args, ptrdiff_t);
2254 case FORMAT_TYPE_UBYTE:
2255 num = (unsigned char) va_arg(args, int);
2257 case FORMAT_TYPE_BYTE:
2258 num = (signed char) va_arg(args, int);
2260 case FORMAT_TYPE_USHORT:
2261 num = (unsigned short) va_arg(args, int);
2263 case FORMAT_TYPE_SHORT:
2264 num = (short) va_arg(args, int);
2266 case FORMAT_TYPE_INT:
2267 num = (int) va_arg(args, int);
2270 num = va_arg(args, unsigned int);
2273 str = number(str, end, num, spec);
2285 /* the trailing null byte doesn't count towards the total */
2289 EXPORT_SYMBOL(vsnprintf);
2292 * vscnprintf - Format a string and place it in a buffer
2293 * @buf: The buffer to place the result into
2294 * @size: The size of the buffer, including the trailing null space
2295 * @fmt: The format string to use
2296 * @args: Arguments for the format string
2298 * The return value is the number of characters which have been written into
2299 * the @buf not including the trailing '\0'. If @size is == 0 the function
2302 * If you're not already dealing with a va_list consider using scnprintf().
2304 * See the vsnprintf() documentation for format string extensions over C99.
2306 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2310 i = vsnprintf(buf, size, fmt, args);
2312 if (likely(i < size))
2318 EXPORT_SYMBOL(vscnprintf);
2321 * snprintf - Format a string and place it in a buffer
2322 * @buf: The buffer to place the result into
2323 * @size: The size of the buffer, including the trailing null space
2324 * @fmt: The format string to use
2325 * @...: Arguments for the format string
2327 * The return value is the number of characters which would be
2328 * generated for the given input, excluding the trailing null,
2329 * as per ISO C99. If the return is greater than or equal to
2330 * @size, the resulting string is truncated.
2332 * See the vsnprintf() documentation for format string extensions over C99.
2334 int snprintf(char *buf, size_t size, const char *fmt, ...)
2339 va_start(args, fmt);
2340 i = vsnprintf(buf, size, fmt, args);
2345 EXPORT_SYMBOL(snprintf);
2348 * scnprintf - Format a string and place it in a buffer
2349 * @buf: The buffer to place the result into
2350 * @size: The size of the buffer, including the trailing null space
2351 * @fmt: The format string to use
2352 * @...: Arguments for the format string
2354 * The return value is the number of characters written into @buf not including
2355 * the trailing '\0'. If @size is == 0 the function returns 0.
2358 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2363 va_start(args, fmt);
2364 i = vscnprintf(buf, size, fmt, args);
2369 EXPORT_SYMBOL(scnprintf);
2372 * vsprintf - Format a string and place it in a buffer
2373 * @buf: The buffer to place the result into
2374 * @fmt: The format string to use
2375 * @args: Arguments for the format string
2377 * The function returns the number of characters written
2378 * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2381 * If you're not already dealing with a va_list consider using sprintf().
2383 * See the vsnprintf() documentation for format string extensions over C99.
2385 int vsprintf(char *buf, const char *fmt, va_list args)
2387 return vsnprintf(buf, INT_MAX, fmt, args);
2389 EXPORT_SYMBOL(vsprintf);
2392 * sprintf - Format a string and place it in a buffer
2393 * @buf: The buffer to place the result into
2394 * @fmt: The format string to use
2395 * @...: Arguments for the format string
2397 * The function returns the number of characters written
2398 * into @buf. Use snprintf() or scnprintf() in order to avoid
2401 * See the vsnprintf() documentation for format string extensions over C99.
2403 int sprintf(char *buf, const char *fmt, ...)
2408 va_start(args, fmt);
2409 i = vsnprintf(buf, INT_MAX, fmt, args);
2414 EXPORT_SYMBOL(sprintf);
2416 #ifdef CONFIG_BINARY_PRINTF
2419 * vbin_printf() - VA arguments to binary data
2420 * bstr_printf() - Binary data to text string
2424 * vbin_printf - Parse a format string and place args' binary value in a buffer
2425 * @bin_buf: The buffer to place args' binary value
2426 * @size: The size of the buffer(by words(32bits), not characters)
2427 * @fmt: The format string to use
2428 * @args: Arguments for the format string
2430 * The format follows C99 vsnprintf, except %n is ignored, and its argument
2433 * The return value is the number of words(32bits) which would be generated for
2437 * If the return value is greater than @size, the resulting bin_buf is NOT
2438 * valid for bstr_printf().
2440 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2442 struct printf_spec spec = {0};
2445 str = (char *)bin_buf;
2446 end = (char *)(bin_buf + size);
2448 #define save_arg(type) \
2450 if (sizeof(type) == 8) { \
2451 unsigned long long value; \
2452 str = PTR_ALIGN(str, sizeof(u32)); \
2453 value = va_arg(args, unsigned long long); \
2454 if (str + sizeof(type) <= end) { \
2455 *(u32 *)str = *(u32 *)&value; \
2456 *(u32 *)(str + 4) = *((u32 *)&value + 1); \
2459 unsigned long value; \
2460 str = PTR_ALIGN(str, sizeof(type)); \
2461 value = va_arg(args, int); \
2462 if (str + sizeof(type) <= end) \
2463 *(typeof(type) *)str = (type)value; \
2465 str += sizeof(type); \
2469 int read = format_decode(fmt, &spec);
2473 switch (spec.type) {
2474 case FORMAT_TYPE_NONE:
2475 case FORMAT_TYPE_PERCENT_CHAR:
2477 case FORMAT_TYPE_INVALID:
2480 case FORMAT_TYPE_WIDTH:
2481 case FORMAT_TYPE_PRECISION:
2485 case FORMAT_TYPE_CHAR:
2489 case FORMAT_TYPE_STR: {
2490 const char *save_str = va_arg(args, char *);
2493 if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
2494 || (unsigned long)save_str < PAGE_SIZE)
2495 save_str = "(null)";
2496 len = strlen(save_str) + 1;
2497 if (str + len < end)
2498 memcpy(str, save_str, len);
2503 case FORMAT_TYPE_PTR:
2505 /* skip all alphanumeric pointer suffixes */
2506 while (isalnum(*fmt))
2511 switch (spec.type) {
2513 case FORMAT_TYPE_LONG_LONG:
2514 save_arg(long long);
2516 case FORMAT_TYPE_ULONG:
2517 case FORMAT_TYPE_LONG:
2518 save_arg(unsigned long);
2520 case FORMAT_TYPE_SIZE_T:
2523 case FORMAT_TYPE_PTRDIFF:
2524 save_arg(ptrdiff_t);
2526 case FORMAT_TYPE_UBYTE:
2527 case FORMAT_TYPE_BYTE:
2530 case FORMAT_TYPE_USHORT:
2531 case FORMAT_TYPE_SHORT:
2541 return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2544 EXPORT_SYMBOL_GPL(vbin_printf);
2547 * bstr_printf - Format a string from binary arguments and place it in a buffer
2548 * @buf: The buffer to place the result into
2549 * @size: The size of the buffer, including the trailing null space
2550 * @fmt: The format string to use
2551 * @bin_buf: Binary arguments for the format string
2553 * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2554 * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2555 * a binary buffer that generated by vbin_printf.
2557 * The format follows C99 vsnprintf, but has some extensions:
2558 * see vsnprintf comment for details.
2560 * The return value is the number of characters which would
2561 * be generated for the given input, excluding the trailing
2562 * '\0', as per ISO C99. If you want to have the exact
2563 * number of characters written into @buf as return value
2564 * (not including the trailing '\0'), use vscnprintf(). If the
2565 * return is greater than or equal to @size, the resulting
2566 * string is truncated.
2568 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2570 struct printf_spec spec = {0};
2572 const char *args = (const char *)bin_buf;
2574 if (WARN_ON_ONCE(size > INT_MAX))
2580 #define get_arg(type) \
2582 typeof(type) value; \
2583 if (sizeof(type) == 8) { \
2584 args = PTR_ALIGN(args, sizeof(u32)); \
2585 *(u32 *)&value = *(u32 *)args; \
2586 *((u32 *)&value + 1) = *(u32 *)(args + 4); \
2588 args = PTR_ALIGN(args, sizeof(type)); \
2589 value = *(typeof(type) *)args; \
2591 args += sizeof(type); \
2595 /* Make sure end is always >= buf */
2602 const char *old_fmt = fmt;
2603 int read = format_decode(fmt, &spec);
2607 switch (spec.type) {
2608 case FORMAT_TYPE_NONE: {
2611 if (copy > end - str)
2613 memcpy(str, old_fmt, copy);
2619 case FORMAT_TYPE_WIDTH:
2620 set_field_width(&spec, get_arg(int));
2623 case FORMAT_TYPE_PRECISION:
2624 set_precision(&spec, get_arg(int));
2627 case FORMAT_TYPE_CHAR: {
2630 if (!(spec.flags & LEFT)) {
2631 while (--spec.field_width > 0) {
2637 c = (unsigned char) get_arg(char);
2641 while (--spec.field_width > 0) {
2649 case FORMAT_TYPE_STR: {
2650 const char *str_arg = args;
2651 args += strlen(str_arg) + 1;
2652 str = string(str, end, (char *)str_arg, spec);
2656 case FORMAT_TYPE_PTR:
2657 str = pointer(fmt, str, end, get_arg(void *), spec);
2658 while (isalnum(*fmt))
2662 case FORMAT_TYPE_PERCENT_CHAR:
2668 case FORMAT_TYPE_INVALID:
2672 unsigned long long num;
2674 switch (spec.type) {
2676 case FORMAT_TYPE_LONG_LONG:
2677 num = get_arg(long long);
2679 case FORMAT_TYPE_ULONG:
2680 case FORMAT_TYPE_LONG:
2681 num = get_arg(unsigned long);
2683 case FORMAT_TYPE_SIZE_T:
2684 num = get_arg(size_t);
2686 case FORMAT_TYPE_PTRDIFF:
2687 num = get_arg(ptrdiff_t);
2689 case FORMAT_TYPE_UBYTE:
2690 num = get_arg(unsigned char);
2692 case FORMAT_TYPE_BYTE:
2693 num = get_arg(signed char);
2695 case FORMAT_TYPE_USHORT:
2696 num = get_arg(unsigned short);
2698 case FORMAT_TYPE_SHORT:
2699 num = get_arg(short);
2701 case FORMAT_TYPE_UINT:
2702 num = get_arg(unsigned int);
2708 str = number(str, end, num, spec);
2710 } /* switch(spec.type) */
2723 /* the trailing null byte doesn't count towards the total */
2726 EXPORT_SYMBOL_GPL(bstr_printf);
2729 * bprintf - Parse a format string and place args' binary value in a buffer
2730 * @bin_buf: The buffer to place args' binary value
2731 * @size: The size of the buffer(by words(32bits), not characters)
2732 * @fmt: The format string to use
2733 * @...: Arguments for the format string
2735 * The function returns the number of words(u32) written
2738 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
2743 va_start(args, fmt);
2744 ret = vbin_printf(bin_buf, size, fmt, args);
2749 EXPORT_SYMBOL_GPL(bprintf);
2751 #endif /* CONFIG_BINARY_PRINTF */
2754 * vsscanf - Unformat a buffer into a list of arguments
2755 * @buf: input buffer
2756 * @fmt: format of buffer
2759 int vsscanf(const char *buf, const char *fmt, va_list args)
2761 const char *str = buf;
2769 unsigned long long u;
2775 /* skip any white space in format */
2776 /* white space in format matchs any amount of
2777 * white space, including none, in the input.
2779 if (isspace(*fmt)) {
2780 fmt = skip_spaces(++fmt);
2781 str = skip_spaces(str);
2784 /* anything that is not a conversion must match exactly */
2785 if (*fmt != '%' && *fmt) {
2786 if (*fmt++ != *str++)
2795 /* skip this conversion.
2796 * advance both strings to next white space
2801 while (!isspace(*fmt) && *fmt != '%' && *fmt) {
2802 /* '%*[' not yet supported, invalid format */
2807 while (!isspace(*str) && *str)
2812 /* get field width */
2814 if (isdigit(*fmt)) {
2815 field_width = skip_atoi(&fmt);
2816 if (field_width <= 0)
2820 /* get conversion qualifier */
2822 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2825 if (unlikely(qualifier == *fmt)) {
2826 if (qualifier == 'h') {
2829 } else if (qualifier == 'l') {
2840 /* return number of characters read so far */
2841 *va_arg(args, int *) = str - buf;
2855 char *s = (char *)va_arg(args, char*);
2856 if (field_width == -1)
2860 } while (--field_width > 0 && *str);
2866 char *s = (char *)va_arg(args, char *);
2867 if (field_width == -1)
2868 field_width = SHRT_MAX;
2869 /* first, skip leading white space in buffer */
2870 str = skip_spaces(str);
2872 /* now copy until next white space */
2873 while (*str && !isspace(*str) && field_width--)
2880 * Warning: This implementation of the '[' conversion specifier
2881 * deviates from its glibc counterpart in the following ways:
2882 * (1) It does NOT support ranges i.e. '-' is NOT a special
2884 * (2) It cannot match the closing bracket ']' itself
2885 * (3) A field width is required
2886 * (4) '%*[' (discard matching input) is currently not supported
2889 * ret = sscanf("00:0a:95","%2[^:]:%2[^:]:%2[^:]",
2890 * buf1, buf2, buf3);
2896 char *s = (char *)va_arg(args, char *);
2897 DECLARE_BITMAP(set, 256) = {0};
2898 unsigned int len = 0;
2899 bool negate = (*fmt == '^');
2901 /* field width is required */
2902 if (field_width == -1)
2908 for ( ; *fmt && *fmt != ']'; ++fmt, ++len)
2909 set_bit((u8)*fmt, set);
2911 /* no ']' or no character set found */
2917 bitmap_complement(set, set, 256);
2918 /* exclude null '\0' byte */
2922 /* match must be non-empty */
2923 if (!test_bit((u8)*str, set))
2926 while (test_bit((u8)*str, set) && field_width--)
2946 /* looking for '%' in str */
2951 /* invalid format; stop here */
2955 /* have some sort of integer conversion.
2956 * first, skip white space in buffer.
2958 str = skip_spaces(str);
2961 if (is_sign && digit == '-')
2965 || (base == 16 && !isxdigit(digit))
2966 || (base == 10 && !isdigit(digit))
2967 || (base == 8 && (!isdigit(digit) || digit > '7'))
2968 || (base == 0 && !isdigit(digit)))
2972 val.s = simple_strntoll(str,
2973 field_width >= 0 ? field_width : INT_MAX,
2976 val.u = simple_strntoull(str,
2977 field_width >= 0 ? field_width : INT_MAX,
2980 switch (qualifier) {
2981 case 'H': /* that's 'hh' in format */
2983 *va_arg(args, signed char *) = val.s;
2985 *va_arg(args, unsigned char *) = val.u;
2989 *va_arg(args, short *) = val.s;
2991 *va_arg(args, unsigned short *) = val.u;
2995 *va_arg(args, long *) = val.s;
2997 *va_arg(args, unsigned long *) = val.u;
3001 *va_arg(args, long long *) = val.s;
3003 *va_arg(args, unsigned long long *) = val.u;
3006 *va_arg(args, size_t *) = val.u;
3010 *va_arg(args, int *) = val.s;
3012 *va_arg(args, unsigned int *) = val.u;
3024 EXPORT_SYMBOL(vsscanf);
3027 * sscanf - Unformat a buffer into a list of arguments
3028 * @buf: input buffer
3029 * @fmt: formatting of buffer
3030 * @...: resulting arguments
3032 int sscanf(const char *buf, const char *fmt, ...)
3037 va_start(args, fmt);
3038 i = vsscanf(buf, fmt, args);
3043 EXPORT_SYMBOL(sscanf);