GNU Linux-libre 4.14.332-gnu1
[releases.git] / lib / vsprintf.c
1 /*
2  *  linux/lib/vsprintf.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
8 /*
9  * Wirzenius wrote this portably, Torvalds fucked it up :-)
10  */
11
12 /*
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
17  */
18
19 #include <stdarg.h>
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>
34 #include <linux/of.h>
35 #include <net/addrconf.h>
36 #ifdef CONFIG_BLOCK
37 #include <linux/blkdev.h>
38 #endif
39
40 #include "../mm/internal.h"     /* For the trace_print_flags arrays */
41
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 */
45
46 #include <linux/string_helpers.h>
47 #include "kstrtox.h"
48
49 static unsigned long long simple_strntoull(const char *startp, size_t max_chars,
50                                            char **endp, unsigned int base)
51 {
52         const char *cp;
53         unsigned long long result = 0ULL;
54         size_t prefix_chars;
55         unsigned int rv;
56
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);
61                 /* FIXME */
62                 cp += (rv & ~KSTRTOX_OVERFLOW);
63         } else {
64                 /* Field too short for prefix + digit, skip over without converting */
65                 cp = startp + max_chars;
66         }
67
68         if (endp)
69                 *endp = (char *)cp;
70
71         return result;
72 }
73
74 /**
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
79  *
80  * This function is obsolete. Please use kstrtoull instead.
81  */
82 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
83 {
84         return simple_strntoull(cp, INT_MAX, endp, base);
85 }
86 EXPORT_SYMBOL(simple_strtoull);
87
88 /**
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
93  *
94  * This function is obsolete. Please use kstrtoul instead.
95  */
96 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
97 {
98         return simple_strtoull(cp, endp, base);
99 }
100 EXPORT_SYMBOL(simple_strtoul);
101
102 /**
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
107  *
108  * This function is obsolete. Please use kstrtol instead.
109  */
110 long simple_strtol(const char *cp, char **endp, unsigned int base)
111 {
112         if (*cp == '-')
113                 return -simple_strtoul(cp + 1, endp, base);
114
115         return simple_strtoul(cp, endp, base);
116 }
117 EXPORT_SYMBOL(simple_strtol);
118
119 static long long simple_strntoll(const char *cp, size_t max_chars, char **endp,
120                                  unsigned int base)
121 {
122         /*
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.
127          */
128         if (*cp == '-' && max_chars > 0)
129                 return -simple_strntoull(cp + 1, max_chars - 1, endp, base);
130
131         return simple_strntoull(cp, max_chars, endp, base);
132 }
133
134 /**
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
139  *
140  * This function is obsolete. Please use kstrtoll instead.
141  */
142 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
143 {
144         return simple_strntoll(cp, INT_MAX, endp, base);
145 }
146 EXPORT_SYMBOL(simple_strtoll);
147
148 static noinline_for_stack
149 int skip_atoi(const char **s)
150 {
151         int i = 0;
152
153         do {
154                 i = i*10 + *((*s)++) - '0';
155         } while (isdigit(**s));
156
157         return i;
158 }
159
160 /*
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).
170  *
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.
176  *
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.
179  *
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.
183  */
184
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),
197 #undef _
198 };
199
200 /*
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.
205 */
206 static noinline_for_stack
207 char *put_dec_trunc8(char *buf, unsigned r)
208 {
209         unsigned q;
210
211         /* 1 <= r < 10^8 */
212         if (r < 100)
213                 goto out_r;
214
215         /* 100 <= r < 10^8 */
216         q = (r * (u64)0x28f5c29) >> 32;
217         *((u16 *)buf) = decpair[r - 100*q];
218         buf += 2;
219
220         /* 1 <= q < 10^6 */
221         if (q < 100)
222                 goto out_q;
223
224         /*  100 <= q < 10^6 */
225         r = (q * (u64)0x28f5c29) >> 32;
226         *((u16 *)buf) = decpair[q - 100*r];
227         buf += 2;
228
229         /* 1 <= r < 10^4 */
230         if (r < 100)
231                 goto out_r;
232
233         /* 100 <= r < 10^4 */
234         q = (r * 0x147b) >> 19;
235         *((u16 *)buf) = decpair[r - 100*q];
236         buf += 2;
237 out_q:
238         /* 1 <= q < 100 */
239         r = q;
240 out_r:
241         /* 1 <= r < 100 */
242         *((u16 *)buf) = decpair[r];
243         buf += r < 10 ? 1 : 2;
244         return buf;
245 }
246
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)
250 {
251         unsigned q;
252
253         /* 0 <= r < 10^8 */
254         q = (r * (u64)0x28f5c29) >> 32;
255         *((u16 *)buf) = decpair[r - 100*q];
256         buf += 2;
257
258         /* 0 <= q < 10^6 */
259         r = (q * (u64)0x28f5c29) >> 32;
260         *((u16 *)buf) = decpair[q - 100*r];
261         buf += 2;
262
263         /* 0 <= r < 10^4 */
264         q = (r * 0x147b) >> 19;
265         *((u16 *)buf) = decpair[r - 100*q];
266         buf += 2;
267
268         /* 0 <= q < 100 */
269         *((u16 *)buf) = decpair[q];
270         buf += 2;
271         return buf;
272 }
273
274 static noinline_for_stack
275 char *put_dec(char *buf, unsigned long long n)
276 {
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));
282         /* 1 <= n < 1e8 */
283         return put_dec_trunc8(buf, n);
284 }
285
286 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
287
288 static void
289 put_dec_full4(char *buf, unsigned r)
290 {
291         unsigned q;
292
293         /* 0 <= r < 10^4 */
294         q = (r * 0x147b) >> 19;
295         *((u16 *)buf) = decpair[r - 100*q];
296         buf += 2;
297         /* 0 <= q < 100 */
298         *((u16 *)buf) = decpair[q];
299 }
300
301 /*
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).
307  */
308 static noinline_for_stack
309 unsigned put_dec_helper4(char *buf, unsigned x)
310 {
311         uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
312
313         put_dec_full4(buf, x - q * 10000);
314         return q;
315 }
316
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.
321  */
322 static
323 char *put_dec(char *buf, unsigned long long n)
324 {
325         uint32_t d3, d2, d1, q, h;
326
327         if (n < 100*1000*1000)
328                 return put_dec_trunc8(buf, n);
329
330         d1  = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
331         h   = (n >> 32);
332         d2  = (h      ) & 0xffff;
333         d3  = (h >> 16); /* implicit "& 0xffff" */
334
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);
339
340         q += 7671 * d3 + 9496 * d2 + 6 * d1;
341         q = put_dec_helper4(buf+4, q);
342
343         q += 4749 * d3 + 42 * d2;
344         q = put_dec_helper4(buf+8, q);
345
346         q += 281 * d3;
347         buf += 12;
348         if (q)
349                 buf = put_dec_trunc8(buf, q);
350         else while (buf[-1] == '0')
351                 --buf;
352
353         return buf;
354 }
355
356 #endif
357
358 /*
359  * Convert passed number to decimal string.
360  * Returns the length of string.  On buffer overflow, returns 0.
361  *
362  * If speed is not important, use snprintf(). It's easy to read the code.
363  */
364 int num_to_str(char *buf, int size, unsigned long long num)
365 {
366         /* put_dec requires 2-byte alignment of the buffer. */
367         char tmp[sizeof(num) * 3] __aligned(2);
368         int idx, len;
369
370         /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
371         if (num <= 9) {
372                 tmp[0] = '0' + num;
373                 len = 1;
374         } else {
375                 len = put_dec(tmp, num) - tmp;
376         }
377
378         if (len > size)
379                 return 0;
380         for (idx = 0; idx < len; ++idx)
381                 buf[idx] = tmp[len - idx - 1];
382         return len;
383 }
384
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" */
392
393 enum format_type {
394         FORMAT_TYPE_NONE, /* Just a string part */
395         FORMAT_TYPE_WIDTH,
396         FORMAT_TYPE_PRECISION,
397         FORMAT_TYPE_CHAR,
398         FORMAT_TYPE_STR,
399         FORMAT_TYPE_PTR,
400         FORMAT_TYPE_PERCENT_CHAR,
401         FORMAT_TYPE_INVALID,
402         FORMAT_TYPE_LONG_LONG,
403         FORMAT_TYPE_ULONG,
404         FORMAT_TYPE_LONG,
405         FORMAT_TYPE_UBYTE,
406         FORMAT_TYPE_BYTE,
407         FORMAT_TYPE_USHORT,
408         FORMAT_TYPE_SHORT,
409         FORMAT_TYPE_UINT,
410         FORMAT_TYPE_INT,
411         FORMAT_TYPE_SIZE_T,
412         FORMAT_TYPE_PTRDIFF
413 };
414
415 struct printf_spec {
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 */
421 } __packed;
422 #define FIELD_WIDTH_MAX ((1 << 23) - 1)
423 #define PRECISION_MAX ((1 << 15) - 1)
424
425 static noinline_for_stack
426 char *number(char *buf, char *end, unsigned long long num,
427              struct printf_spec spec)
428 {
429         /* put_dec requires 2-byte alignment of the buffer. */
430         char tmp[3 * sizeof(num)] __aligned(2);
431         char sign;
432         char locase;
433         int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
434         int i;
435         bool is_zero = num == 0LL;
436         int field_width = spec.field_width;
437         int precision = spec.precision;
438
439         BUILD_BUG_ON(sizeof(struct printf_spec) != 8);
440
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;
446         sign = 0;
447         if (spec.flags & SIGN) {
448                 if ((signed long long)num < 0) {
449                         sign = '-';
450                         num = -(signed long long)num;
451                         field_width--;
452                 } else if (spec.flags & PLUS) {
453                         sign = '+';
454                         field_width--;
455                 } else if (spec.flags & SPACE) {
456                         sign = ' ';
457                         field_width--;
458                 }
459         }
460         if (need_pfx) {
461                 if (spec.base == 16)
462                         field_width -= 2;
463                 else if (!is_zero)
464                         field_width--;
465         }
466
467         /* generate full string in tmp[], in reverse order */
468         i = 0;
469         if (num < spec.base)
470                 tmp[i++] = hex_asc_upper[num] | locase;
471         else if (spec.base != 10) { /* 8 or 16 */
472                 int mask = spec.base - 1;
473                 int shift = 3;
474
475                 if (spec.base == 16)
476                         shift = 4;
477                 do {
478                         tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
479                         num >>= shift;
480                 } while (num);
481         } else { /* base 10 */
482                 i = put_dec(tmp, num) - tmp;
483         }
484
485         /* printing 100 using %2d gives "100", not "00" */
486         if (i > precision)
487                 precision = i;
488         /* leading space padding */
489         field_width -= precision;
490         if (!(spec.flags & (ZEROPAD | LEFT))) {
491                 while (--field_width >= 0) {
492                         if (buf < end)
493                                 *buf = ' ';
494                         ++buf;
495                 }
496         }
497         /* sign */
498         if (sign) {
499                 if (buf < end)
500                         *buf = sign;
501                 ++buf;
502         }
503         /* "0x" / "0" prefix */
504         if (need_pfx) {
505                 if (spec.base == 16 || !is_zero) {
506                         if (buf < end)
507                                 *buf = '0';
508                         ++buf;
509                 }
510                 if (spec.base == 16) {
511                         if (buf < end)
512                                 *buf = ('X' | locase);
513                         ++buf;
514                 }
515         }
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) {
521                         if (buf < end)
522                                 *buf = c;
523                         ++buf;
524                 }
525         }
526         /* hmm even more zero padding? */
527         while (i <= --precision) {
528                 if (buf < end)
529                         *buf = '0';
530                 ++buf;
531         }
532         /* actual digits of result */
533         while (--i >= 0) {
534                 if (buf < end)
535                         *buf = tmp[i];
536                 ++buf;
537         }
538         /* trailing space padding */
539         while (--field_width >= 0) {
540                 if (buf < end)
541                         *buf = ' ';
542                 ++buf;
543         }
544
545         return buf;
546 }
547
548 static noinline_for_stack
549 char *special_hex_number(char *buf, char *end, unsigned long long num, int size)
550 {
551         struct printf_spec spec;
552
553         spec.type = FORMAT_TYPE_PTR;
554         spec.field_width = 2 + 2 * size;        /* 0x + hex */
555         spec.flags = SPECIAL | SMALL | ZEROPAD;
556         spec.base = 16;
557         spec.precision = -1;
558
559         return number(buf, end, num, spec);
560 }
561
562 static void move_right(char *buf, char *end, unsigned len, unsigned spaces)
563 {
564         size_t size;
565         if (buf >= end) /* nowhere to put anything */
566                 return;
567         size = end - buf;
568         if (size <= spaces) {
569                 memset(buf, ' ', size);
570                 return;
571         }
572         if (len) {
573                 if (len > size - spaces)
574                         len = size - spaces;
575                 memmove(buf + spaces, buf, len);
576         }
577         memset(buf, ' ', spaces);
578 }
579
580 /*
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.
587  */
588 static noinline_for_stack
589 char *widen_string(char *buf, int n, char *end, struct printf_spec spec)
590 {
591         unsigned spaces;
592
593         if (likely(n >= spec.field_width))
594                 return buf;
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);
599                 return buf + spaces;
600         }
601         while (spaces--) {
602                 if (buf < end)
603                         *buf = ' ';
604                 ++buf;
605         }
606         return buf;
607 }
608
609 static noinline_for_stack
610 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
611 {
612         int len = 0;
613         size_t lim = spec.precision;
614
615         if ((unsigned long)s < PAGE_SIZE)
616                 s = "(null)";
617
618         while (lim--) {
619                 char c = *s++;
620                 if (!c)
621                         break;
622                 if (buf < end)
623                         *buf = c;
624                 ++buf;
625                 ++len;
626         }
627         return widen_string(buf, len, end, spec);
628 }
629
630 static noinline_for_stack
631 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
632                   const char *fmt)
633 {
634         const char *array[4], *s;
635         const struct dentry *p;
636         int depth;
637         int i, n;
638
639         switch (fmt[1]) {
640                 case '2': case '3': case '4':
641                         depth = fmt[1] - '0';
642                         break;
643                 default:
644                         depth = 1;
645         }
646
647         rcu_read_lock();
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);
651                 if (p == d) {
652                         if (i)
653                                 array[i] = "";
654                         i++;
655                         break;
656                 }
657         }
658         s = array[--i];
659         for (n = 0; n != spec.precision; n++, buf++) {
660                 char c = *s++;
661                 if (!c) {
662                         if (!i)
663                                 break;
664                         c = '/';
665                         s = array[--i];
666                 }
667                 if (buf < end)
668                         *buf = c;
669         }
670         rcu_read_unlock();
671         return widen_string(buf, n, end, spec);
672 }
673
674 #ifdef CONFIG_BLOCK
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)
678 {
679         struct gendisk *hd = bdev->bd_disk;
680         
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])) {
684                         if (buf < end)
685                                 *buf = 'p';
686                         buf++;
687                 }
688                 buf = number(buf, end, bdev->bd_part->partno, spec);
689         }
690         return buf;
691 }
692 #endif
693
694 static noinline_for_stack
695 char *symbol_string(char *buf, char *end, void *ptr,
696                     struct printf_spec spec, const char *fmt)
697 {
698         unsigned long value;
699 #ifdef CONFIG_KALLSYMS
700         char sym[KSYM_SYMBOL_LEN];
701 #endif
702
703         if (fmt[1] == 'R')
704                 ptr = __builtin_extract_return_addr(ptr);
705         value = (unsigned long)ptr;
706
707 #ifdef CONFIG_KALLSYMS
708         if (*fmt == 'B')
709                 sprint_backtrace(sym, value);
710         else if (*fmt != 'f' && *fmt != 's')
711                 sprint_symbol(sym, value);
712         else
713                 sprint_symbol_no_offset(sym, value);
714
715         return string(buf, end, sym, spec);
716 #else
717         return special_hex_number(buf, end, value, sizeof(void *));
718 #endif
719 }
720
721 static noinline_for_stack
722 char *resource_string(char *buf, char *end, struct resource *res,
723                       struct printf_spec spec, const char *fmt)
724 {
725 #ifndef IO_RSRC_PRINTK_SIZE
726 #define IO_RSRC_PRINTK_SIZE     6
727 #endif
728
729 #ifndef MEM_RSRC_PRINTK_SIZE
730 #define MEM_RSRC_PRINTK_SIZE    10
731 #endif
732         static const struct printf_spec io_spec = {
733                 .base = 16,
734                 .field_width = IO_RSRC_PRINTK_SIZE,
735                 .precision = -1,
736                 .flags = SPECIAL | SMALL | ZEROPAD,
737         };
738         static const struct printf_spec mem_spec = {
739                 .base = 16,
740                 .field_width = MEM_RSRC_PRINTK_SIZE,
741                 .precision = -1,
742                 .flags = SPECIAL | SMALL | ZEROPAD,
743         };
744         static const struct printf_spec bus_spec = {
745                 .base = 16,
746                 .field_width = 2,
747                 .precision = -1,
748                 .flags = SMALL | ZEROPAD,
749         };
750         static const struct printf_spec dec_spec = {
751                 .base = 10,
752                 .precision = -1,
753                 .flags = 0,
754         };
755         static const struct printf_spec str_spec = {
756                 .field_width = -1,
757                 .precision = 10,
758                 .flags = LEFT,
759         };
760         static const struct printf_spec flag_spec = {
761                 .base = 16,
762                 .precision = -1,
763                 .flags = SPECIAL | SMALL,
764         };
765
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)];
774
775         char *p = sym, *pend = sym + sizeof(sym);
776         int decode = (fmt[0] == 'R') ? 1 : 0;
777         const struct printf_spec *specp;
778
779         *p++ = '[';
780         if (res->flags & IORESOURCE_IO) {
781                 p = string(p, pend, "io  ", str_spec);
782                 specp = &io_spec;
783         } else if (res->flags & IORESOURCE_MEM) {
784                 p = string(p, pend, "mem ", str_spec);
785                 specp = &mem_spec;
786         } else if (res->flags & IORESOURCE_IRQ) {
787                 p = string(p, pend, "irq ", str_spec);
788                 specp = &dec_spec;
789         } else if (res->flags & IORESOURCE_DMA) {
790                 p = string(p, pend, "dma ", str_spec);
791                 specp = &dec_spec;
792         } else if (res->flags & IORESOURCE_BUS) {
793                 p = string(p, pend, "bus ", str_spec);
794                 specp = &bus_spec;
795         } else {
796                 p = string(p, pend, "??? ", str_spec);
797                 specp = &mem_spec;
798                 decode = 0;
799         }
800         if (decode && res->flags & IORESOURCE_UNSET) {
801                 p = string(p, pend, "size ", str_spec);
802                 p = number(p, pend, resource_size(res), *specp);
803         } else {
804                 p = number(p, pend, res->start, *specp);
805                 if (res->start != res->end) {
806                         *p++ = '-';
807                         p = number(p, pend, res->end, *specp);
808                 }
809         }
810         if (decode) {
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);
819         } else {
820                 p = string(p, pend, " flags ", str_spec);
821                 p = number(p, pend, res->flags, flag_spec);
822         }
823         *p++ = ']';
824         *p = '\0';
825
826         return string(buf, end, sym, spec);
827 }
828
829 static noinline_for_stack
830 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
831                  const char *fmt)
832 {
833         int i, len = 1;         /* if we pass '%ph[CDN]', field width remains
834                                    negative value, fallback to the default */
835         char separator;
836
837         if (spec.field_width == 0)
838                 /* nothing to print */
839                 return buf;
840
841         if (ZERO_OR_NULL_PTR(addr))
842                 /* NULL pointer */
843                 return string(buf, end, NULL, spec);
844
845         switch (fmt[1]) {
846         case 'C':
847                 separator = ':';
848                 break;
849         case 'D':
850                 separator = '-';
851                 break;
852         case 'N':
853                 separator = 0;
854                 break;
855         default:
856                 separator = ' ';
857                 break;
858         }
859
860         if (spec.field_width > 0)
861                 len = min_t(int, spec.field_width, 64);
862
863         for (i = 0; i < len; ++i) {
864                 if (buf < end)
865                         *buf = hex_asc_hi(addr[i]);
866                 ++buf;
867                 if (buf < end)
868                         *buf = hex_asc_lo(addr[i]);
869                 ++buf;
870
871                 if (separator && i != len - 1) {
872                         if (buf < end)
873                                 *buf = separator;
874                         ++buf;
875                 }
876         }
877
878         return buf;
879 }
880
881 static noinline_for_stack
882 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
883                     struct printf_spec spec, const char *fmt)
884 {
885         const int CHUNKSZ = 32;
886         int nr_bits = max_t(int, spec.field_width, 0);
887         int i, chunksz;
888         bool first = true;
889
890         /* reused to print numbers */
891         spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
892
893         chunksz = nr_bits & (CHUNKSZ - 1);
894         if (chunksz == 0)
895                 chunksz = CHUNKSZ;
896
897         i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
898         for (; i >= 0; i -= CHUNKSZ) {
899                 u32 chunkmask, val;
900                 int word, bit;
901
902                 chunkmask = ((1ULL << chunksz) - 1);
903                 word = i / BITS_PER_LONG;
904                 bit = i % BITS_PER_LONG;
905                 val = (bitmap[word] >> bit) & chunkmask;
906
907                 if (!first) {
908                         if (buf < end)
909                                 *buf = ',';
910                         buf++;
911                 }
912                 first = false;
913
914                 spec.field_width = DIV_ROUND_UP(chunksz, 4);
915                 buf = number(buf, end, val, spec);
916
917                 chunksz = CHUNKSZ;
918         }
919         return buf;
920 }
921
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)
925 {
926         int nr_bits = max_t(int, spec.field_width, 0);
927         /* current bit is 'cur', most recently seen range is [rbot, rtop] */
928         int cur, rbot, rtop;
929         bool first = true;
930
931         /* reused to print numbers */
932         spec = (struct printf_spec){ .base = 10 };
933
934         rbot = cur = find_first_bit(bitmap, nr_bits);
935         while (cur < nr_bits) {
936                 rtop = cur;
937                 cur = find_next_bit(bitmap, nr_bits, cur + 1);
938                 if (cur < nr_bits && cur <= rtop + 1)
939                         continue;
940
941                 if (!first) {
942                         if (buf < end)
943                                 *buf = ',';
944                         buf++;
945                 }
946                 first = false;
947
948                 buf = number(buf, end, rbot, spec);
949                 if (rbot < rtop) {
950                         if (buf < end)
951                                 *buf = '-';
952                         buf++;
953
954                         buf = number(buf, end, rtop, spec);
955                 }
956
957                 rbot = cur;
958         }
959         return buf;
960 }
961
962 static noinline_for_stack
963 char *mac_address_string(char *buf, char *end, u8 *addr,
964                          struct printf_spec spec, const char *fmt)
965 {
966         char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
967         char *p = mac_addr;
968         int i;
969         char separator;
970         bool reversed = false;
971
972         switch (fmt[1]) {
973         case 'F':
974                 separator = '-';
975                 break;
976
977         case 'R':
978                 reversed = true;
979                 /* fall through */
980
981         default:
982                 separator = ':';
983                 break;
984         }
985
986         for (i = 0; i < 6; i++) {
987                 if (reversed)
988                         p = hex_byte_pack(p, addr[5 - i]);
989                 else
990                         p = hex_byte_pack(p, addr[i]);
991
992                 if (fmt[0] == 'M' && i != 5)
993                         *p++ = separator;
994         }
995         *p = '\0';
996
997         return string(buf, end, mac_addr, spec);
998 }
999
1000 static noinline_for_stack
1001 char *ip4_string(char *p, const u8 *addr, const char *fmt)
1002 {
1003         int i;
1004         bool leading_zeros = (fmt[0] == 'i');
1005         int index;
1006         int step;
1007
1008         switch (fmt[2]) {
1009         case 'h':
1010 #ifdef __BIG_ENDIAN
1011                 index = 0;
1012                 step = 1;
1013 #else
1014                 index = 3;
1015                 step = -1;
1016 #endif
1017                 break;
1018         case 'l':
1019                 index = 3;
1020                 step = -1;
1021                 break;
1022         case 'n':
1023         case 'b':
1024         default:
1025                 index = 0;
1026                 step = 1;
1027                 break;
1028         }
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) {
1033                         if (digits < 3)
1034                                 *p++ = '0';
1035                         if (digits < 2)
1036                                 *p++ = '0';
1037                 }
1038                 /* reverse the digits in the quad */
1039                 while (digits--)
1040                         *p++ = temp[digits];
1041                 if (i < 3)
1042                         *p++ = '.';
1043                 index += step;
1044         }
1045         *p = '\0';
1046
1047         return p;
1048 }
1049
1050 static noinline_for_stack
1051 char *ip6_compressed_string(char *p, const char *addr)
1052 {
1053         int i, j, range;
1054         unsigned char zerolength[8];
1055         int longest = 1;
1056         int colonpos = -1;
1057         u16 word;
1058         u8 hi, lo;
1059         bool needcolon = false;
1060         bool useIPv4;
1061         struct in6_addr in6;
1062
1063         memcpy(&in6, addr, sizeof(struct in6_addr));
1064
1065         useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
1066
1067         memset(zerolength, 0, sizeof(zerolength));
1068
1069         if (useIPv4)
1070                 range = 6;
1071         else
1072                 range = 8;
1073
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)
1078                                 break;
1079                         zerolength[i]++;
1080                 }
1081         }
1082         for (i = 0; i < range; i++) {
1083                 if (zerolength[i] > longest) {
1084                         longest = zerolength[i];
1085                         colonpos = i;
1086                 }
1087         }
1088         if (longest == 1)               /* don't compress a single 0 */
1089                 colonpos = -1;
1090
1091         /* emit address */
1092         for (i = 0; i < range; i++) {
1093                 if (i == colonpos) {
1094                         if (needcolon || i == 0)
1095                                 *p++ = ':';
1096                         *p++ = ':';
1097                         needcolon = false;
1098                         i += longest - 1;
1099                         continue;
1100                 }
1101                 if (needcolon) {
1102                         *p++ = ':';
1103                         needcolon = false;
1104                 }
1105                 /* hex u16 without leading 0s */
1106                 word = ntohs(in6.s6_addr16[i]);
1107                 hi = word >> 8;
1108                 lo = word & 0xff;
1109                 if (hi) {
1110                         if (hi > 0x0f)
1111                                 p = hex_byte_pack(p, hi);
1112                         else
1113                                 *p++ = hex_asc_lo(hi);
1114                         p = hex_byte_pack(p, lo);
1115                 }
1116                 else if (lo > 0x0f)
1117                         p = hex_byte_pack(p, lo);
1118                 else
1119                         *p++ = hex_asc_lo(lo);
1120                 needcolon = true;
1121         }
1122
1123         if (useIPv4) {
1124                 if (needcolon)
1125                         *p++ = ':';
1126                 p = ip4_string(p, &in6.s6_addr[12], "I4");
1127         }
1128         *p = '\0';
1129
1130         return p;
1131 }
1132
1133 static noinline_for_stack
1134 char *ip6_string(char *p, const char *addr, const char *fmt)
1135 {
1136         int i;
1137
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)
1142                         *p++ = ':';
1143         }
1144         *p = '\0';
1145
1146         return p;
1147 }
1148
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)
1152 {
1153         char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1154
1155         if (fmt[0] == 'I' && fmt[2] == 'c')
1156                 ip6_compressed_string(ip6_addr, addr);
1157         else
1158                 ip6_string(ip6_addr, addr, fmt);
1159
1160         return string(buf, end, ip6_addr, spec);
1161 }
1162
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)
1166 {
1167         char ip4_addr[sizeof("255.255.255.255")];
1168
1169         ip4_string(ip4_addr, addr, fmt);
1170
1171         return string(buf, end, ip4_addr, spec);
1172 }
1173
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)
1177 {
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' };
1185         u8 off = 0;
1186
1187         fmt++;
1188         while (isalpha(*++fmt)) {
1189                 switch (*fmt) {
1190                 case 'p':
1191                         have_p = true;
1192                         break;
1193                 case 'f':
1194                         have_f = true;
1195                         break;
1196                 case 's':
1197                         have_s = true;
1198                         break;
1199                 case 'c':
1200                         have_c = true;
1201                         break;
1202                 }
1203         }
1204
1205         if (have_p || have_s || have_f) {
1206                 *p = '[';
1207                 off = 1;
1208         }
1209
1210         if (fmt6[0] == 'I' && have_c)
1211                 p = ip6_compressed_string(ip6_addr + off, addr);
1212         else
1213                 p = ip6_string(ip6_addr + off, addr, fmt6);
1214
1215         if (have_p || have_s || have_f)
1216                 *p++ = ']';
1217
1218         if (have_p) {
1219                 *p++ = ':';
1220                 p = number(p, pend, ntohs(sa->sin6_port), spec);
1221         }
1222         if (have_f) {
1223                 *p++ = '/';
1224                 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1225                                           IPV6_FLOWINFO_MASK), spec);
1226         }
1227         if (have_s) {
1228                 *p++ = '%';
1229                 p = number(p, pend, sa->sin6_scope_id, spec);
1230         }
1231         *p = '\0';
1232
1233         return string(buf, end, ip6_addr, spec);
1234 }
1235
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)
1239 {
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 };
1245
1246         fmt++;
1247         while (isalpha(*++fmt)) {
1248                 switch (*fmt) {
1249                 case 'p':
1250                         have_p = true;
1251                         break;
1252                 case 'h':
1253                 case 'l':
1254                 case 'n':
1255                 case 'b':
1256                         fmt4[2] = *fmt;
1257                         break;
1258                 }
1259         }
1260
1261         p = ip4_string(ip4_addr, addr, fmt4);
1262         if (have_p) {
1263                 *p++ = ':';
1264                 p = number(p, pend, ntohs(sa->sin_port), spec);
1265         }
1266         *p = '\0';
1267
1268         return string(buf, end, ip4_addr, spec);
1269 }
1270
1271 static noinline_for_stack
1272 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1273                      const char *fmt)
1274 {
1275         bool found = true;
1276         int count = 1;
1277         unsigned int flags = 0;
1278         int len;
1279
1280         if (spec.field_width == 0)
1281                 return buf;                             /* nothing to print */
1282
1283         if (ZERO_OR_NULL_PTR(addr))
1284                 return string(buf, end, NULL, spec);    /* NULL pointer */
1285
1286
1287         do {
1288                 switch (fmt[count++]) {
1289                 case 'a':
1290                         flags |= ESCAPE_ANY;
1291                         break;
1292                 case 'c':
1293                         flags |= ESCAPE_SPECIAL;
1294                         break;
1295                 case 'h':
1296                         flags |= ESCAPE_HEX;
1297                         break;
1298                 case 'n':
1299                         flags |= ESCAPE_NULL;
1300                         break;
1301                 case 'o':
1302                         flags |= ESCAPE_OCTAL;
1303                         break;
1304                 case 'p':
1305                         flags |= ESCAPE_NP;
1306                         break;
1307                 case 's':
1308                         flags |= ESCAPE_SPACE;
1309                         break;
1310                 default:
1311                         found = false;
1312                         break;
1313                 }
1314         } while (found);
1315
1316         if (!flags)
1317                 flags = ESCAPE_ANY_NP;
1318
1319         len = spec.field_width < 0 ? 1 : spec.field_width;
1320
1321         /*
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.
1325          */
1326         buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1327
1328         return buf;
1329 }
1330
1331 static noinline_for_stack
1332 char *uuid_string(char *buf, char *end, const u8 *addr,
1333                   struct printf_spec spec, const char *fmt)
1334 {
1335         char uuid[UUID_STRING_LEN + 1];
1336         char *p = uuid;
1337         int i;
1338         const u8 *index = uuid_index;
1339         bool uc = false;
1340
1341         switch (*(++fmt)) {
1342         case 'L':
1343                 uc = true;              /* fall-through */
1344         case 'l':
1345                 index = guid_index;
1346                 break;
1347         case 'B':
1348                 uc = true;
1349                 break;
1350         }
1351
1352         for (i = 0; i < 16; i++) {
1353                 if (uc)
1354                         p = hex_byte_pack_upper(p, addr[index[i]]);
1355                 else
1356                         p = hex_byte_pack(p, addr[index[i]]);
1357                 switch (i) {
1358                 case 3:
1359                 case 5:
1360                 case 7:
1361                 case 9:
1362                         *p++ = '-';
1363                         break;
1364                 }
1365         }
1366
1367         *p = 0;
1368
1369         return string(buf, end, uuid, spec);
1370 }
1371
1372 static noinline_for_stack
1373 char *netdev_bits(char *buf, char *end, const void *addr, const char *fmt)
1374 {
1375         unsigned long long num;
1376         int size;
1377
1378         switch (fmt[1]) {
1379         case 'F':
1380                 num = *(const netdev_features_t *)addr;
1381                 size = sizeof(netdev_features_t);
1382                 break;
1383         default:
1384                 num = (unsigned long)addr;
1385                 size = sizeof(unsigned long);
1386                 break;
1387         }
1388
1389         return special_hex_number(buf, end, num, size);
1390 }
1391
1392 static noinline_for_stack
1393 char *address_val(char *buf, char *end, const void *addr, const char *fmt)
1394 {
1395         unsigned long long num;
1396         int size;
1397
1398         switch (fmt[1]) {
1399         case 'd':
1400                 num = *(const dma_addr_t *)addr;
1401                 size = sizeof(dma_addr_t);
1402                 break;
1403         case 'p':
1404         default:
1405                 num = *(const phys_addr_t *)addr;
1406                 size = sizeof(phys_addr_t);
1407                 break;
1408         }
1409
1410         return special_hex_number(buf, end, num, size);
1411 }
1412
1413 static noinline_for_stack
1414 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1415             const char *fmt)
1416 {
1417         if (!IS_ENABLED(CONFIG_HAVE_CLK) || !clk)
1418                 return string(buf, end, NULL, spec);
1419
1420         switch (fmt[1]) {
1421         case 'n':
1422         default:
1423 #ifdef CONFIG_COMMON_CLK
1424                 return string(buf, end, __clk_get_name(clk), spec);
1425 #else
1426                 return special_hex_number(buf, end, (unsigned long)clk, sizeof(unsigned long));
1427 #endif
1428         }
1429 }
1430
1431 static
1432 char *format_flags(char *buf, char *end, unsigned long flags,
1433                                         const struct trace_print_flags *names)
1434 {
1435         unsigned long mask;
1436         const struct printf_spec strspec = {
1437                 .field_width = -1,
1438                 .precision = -1,
1439         };
1440         const struct printf_spec numspec = {
1441                 .flags = SPECIAL|SMALL,
1442                 .field_width = -1,
1443                 .precision = -1,
1444                 .base = 16,
1445         };
1446
1447         for ( ; flags && names->name; names++) {
1448                 mask = names->mask;
1449                 if ((flags & mask) != mask)
1450                         continue;
1451
1452                 buf = string(buf, end, names->name, strspec);
1453
1454                 flags &= ~mask;
1455                 if (flags) {
1456                         if (buf < end)
1457                                 *buf = '|';
1458                         buf++;
1459                 }
1460         }
1461
1462         if (flags)
1463                 buf = number(buf, end, flags, numspec);
1464
1465         return buf;
1466 }
1467
1468 static noinline_for_stack
1469 char *flags_string(char *buf, char *end, void *flags_ptr, const char *fmt)
1470 {
1471         unsigned long flags;
1472         const struct trace_print_flags *names;
1473
1474         switch (fmt[1]) {
1475         case 'p':
1476                 flags = *(unsigned long *)flags_ptr;
1477                 /* Remove zone id */
1478                 flags &= (1UL << NR_PAGEFLAGS) - 1;
1479                 names = pageflag_names;
1480                 break;
1481         case 'v':
1482                 flags = *(unsigned long *)flags_ptr;
1483                 names = vmaflag_names;
1484                 break;
1485         case 'g':
1486                 flags = *(gfp_t *)flags_ptr;
1487                 names = gfpflag_names;
1488                 break;
1489         default:
1490                 WARN_ONCE(1, "Unsupported flags modifier: %c\n", fmt[1]);
1491                 return buf;
1492         }
1493
1494         return format_flags(buf, end, flags, names);
1495 }
1496
1497 static const char *device_node_name_for_depth(const struct device_node *np, int depth)
1498 {
1499         for ( ; np && depth; depth--)
1500                 np = np->parent;
1501
1502         return kbasename(np->full_name);
1503 }
1504
1505 static noinline_for_stack
1506 char *device_node_gen_full_name(const struct device_node *np, char *buf, char *end)
1507 {
1508         int depth;
1509         const struct device_node *parent = np->parent;
1510         static const struct printf_spec strspec = {
1511                 .field_width = -1,
1512                 .precision = -1,
1513         };
1514
1515         /* special case for root node */
1516         if (!parent)
1517                 return string(buf, end, "/", strspec);
1518
1519         for (depth = 0; parent->parent; depth++)
1520                 parent = parent->parent;
1521
1522         for ( ; depth >= 0; depth--) {
1523                 buf = string(buf, end, "/", strspec);
1524                 buf = string(buf, end, device_node_name_for_depth(np, depth),
1525                              strspec);
1526         }
1527         return buf;
1528 }
1529
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)
1533 {
1534         char tbuf[sizeof("xxxx") + 1];
1535         const char *p;
1536         int ret;
1537         char *buf_start = buf;
1538         struct property *prop;
1539         bool has_mult, pass;
1540         static const struct printf_spec num_spec = {
1541                 .flags = SMALL,
1542                 .field_width = -1,
1543                 .precision = -1,
1544                 .base = 10,
1545         };
1546
1547         struct printf_spec str_spec = spec;
1548         str_spec.field_width = -1;
1549
1550         if (!IS_ENABLED(CONFIG_OF))
1551                 return string(buf, end, "(!OF)", spec);
1552
1553         if ((unsigned long)dn < PAGE_SIZE)
1554                 return string(buf, end, "(null)", spec);
1555
1556         /* simple case without anything any more format specifiers */
1557         fmt++;
1558         if (fmt[0] == '\0' || strcspn(fmt,"fnpPFcC") > 0)
1559                 fmt = "f";
1560
1561         for (pass = false; strspn(fmt,"fnpPFcC"); fmt++, pass = true) {
1562                 if (pass) {
1563                         if (buf < end)
1564                                 *buf = ':';
1565                         buf++;
1566                 }
1567
1568                 switch (*fmt) {
1569                 case 'f':       /* full_name */
1570                         buf = device_node_gen_full_name(dn, buf, end);
1571                         break;
1572                 case 'n':       /* name */
1573                         buf = string(buf, end, dn->name, str_spec);
1574                         break;
1575                 case 'p':       /* phandle */
1576                         buf = number(buf, end, (unsigned int)dn->phandle, num_spec);
1577                         break;
1578                 case 'P':       /* path-spec */
1579                         p = kbasename(of_node_full_name(dn));
1580                         if (!p[1])
1581                                 p = "/";
1582                         buf = string(buf, end, p, str_spec);
1583                         break;
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' : '-';
1589                         tbuf[4] = 0;
1590                         buf = string(buf, end, tbuf, str_spec);
1591                         break;
1592                 case 'c':       /* major compatible string */
1593                         ret = of_property_read_string(dn, "compatible", &p);
1594                         if (!ret)
1595                                 buf = string(buf, end, p, str_spec);
1596                         break;
1597                 case 'C':       /* full compatible string */
1598                         has_mult = false;
1599                         of_property_for_each_string(dn, "compatible", prop, p) {
1600                                 if (has_mult)
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);
1605
1606                                 has_mult = true;
1607                         }
1608                         break;
1609                 default:
1610                         break;
1611                 }
1612         }
1613
1614         return widen_string(buf, buf - buf_start, end, spec);
1615 }
1616
1617 int kptr_restrict __read_mostly;
1618
1619 /*
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
1622  * specifiers.
1623  *
1624  * Please update scripts/checkpatch.pl when adding/removing conversion
1625  * characters.  (Search for "check for vsprintf extension").
1626  *
1627  * Right now we handle:
1628  *
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
1650  *       [S][pfs]
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)
1656  *       [S][pfs]
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
1664  *                details):
1665  *                  a - ESCAPE_ANY
1666  *                  c - ESCAPE_SPECIAL
1667  *                  h - ESCAPE_HEX
1668  *                  n - ESCAPE_NULL
1669  *                  o - ESCAPE_OCTAL
1670  *                  p - ESCAPE_NP
1671  *                  s - ESCAPE_SPACE
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):
1693  *              C colon
1694  *              D dash
1695  *              N no separator
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
1723  *
1724  * ** Please update also Documentation/printk-formats.txt when making changes **
1725  *
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.
1729  */
1730 static noinline_for_stack
1731 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1732               struct printf_spec spec)
1733 {
1734         const int default_width = 2 * sizeof(void *);
1735
1736         if (!ptr && *fmt != 'K') {
1737                 /*
1738                  * Print (null) with the same width as a pointer so it makes
1739                  * tabular output look nice.
1740                  */
1741                 if (spec.field_width == -1)
1742                         spec.field_width = default_width;
1743                 return string(buf, end, "(null)", spec);
1744         }
1745
1746         switch (*fmt) {
1747         case 'F':
1748         case 'f':
1749                 ptr = dereference_function_descriptor(ptr);
1750                 /* Fallthrough */
1751         case 'S':
1752         case 's':
1753         case 'B':
1754                 return symbol_string(buf, end, ptr, spec, fmt);
1755         case 'R':
1756         case 'r':
1757                 return resource_string(buf, end, ptr, spec, fmt);
1758         case 'h':
1759                 return hex_string(buf, end, ptr, spec, fmt);
1760         case 'b':
1761                 switch (fmt[1]) {
1762                 case 'l':
1763                         return bitmap_list_string(buf, end, ptr, spec, fmt);
1764                 default:
1765                         return bitmap_string(buf, end, ptr, spec, fmt);
1766                 }
1767         case 'M':                       /* Colon separated: 00:01:02:03:04:05 */
1768         case 'm':                       /* Contiguous: 000102030405 */
1769                                         /* [mM]F (FDDI) */
1770                                         /* [mM]R (Reverse order; Bluetooth) */
1771                 return mac_address_string(buf, end, ptr, spec, fmt);
1772         case 'I':                       /* Formatted IP supported
1773                                          * 4:   1.2.3.4
1774                                          * 6:   0001:0203:...:0708
1775                                          * 6c:  1::708 or 1::1.2.3.4
1776                                          */
1777         case 'i':                       /* Contiguous:
1778                                          * 4:   001.002.003.004
1779                                          * 6:   000102...0f
1780                                          */
1781                 switch (fmt[1]) {
1782                 case '6':
1783                         return ip6_addr_string(buf, end, ptr, spec, fmt);
1784                 case '4':
1785                         return ip4_addr_string(buf, end, ptr, spec, fmt);
1786                 case 'S': {
1787                         const union {
1788                                 struct sockaddr         raw;
1789                                 struct sockaddr_in      v4;
1790                                 struct sockaddr_in6     v6;
1791                         } *sa = ptr;
1792
1793                         switch (sa->raw.sa_family) {
1794                         case AF_INET:
1795                                 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1796                         case AF_INET6:
1797                                 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1798                         default:
1799                                 return string(buf, end, "(invalid address)", spec);
1800                         }}
1801                 }
1802                 break;
1803         case 'E':
1804                 return escaped_string(buf, end, ptr, spec, fmt);
1805         case 'U':
1806                 return uuid_string(buf, end, ptr, spec, fmt);
1807         case 'V':
1808                 {
1809                         va_list va;
1810
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);
1814                         va_end(va);
1815                         return buf;
1816                 }
1817         case 'K':
1818                 switch (kptr_restrict) {
1819                 case 0:
1820                         /* Always print %pK values */
1821                         break;
1822                 case 1: {
1823                         const struct cred *cred;
1824
1825                         /*
1826                          * kptr_restrict==1 cannot be used in IRQ context
1827                          * because its test for CAP_SYSLOG would be meaningless.
1828                          */
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);
1833                         }
1834
1835                         /*
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.
1843                          */
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))
1848                                 ptr = NULL;
1849                         break;
1850                 }
1851                 case 2:
1852                 default:
1853                         /* Always print 0's for %pK */
1854                         ptr = NULL;
1855                         break;
1856                 }
1857                 break;
1858
1859         case 'N':
1860                 return netdev_bits(buf, end, ptr, fmt);
1861         case 'a':
1862                 return address_val(buf, end, ptr, fmt);
1863         case 'd':
1864                 return dentry_name(buf, end, ptr, spec, fmt);
1865         case 'C':
1866                 return clock(buf, end, ptr, spec, fmt);
1867         case 'D':
1868                 return dentry_name(buf, end,
1869                                    ((const struct file *)ptr)->f_path.dentry,
1870                                    spec, fmt);
1871 #ifdef CONFIG_BLOCK
1872         case 'g':
1873                 return bdev_name(buf, end, ptr, spec, fmt);
1874 #endif
1875
1876         case 'G':
1877                 return flags_string(buf, end, ptr, fmt);
1878         case 'O':
1879                 switch (fmt[1]) {
1880                 case 'F':
1881                         return device_node_string(buf, end, ptr, spec, fmt + 1);
1882                 }
1883         }
1884         spec.flags |= SMALL;
1885         if (spec.field_width == -1) {
1886                 spec.field_width = default_width;
1887                 spec.flags |= ZEROPAD;
1888         }
1889         spec.base = 16;
1890
1891         return number(buf, end, (unsigned long) ptr, spec);
1892 }
1893
1894 /*
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
1900  *
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
1906  *
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, ...)
1914  */
1915 static noinline_for_stack
1916 int format_decode(const char *fmt, struct printf_spec *spec)
1917 {
1918         const char *start = fmt;
1919         char qualifier;
1920
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;
1926                 }
1927                 spec->type = FORMAT_TYPE_NONE;
1928                 goto precision;
1929         }
1930
1931         /* we finished early by reading the precision */
1932         if (spec->type == FORMAT_TYPE_PRECISION) {
1933                 if (spec->precision < 0)
1934                         spec->precision = 0;
1935
1936                 spec->type = FORMAT_TYPE_NONE;
1937                 goto qualifier;
1938         }
1939
1940         /* By default */
1941         spec->type = FORMAT_TYPE_NONE;
1942
1943         for (; *fmt ; ++fmt) {
1944                 if (*fmt == '%')
1945                         break;
1946         }
1947
1948         /* Return the current non-format string */
1949         if (fmt != start || !*fmt)
1950                 return fmt - start;
1951
1952         /* Process flags */
1953         spec->flags = 0;
1954
1955         while (1) { /* this also skips first '%' */
1956                 bool found = true;
1957
1958                 ++fmt;
1959
1960                 switch (*fmt) {
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;
1967                 }
1968
1969                 if (!found)
1970                         break;
1971         }
1972
1973         /* get field width */
1974         spec->field_width = -1;
1975
1976         if (isdigit(*fmt))
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;
1982         }
1983
1984 precision:
1985         /* get the precision */
1986         spec->precision = -1;
1987         if (*fmt == '.') {
1988                 ++fmt;
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;
1997                 }
1998         }
1999
2000 qualifier:
2001         /* get the conversion qualifier */
2002         qualifier = 0;
2003         if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2004             *fmt == 'z' || *fmt == 't') {
2005                 qualifier = *fmt++;
2006                 if (unlikely(qualifier == *fmt)) {
2007                         if (qualifier == 'l') {
2008                                 qualifier = 'L';
2009                                 ++fmt;
2010                         } else if (qualifier == 'h') {
2011                                 qualifier = 'H';
2012                                 ++fmt;
2013                         }
2014                 }
2015         }
2016
2017         /* default base */
2018         spec->base = 10;
2019         switch (*fmt) {
2020         case 'c':
2021                 spec->type = FORMAT_TYPE_CHAR;
2022                 return ++fmt - start;
2023
2024         case 's':
2025                 spec->type = FORMAT_TYPE_STR;
2026                 return ++fmt - start;
2027
2028         case 'p':
2029                 spec->type = FORMAT_TYPE_PTR;
2030                 return ++fmt - start;
2031
2032         case '%':
2033                 spec->type = FORMAT_TYPE_PERCENT_CHAR;
2034                 return ++fmt - start;
2035
2036         /* integer number formats - set up the flags and "break" */
2037         case 'o':
2038                 spec->base = 8;
2039                 break;
2040
2041         case 'x':
2042                 spec->flags |= SMALL;
2043
2044         case 'X':
2045                 spec->base = 16;
2046                 break;
2047
2048         case 'd':
2049         case 'i':
2050                 spec->flags |= SIGN;
2051         case 'u':
2052                 break;
2053
2054         case 'n':
2055                 /*
2056                  * Since %n poses a greater security risk than
2057                  * utility, treat it as any other invalid or
2058                  * unsupported format specifier.
2059                  */
2060                 /* Fall-through */
2061
2062         default:
2063                 WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt);
2064                 spec->type = FORMAT_TYPE_INVALID;
2065                 return fmt - start;
2066         }
2067
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);
2083         } else {
2084                 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
2085                 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
2086         }
2087
2088         return ++fmt - start;
2089 }
2090
2091 static void
2092 set_field_width(struct printf_spec *spec, int width)
2093 {
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);
2097         }
2098 }
2099
2100 static void
2101 set_precision(struct printf_spec *spec, int prec)
2102 {
2103         spec->precision = prec;
2104         if (WARN_ONCE(spec->precision != prec, "precision %d too large", prec)) {
2105                 spec->precision = clamp(prec, 0, PRECISION_MAX);
2106         }
2107 }
2108
2109 /**
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
2115  *
2116  * This function generally follows C99 vsnprintf, but has some
2117  * extensions and a few limitations:
2118  *
2119  *  - ``%n`` is unsupported
2120  *  - ``%p*`` is handled by pointer()
2121  *
2122  * See pointer() or Documentation/printk-formats.txt for more
2123  * extensive description.
2124  *
2125  * **Please update the documentation in both places when making changes**
2126  *
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.
2134  *
2135  * If you're not already dealing with a va_list consider using snprintf().
2136  */
2137 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
2138 {
2139         unsigned long long num;
2140         char *str, *end;
2141         struct printf_spec spec = {0};
2142
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))
2146                 return 0;
2147
2148         str = buf;
2149         end = buf + size;
2150
2151         /* Make sure end is always >= buf */
2152         if (end < buf) {
2153                 end = ((void *)-1);
2154                 size = end - buf;
2155         }
2156
2157         while (*fmt) {
2158                 const char *old_fmt = fmt;
2159                 int read = format_decode(fmt, &spec);
2160
2161                 fmt += read;
2162
2163                 switch (spec.type) {
2164                 case FORMAT_TYPE_NONE: {
2165                         int copy = read;
2166                         if (str < end) {
2167                                 if (copy > end - str)
2168                                         copy = end - str;
2169                                 memcpy(str, old_fmt, copy);
2170                         }
2171                         str += read;
2172                         break;
2173                 }
2174
2175                 case FORMAT_TYPE_WIDTH:
2176                         set_field_width(&spec, va_arg(args, int));
2177                         break;
2178
2179                 case FORMAT_TYPE_PRECISION:
2180                         set_precision(&spec, va_arg(args, int));
2181                         break;
2182
2183                 case FORMAT_TYPE_CHAR: {
2184                         char c;
2185
2186                         if (!(spec.flags & LEFT)) {
2187                                 while (--spec.field_width > 0) {
2188                                         if (str < end)
2189                                                 *str = ' ';
2190                                         ++str;
2191
2192                                 }
2193                         }
2194                         c = (unsigned char) va_arg(args, int);
2195                         if (str < end)
2196                                 *str = c;
2197                         ++str;
2198                         while (--spec.field_width > 0) {
2199                                 if (str < end)
2200                                         *str = ' ';
2201                                 ++str;
2202                         }
2203                         break;
2204                 }
2205
2206                 case FORMAT_TYPE_STR:
2207                         str = string(str, end, va_arg(args, char *), spec);
2208                         break;
2209
2210                 case FORMAT_TYPE_PTR:
2211                         str = pointer(fmt, str, end, va_arg(args, void *),
2212                                       spec);
2213                         while (isalnum(*fmt))
2214                                 fmt++;
2215                         break;
2216
2217                 case FORMAT_TYPE_PERCENT_CHAR:
2218                         if (str < end)
2219                                 *str = '%';
2220                         ++str;
2221                         break;
2222
2223                 case FORMAT_TYPE_INVALID:
2224                         /*
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
2230                          * sync.
2231                          */
2232                         goto out;
2233
2234                 default:
2235                         switch (spec.type) {
2236                         case FORMAT_TYPE_LONG_LONG:
2237                                 num = va_arg(args, long long);
2238                                 break;
2239                         case FORMAT_TYPE_ULONG:
2240                                 num = va_arg(args, unsigned long);
2241                                 break;
2242                         case FORMAT_TYPE_LONG:
2243                                 num = va_arg(args, long);
2244                                 break;
2245                         case FORMAT_TYPE_SIZE_T:
2246                                 if (spec.flags & SIGN)
2247                                         num = va_arg(args, ssize_t);
2248                                 else
2249                                         num = va_arg(args, size_t);
2250                                 break;
2251                         case FORMAT_TYPE_PTRDIFF:
2252                                 num = va_arg(args, ptrdiff_t);
2253                                 break;
2254                         case FORMAT_TYPE_UBYTE:
2255                                 num = (unsigned char) va_arg(args, int);
2256                                 break;
2257                         case FORMAT_TYPE_BYTE:
2258                                 num = (signed char) va_arg(args, int);
2259                                 break;
2260                         case FORMAT_TYPE_USHORT:
2261                                 num = (unsigned short) va_arg(args, int);
2262                                 break;
2263                         case FORMAT_TYPE_SHORT:
2264                                 num = (short) va_arg(args, int);
2265                                 break;
2266                         case FORMAT_TYPE_INT:
2267                                 num = (int) va_arg(args, int);
2268                                 break;
2269                         default:
2270                                 num = va_arg(args, unsigned int);
2271                         }
2272
2273                         str = number(str, end, num, spec);
2274                 }
2275         }
2276
2277 out:
2278         if (size > 0) {
2279                 if (str < end)
2280                         *str = '\0';
2281                 else
2282                         end[-1] = '\0';
2283         }
2284
2285         /* the trailing null byte doesn't count towards the total */
2286         return str-buf;
2287
2288 }
2289 EXPORT_SYMBOL(vsnprintf);
2290
2291 /**
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
2297  *
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
2300  * returns 0.
2301  *
2302  * If you're not already dealing with a va_list consider using scnprintf().
2303  *
2304  * See the vsnprintf() documentation for format string extensions over C99.
2305  */
2306 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2307 {
2308         int i;
2309
2310         i = vsnprintf(buf, size, fmt, args);
2311
2312         if (likely(i < size))
2313                 return i;
2314         if (size != 0)
2315                 return size - 1;
2316         return 0;
2317 }
2318 EXPORT_SYMBOL(vscnprintf);
2319
2320 /**
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
2326  *
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.
2331  *
2332  * See the vsnprintf() documentation for format string extensions over C99.
2333  */
2334 int snprintf(char *buf, size_t size, const char *fmt, ...)
2335 {
2336         va_list args;
2337         int i;
2338
2339         va_start(args, fmt);
2340         i = vsnprintf(buf, size, fmt, args);
2341         va_end(args);
2342
2343         return i;
2344 }
2345 EXPORT_SYMBOL(snprintf);
2346
2347 /**
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
2353  *
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.
2356  */
2357
2358 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2359 {
2360         va_list args;
2361         int i;
2362
2363         va_start(args, fmt);
2364         i = vscnprintf(buf, size, fmt, args);
2365         va_end(args);
2366
2367         return i;
2368 }
2369 EXPORT_SYMBOL(scnprintf);
2370
2371 /**
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
2376  *
2377  * The function returns the number of characters written
2378  * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2379  * buffer overflows.
2380  *
2381  * If you're not already dealing with a va_list consider using sprintf().
2382  *
2383  * See the vsnprintf() documentation for format string extensions over C99.
2384  */
2385 int vsprintf(char *buf, const char *fmt, va_list args)
2386 {
2387         return vsnprintf(buf, INT_MAX, fmt, args);
2388 }
2389 EXPORT_SYMBOL(vsprintf);
2390
2391 /**
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
2396  *
2397  * The function returns the number of characters written
2398  * into @buf. Use snprintf() or scnprintf() in order to avoid
2399  * buffer overflows.
2400  *
2401  * See the vsnprintf() documentation for format string extensions over C99.
2402  */
2403 int sprintf(char *buf, const char *fmt, ...)
2404 {
2405         va_list args;
2406         int i;
2407
2408         va_start(args, fmt);
2409         i = vsnprintf(buf, INT_MAX, fmt, args);
2410         va_end(args);
2411
2412         return i;
2413 }
2414 EXPORT_SYMBOL(sprintf);
2415
2416 #ifdef CONFIG_BINARY_PRINTF
2417 /*
2418  * bprintf service:
2419  * vbin_printf() - VA arguments to binary data
2420  * bstr_printf() - Binary data to text string
2421  */
2422
2423 /**
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
2429  *
2430  * The format follows C99 vsnprintf, except %n is ignored, and its argument
2431  * is skipped.
2432  *
2433  * The return value is the number of words(32bits) which would be generated for
2434  * the given input.
2435  *
2436  * NOTE:
2437  * If the return value is greater than @size, the resulting bin_buf is NOT
2438  * valid for bstr_printf().
2439  */
2440 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2441 {
2442         struct printf_spec spec = {0};
2443         char *str, *end;
2444
2445         str = (char *)bin_buf;
2446         end = (char *)(bin_buf + size);
2447
2448 #define save_arg(type)                                                  \
2449 do {                                                                    \
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);       \
2457                 }                                                       \
2458         } else {                                                        \
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;             \
2464         }                                                               \
2465         str += sizeof(type);                                            \
2466 } while (0)
2467
2468         while (*fmt) {
2469                 int read = format_decode(fmt, &spec);
2470
2471                 fmt += read;
2472
2473                 switch (spec.type) {
2474                 case FORMAT_TYPE_NONE:
2475                 case FORMAT_TYPE_PERCENT_CHAR:
2476                         break;
2477                 case FORMAT_TYPE_INVALID:
2478                         goto out;
2479
2480                 case FORMAT_TYPE_WIDTH:
2481                 case FORMAT_TYPE_PRECISION:
2482                         save_arg(int);
2483                         break;
2484
2485                 case FORMAT_TYPE_CHAR:
2486                         save_arg(char);
2487                         break;
2488
2489                 case FORMAT_TYPE_STR: {
2490                         const char *save_str = va_arg(args, char *);
2491                         size_t len;
2492
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);
2499                         str += len;
2500                         break;
2501                 }
2502
2503                 case FORMAT_TYPE_PTR:
2504                         save_arg(void *);
2505                         /* skip all alphanumeric pointer suffixes */
2506                         while (isalnum(*fmt))
2507                                 fmt++;
2508                         break;
2509
2510                 default:
2511                         switch (spec.type) {
2512
2513                         case FORMAT_TYPE_LONG_LONG:
2514                                 save_arg(long long);
2515                                 break;
2516                         case FORMAT_TYPE_ULONG:
2517                         case FORMAT_TYPE_LONG:
2518                                 save_arg(unsigned long);
2519                                 break;
2520                         case FORMAT_TYPE_SIZE_T:
2521                                 save_arg(size_t);
2522                                 break;
2523                         case FORMAT_TYPE_PTRDIFF:
2524                                 save_arg(ptrdiff_t);
2525                                 break;
2526                         case FORMAT_TYPE_UBYTE:
2527                         case FORMAT_TYPE_BYTE:
2528                                 save_arg(char);
2529                                 break;
2530                         case FORMAT_TYPE_USHORT:
2531                         case FORMAT_TYPE_SHORT:
2532                                 save_arg(short);
2533                                 break;
2534                         default:
2535                                 save_arg(int);
2536                         }
2537                 }
2538         }
2539
2540 out:
2541         return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2542 #undef save_arg
2543 }
2544 EXPORT_SYMBOL_GPL(vbin_printf);
2545
2546 /**
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
2552  *
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.
2556  *
2557  * The format follows C99 vsnprintf, but has some extensions:
2558  *  see vsnprintf comment for details.
2559  *
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.
2567  */
2568 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2569 {
2570         struct printf_spec spec = {0};
2571         char *str, *end;
2572         const char *args = (const char *)bin_buf;
2573
2574         if (WARN_ON_ONCE(size > INT_MAX))
2575                 return 0;
2576
2577         str = buf;
2578         end = buf + size;
2579
2580 #define get_arg(type)                                                   \
2581 ({                                                                      \
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);              \
2587         } else {                                                        \
2588                 args = PTR_ALIGN(args, sizeof(type));                   \
2589                 value = *(typeof(type) *)args;                          \
2590         }                                                               \
2591         args += sizeof(type);                                           \
2592         value;                                                          \
2593 })
2594
2595         /* Make sure end is always >= buf */
2596         if (end < buf) {
2597                 end = ((void *)-1);
2598                 size = end - buf;
2599         }
2600
2601         while (*fmt) {
2602                 const char *old_fmt = fmt;
2603                 int read = format_decode(fmt, &spec);
2604
2605                 fmt += read;
2606
2607                 switch (spec.type) {
2608                 case FORMAT_TYPE_NONE: {
2609                         int copy = read;
2610                         if (str < end) {
2611                                 if (copy > end - str)
2612                                         copy = end - str;
2613                                 memcpy(str, old_fmt, copy);
2614                         }
2615                         str += read;
2616                         break;
2617                 }
2618
2619                 case FORMAT_TYPE_WIDTH:
2620                         set_field_width(&spec, get_arg(int));
2621                         break;
2622
2623                 case FORMAT_TYPE_PRECISION:
2624                         set_precision(&spec, get_arg(int));
2625                         break;
2626
2627                 case FORMAT_TYPE_CHAR: {
2628                         char c;
2629
2630                         if (!(spec.flags & LEFT)) {
2631                                 while (--spec.field_width > 0) {
2632                                         if (str < end)
2633                                                 *str = ' ';
2634                                         ++str;
2635                                 }
2636                         }
2637                         c = (unsigned char) get_arg(char);
2638                         if (str < end)
2639                                 *str = c;
2640                         ++str;
2641                         while (--spec.field_width > 0) {
2642                                 if (str < end)
2643                                         *str = ' ';
2644                                 ++str;
2645                         }
2646                         break;
2647                 }
2648
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);
2653                         break;
2654                 }
2655
2656                 case FORMAT_TYPE_PTR:
2657                         str = pointer(fmt, str, end, get_arg(void *), spec);
2658                         while (isalnum(*fmt))
2659                                 fmt++;
2660                         break;
2661
2662                 case FORMAT_TYPE_PERCENT_CHAR:
2663                         if (str < end)
2664                                 *str = '%';
2665                         ++str;
2666                         break;
2667
2668                 case FORMAT_TYPE_INVALID:
2669                         goto out;
2670
2671                 default: {
2672                         unsigned long long num;
2673
2674                         switch (spec.type) {
2675
2676                         case FORMAT_TYPE_LONG_LONG:
2677                                 num = get_arg(long long);
2678                                 break;
2679                         case FORMAT_TYPE_ULONG:
2680                         case FORMAT_TYPE_LONG:
2681                                 num = get_arg(unsigned long);
2682                                 break;
2683                         case FORMAT_TYPE_SIZE_T:
2684                                 num = get_arg(size_t);
2685                                 break;
2686                         case FORMAT_TYPE_PTRDIFF:
2687                                 num = get_arg(ptrdiff_t);
2688                                 break;
2689                         case FORMAT_TYPE_UBYTE:
2690                                 num = get_arg(unsigned char);
2691                                 break;
2692                         case FORMAT_TYPE_BYTE:
2693                                 num = get_arg(signed char);
2694                                 break;
2695                         case FORMAT_TYPE_USHORT:
2696                                 num = get_arg(unsigned short);
2697                                 break;
2698                         case FORMAT_TYPE_SHORT:
2699                                 num = get_arg(short);
2700                                 break;
2701                         case FORMAT_TYPE_UINT:
2702                                 num = get_arg(unsigned int);
2703                                 break;
2704                         default:
2705                                 num = get_arg(int);
2706                         }
2707
2708                         str = number(str, end, num, spec);
2709                 } /* default: */
2710                 } /* switch(spec.type) */
2711         } /* while(*fmt) */
2712
2713 out:
2714         if (size > 0) {
2715                 if (str < end)
2716                         *str = '\0';
2717                 else
2718                         end[-1] = '\0';
2719         }
2720
2721 #undef get_arg
2722
2723         /* the trailing null byte doesn't count towards the total */
2724         return str - buf;
2725 }
2726 EXPORT_SYMBOL_GPL(bstr_printf);
2727
2728 /**
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
2734  *
2735  * The function returns the number of words(u32) written
2736  * into @bin_buf.
2737  */
2738 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
2739 {
2740         va_list args;
2741         int ret;
2742
2743         va_start(args, fmt);
2744         ret = vbin_printf(bin_buf, size, fmt, args);
2745         va_end(args);
2746
2747         return ret;
2748 }
2749 EXPORT_SYMBOL_GPL(bprintf);
2750
2751 #endif /* CONFIG_BINARY_PRINTF */
2752
2753 /**
2754  * vsscanf - Unformat a buffer into a list of arguments
2755  * @buf:        input buffer
2756  * @fmt:        format of buffer
2757  * @args:       arguments
2758  */
2759 int vsscanf(const char *buf, const char *fmt, va_list args)
2760 {
2761         const char *str = buf;
2762         char *next;
2763         char digit;
2764         int num = 0;
2765         u8 qualifier;
2766         unsigned int base;
2767         union {
2768                 long long s;
2769                 unsigned long long u;
2770         } val;
2771         s16 field_width;
2772         bool is_sign;
2773
2774         while (*fmt) {
2775                 /* skip any white space in format */
2776                 /* white space in format matchs any amount of
2777                  * white space, including none, in the input.
2778                  */
2779                 if (isspace(*fmt)) {
2780                         fmt = skip_spaces(++fmt);
2781                         str = skip_spaces(str);
2782                 }
2783
2784                 /* anything that is not a conversion must match exactly */
2785                 if (*fmt != '%' && *fmt) {
2786                         if (*fmt++ != *str++)
2787                                 break;
2788                         continue;
2789                 }
2790
2791                 if (!*fmt)
2792                         break;
2793                 ++fmt;
2794
2795                 /* skip this conversion.
2796                  * advance both strings to next white space
2797                  */
2798                 if (*fmt == '*') {
2799                         if (!*str)
2800                                 break;
2801                         while (!isspace(*fmt) && *fmt != '%' && *fmt) {
2802                                 /* '%*[' not yet supported, invalid format */
2803                                 if (*fmt == '[')
2804                                         return num;
2805                                 fmt++;
2806                         }
2807                         while (!isspace(*str) && *str)
2808                                 str++;
2809                         continue;
2810                 }
2811
2812                 /* get field width */
2813                 field_width = -1;
2814                 if (isdigit(*fmt)) {
2815                         field_width = skip_atoi(&fmt);
2816                         if (field_width <= 0)
2817                                 break;
2818                 }
2819
2820                 /* get conversion qualifier */
2821                 qualifier = -1;
2822                 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2823                     *fmt == 'z') {
2824                         qualifier = *fmt++;
2825                         if (unlikely(qualifier == *fmt)) {
2826                                 if (qualifier == 'h') {
2827                                         qualifier = 'H';
2828                                         fmt++;
2829                                 } else if (qualifier == 'l') {
2830                                         qualifier = 'L';
2831                                         fmt++;
2832                                 }
2833                         }
2834                 }
2835
2836                 if (!*fmt)
2837                         break;
2838
2839                 if (*fmt == 'n') {
2840                         /* return number of characters read so far */
2841                         *va_arg(args, int *) = str - buf;
2842                         ++fmt;
2843                         continue;
2844                 }
2845
2846                 if (!*str)
2847                         break;
2848
2849                 base = 10;
2850                 is_sign = false;
2851
2852                 switch (*fmt++) {
2853                 case 'c':
2854                 {
2855                         char *s = (char *)va_arg(args, char*);
2856                         if (field_width == -1)
2857                                 field_width = 1;
2858                         do {
2859                                 *s++ = *str++;
2860                         } while (--field_width > 0 && *str);
2861                         num++;
2862                 }
2863                 continue;
2864                 case 's':
2865                 {
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);
2871
2872                         /* now copy until next white space */
2873                         while (*str && !isspace(*str) && field_width--)
2874                                 *s++ = *str++;
2875                         *s = '\0';
2876                         num++;
2877                 }
2878                 continue;
2879                 /*
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
2883                  *     character
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
2887                  *
2888                  * Example usage:
2889                  * ret = sscanf("00:0a:95","%2[^:]:%2[^:]:%2[^:]",
2890                  *              buf1, buf2, buf3);
2891                  * if (ret < 3)
2892                  *    // etc..
2893                  */
2894                 case '[':
2895                 {
2896                         char *s = (char *)va_arg(args, char *);
2897                         DECLARE_BITMAP(set, 256) = {0};
2898                         unsigned int len = 0;
2899                         bool negate = (*fmt == '^');
2900
2901                         /* field width is required */
2902                         if (field_width == -1)
2903                                 return num;
2904
2905                         if (negate)
2906                                 ++fmt;
2907
2908                         for ( ; *fmt && *fmt != ']'; ++fmt, ++len)
2909                                 set_bit((u8)*fmt, set);
2910
2911                         /* no ']' or no character set found */
2912                         if (!*fmt || !len)
2913                                 return num;
2914                         ++fmt;
2915
2916                         if (negate) {
2917                                 bitmap_complement(set, set, 256);
2918                                 /* exclude null '\0' byte */
2919                                 clear_bit(0, set);
2920                         }
2921
2922                         /* match must be non-empty */
2923                         if (!test_bit((u8)*str, set))
2924                                 return num;
2925
2926                         while (test_bit((u8)*str, set) && field_width--)
2927                                 *s++ = *str++;
2928                         *s = '\0';
2929                         ++num;
2930                 }
2931                 continue;
2932                 case 'o':
2933                         base = 8;
2934                         break;
2935                 case 'x':
2936                 case 'X':
2937                         base = 16;
2938                         break;
2939                 case 'i':
2940                         base = 0;
2941                 case 'd':
2942                         is_sign = true;
2943                 case 'u':
2944                         break;
2945                 case '%':
2946                         /* looking for '%' in str */
2947                         if (*str++ != '%')
2948                                 return num;
2949                         continue;
2950                 default:
2951                         /* invalid format; stop here */
2952                         return num;
2953                 }
2954
2955                 /* have some sort of integer conversion.
2956                  * first, skip white space in buffer.
2957                  */
2958                 str = skip_spaces(str);
2959
2960                 digit = *str;
2961                 if (is_sign && digit == '-')
2962                         digit = *(str + 1);
2963
2964                 if (!digit
2965                     || (base == 16 && !isxdigit(digit))
2966                     || (base == 10 && !isdigit(digit))
2967                     || (base == 8 && (!isdigit(digit) || digit > '7'))
2968                     || (base == 0 && !isdigit(digit)))
2969                         break;
2970
2971                 if (is_sign)
2972                         val.s = simple_strntoll(str,
2973                                                 field_width >= 0 ? field_width : INT_MAX,
2974                                                 &next, base);
2975                 else
2976                         val.u = simple_strntoull(str,
2977                                                  field_width >= 0 ? field_width : INT_MAX,
2978                                                  &next, base);
2979
2980                 switch (qualifier) {
2981                 case 'H':       /* that's 'hh' in format */
2982                         if (is_sign)
2983                                 *va_arg(args, signed char *) = val.s;
2984                         else
2985                                 *va_arg(args, unsigned char *) = val.u;
2986                         break;
2987                 case 'h':
2988                         if (is_sign)
2989                                 *va_arg(args, short *) = val.s;
2990                         else
2991                                 *va_arg(args, unsigned short *) = val.u;
2992                         break;
2993                 case 'l':
2994                         if (is_sign)
2995                                 *va_arg(args, long *) = val.s;
2996                         else
2997                                 *va_arg(args, unsigned long *) = val.u;
2998                         break;
2999                 case 'L':
3000                         if (is_sign)
3001                                 *va_arg(args, long long *) = val.s;
3002                         else
3003                                 *va_arg(args, unsigned long long *) = val.u;
3004                         break;
3005                 case 'z':
3006                         *va_arg(args, size_t *) = val.u;
3007                         break;
3008                 default:
3009                         if (is_sign)
3010                                 *va_arg(args, int *) = val.s;
3011                         else
3012                                 *va_arg(args, unsigned int *) = val.u;
3013                         break;
3014                 }
3015                 num++;
3016
3017                 if (!next)
3018                         break;
3019                 str = next;
3020         }
3021
3022         return num;
3023 }
3024 EXPORT_SYMBOL(vsscanf);
3025
3026 /**
3027  * sscanf - Unformat a buffer into a list of arguments
3028  * @buf:        input buffer
3029  * @fmt:        formatting of buffer
3030  * @...:        resulting arguments
3031  */
3032 int sscanf(const char *buf, const char *fmt, ...)
3033 {
3034         va_list args;
3035         int i;
3036
3037         va_start(args, fmt);
3038         i = vsscanf(buf, fmt, args);
3039         va_end(args);
3040
3041         return i;
3042 }
3043 EXPORT_SYMBOL(sscanf);