vsprintf: Consolidate handling of unknown pointer specifiers
[linux-2.6-microblaze.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/build_bug.h>
21 #include <linux/clk.h>
22 #include <linux/clk-provider.h>
23 #include <linux/module.h>       /* for KSYM_SYMBOL_LEN */
24 #include <linux/types.h>
25 #include <linux/string.h>
26 #include <linux/ctype.h>
27 #include <linux/kernel.h>
28 #include <linux/kallsyms.h>
29 #include <linux/math64.h>
30 #include <linux/uaccess.h>
31 #include <linux/ioport.h>
32 #include <linux/dcache.h>
33 #include <linux/cred.h>
34 #include <linux/rtc.h>
35 #include <linux/uuid.h>
36 #include <linux/of.h>
37 #include <net/addrconf.h>
38 #include <linux/siphash.h>
39 #include <linux/compiler.h>
40 #ifdef CONFIG_BLOCK
41 #include <linux/blkdev.h>
42 #endif
43
44 #include "../mm/internal.h"     /* For the trace_print_flags arrays */
45
46 #include <asm/page.h>           /* for PAGE_SIZE */
47 #include <asm/byteorder.h>      /* cpu_to_le16 */
48
49 #include <linux/string_helpers.h>
50 #include "kstrtox.h"
51
52 /**
53  * simple_strtoull - convert a string to an unsigned long long
54  * @cp: The start of the string
55  * @endp: A pointer to the end of the parsed string will be placed here
56  * @base: The number base to use
57  *
58  * This function is obsolete. Please use kstrtoull instead.
59  */
60 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
61 {
62         unsigned long long result;
63         unsigned int rv;
64
65         cp = _parse_integer_fixup_radix(cp, &base);
66         rv = _parse_integer(cp, base, &result);
67         /* FIXME */
68         cp += (rv & ~KSTRTOX_OVERFLOW);
69
70         if (endp)
71                 *endp = (char *)cp;
72
73         return result;
74 }
75 EXPORT_SYMBOL(simple_strtoull);
76
77 /**
78  * simple_strtoul - convert a string to an unsigned long
79  * @cp: The start of the string
80  * @endp: A pointer to the end of the parsed string will be placed here
81  * @base: The number base to use
82  *
83  * This function is obsolete. Please use kstrtoul instead.
84  */
85 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
86 {
87         return simple_strtoull(cp, endp, base);
88 }
89 EXPORT_SYMBOL(simple_strtoul);
90
91 /**
92  * simple_strtol - convert a string to a signed long
93  * @cp: The start of the string
94  * @endp: A pointer to the end of the parsed string will be placed here
95  * @base: The number base to use
96  *
97  * This function is obsolete. Please use kstrtol instead.
98  */
99 long simple_strtol(const char *cp, char **endp, unsigned int base)
100 {
101         if (*cp == '-')
102                 return -simple_strtoul(cp + 1, endp, base);
103
104         return simple_strtoul(cp, endp, base);
105 }
106 EXPORT_SYMBOL(simple_strtol);
107
108 /**
109  * simple_strtoll - convert a string to a signed long long
110  * @cp: The start of the string
111  * @endp: A pointer to the end of the parsed string will be placed here
112  * @base: The number base to use
113  *
114  * This function is obsolete. Please use kstrtoll instead.
115  */
116 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
117 {
118         if (*cp == '-')
119                 return -simple_strtoull(cp + 1, endp, base);
120
121         return simple_strtoull(cp, endp, base);
122 }
123 EXPORT_SYMBOL(simple_strtoll);
124
125 static noinline_for_stack
126 int skip_atoi(const char **s)
127 {
128         int i = 0;
129
130         do {
131                 i = i*10 + *((*s)++) - '0';
132         } while (isdigit(**s));
133
134         return i;
135 }
136
137 /*
138  * Decimal conversion is by far the most typical, and is used for
139  * /proc and /sys data. This directly impacts e.g. top performance
140  * with many processes running. We optimize it for speed by emitting
141  * two characters at a time, using a 200 byte lookup table. This
142  * roughly halves the number of multiplications compared to computing
143  * the digits one at a time. Implementation strongly inspired by the
144  * previous version, which in turn used ideas described at
145  * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
146  * from the author, Douglas W. Jones).
147  *
148  * It turns out there is precisely one 26 bit fixed-point
149  * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
150  * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
151  * range happens to be somewhat larger (x <= 1073741898), but that's
152  * irrelevant for our purpose.
153  *
154  * For dividing a number in the range [10^4, 10^6-1] by 100, we still
155  * need a 32x32->64 bit multiply, so we simply use the same constant.
156  *
157  * For dividing a number in the range [100, 10^4-1] by 100, there are
158  * several options. The simplest is (x * 0x147b) >> 19, which is valid
159  * for all x <= 43698.
160  */
161
162 static const u16 decpair[100] = {
163 #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
164         _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
165         _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
166         _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
167         _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
168         _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
169         _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
170         _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
171         _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
172         _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
173         _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
174 #undef _
175 };
176
177 /*
178  * This will print a single '0' even if r == 0, since we would
179  * immediately jump to out_r where two 0s would be written but only
180  * one of them accounted for in buf. This is needed by ip4_string
181  * below. All other callers pass a non-zero value of r.
182 */
183 static noinline_for_stack
184 char *put_dec_trunc8(char *buf, unsigned r)
185 {
186         unsigned q;
187
188         /* 1 <= r < 10^8 */
189         if (r < 100)
190                 goto out_r;
191
192         /* 100 <= r < 10^8 */
193         q = (r * (u64)0x28f5c29) >> 32;
194         *((u16 *)buf) = decpair[r - 100*q];
195         buf += 2;
196
197         /* 1 <= q < 10^6 */
198         if (q < 100)
199                 goto out_q;
200
201         /*  100 <= q < 10^6 */
202         r = (q * (u64)0x28f5c29) >> 32;
203         *((u16 *)buf) = decpair[q - 100*r];
204         buf += 2;
205
206         /* 1 <= r < 10^4 */
207         if (r < 100)
208                 goto out_r;
209
210         /* 100 <= r < 10^4 */
211         q = (r * 0x147b) >> 19;
212         *((u16 *)buf) = decpair[r - 100*q];
213         buf += 2;
214 out_q:
215         /* 1 <= q < 100 */
216         r = q;
217 out_r:
218         /* 1 <= r < 100 */
219         *((u16 *)buf) = decpair[r];
220         buf += r < 10 ? 1 : 2;
221         return buf;
222 }
223
224 #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
225 static noinline_for_stack
226 char *put_dec_full8(char *buf, unsigned r)
227 {
228         unsigned q;
229
230         /* 0 <= r < 10^8 */
231         q = (r * (u64)0x28f5c29) >> 32;
232         *((u16 *)buf) = decpair[r - 100*q];
233         buf += 2;
234
235         /* 0 <= q < 10^6 */
236         r = (q * (u64)0x28f5c29) >> 32;
237         *((u16 *)buf) = decpair[q - 100*r];
238         buf += 2;
239
240         /* 0 <= r < 10^4 */
241         q = (r * 0x147b) >> 19;
242         *((u16 *)buf) = decpair[r - 100*q];
243         buf += 2;
244
245         /* 0 <= q < 100 */
246         *((u16 *)buf) = decpair[q];
247         buf += 2;
248         return buf;
249 }
250
251 static noinline_for_stack
252 char *put_dec(char *buf, unsigned long long n)
253 {
254         if (n >= 100*1000*1000)
255                 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
256         /* 1 <= n <= 1.6e11 */
257         if (n >= 100*1000*1000)
258                 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
259         /* 1 <= n < 1e8 */
260         return put_dec_trunc8(buf, n);
261 }
262
263 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
264
265 static void
266 put_dec_full4(char *buf, unsigned r)
267 {
268         unsigned q;
269
270         /* 0 <= r < 10^4 */
271         q = (r * 0x147b) >> 19;
272         *((u16 *)buf) = decpair[r - 100*q];
273         buf += 2;
274         /* 0 <= q < 100 */
275         *((u16 *)buf) = decpair[q];
276 }
277
278 /*
279  * Call put_dec_full4 on x % 10000, return x / 10000.
280  * The approximation x/10000 == (x * 0x346DC5D7) >> 43
281  * holds for all x < 1,128,869,999.  The largest value this
282  * helper will ever be asked to convert is 1,125,520,955.
283  * (second call in the put_dec code, assuming n is all-ones).
284  */
285 static noinline_for_stack
286 unsigned put_dec_helper4(char *buf, unsigned x)
287 {
288         uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
289
290         put_dec_full4(buf, x - q * 10000);
291         return q;
292 }
293
294 /* Based on code by Douglas W. Jones found at
295  * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
296  * (with permission from the author).
297  * Performs no 64-bit division and hence should be fast on 32-bit machines.
298  */
299 static
300 char *put_dec(char *buf, unsigned long long n)
301 {
302         uint32_t d3, d2, d1, q, h;
303
304         if (n < 100*1000*1000)
305                 return put_dec_trunc8(buf, n);
306
307         d1  = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
308         h   = (n >> 32);
309         d2  = (h      ) & 0xffff;
310         d3  = (h >> 16); /* implicit "& 0xffff" */
311
312         /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
313              = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
314         q   = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
315         q = put_dec_helper4(buf, q);
316
317         q += 7671 * d3 + 9496 * d2 + 6 * d1;
318         q = put_dec_helper4(buf+4, q);
319
320         q += 4749 * d3 + 42 * d2;
321         q = put_dec_helper4(buf+8, q);
322
323         q += 281 * d3;
324         buf += 12;
325         if (q)
326                 buf = put_dec_trunc8(buf, q);
327         else while (buf[-1] == '0')
328                 --buf;
329
330         return buf;
331 }
332
333 #endif
334
335 /*
336  * Convert passed number to decimal string.
337  * Returns the length of string.  On buffer overflow, returns 0.
338  *
339  * If speed is not important, use snprintf(). It's easy to read the code.
340  */
341 int num_to_str(char *buf, int size, unsigned long long num, unsigned int width)
342 {
343         /* put_dec requires 2-byte alignment of the buffer. */
344         char tmp[sizeof(num) * 3] __aligned(2);
345         int idx, len;
346
347         /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
348         if (num <= 9) {
349                 tmp[0] = '0' + num;
350                 len = 1;
351         } else {
352                 len = put_dec(tmp, num) - tmp;
353         }
354
355         if (len > size || width > size)
356                 return 0;
357
358         if (width > len) {
359                 width = width - len;
360                 for (idx = 0; idx < width; idx++)
361                         buf[idx] = ' ';
362         } else {
363                 width = 0;
364         }
365
366         for (idx = 0; idx < len; ++idx)
367                 buf[idx + width] = tmp[len - idx - 1];
368
369         return len + width;
370 }
371
372 #define SIGN    1               /* unsigned/signed, must be 1 */
373 #define LEFT    2               /* left justified */
374 #define PLUS    4               /* show plus */
375 #define SPACE   8               /* space if plus */
376 #define ZEROPAD 16              /* pad with zero, must be 16 == '0' - ' ' */
377 #define SMALL   32              /* use lowercase in hex (must be 32 == 0x20) */
378 #define SPECIAL 64              /* prefix hex with "0x", octal with "0" */
379
380 enum format_type {
381         FORMAT_TYPE_NONE, /* Just a string part */
382         FORMAT_TYPE_WIDTH,
383         FORMAT_TYPE_PRECISION,
384         FORMAT_TYPE_CHAR,
385         FORMAT_TYPE_STR,
386         FORMAT_TYPE_PTR,
387         FORMAT_TYPE_PERCENT_CHAR,
388         FORMAT_TYPE_INVALID,
389         FORMAT_TYPE_LONG_LONG,
390         FORMAT_TYPE_ULONG,
391         FORMAT_TYPE_LONG,
392         FORMAT_TYPE_UBYTE,
393         FORMAT_TYPE_BYTE,
394         FORMAT_TYPE_USHORT,
395         FORMAT_TYPE_SHORT,
396         FORMAT_TYPE_UINT,
397         FORMAT_TYPE_INT,
398         FORMAT_TYPE_SIZE_T,
399         FORMAT_TYPE_PTRDIFF
400 };
401
402 struct printf_spec {
403         unsigned int    type:8;         /* format_type enum */
404         signed int      field_width:24; /* width of output field */
405         unsigned int    flags:8;        /* flags to number() */
406         unsigned int    base:8;         /* number base, 8, 10 or 16 only */
407         signed int      precision:16;   /* # of digits/chars */
408 } __packed;
409 static_assert(sizeof(struct printf_spec) == 8);
410
411 #define FIELD_WIDTH_MAX ((1 << 23) - 1)
412 #define PRECISION_MAX ((1 << 15) - 1)
413
414 static noinline_for_stack
415 char *number(char *buf, char *end, unsigned long long num,
416              struct printf_spec spec)
417 {
418         /* put_dec requires 2-byte alignment of the buffer. */
419         char tmp[3 * sizeof(num)] __aligned(2);
420         char sign;
421         char locase;
422         int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
423         int i;
424         bool is_zero = num == 0LL;
425         int field_width = spec.field_width;
426         int precision = spec.precision;
427
428         /* locase = 0 or 0x20. ORing digits or letters with 'locase'
429          * produces same digits or (maybe lowercased) letters */
430         locase = (spec.flags & SMALL);
431         if (spec.flags & LEFT)
432                 spec.flags &= ~ZEROPAD;
433         sign = 0;
434         if (spec.flags & SIGN) {
435                 if ((signed long long)num < 0) {
436                         sign = '-';
437                         num = -(signed long long)num;
438                         field_width--;
439                 } else if (spec.flags & PLUS) {
440                         sign = '+';
441                         field_width--;
442                 } else if (spec.flags & SPACE) {
443                         sign = ' ';
444                         field_width--;
445                 }
446         }
447         if (need_pfx) {
448                 if (spec.base == 16)
449                         field_width -= 2;
450                 else if (!is_zero)
451                         field_width--;
452         }
453
454         /* generate full string in tmp[], in reverse order */
455         i = 0;
456         if (num < spec.base)
457                 tmp[i++] = hex_asc_upper[num] | locase;
458         else if (spec.base != 10) { /* 8 or 16 */
459                 int mask = spec.base - 1;
460                 int shift = 3;
461
462                 if (spec.base == 16)
463                         shift = 4;
464                 do {
465                         tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
466                         num >>= shift;
467                 } while (num);
468         } else { /* base 10 */
469                 i = put_dec(tmp, num) - tmp;
470         }
471
472         /* printing 100 using %2d gives "100", not "00" */
473         if (i > precision)
474                 precision = i;
475         /* leading space padding */
476         field_width -= precision;
477         if (!(spec.flags & (ZEROPAD | LEFT))) {
478                 while (--field_width >= 0) {
479                         if (buf < end)
480                                 *buf = ' ';
481                         ++buf;
482                 }
483         }
484         /* sign */
485         if (sign) {
486                 if (buf < end)
487                         *buf = sign;
488                 ++buf;
489         }
490         /* "0x" / "0" prefix */
491         if (need_pfx) {
492                 if (spec.base == 16 || !is_zero) {
493                         if (buf < end)
494                                 *buf = '0';
495                         ++buf;
496                 }
497                 if (spec.base == 16) {
498                         if (buf < end)
499                                 *buf = ('X' | locase);
500                         ++buf;
501                 }
502         }
503         /* zero or space padding */
504         if (!(spec.flags & LEFT)) {
505                 char c = ' ' + (spec.flags & ZEROPAD);
506                 BUILD_BUG_ON(' ' + ZEROPAD != '0');
507                 while (--field_width >= 0) {
508                         if (buf < end)
509                                 *buf = c;
510                         ++buf;
511                 }
512         }
513         /* hmm even more zero padding? */
514         while (i <= --precision) {
515                 if (buf < end)
516                         *buf = '0';
517                 ++buf;
518         }
519         /* actual digits of result */
520         while (--i >= 0) {
521                 if (buf < end)
522                         *buf = tmp[i];
523                 ++buf;
524         }
525         /* trailing space padding */
526         while (--field_width >= 0) {
527                 if (buf < end)
528                         *buf = ' ';
529                 ++buf;
530         }
531
532         return buf;
533 }
534
535 static noinline_for_stack
536 char *special_hex_number(char *buf, char *end, unsigned long long num, int size)
537 {
538         struct printf_spec spec;
539
540         spec.type = FORMAT_TYPE_PTR;
541         spec.field_width = 2 + 2 * size;        /* 0x + hex */
542         spec.flags = SPECIAL | SMALL | ZEROPAD;
543         spec.base = 16;
544         spec.precision = -1;
545
546         return number(buf, end, num, spec);
547 }
548
549 static void move_right(char *buf, char *end, unsigned len, unsigned spaces)
550 {
551         size_t size;
552         if (buf >= end) /* nowhere to put anything */
553                 return;
554         size = end - buf;
555         if (size <= spaces) {
556                 memset(buf, ' ', size);
557                 return;
558         }
559         if (len) {
560                 if (len > size - spaces)
561                         len = size - spaces;
562                 memmove(buf + spaces, buf, len);
563         }
564         memset(buf, ' ', spaces);
565 }
566
567 /*
568  * Handle field width padding for a string.
569  * @buf: current buffer position
570  * @n: length of string
571  * @end: end of output buffer
572  * @spec: for field width and flags
573  * Returns: new buffer position after padding.
574  */
575 static noinline_for_stack
576 char *widen_string(char *buf, int n, char *end, struct printf_spec spec)
577 {
578         unsigned spaces;
579
580         if (likely(n >= spec.field_width))
581                 return buf;
582         /* we want to pad the sucker */
583         spaces = spec.field_width - n;
584         if (!(spec.flags & LEFT)) {
585                 move_right(buf - n, end, n, spaces);
586                 return buf + spaces;
587         }
588         while (spaces--) {
589                 if (buf < end)
590                         *buf = ' ';
591                 ++buf;
592         }
593         return buf;
594 }
595
596 /* Handle string from a well known address. */
597 static char *string_nocheck(char *buf, char *end, const char *s,
598                             struct printf_spec spec)
599 {
600         int len = 0;
601         size_t lim = spec.precision;
602
603         while (lim--) {
604                 char c = *s++;
605                 if (!c)
606                         break;
607                 if (buf < end)
608                         *buf = c;
609                 ++buf;
610                 ++len;
611         }
612         return widen_string(buf, len, end, spec);
613 }
614
615 static noinline_for_stack
616 char *string(char *buf, char *end, const char *s,
617              struct printf_spec spec)
618 {
619         if ((unsigned long)s < PAGE_SIZE)
620                 s = "(null)";
621
622         return string_nocheck(buf, end, s, spec);
623 }
624
625 char *pointer_string(char *buf, char *end, const void *ptr,
626                      struct printf_spec spec)
627 {
628         spec.base = 16;
629         spec.flags |= SMALL;
630         if (spec.field_width == -1) {
631                 spec.field_width = 2 * sizeof(ptr);
632                 spec.flags |= ZEROPAD;
633         }
634
635         return number(buf, end, (unsigned long int)ptr, spec);
636 }
637
638 /* Make pointers available for printing early in the boot sequence. */
639 static int debug_boot_weak_hash __ro_after_init;
640
641 static int __init debug_boot_weak_hash_enable(char *str)
642 {
643         debug_boot_weak_hash = 1;
644         pr_info("debug_boot_weak_hash enabled\n");
645         return 0;
646 }
647 early_param("debug_boot_weak_hash", debug_boot_weak_hash_enable);
648
649 static DEFINE_STATIC_KEY_TRUE(not_filled_random_ptr_key);
650 static siphash_key_t ptr_key __read_mostly;
651
652 static void enable_ptr_key_workfn(struct work_struct *work)
653 {
654         get_random_bytes(&ptr_key, sizeof(ptr_key));
655         /* Needs to run from preemptible context */
656         static_branch_disable(&not_filled_random_ptr_key);
657 }
658
659 static DECLARE_WORK(enable_ptr_key_work, enable_ptr_key_workfn);
660
661 static void fill_random_ptr_key(struct random_ready_callback *unused)
662 {
663         /* This may be in an interrupt handler. */
664         queue_work(system_unbound_wq, &enable_ptr_key_work);
665 }
666
667 static struct random_ready_callback random_ready = {
668         .func = fill_random_ptr_key
669 };
670
671 static int __init initialize_ptr_random(void)
672 {
673         int key_size = sizeof(ptr_key);
674         int ret;
675
676         /* Use hw RNG if available. */
677         if (get_random_bytes_arch(&ptr_key, key_size) == key_size) {
678                 static_branch_disable(&not_filled_random_ptr_key);
679                 return 0;
680         }
681
682         ret = add_random_ready_callback(&random_ready);
683         if (!ret) {
684                 return 0;
685         } else if (ret == -EALREADY) {
686                 /* This is in preemptible context */
687                 enable_ptr_key_workfn(&enable_ptr_key_work);
688                 return 0;
689         }
690
691         return ret;
692 }
693 early_initcall(initialize_ptr_random);
694
695 /* Maps a pointer to a 32 bit unique identifier. */
696 static char *ptr_to_id(char *buf, char *end, const void *ptr,
697                        struct printf_spec spec)
698 {
699         const char *str = sizeof(ptr) == 8 ? "(____ptrval____)" : "(ptrval)";
700         unsigned long hashval;
701
702         /* When debugging early boot use non-cryptographically secure hash. */
703         if (unlikely(debug_boot_weak_hash)) {
704                 hashval = hash_long((unsigned long)ptr, 32);
705                 return pointer_string(buf, end, (const void *)hashval, spec);
706         }
707
708         if (static_branch_unlikely(&not_filled_random_ptr_key)) {
709                 spec.field_width = 2 * sizeof(ptr);
710                 /* string length must be less than default_width */
711                 return string_nocheck(buf, end, str, spec);
712         }
713
714 #ifdef CONFIG_64BIT
715         hashval = (unsigned long)siphash_1u64((u64)ptr, &ptr_key);
716         /*
717          * Mask off the first 32 bits, this makes explicit that we have
718          * modified the address (and 32 bits is plenty for a unique ID).
719          */
720         hashval = hashval & 0xffffffff;
721 #else
722         hashval = (unsigned long)siphash_1u32((u32)ptr, &ptr_key);
723 #endif
724         return pointer_string(buf, end, (const void *)hashval, spec);
725 }
726
727 int kptr_restrict __read_mostly;
728
729 static noinline_for_stack
730 char *restricted_pointer(char *buf, char *end, const void *ptr,
731                          struct printf_spec spec)
732 {
733         switch (kptr_restrict) {
734         case 0:
735                 /* Handle as %p, hash and do _not_ leak addresses. */
736                 return ptr_to_id(buf, end, ptr, spec);
737         case 1: {
738                 const struct cred *cred;
739
740                 /*
741                  * kptr_restrict==1 cannot be used in IRQ context
742                  * because its test for CAP_SYSLOG would be meaningless.
743                  */
744                 if (in_irq() || in_serving_softirq() || in_nmi()) {
745                         if (spec.field_width == -1)
746                                 spec.field_width = 2 * sizeof(ptr);
747                         return string_nocheck(buf, end, "pK-error", spec);
748                 }
749
750                 /*
751                  * Only print the real pointer value if the current
752                  * process has CAP_SYSLOG and is running with the
753                  * same credentials it started with. This is because
754                  * access to files is checked at open() time, but %pK
755                  * checks permission at read() time. We don't want to
756                  * leak pointer values if a binary opens a file using
757                  * %pK and then elevates privileges before reading it.
758                  */
759                 cred = current_cred();
760                 if (!has_capability_noaudit(current, CAP_SYSLOG) ||
761                     !uid_eq(cred->euid, cred->uid) ||
762                     !gid_eq(cred->egid, cred->gid))
763                         ptr = NULL;
764                 break;
765         }
766         case 2:
767         default:
768                 /* Always print 0's for %pK */
769                 ptr = NULL;
770                 break;
771         }
772
773         return pointer_string(buf, end, ptr, spec);
774 }
775
776 static noinline_for_stack
777 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
778                   const char *fmt)
779 {
780         const char *array[4], *s;
781         const struct dentry *p;
782         int depth;
783         int i, n;
784
785         switch (fmt[1]) {
786                 case '2': case '3': case '4':
787                         depth = fmt[1] - '0';
788                         break;
789                 default:
790                         depth = 1;
791         }
792
793         rcu_read_lock();
794         for (i = 0; i < depth; i++, d = p) {
795                 p = READ_ONCE(d->d_parent);
796                 array[i] = READ_ONCE(d->d_name.name);
797                 if (p == d) {
798                         if (i)
799                                 array[i] = "";
800                         i++;
801                         break;
802                 }
803         }
804         s = array[--i];
805         for (n = 0; n != spec.precision; n++, buf++) {
806                 char c = *s++;
807                 if (!c) {
808                         if (!i)
809                                 break;
810                         c = '/';
811                         s = array[--i];
812                 }
813                 if (buf < end)
814                         *buf = c;
815         }
816         rcu_read_unlock();
817         return widen_string(buf, n, end, spec);
818 }
819
820 #ifdef CONFIG_BLOCK
821 static noinline_for_stack
822 char *bdev_name(char *buf, char *end, struct block_device *bdev,
823                 struct printf_spec spec, const char *fmt)
824 {
825         struct gendisk *hd = bdev->bd_disk;
826         
827         buf = string(buf, end, hd->disk_name, spec);
828         if (bdev->bd_part->partno) {
829                 if (isdigit(hd->disk_name[strlen(hd->disk_name)-1])) {
830                         if (buf < end)
831                                 *buf = 'p';
832                         buf++;
833                 }
834                 buf = number(buf, end, bdev->bd_part->partno, spec);
835         }
836         return buf;
837 }
838 #endif
839
840 static noinline_for_stack
841 char *symbol_string(char *buf, char *end, void *ptr,
842                     struct printf_spec spec, const char *fmt)
843 {
844         unsigned long value;
845 #ifdef CONFIG_KALLSYMS
846         char sym[KSYM_SYMBOL_LEN];
847 #endif
848
849         if (fmt[1] == 'R')
850                 ptr = __builtin_extract_return_addr(ptr);
851         value = (unsigned long)ptr;
852
853 #ifdef CONFIG_KALLSYMS
854         if (*fmt == 'B')
855                 sprint_backtrace(sym, value);
856         else if (*fmt != 'f' && *fmt != 's')
857                 sprint_symbol(sym, value);
858         else
859                 sprint_symbol_no_offset(sym, value);
860
861         return string_nocheck(buf, end, sym, spec);
862 #else
863         return special_hex_number(buf, end, value, sizeof(void *));
864 #endif
865 }
866
867 static const struct printf_spec default_str_spec = {
868         .field_width = -1,
869         .precision = -1,
870 };
871
872 static const struct printf_spec default_flag_spec = {
873         .base = 16,
874         .precision = -1,
875         .flags = SPECIAL | SMALL,
876 };
877
878 static const struct printf_spec default_dec_spec = {
879         .base = 10,
880         .precision = -1,
881 };
882
883 static const struct printf_spec default_dec02_spec = {
884         .base = 10,
885         .field_width = 2,
886         .precision = -1,
887         .flags = ZEROPAD,
888 };
889
890 static const struct printf_spec default_dec04_spec = {
891         .base = 10,
892         .field_width = 4,
893         .precision = -1,
894         .flags = ZEROPAD,
895 };
896
897 static noinline_for_stack
898 char *resource_string(char *buf, char *end, struct resource *res,
899                       struct printf_spec spec, const char *fmt)
900 {
901 #ifndef IO_RSRC_PRINTK_SIZE
902 #define IO_RSRC_PRINTK_SIZE     6
903 #endif
904
905 #ifndef MEM_RSRC_PRINTK_SIZE
906 #define MEM_RSRC_PRINTK_SIZE    10
907 #endif
908         static const struct printf_spec io_spec = {
909                 .base = 16,
910                 .field_width = IO_RSRC_PRINTK_SIZE,
911                 .precision = -1,
912                 .flags = SPECIAL | SMALL | ZEROPAD,
913         };
914         static const struct printf_spec mem_spec = {
915                 .base = 16,
916                 .field_width = MEM_RSRC_PRINTK_SIZE,
917                 .precision = -1,
918                 .flags = SPECIAL | SMALL | ZEROPAD,
919         };
920         static const struct printf_spec bus_spec = {
921                 .base = 16,
922                 .field_width = 2,
923                 .precision = -1,
924                 .flags = SMALL | ZEROPAD,
925         };
926         static const struct printf_spec str_spec = {
927                 .field_width = -1,
928                 .precision = 10,
929                 .flags = LEFT,
930         };
931
932         /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
933          * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
934 #define RSRC_BUF_SIZE           ((2 * sizeof(resource_size_t)) + 4)
935 #define FLAG_BUF_SIZE           (2 * sizeof(res->flags))
936 #define DECODED_BUF_SIZE        sizeof("[mem - 64bit pref window disabled]")
937 #define RAW_BUF_SIZE            sizeof("[mem - flags 0x]")
938         char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
939                      2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
940
941         char *p = sym, *pend = sym + sizeof(sym);
942         int decode = (fmt[0] == 'R') ? 1 : 0;
943         const struct printf_spec *specp;
944
945         *p++ = '[';
946         if (res->flags & IORESOURCE_IO) {
947                 p = string_nocheck(p, pend, "io  ", str_spec);
948                 specp = &io_spec;
949         } else if (res->flags & IORESOURCE_MEM) {
950                 p = string_nocheck(p, pend, "mem ", str_spec);
951                 specp = &mem_spec;
952         } else if (res->flags & IORESOURCE_IRQ) {
953                 p = string_nocheck(p, pend, "irq ", str_spec);
954                 specp = &default_dec_spec;
955         } else if (res->flags & IORESOURCE_DMA) {
956                 p = string_nocheck(p, pend, "dma ", str_spec);
957                 specp = &default_dec_spec;
958         } else if (res->flags & IORESOURCE_BUS) {
959                 p = string_nocheck(p, pend, "bus ", str_spec);
960                 specp = &bus_spec;
961         } else {
962                 p = string_nocheck(p, pend, "??? ", str_spec);
963                 specp = &mem_spec;
964                 decode = 0;
965         }
966         if (decode && res->flags & IORESOURCE_UNSET) {
967                 p = string_nocheck(p, pend, "size ", str_spec);
968                 p = number(p, pend, resource_size(res), *specp);
969         } else {
970                 p = number(p, pend, res->start, *specp);
971                 if (res->start != res->end) {
972                         *p++ = '-';
973                         p = number(p, pend, res->end, *specp);
974                 }
975         }
976         if (decode) {
977                 if (res->flags & IORESOURCE_MEM_64)
978                         p = string_nocheck(p, pend, " 64bit", str_spec);
979                 if (res->flags & IORESOURCE_PREFETCH)
980                         p = string_nocheck(p, pend, " pref", str_spec);
981                 if (res->flags & IORESOURCE_WINDOW)
982                         p = string_nocheck(p, pend, " window", str_spec);
983                 if (res->flags & IORESOURCE_DISABLED)
984                         p = string_nocheck(p, pend, " disabled", str_spec);
985         } else {
986                 p = string_nocheck(p, pend, " flags ", str_spec);
987                 p = number(p, pend, res->flags, default_flag_spec);
988         }
989         *p++ = ']';
990         *p = '\0';
991
992         return string_nocheck(buf, end, sym, spec);
993 }
994
995 static noinline_for_stack
996 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
997                  const char *fmt)
998 {
999         int i, len = 1;         /* if we pass '%ph[CDN]', field width remains
1000                                    negative value, fallback to the default */
1001         char separator;
1002
1003         if (spec.field_width == 0)
1004                 /* nothing to print */
1005                 return buf;
1006
1007         if (ZERO_OR_NULL_PTR(addr))
1008                 /* NULL pointer */
1009                 return string(buf, end, NULL, spec);
1010
1011         switch (fmt[1]) {
1012         case 'C':
1013                 separator = ':';
1014                 break;
1015         case 'D':
1016                 separator = '-';
1017                 break;
1018         case 'N':
1019                 separator = 0;
1020                 break;
1021         default:
1022                 separator = ' ';
1023                 break;
1024         }
1025
1026         if (spec.field_width > 0)
1027                 len = min_t(int, spec.field_width, 64);
1028
1029         for (i = 0; i < len; ++i) {
1030                 if (buf < end)
1031                         *buf = hex_asc_hi(addr[i]);
1032                 ++buf;
1033                 if (buf < end)
1034                         *buf = hex_asc_lo(addr[i]);
1035                 ++buf;
1036
1037                 if (separator && i != len - 1) {
1038                         if (buf < end)
1039                                 *buf = separator;
1040                         ++buf;
1041                 }
1042         }
1043
1044         return buf;
1045 }
1046
1047 static noinline_for_stack
1048 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
1049                     struct printf_spec spec, const char *fmt)
1050 {
1051         const int CHUNKSZ = 32;
1052         int nr_bits = max_t(int, spec.field_width, 0);
1053         int i, chunksz;
1054         bool first = true;
1055
1056         /* reused to print numbers */
1057         spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
1058
1059         chunksz = nr_bits & (CHUNKSZ - 1);
1060         if (chunksz == 0)
1061                 chunksz = CHUNKSZ;
1062
1063         i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
1064         for (; i >= 0; i -= CHUNKSZ) {
1065                 u32 chunkmask, val;
1066                 int word, bit;
1067
1068                 chunkmask = ((1ULL << chunksz) - 1);
1069                 word = i / BITS_PER_LONG;
1070                 bit = i % BITS_PER_LONG;
1071                 val = (bitmap[word] >> bit) & chunkmask;
1072
1073                 if (!first) {
1074                         if (buf < end)
1075                                 *buf = ',';
1076                         buf++;
1077                 }
1078                 first = false;
1079
1080                 spec.field_width = DIV_ROUND_UP(chunksz, 4);
1081                 buf = number(buf, end, val, spec);
1082
1083                 chunksz = CHUNKSZ;
1084         }
1085         return buf;
1086 }
1087
1088 static noinline_for_stack
1089 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
1090                          struct printf_spec spec, const char *fmt)
1091 {
1092         int nr_bits = max_t(int, spec.field_width, 0);
1093         /* current bit is 'cur', most recently seen range is [rbot, rtop] */
1094         int cur, rbot, rtop;
1095         bool first = true;
1096
1097         rbot = cur = find_first_bit(bitmap, nr_bits);
1098         while (cur < nr_bits) {
1099                 rtop = cur;
1100                 cur = find_next_bit(bitmap, nr_bits, cur + 1);
1101                 if (cur < nr_bits && cur <= rtop + 1)
1102                         continue;
1103
1104                 if (!first) {
1105                         if (buf < end)
1106                                 *buf = ',';
1107                         buf++;
1108                 }
1109                 first = false;
1110
1111                 buf = number(buf, end, rbot, default_dec_spec);
1112                 if (rbot < rtop) {
1113                         if (buf < end)
1114                                 *buf = '-';
1115                         buf++;
1116
1117                         buf = number(buf, end, rtop, default_dec_spec);
1118                 }
1119
1120                 rbot = cur;
1121         }
1122         return buf;
1123 }
1124
1125 static noinline_for_stack
1126 char *mac_address_string(char *buf, char *end, u8 *addr,
1127                          struct printf_spec spec, const char *fmt)
1128 {
1129         char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
1130         char *p = mac_addr;
1131         int i;
1132         char separator;
1133         bool reversed = false;
1134
1135         switch (fmt[1]) {
1136         case 'F':
1137                 separator = '-';
1138                 break;
1139
1140         case 'R':
1141                 reversed = true;
1142                 /* fall through */
1143
1144         default:
1145                 separator = ':';
1146                 break;
1147         }
1148
1149         for (i = 0; i < 6; i++) {
1150                 if (reversed)
1151                         p = hex_byte_pack(p, addr[5 - i]);
1152                 else
1153                         p = hex_byte_pack(p, addr[i]);
1154
1155                 if (fmt[0] == 'M' && i != 5)
1156                         *p++ = separator;
1157         }
1158         *p = '\0';
1159
1160         return string_nocheck(buf, end, mac_addr, spec);
1161 }
1162
1163 static noinline_for_stack
1164 char *ip4_string(char *p, const u8 *addr, const char *fmt)
1165 {
1166         int i;
1167         bool leading_zeros = (fmt[0] == 'i');
1168         int index;
1169         int step;
1170
1171         switch (fmt[2]) {
1172         case 'h':
1173 #ifdef __BIG_ENDIAN
1174                 index = 0;
1175                 step = 1;
1176 #else
1177                 index = 3;
1178                 step = -1;
1179 #endif
1180                 break;
1181         case 'l':
1182                 index = 3;
1183                 step = -1;
1184                 break;
1185         case 'n':
1186         case 'b':
1187         default:
1188                 index = 0;
1189                 step = 1;
1190                 break;
1191         }
1192         for (i = 0; i < 4; i++) {
1193                 char temp[4] __aligned(2);      /* hold each IP quad in reverse order */
1194                 int digits = put_dec_trunc8(temp, addr[index]) - temp;
1195                 if (leading_zeros) {
1196                         if (digits < 3)
1197                                 *p++ = '0';
1198                         if (digits < 2)
1199                                 *p++ = '0';
1200                 }
1201                 /* reverse the digits in the quad */
1202                 while (digits--)
1203                         *p++ = temp[digits];
1204                 if (i < 3)
1205                         *p++ = '.';
1206                 index += step;
1207         }
1208         *p = '\0';
1209
1210         return p;
1211 }
1212
1213 static noinline_for_stack
1214 char *ip6_compressed_string(char *p, const char *addr)
1215 {
1216         int i, j, range;
1217         unsigned char zerolength[8];
1218         int longest = 1;
1219         int colonpos = -1;
1220         u16 word;
1221         u8 hi, lo;
1222         bool needcolon = false;
1223         bool useIPv4;
1224         struct in6_addr in6;
1225
1226         memcpy(&in6, addr, sizeof(struct in6_addr));
1227
1228         useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
1229
1230         memset(zerolength, 0, sizeof(zerolength));
1231
1232         if (useIPv4)
1233                 range = 6;
1234         else
1235                 range = 8;
1236
1237         /* find position of longest 0 run */
1238         for (i = 0; i < range; i++) {
1239                 for (j = i; j < range; j++) {
1240                         if (in6.s6_addr16[j] != 0)
1241                                 break;
1242                         zerolength[i]++;
1243                 }
1244         }
1245         for (i = 0; i < range; i++) {
1246                 if (zerolength[i] > longest) {
1247                         longest = zerolength[i];
1248                         colonpos = i;
1249                 }
1250         }
1251         if (longest == 1)               /* don't compress a single 0 */
1252                 colonpos = -1;
1253
1254         /* emit address */
1255         for (i = 0; i < range; i++) {
1256                 if (i == colonpos) {
1257                         if (needcolon || i == 0)
1258                                 *p++ = ':';
1259                         *p++ = ':';
1260                         needcolon = false;
1261                         i += longest - 1;
1262                         continue;
1263                 }
1264                 if (needcolon) {
1265                         *p++ = ':';
1266                         needcolon = false;
1267                 }
1268                 /* hex u16 without leading 0s */
1269                 word = ntohs(in6.s6_addr16[i]);
1270                 hi = word >> 8;
1271                 lo = word & 0xff;
1272                 if (hi) {
1273                         if (hi > 0x0f)
1274                                 p = hex_byte_pack(p, hi);
1275                         else
1276                                 *p++ = hex_asc_lo(hi);
1277                         p = hex_byte_pack(p, lo);
1278                 }
1279                 else if (lo > 0x0f)
1280                         p = hex_byte_pack(p, lo);
1281                 else
1282                         *p++ = hex_asc_lo(lo);
1283                 needcolon = true;
1284         }
1285
1286         if (useIPv4) {
1287                 if (needcolon)
1288                         *p++ = ':';
1289                 p = ip4_string(p, &in6.s6_addr[12], "I4");
1290         }
1291         *p = '\0';
1292
1293         return p;
1294 }
1295
1296 static noinline_for_stack
1297 char *ip6_string(char *p, const char *addr, const char *fmt)
1298 {
1299         int i;
1300
1301         for (i = 0; i < 8; i++) {
1302                 p = hex_byte_pack(p, *addr++);
1303                 p = hex_byte_pack(p, *addr++);
1304                 if (fmt[0] == 'I' && i != 7)
1305                         *p++ = ':';
1306         }
1307         *p = '\0';
1308
1309         return p;
1310 }
1311
1312 static noinline_for_stack
1313 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1314                       struct printf_spec spec, const char *fmt)
1315 {
1316         char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1317
1318         if (fmt[0] == 'I' && fmt[2] == 'c')
1319                 ip6_compressed_string(ip6_addr, addr);
1320         else
1321                 ip6_string(ip6_addr, addr, fmt);
1322
1323         return string_nocheck(buf, end, ip6_addr, spec);
1324 }
1325
1326 static noinline_for_stack
1327 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1328                       struct printf_spec spec, const char *fmt)
1329 {
1330         char ip4_addr[sizeof("255.255.255.255")];
1331
1332         ip4_string(ip4_addr, addr, fmt);
1333
1334         return string_nocheck(buf, end, ip4_addr, spec);
1335 }
1336
1337 static noinline_for_stack
1338 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1339                          struct printf_spec spec, const char *fmt)
1340 {
1341         bool have_p = false, have_s = false, have_f = false, have_c = false;
1342         char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1343                       sizeof(":12345") + sizeof("/123456789") +
1344                       sizeof("%1234567890")];
1345         char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1346         const u8 *addr = (const u8 *) &sa->sin6_addr;
1347         char fmt6[2] = { fmt[0], '6' };
1348         u8 off = 0;
1349
1350         fmt++;
1351         while (isalpha(*++fmt)) {
1352                 switch (*fmt) {
1353                 case 'p':
1354                         have_p = true;
1355                         break;
1356                 case 'f':
1357                         have_f = true;
1358                         break;
1359                 case 's':
1360                         have_s = true;
1361                         break;
1362                 case 'c':
1363                         have_c = true;
1364                         break;
1365                 }
1366         }
1367
1368         if (have_p || have_s || have_f) {
1369                 *p = '[';
1370                 off = 1;
1371         }
1372
1373         if (fmt6[0] == 'I' && have_c)
1374                 p = ip6_compressed_string(ip6_addr + off, addr);
1375         else
1376                 p = ip6_string(ip6_addr + off, addr, fmt6);
1377
1378         if (have_p || have_s || have_f)
1379                 *p++ = ']';
1380
1381         if (have_p) {
1382                 *p++ = ':';
1383                 p = number(p, pend, ntohs(sa->sin6_port), spec);
1384         }
1385         if (have_f) {
1386                 *p++ = '/';
1387                 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1388                                           IPV6_FLOWINFO_MASK), spec);
1389         }
1390         if (have_s) {
1391                 *p++ = '%';
1392                 p = number(p, pend, sa->sin6_scope_id, spec);
1393         }
1394         *p = '\0';
1395
1396         return string_nocheck(buf, end, ip6_addr, spec);
1397 }
1398
1399 static noinline_for_stack
1400 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1401                          struct printf_spec spec, const char *fmt)
1402 {
1403         bool have_p = false;
1404         char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1405         char *pend = ip4_addr + sizeof(ip4_addr);
1406         const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1407         char fmt4[3] = { fmt[0], '4', 0 };
1408
1409         fmt++;
1410         while (isalpha(*++fmt)) {
1411                 switch (*fmt) {
1412                 case 'p':
1413                         have_p = true;
1414                         break;
1415                 case 'h':
1416                 case 'l':
1417                 case 'n':
1418                 case 'b':
1419                         fmt4[2] = *fmt;
1420                         break;
1421                 }
1422         }
1423
1424         p = ip4_string(ip4_addr, addr, fmt4);
1425         if (have_p) {
1426                 *p++ = ':';
1427                 p = number(p, pend, ntohs(sa->sin_port), spec);
1428         }
1429         *p = '\0';
1430
1431         return string_nocheck(buf, end, ip4_addr, spec);
1432 }
1433
1434 static noinline_for_stack
1435 char *ip_addr_string(char *buf, char *end, const void *ptr,
1436                      struct printf_spec spec, const char *fmt)
1437 {
1438         char *err_fmt_msg;
1439
1440         switch (fmt[1]) {
1441         case '6':
1442                 return ip6_addr_string(buf, end, ptr, spec, fmt);
1443         case '4':
1444                 return ip4_addr_string(buf, end, ptr, spec, fmt);
1445         case 'S': {
1446                 const union {
1447                         struct sockaddr         raw;
1448                         struct sockaddr_in      v4;
1449                         struct sockaddr_in6     v6;
1450                 } *sa = ptr;
1451
1452                 switch (sa->raw.sa_family) {
1453                 case AF_INET:
1454                         return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1455                 case AF_INET6:
1456                         return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1457                 default:
1458                         return string_nocheck(buf, end, "(invalid address)", spec);
1459                 }}
1460         }
1461
1462         err_fmt_msg = fmt[0] == 'i' ? "(%pi?)" : "(%pI?)";
1463         return string_nocheck(buf, end, err_fmt_msg, spec);
1464 }
1465
1466 static noinline_for_stack
1467 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1468                      const char *fmt)
1469 {
1470         bool found = true;
1471         int count = 1;
1472         unsigned int flags = 0;
1473         int len;
1474
1475         if (spec.field_width == 0)
1476                 return buf;                             /* nothing to print */
1477
1478         if (ZERO_OR_NULL_PTR(addr))
1479                 return string(buf, end, NULL, spec);    /* NULL pointer */
1480
1481
1482         do {
1483                 switch (fmt[count++]) {
1484                 case 'a':
1485                         flags |= ESCAPE_ANY;
1486                         break;
1487                 case 'c':
1488                         flags |= ESCAPE_SPECIAL;
1489                         break;
1490                 case 'h':
1491                         flags |= ESCAPE_HEX;
1492                         break;
1493                 case 'n':
1494                         flags |= ESCAPE_NULL;
1495                         break;
1496                 case 'o':
1497                         flags |= ESCAPE_OCTAL;
1498                         break;
1499                 case 'p':
1500                         flags |= ESCAPE_NP;
1501                         break;
1502                 case 's':
1503                         flags |= ESCAPE_SPACE;
1504                         break;
1505                 default:
1506                         found = false;
1507                         break;
1508                 }
1509         } while (found);
1510
1511         if (!flags)
1512                 flags = ESCAPE_ANY_NP;
1513
1514         len = spec.field_width < 0 ? 1 : spec.field_width;
1515
1516         /*
1517          * string_escape_mem() writes as many characters as it can to
1518          * the given buffer, and returns the total size of the output
1519          * had the buffer been big enough.
1520          */
1521         buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1522
1523         return buf;
1524 }
1525
1526 static char *va_format(char *buf, char *end, struct va_format *va_fmt)
1527 {
1528         va_list va;
1529
1530         va_copy(va, *va_fmt->va);
1531         buf += vsnprintf(buf, end > buf ? end - buf : 0, va_fmt->fmt, va);
1532         va_end(va);
1533
1534         return buf;
1535 }
1536
1537 static noinline_for_stack
1538 char *uuid_string(char *buf, char *end, const u8 *addr,
1539                   struct printf_spec spec, const char *fmt)
1540 {
1541         char uuid[UUID_STRING_LEN + 1];
1542         char *p = uuid;
1543         int i;
1544         const u8 *index = uuid_index;
1545         bool uc = false;
1546
1547         switch (*(++fmt)) {
1548         case 'L':
1549                 uc = true;              /* fall-through */
1550         case 'l':
1551                 index = guid_index;
1552                 break;
1553         case 'B':
1554                 uc = true;
1555                 break;
1556         }
1557
1558         for (i = 0; i < 16; i++) {
1559                 if (uc)
1560                         p = hex_byte_pack_upper(p, addr[index[i]]);
1561                 else
1562                         p = hex_byte_pack(p, addr[index[i]]);
1563                 switch (i) {
1564                 case 3:
1565                 case 5:
1566                 case 7:
1567                 case 9:
1568                         *p++ = '-';
1569                         break;
1570                 }
1571         }
1572
1573         *p = 0;
1574
1575         return string_nocheck(buf, end, uuid, spec);
1576 }
1577
1578 static noinline_for_stack
1579 char *netdev_bits(char *buf, char *end, const void *addr,
1580                   struct printf_spec spec,  const char *fmt)
1581 {
1582         unsigned long long num;
1583         int size;
1584
1585         switch (fmt[1]) {
1586         case 'F':
1587                 num = *(const netdev_features_t *)addr;
1588                 size = sizeof(netdev_features_t);
1589                 break;
1590         default:
1591                 return string_nocheck(buf, end, "(%pN?)", spec);
1592         }
1593
1594         return special_hex_number(buf, end, num, size);
1595 }
1596
1597 static noinline_for_stack
1598 char *address_val(char *buf, char *end, const void *addr, const char *fmt)
1599 {
1600         unsigned long long num;
1601         int size;
1602
1603         switch (fmt[1]) {
1604         case 'd':
1605                 num = *(const dma_addr_t *)addr;
1606                 size = sizeof(dma_addr_t);
1607                 break;
1608         case 'p':
1609         default:
1610                 num = *(const phys_addr_t *)addr;
1611                 size = sizeof(phys_addr_t);
1612                 break;
1613         }
1614
1615         return special_hex_number(buf, end, num, size);
1616 }
1617
1618 static noinline_for_stack
1619 char *date_str(char *buf, char *end, const struct rtc_time *tm, bool r)
1620 {
1621         int year = tm->tm_year + (r ? 0 : 1900);
1622         int mon = tm->tm_mon + (r ? 0 : 1);
1623
1624         buf = number(buf, end, year, default_dec04_spec);
1625         if (buf < end)
1626                 *buf = '-';
1627         buf++;
1628
1629         buf = number(buf, end, mon, default_dec02_spec);
1630         if (buf < end)
1631                 *buf = '-';
1632         buf++;
1633
1634         return number(buf, end, tm->tm_mday, default_dec02_spec);
1635 }
1636
1637 static noinline_for_stack
1638 char *time_str(char *buf, char *end, const struct rtc_time *tm, bool r)
1639 {
1640         buf = number(buf, end, tm->tm_hour, default_dec02_spec);
1641         if (buf < end)
1642                 *buf = ':';
1643         buf++;
1644
1645         buf = number(buf, end, tm->tm_min, default_dec02_spec);
1646         if (buf < end)
1647                 *buf = ':';
1648         buf++;
1649
1650         return number(buf, end, tm->tm_sec, default_dec02_spec);
1651 }
1652
1653 static noinline_for_stack
1654 char *rtc_str(char *buf, char *end, const struct rtc_time *tm, const char *fmt)
1655 {
1656         bool have_t = true, have_d = true;
1657         bool raw = false;
1658         int count = 2;
1659
1660         switch (fmt[count]) {
1661         case 'd':
1662                 have_t = false;
1663                 count++;
1664                 break;
1665         case 't':
1666                 have_d = false;
1667                 count++;
1668                 break;
1669         }
1670
1671         raw = fmt[count] == 'r';
1672
1673         if (have_d)
1674                 buf = date_str(buf, end, tm, raw);
1675         if (have_d && have_t) {
1676                 /* Respect ISO 8601 */
1677                 if (buf < end)
1678                         *buf = 'T';
1679                 buf++;
1680         }
1681         if (have_t)
1682                 buf = time_str(buf, end, tm, raw);
1683
1684         return buf;
1685 }
1686
1687 static noinline_for_stack
1688 char *time_and_date(char *buf, char *end, void *ptr, struct printf_spec spec,
1689                     const char *fmt)
1690 {
1691         switch (fmt[1]) {
1692         case 'R':
1693                 return rtc_str(buf, end, (const struct rtc_time *)ptr, fmt);
1694         default:
1695                 return string_nocheck(buf, end, "(%ptR?)", spec);
1696         }
1697 }
1698
1699 static noinline_for_stack
1700 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1701             const char *fmt)
1702 {
1703         if (!IS_ENABLED(CONFIG_HAVE_CLK))
1704                 return string_nocheck(buf, end, "(%pC?)", spec);
1705
1706         if (!clk)
1707                 return string(buf, end, NULL, spec);
1708
1709         switch (fmt[1]) {
1710         case 'n':
1711         default:
1712 #ifdef CONFIG_COMMON_CLK
1713                 return string(buf, end, __clk_get_name(clk), spec);
1714 #else
1715                 return string_nocheck(buf, end, "(%pC?)", spec);
1716 #endif
1717         }
1718 }
1719
1720 static
1721 char *format_flags(char *buf, char *end, unsigned long flags,
1722                                         const struct trace_print_flags *names)
1723 {
1724         unsigned long mask;
1725
1726         for ( ; flags && names->name; names++) {
1727                 mask = names->mask;
1728                 if ((flags & mask) != mask)
1729                         continue;
1730
1731                 buf = string(buf, end, names->name, default_str_spec);
1732
1733                 flags &= ~mask;
1734                 if (flags) {
1735                         if (buf < end)
1736                                 *buf = '|';
1737                         buf++;
1738                 }
1739         }
1740
1741         if (flags)
1742                 buf = number(buf, end, flags, default_flag_spec);
1743
1744         return buf;
1745 }
1746
1747 static noinline_for_stack
1748 char *flags_string(char *buf, char *end, void *flags_ptr,
1749                    struct printf_spec spec, const char *fmt)
1750 {
1751         unsigned long flags;
1752         const struct trace_print_flags *names;
1753
1754         switch (fmt[1]) {
1755         case 'p':
1756                 flags = *(unsigned long *)flags_ptr;
1757                 /* Remove zone id */
1758                 flags &= (1UL << NR_PAGEFLAGS) - 1;
1759                 names = pageflag_names;
1760                 break;
1761         case 'v':
1762                 flags = *(unsigned long *)flags_ptr;
1763                 names = vmaflag_names;
1764                 break;
1765         case 'g':
1766                 flags = *(gfp_t *)flags_ptr;
1767                 names = gfpflag_names;
1768                 break;
1769         default:
1770                 return string_nocheck(buf, end, "(%pG?)", spec);
1771         }
1772
1773         return format_flags(buf, end, flags, names);
1774 }
1775
1776 static const char *device_node_name_for_depth(const struct device_node *np, int depth)
1777 {
1778         for ( ; np && depth; depth--)
1779                 np = np->parent;
1780
1781         return kbasename(np->full_name);
1782 }
1783
1784 static noinline_for_stack
1785 char *device_node_gen_full_name(const struct device_node *np, char *buf, char *end)
1786 {
1787         int depth;
1788         const struct device_node *parent = np->parent;
1789
1790         /* special case for root node */
1791         if (!parent)
1792                 return string_nocheck(buf, end, "/", default_str_spec);
1793
1794         for (depth = 0; parent->parent; depth++)
1795                 parent = parent->parent;
1796
1797         for ( ; depth >= 0; depth--) {
1798                 buf = string_nocheck(buf, end, "/", default_str_spec);
1799                 buf = string(buf, end, device_node_name_for_depth(np, depth),
1800                              default_str_spec);
1801         }
1802         return buf;
1803 }
1804
1805 static noinline_for_stack
1806 char *device_node_string(char *buf, char *end, struct device_node *dn,
1807                          struct printf_spec spec, const char *fmt)
1808 {
1809         char tbuf[sizeof("xxxx") + 1];
1810         const char *p;
1811         int ret;
1812         char *buf_start = buf;
1813         struct property *prop;
1814         bool has_mult, pass;
1815         static const struct printf_spec num_spec = {
1816                 .flags = SMALL,
1817                 .field_width = -1,
1818                 .precision = -1,
1819                 .base = 10,
1820         };
1821
1822         struct printf_spec str_spec = spec;
1823         str_spec.field_width = -1;
1824
1825         if (!IS_ENABLED(CONFIG_OF))
1826                 return string_nocheck(buf, end, "(%pOF?)", spec);
1827
1828         if ((unsigned long)dn < PAGE_SIZE)
1829                 return string_nocheck(buf, end, "(null)", spec);
1830
1831         /* simple case without anything any more format specifiers */
1832         fmt++;
1833         if (fmt[0] == '\0' || strcspn(fmt,"fnpPFcC") > 0)
1834                 fmt = "f";
1835
1836         for (pass = false; strspn(fmt,"fnpPFcC"); fmt++, pass = true) {
1837                 int precision;
1838                 if (pass) {
1839                         if (buf < end)
1840                                 *buf = ':';
1841                         buf++;
1842                 }
1843
1844                 switch (*fmt) {
1845                 case 'f':       /* full_name */
1846                         buf = device_node_gen_full_name(dn, buf, end);
1847                         break;
1848                 case 'n':       /* name */
1849                         p = kbasename(of_node_full_name(dn));
1850                         precision = str_spec.precision;
1851                         str_spec.precision = strchrnul(p, '@') - p;
1852                         buf = string(buf, end, p, str_spec);
1853                         str_spec.precision = precision;
1854                         break;
1855                 case 'p':       /* phandle */
1856                         buf = number(buf, end, (unsigned int)dn->phandle, num_spec);
1857                         break;
1858                 case 'P':       /* path-spec */
1859                         p = kbasename(of_node_full_name(dn));
1860                         if (!p[1])
1861                                 p = "/";
1862                         buf = string(buf, end, p, str_spec);
1863                         break;
1864                 case 'F':       /* flags */
1865                         tbuf[0] = of_node_check_flag(dn, OF_DYNAMIC) ? 'D' : '-';
1866                         tbuf[1] = of_node_check_flag(dn, OF_DETACHED) ? 'd' : '-';
1867                         tbuf[2] = of_node_check_flag(dn, OF_POPULATED) ? 'P' : '-';
1868                         tbuf[3] = of_node_check_flag(dn, OF_POPULATED_BUS) ? 'B' : '-';
1869                         tbuf[4] = 0;
1870                         buf = string_nocheck(buf, end, tbuf, str_spec);
1871                         break;
1872                 case 'c':       /* major compatible string */
1873                         ret = of_property_read_string(dn, "compatible", &p);
1874                         if (!ret)
1875                                 buf = string(buf, end, p, str_spec);
1876                         break;
1877                 case 'C':       /* full compatible string */
1878                         has_mult = false;
1879                         of_property_for_each_string(dn, "compatible", prop, p) {
1880                                 if (has_mult)
1881                                         buf = string_nocheck(buf, end, ",", str_spec);
1882                                 buf = string_nocheck(buf, end, "\"", str_spec);
1883                                 buf = string(buf, end, p, str_spec);
1884                                 buf = string_nocheck(buf, end, "\"", str_spec);
1885
1886                                 has_mult = true;
1887                         }
1888                         break;
1889                 default:
1890                         break;
1891                 }
1892         }
1893
1894         return widen_string(buf, buf - buf_start, end, spec);
1895 }
1896
1897 static char *kobject_string(char *buf, char *end, void *ptr,
1898                             struct printf_spec spec, const char *fmt)
1899 {
1900         switch (fmt[1]) {
1901         case 'F':
1902                 return device_node_string(buf, end, ptr, spec, fmt + 1);
1903         }
1904
1905         return string_nocheck(buf, end, "(%pO?)", spec);
1906 }
1907
1908 /*
1909  * Show a '%p' thing.  A kernel extension is that the '%p' is followed
1910  * by an extra set of alphanumeric characters that are extended format
1911  * specifiers.
1912  *
1913  * Please update scripts/checkpatch.pl when adding/removing conversion
1914  * characters.  (Search for "check for vsprintf extension").
1915  *
1916  * Right now we handle:
1917  *
1918  * - 'S' For symbolic direct pointers (or function descriptors) with offset
1919  * - 's' For symbolic direct pointers (or function descriptors) without offset
1920  * - 'F' Same as 'S'
1921  * - 'f' Same as 's'
1922  * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1923  * - 'B' For backtraced symbolic direct pointers with offset
1924  * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1925  * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
1926  * - 'b[l]' For a bitmap, the number of bits is determined by the field
1927  *       width which must be explicitly specified either as part of the
1928  *       format string '%32b[l]' or through '%*b[l]', [l] selects
1929  *       range-list format instead of hex format
1930  * - 'M' For a 6-byte MAC address, it prints the address in the
1931  *       usual colon-separated hex notation
1932  * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1933  * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1934  *       with a dash-separated hex notation
1935  * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1936  * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1937  *       IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1938  *       IPv6 uses colon separated network-order 16 bit hex with leading 0's
1939  *       [S][pfs]
1940  *       Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1941  *       [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1942  * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1943  *       IPv6 omits the colons (01020304...0f)
1944  *       IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
1945  *       [S][pfs]
1946  *       Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1947  *       [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1948  * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1949  * - 'I[6S]c' for IPv6 addresses printed as specified by
1950  *       http://tools.ietf.org/html/rfc5952
1951  * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1952  *                of the following flags (see string_escape_mem() for the
1953  *                details):
1954  *                  a - ESCAPE_ANY
1955  *                  c - ESCAPE_SPECIAL
1956  *                  h - ESCAPE_HEX
1957  *                  n - ESCAPE_NULL
1958  *                  o - ESCAPE_OCTAL
1959  *                  p - ESCAPE_NP
1960  *                  s - ESCAPE_SPACE
1961  *                By default ESCAPE_ANY_NP is used.
1962  * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1963  *       "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1964  *       Options for %pU are:
1965  *         b big endian lower case hex (default)
1966  *         B big endian UPPER case hex
1967  *         l little endian lower case hex
1968  *         L little endian UPPER case hex
1969  *           big endian output byte order is:
1970  *             [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1971  *           little endian output byte order is:
1972  *             [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1973  * - 'V' For a struct va_format which contains a format string * and va_list *,
1974  *       call vsnprintf(->format, *->va_list).
1975  *       Implements a "recursive vsnprintf".
1976  *       Do not use this feature without some mechanism to verify the
1977  *       correctness of the format string and va_list arguments.
1978  * - 'K' For a kernel pointer that should be hidden from unprivileged users
1979  * - 'NF' For a netdev_features_t
1980  * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1981  *            a certain separator (' ' by default):
1982  *              C colon
1983  *              D dash
1984  *              N no separator
1985  *            The maximum supported length is 64 bytes of the input. Consider
1986  *            to use print_hex_dump() for the larger input.
1987  * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1988  *           (default assumed to be phys_addr_t, passed by reference)
1989  * - 'd[234]' For a dentry name (optionally 2-4 last components)
1990  * - 'D[234]' Same as 'd' but for a struct file
1991  * - 'g' For block_device name (gendisk + partition number)
1992  * - 't[R][dt][r]' For time and date as represented:
1993  *      R    struct rtc_time
1994  * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1995  *       (legacy clock framework) of the clock
1996  * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1997  *        (legacy clock framework) of the clock
1998  * - 'G' For flags to be printed as a collection of symbolic strings that would
1999  *       construct the specific value. Supported flags given by option:
2000  *       p page flags (see struct page) given as pointer to unsigned long
2001  *       g gfp flags (GFP_* and __GFP_*) given as pointer to gfp_t
2002  *       v vma flags (VM_*) given as pointer to unsigned long
2003  * - 'OF[fnpPcCF]'  For a device tree object
2004  *                  Without any optional arguments prints the full_name
2005  *                  f device node full_name
2006  *                  n device node name
2007  *                  p device node phandle
2008  *                  P device node path spec (name + @unit)
2009  *                  F device node flags
2010  *                  c major compatible string
2011  *                  C full compatible string
2012  * - 'x' For printing the address. Equivalent to "%lx".
2013  *
2014  * ** When making changes please also update:
2015  *      Documentation/core-api/printk-formats.rst
2016  *
2017  * Note: The default behaviour (unadorned %p) is to hash the address,
2018  * rendering it useful as a unique identifier.
2019  */
2020 static noinline_for_stack
2021 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
2022               struct printf_spec spec)
2023 {
2024         const int default_width = 2 * sizeof(void *);
2025
2026         if (!ptr && *fmt != 'K' && *fmt != 'x') {
2027                 /*
2028                  * Print (null) with the same width as a pointer so it makes
2029                  * tabular output look nice.
2030                  */
2031                 if (spec.field_width == -1)
2032                         spec.field_width = default_width;
2033                 return string_nocheck(buf, end, "(null)", spec);
2034         }
2035
2036         switch (*fmt) {
2037         case 'F':
2038         case 'f':
2039         case 'S':
2040         case 's':
2041                 ptr = dereference_symbol_descriptor(ptr);
2042                 /* Fallthrough */
2043         case 'B':
2044                 return symbol_string(buf, end, ptr, spec, fmt);
2045         case 'R':
2046         case 'r':
2047                 return resource_string(buf, end, ptr, spec, fmt);
2048         case 'h':
2049                 return hex_string(buf, end, ptr, spec, fmt);
2050         case 'b':
2051                 switch (fmt[1]) {
2052                 case 'l':
2053                         return bitmap_list_string(buf, end, ptr, spec, fmt);
2054                 default:
2055                         return bitmap_string(buf, end, ptr, spec, fmt);
2056                 }
2057         case 'M':                       /* Colon separated: 00:01:02:03:04:05 */
2058         case 'm':                       /* Contiguous: 000102030405 */
2059                                         /* [mM]F (FDDI) */
2060                                         /* [mM]R (Reverse order; Bluetooth) */
2061                 return mac_address_string(buf, end, ptr, spec, fmt);
2062         case 'I':                       /* Formatted IP supported
2063                                          * 4:   1.2.3.4
2064                                          * 6:   0001:0203:...:0708
2065                                          * 6c:  1::708 or 1::1.2.3.4
2066                                          */
2067         case 'i':                       /* Contiguous:
2068                                          * 4:   001.002.003.004
2069                                          * 6:   000102...0f
2070                                          */
2071                 return ip_addr_string(buf, end, ptr, spec, fmt);
2072         case 'E':
2073                 return escaped_string(buf, end, ptr, spec, fmt);
2074         case 'U':
2075                 return uuid_string(buf, end, ptr, spec, fmt);
2076         case 'V':
2077                 return va_format(buf, end, ptr);
2078         case 'K':
2079                 return restricted_pointer(buf, end, ptr, spec);
2080         case 'N':
2081                 return netdev_bits(buf, end, ptr, spec, fmt);
2082         case 'a':
2083                 return address_val(buf, end, ptr, fmt);
2084         case 'd':
2085                 return dentry_name(buf, end, ptr, spec, fmt);
2086         case 't':
2087                 return time_and_date(buf, end, ptr, spec, fmt);
2088         case 'C':
2089                 return clock(buf, end, ptr, spec, fmt);
2090         case 'D':
2091                 return dentry_name(buf, end,
2092                                    ((const struct file *)ptr)->f_path.dentry,
2093                                    spec, fmt);
2094 #ifdef CONFIG_BLOCK
2095         case 'g':
2096                 return bdev_name(buf, end, ptr, spec, fmt);
2097 #endif
2098
2099         case 'G':
2100                 return flags_string(buf, end, ptr, spec, fmt);
2101         case 'O':
2102                 return kobject_string(buf, end, ptr, spec, fmt);
2103         case 'x':
2104                 return pointer_string(buf, end, ptr, spec);
2105         }
2106
2107         /* default is to _not_ leak addresses, hash before printing */
2108         return ptr_to_id(buf, end, ptr, spec);
2109 }
2110
2111 /*
2112  * Helper function to decode printf style format.
2113  * Each call decode a token from the format and return the
2114  * number of characters read (or likely the delta where it wants
2115  * to go on the next call).
2116  * The decoded token is returned through the parameters
2117  *
2118  * 'h', 'l', or 'L' for integer fields
2119  * 'z' support added 23/7/1999 S.H.
2120  * 'z' changed to 'Z' --davidm 1/25/99
2121  * 'Z' changed to 'z' --adobriyan 2017-01-25
2122  * 't' added for ptrdiff_t
2123  *
2124  * @fmt: the format string
2125  * @type of the token returned
2126  * @flags: various flags such as +, -, # tokens..
2127  * @field_width: overwritten width
2128  * @base: base of the number (octal, hex, ...)
2129  * @precision: precision of a number
2130  * @qualifier: qualifier of a number (long, size_t, ...)
2131  */
2132 static noinline_for_stack
2133 int format_decode(const char *fmt, struct printf_spec *spec)
2134 {
2135         const char *start = fmt;
2136         char qualifier;
2137
2138         /* we finished early by reading the field width */
2139         if (spec->type == FORMAT_TYPE_WIDTH) {
2140                 if (spec->field_width < 0) {
2141                         spec->field_width = -spec->field_width;
2142                         spec->flags |= LEFT;
2143                 }
2144                 spec->type = FORMAT_TYPE_NONE;
2145                 goto precision;
2146         }
2147
2148         /* we finished early by reading the precision */
2149         if (spec->type == FORMAT_TYPE_PRECISION) {
2150                 if (spec->precision < 0)
2151                         spec->precision = 0;
2152
2153                 spec->type = FORMAT_TYPE_NONE;
2154                 goto qualifier;
2155         }
2156
2157         /* By default */
2158         spec->type = FORMAT_TYPE_NONE;
2159
2160         for (; *fmt ; ++fmt) {
2161                 if (*fmt == '%')
2162                         break;
2163         }
2164
2165         /* Return the current non-format string */
2166         if (fmt != start || !*fmt)
2167                 return fmt - start;
2168
2169         /* Process flags */
2170         spec->flags = 0;
2171
2172         while (1) { /* this also skips first '%' */
2173                 bool found = true;
2174
2175                 ++fmt;
2176
2177                 switch (*fmt) {
2178                 case '-': spec->flags |= LEFT;    break;
2179                 case '+': spec->flags |= PLUS;    break;
2180                 case ' ': spec->flags |= SPACE;   break;
2181                 case '#': spec->flags |= SPECIAL; break;
2182                 case '0': spec->flags |= ZEROPAD; break;
2183                 default:  found = false;
2184                 }
2185
2186                 if (!found)
2187                         break;
2188         }
2189
2190         /* get field width */
2191         spec->field_width = -1;
2192
2193         if (isdigit(*fmt))
2194                 spec->field_width = skip_atoi(&fmt);
2195         else if (*fmt == '*') {
2196                 /* it's the next argument */
2197                 spec->type = FORMAT_TYPE_WIDTH;
2198                 return ++fmt - start;
2199         }
2200
2201 precision:
2202         /* get the precision */
2203         spec->precision = -1;
2204         if (*fmt == '.') {
2205                 ++fmt;
2206                 if (isdigit(*fmt)) {
2207                         spec->precision = skip_atoi(&fmt);
2208                         if (spec->precision < 0)
2209                                 spec->precision = 0;
2210                 } else if (*fmt == '*') {
2211                         /* it's the next argument */
2212                         spec->type = FORMAT_TYPE_PRECISION;
2213                         return ++fmt - start;
2214                 }
2215         }
2216
2217 qualifier:
2218         /* get the conversion qualifier */
2219         qualifier = 0;
2220         if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2221             *fmt == 'z' || *fmt == 't') {
2222                 qualifier = *fmt++;
2223                 if (unlikely(qualifier == *fmt)) {
2224                         if (qualifier == 'l') {
2225                                 qualifier = 'L';
2226                                 ++fmt;
2227                         } else if (qualifier == 'h') {
2228                                 qualifier = 'H';
2229                                 ++fmt;
2230                         }
2231                 }
2232         }
2233
2234         /* default base */
2235         spec->base = 10;
2236         switch (*fmt) {
2237         case 'c':
2238                 spec->type = FORMAT_TYPE_CHAR;
2239                 return ++fmt - start;
2240
2241         case 's':
2242                 spec->type = FORMAT_TYPE_STR;
2243                 return ++fmt - start;
2244
2245         case 'p':
2246                 spec->type = FORMAT_TYPE_PTR;
2247                 return ++fmt - start;
2248
2249         case '%':
2250                 spec->type = FORMAT_TYPE_PERCENT_CHAR;
2251                 return ++fmt - start;
2252
2253         /* integer number formats - set up the flags and "break" */
2254         case 'o':
2255                 spec->base = 8;
2256                 break;
2257
2258         case 'x':
2259                 spec->flags |= SMALL;
2260                 /* fall through */
2261
2262         case 'X':
2263                 spec->base = 16;
2264                 break;
2265
2266         case 'd':
2267         case 'i':
2268                 spec->flags |= SIGN;
2269         case 'u':
2270                 break;
2271
2272         case 'n':
2273                 /*
2274                  * Since %n poses a greater security risk than
2275                  * utility, treat it as any other invalid or
2276                  * unsupported format specifier.
2277                  */
2278                 /* Fall-through */
2279
2280         default:
2281                 WARN_ONCE(1, "Please remove unsupported %%%c in format string\n", *fmt);
2282                 spec->type = FORMAT_TYPE_INVALID;
2283                 return fmt - start;
2284         }
2285
2286         if (qualifier == 'L')
2287                 spec->type = FORMAT_TYPE_LONG_LONG;
2288         else if (qualifier == 'l') {
2289                 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
2290                 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
2291         } else if (qualifier == 'z') {
2292                 spec->type = FORMAT_TYPE_SIZE_T;
2293         } else if (qualifier == 't') {
2294                 spec->type = FORMAT_TYPE_PTRDIFF;
2295         } else if (qualifier == 'H') {
2296                 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
2297                 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
2298         } else if (qualifier == 'h') {
2299                 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
2300                 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
2301         } else {
2302                 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
2303                 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
2304         }
2305
2306         return ++fmt - start;
2307 }
2308
2309 static void
2310 set_field_width(struct printf_spec *spec, int width)
2311 {
2312         spec->field_width = width;
2313         if (WARN_ONCE(spec->field_width != width, "field width %d too large", width)) {
2314                 spec->field_width = clamp(width, -FIELD_WIDTH_MAX, FIELD_WIDTH_MAX);
2315         }
2316 }
2317
2318 static void
2319 set_precision(struct printf_spec *spec, int prec)
2320 {
2321         spec->precision = prec;
2322         if (WARN_ONCE(spec->precision != prec, "precision %d too large", prec)) {
2323                 spec->precision = clamp(prec, 0, PRECISION_MAX);
2324         }
2325 }
2326
2327 /**
2328  * vsnprintf - Format a string and place it in a buffer
2329  * @buf: The buffer to place the result into
2330  * @size: The size of the buffer, including the trailing null space
2331  * @fmt: The format string to use
2332  * @args: Arguments for the format string
2333  *
2334  * This function generally follows C99 vsnprintf, but has some
2335  * extensions and a few limitations:
2336  *
2337  *  - ``%n`` is unsupported
2338  *  - ``%p*`` is handled by pointer()
2339  *
2340  * See pointer() or Documentation/core-api/printk-formats.rst for more
2341  * extensive description.
2342  *
2343  * **Please update the documentation in both places when making changes**
2344  *
2345  * The return value is the number of characters which would
2346  * be generated for the given input, excluding the trailing
2347  * '\0', as per ISO C99. If you want to have the exact
2348  * number of characters written into @buf as return value
2349  * (not including the trailing '\0'), use vscnprintf(). If the
2350  * return is greater than or equal to @size, the resulting
2351  * string is truncated.
2352  *
2353  * If you're not already dealing with a va_list consider using snprintf().
2354  */
2355 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
2356 {
2357         unsigned long long num;
2358         char *str, *end;
2359         struct printf_spec spec = {0};
2360
2361         /* Reject out-of-range values early.  Large positive sizes are
2362            used for unknown buffer sizes. */
2363         if (WARN_ON_ONCE(size > INT_MAX))
2364                 return 0;
2365
2366         str = buf;
2367         end = buf + size;
2368
2369         /* Make sure end is always >= buf */
2370         if (end < buf) {
2371                 end = ((void *)-1);
2372                 size = end - buf;
2373         }
2374
2375         while (*fmt) {
2376                 const char *old_fmt = fmt;
2377                 int read = format_decode(fmt, &spec);
2378
2379                 fmt += read;
2380
2381                 switch (spec.type) {
2382                 case FORMAT_TYPE_NONE: {
2383                         int copy = read;
2384                         if (str < end) {
2385                                 if (copy > end - str)
2386                                         copy = end - str;
2387                                 memcpy(str, old_fmt, copy);
2388                         }
2389                         str += read;
2390                         break;
2391                 }
2392
2393                 case FORMAT_TYPE_WIDTH:
2394                         set_field_width(&spec, va_arg(args, int));
2395                         break;
2396
2397                 case FORMAT_TYPE_PRECISION:
2398                         set_precision(&spec, va_arg(args, int));
2399                         break;
2400
2401                 case FORMAT_TYPE_CHAR: {
2402                         char c;
2403
2404                         if (!(spec.flags & LEFT)) {
2405                                 while (--spec.field_width > 0) {
2406                                         if (str < end)
2407                                                 *str = ' ';
2408                                         ++str;
2409
2410                                 }
2411                         }
2412                         c = (unsigned char) va_arg(args, int);
2413                         if (str < end)
2414                                 *str = c;
2415                         ++str;
2416                         while (--spec.field_width > 0) {
2417                                 if (str < end)
2418                                         *str = ' ';
2419                                 ++str;
2420                         }
2421                         break;
2422                 }
2423
2424                 case FORMAT_TYPE_STR:
2425                         str = string(str, end, va_arg(args, char *), spec);
2426                         break;
2427
2428                 case FORMAT_TYPE_PTR:
2429                         str = pointer(fmt, str, end, va_arg(args, void *),
2430                                       spec);
2431                         while (isalnum(*fmt))
2432                                 fmt++;
2433                         break;
2434
2435                 case FORMAT_TYPE_PERCENT_CHAR:
2436                         if (str < end)
2437                                 *str = '%';
2438                         ++str;
2439                         break;
2440
2441                 case FORMAT_TYPE_INVALID:
2442                         /*
2443                          * Presumably the arguments passed gcc's type
2444                          * checking, but there is no safe or sane way
2445                          * for us to continue parsing the format and
2446                          * fetching from the va_list; the remaining
2447                          * specifiers and arguments would be out of
2448                          * sync.
2449                          */
2450                         goto out;
2451
2452                 default:
2453                         switch (spec.type) {
2454                         case FORMAT_TYPE_LONG_LONG:
2455                                 num = va_arg(args, long long);
2456                                 break;
2457                         case FORMAT_TYPE_ULONG:
2458                                 num = va_arg(args, unsigned long);
2459                                 break;
2460                         case FORMAT_TYPE_LONG:
2461                                 num = va_arg(args, long);
2462                                 break;
2463                         case FORMAT_TYPE_SIZE_T:
2464                                 if (spec.flags & SIGN)
2465                                         num = va_arg(args, ssize_t);
2466                                 else
2467                                         num = va_arg(args, size_t);
2468                                 break;
2469                         case FORMAT_TYPE_PTRDIFF:
2470                                 num = va_arg(args, ptrdiff_t);
2471                                 break;
2472                         case FORMAT_TYPE_UBYTE:
2473                                 num = (unsigned char) va_arg(args, int);
2474                                 break;
2475                         case FORMAT_TYPE_BYTE:
2476                                 num = (signed char) va_arg(args, int);
2477                                 break;
2478                         case FORMAT_TYPE_USHORT:
2479                                 num = (unsigned short) va_arg(args, int);
2480                                 break;
2481                         case FORMAT_TYPE_SHORT:
2482                                 num = (short) va_arg(args, int);
2483                                 break;
2484                         case FORMAT_TYPE_INT:
2485                                 num = (int) va_arg(args, int);
2486                                 break;
2487                         default:
2488                                 num = va_arg(args, unsigned int);
2489                         }
2490
2491                         str = number(str, end, num, spec);
2492                 }
2493         }
2494
2495 out:
2496         if (size > 0) {
2497                 if (str < end)
2498                         *str = '\0';
2499                 else
2500                         end[-1] = '\0';
2501         }
2502
2503         /* the trailing null byte doesn't count towards the total */
2504         return str-buf;
2505
2506 }
2507 EXPORT_SYMBOL(vsnprintf);
2508
2509 /**
2510  * vscnprintf - Format a string and place it in a buffer
2511  * @buf: The buffer to place the result into
2512  * @size: The size of the buffer, including the trailing null space
2513  * @fmt: The format string to use
2514  * @args: Arguments for the format string
2515  *
2516  * The return value is the number of characters which have been written into
2517  * the @buf not including the trailing '\0'. If @size is == 0 the function
2518  * returns 0.
2519  *
2520  * If you're not already dealing with a va_list consider using scnprintf().
2521  *
2522  * See the vsnprintf() documentation for format string extensions over C99.
2523  */
2524 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2525 {
2526         int i;
2527
2528         i = vsnprintf(buf, size, fmt, args);
2529
2530         if (likely(i < size))
2531                 return i;
2532         if (size != 0)
2533                 return size - 1;
2534         return 0;
2535 }
2536 EXPORT_SYMBOL(vscnprintf);
2537
2538 /**
2539  * snprintf - Format a string and place it in a buffer
2540  * @buf: The buffer to place the result into
2541  * @size: The size of the buffer, including the trailing null space
2542  * @fmt: The format string to use
2543  * @...: Arguments for the format string
2544  *
2545  * The return value is the number of characters which would be
2546  * generated for the given input, excluding the trailing null,
2547  * as per ISO C99.  If the return is greater than or equal to
2548  * @size, the resulting string is truncated.
2549  *
2550  * See the vsnprintf() documentation for format string extensions over C99.
2551  */
2552 int snprintf(char *buf, size_t size, const char *fmt, ...)
2553 {
2554         va_list args;
2555         int i;
2556
2557         va_start(args, fmt);
2558         i = vsnprintf(buf, size, fmt, args);
2559         va_end(args);
2560
2561         return i;
2562 }
2563 EXPORT_SYMBOL(snprintf);
2564
2565 /**
2566  * scnprintf - Format a string and place it in a buffer
2567  * @buf: The buffer to place the result into
2568  * @size: The size of the buffer, including the trailing null space
2569  * @fmt: The format string to use
2570  * @...: Arguments for the format string
2571  *
2572  * The return value is the number of characters written into @buf not including
2573  * the trailing '\0'. If @size is == 0 the function returns 0.
2574  */
2575
2576 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2577 {
2578         va_list args;
2579         int i;
2580
2581         va_start(args, fmt);
2582         i = vscnprintf(buf, size, fmt, args);
2583         va_end(args);
2584
2585         return i;
2586 }
2587 EXPORT_SYMBOL(scnprintf);
2588
2589 /**
2590  * vsprintf - Format a string and place it in a buffer
2591  * @buf: The buffer to place the result into
2592  * @fmt: The format string to use
2593  * @args: Arguments for the format string
2594  *
2595  * The function returns the number of characters written
2596  * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2597  * buffer overflows.
2598  *
2599  * If you're not already dealing with a va_list consider using sprintf().
2600  *
2601  * See the vsnprintf() documentation for format string extensions over C99.
2602  */
2603 int vsprintf(char *buf, const char *fmt, va_list args)
2604 {
2605         return vsnprintf(buf, INT_MAX, fmt, args);
2606 }
2607 EXPORT_SYMBOL(vsprintf);
2608
2609 /**
2610  * sprintf - Format a string and place it in a buffer
2611  * @buf: The buffer to place the result into
2612  * @fmt: The format string to use
2613  * @...: Arguments for the format string
2614  *
2615  * The function returns the number of characters written
2616  * into @buf. Use snprintf() or scnprintf() in order to avoid
2617  * buffer overflows.
2618  *
2619  * See the vsnprintf() documentation for format string extensions over C99.
2620  */
2621 int sprintf(char *buf, const char *fmt, ...)
2622 {
2623         va_list args;
2624         int i;
2625
2626         va_start(args, fmt);
2627         i = vsnprintf(buf, INT_MAX, fmt, args);
2628         va_end(args);
2629
2630         return i;
2631 }
2632 EXPORT_SYMBOL(sprintf);
2633
2634 #ifdef CONFIG_BINARY_PRINTF
2635 /*
2636  * bprintf service:
2637  * vbin_printf() - VA arguments to binary data
2638  * bstr_printf() - Binary data to text string
2639  */
2640
2641 /**
2642  * vbin_printf - Parse a format string and place args' binary value in a buffer
2643  * @bin_buf: The buffer to place args' binary value
2644  * @size: The size of the buffer(by words(32bits), not characters)
2645  * @fmt: The format string to use
2646  * @args: Arguments for the format string
2647  *
2648  * The format follows C99 vsnprintf, except %n is ignored, and its argument
2649  * is skipped.
2650  *
2651  * The return value is the number of words(32bits) which would be generated for
2652  * the given input.
2653  *
2654  * NOTE:
2655  * If the return value is greater than @size, the resulting bin_buf is NOT
2656  * valid for bstr_printf().
2657  */
2658 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2659 {
2660         struct printf_spec spec = {0};
2661         char *str, *end;
2662         int width;
2663
2664         str = (char *)bin_buf;
2665         end = (char *)(bin_buf + size);
2666
2667 #define save_arg(type)                                                  \
2668 ({                                                                      \
2669         unsigned long long value;                                       \
2670         if (sizeof(type) == 8) {                                        \
2671                 unsigned long long val8;                                \
2672                 str = PTR_ALIGN(str, sizeof(u32));                      \
2673                 val8 = va_arg(args, unsigned long long);                \
2674                 if (str + sizeof(type) <= end) {                        \
2675                         *(u32 *)str = *(u32 *)&val8;                    \
2676                         *(u32 *)(str + 4) = *((u32 *)&val8 + 1);        \
2677                 }                                                       \
2678                 value = val8;                                           \
2679         } else {                                                        \
2680                 unsigned int val4;                                      \
2681                 str = PTR_ALIGN(str, sizeof(type));                     \
2682                 val4 = va_arg(args, int);                               \
2683                 if (str + sizeof(type) <= end)                          \
2684                         *(typeof(type) *)str = (type)(long)val4;        \
2685                 value = (unsigned long long)val4;                       \
2686         }                                                               \
2687         str += sizeof(type);                                            \
2688         value;                                                          \
2689 })
2690
2691         while (*fmt) {
2692                 int read = format_decode(fmt, &spec);
2693
2694                 fmt += read;
2695
2696                 switch (spec.type) {
2697                 case FORMAT_TYPE_NONE:
2698                 case FORMAT_TYPE_PERCENT_CHAR:
2699                         break;
2700                 case FORMAT_TYPE_INVALID:
2701                         goto out;
2702
2703                 case FORMAT_TYPE_WIDTH:
2704                 case FORMAT_TYPE_PRECISION:
2705                         width = (int)save_arg(int);
2706                         /* Pointers may require the width */
2707                         if (*fmt == 'p')
2708                                 set_field_width(&spec, width);
2709                         break;
2710
2711                 case FORMAT_TYPE_CHAR:
2712                         save_arg(char);
2713                         break;
2714
2715                 case FORMAT_TYPE_STR: {
2716                         const char *save_str = va_arg(args, char *);
2717                         size_t len;
2718
2719                         if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
2720                                         || (unsigned long)save_str < PAGE_SIZE)
2721                                 save_str = "(null)";
2722                         len = strlen(save_str) + 1;
2723                         if (str + len < end)
2724                                 memcpy(str, save_str, len);
2725                         str += len;
2726                         break;
2727                 }
2728
2729                 case FORMAT_TYPE_PTR:
2730                         /* Dereferenced pointers must be done now */
2731                         switch (*fmt) {
2732                         /* Dereference of functions is still OK */
2733                         case 'S':
2734                         case 's':
2735                         case 'F':
2736                         case 'f':
2737                         case 'x':
2738                         case 'K':
2739                                 save_arg(void *);
2740                                 break;
2741                         default:
2742                                 if (!isalnum(*fmt)) {
2743                                         save_arg(void *);
2744                                         break;
2745                                 }
2746                                 str = pointer(fmt, str, end, va_arg(args, void *),
2747                                               spec);
2748                                 if (str + 1 < end)
2749                                         *str++ = '\0';
2750                                 else
2751                                         end[-1] = '\0'; /* Must be nul terminated */
2752                         }
2753                         /* skip all alphanumeric pointer suffixes */
2754                         while (isalnum(*fmt))
2755                                 fmt++;
2756                         break;
2757
2758                 default:
2759                         switch (spec.type) {
2760
2761                         case FORMAT_TYPE_LONG_LONG:
2762                                 save_arg(long long);
2763                                 break;
2764                         case FORMAT_TYPE_ULONG:
2765                         case FORMAT_TYPE_LONG:
2766                                 save_arg(unsigned long);
2767                                 break;
2768                         case FORMAT_TYPE_SIZE_T:
2769                                 save_arg(size_t);
2770                                 break;
2771                         case FORMAT_TYPE_PTRDIFF:
2772                                 save_arg(ptrdiff_t);
2773                                 break;
2774                         case FORMAT_TYPE_UBYTE:
2775                         case FORMAT_TYPE_BYTE:
2776                                 save_arg(char);
2777                                 break;
2778                         case FORMAT_TYPE_USHORT:
2779                         case FORMAT_TYPE_SHORT:
2780                                 save_arg(short);
2781                                 break;
2782                         default:
2783                                 save_arg(int);
2784                         }
2785                 }
2786         }
2787
2788 out:
2789         return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2790 #undef save_arg
2791 }
2792 EXPORT_SYMBOL_GPL(vbin_printf);
2793
2794 /**
2795  * bstr_printf - Format a string from binary arguments and place it in a buffer
2796  * @buf: The buffer to place the result into
2797  * @size: The size of the buffer, including the trailing null space
2798  * @fmt: The format string to use
2799  * @bin_buf: Binary arguments for the format string
2800  *
2801  * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2802  * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2803  * a binary buffer that generated by vbin_printf.
2804  *
2805  * The format follows C99 vsnprintf, but has some extensions:
2806  *  see vsnprintf comment for details.
2807  *
2808  * The return value is the number of characters which would
2809  * be generated for the given input, excluding the trailing
2810  * '\0', as per ISO C99. If you want to have the exact
2811  * number of characters written into @buf as return value
2812  * (not including the trailing '\0'), use vscnprintf(). If the
2813  * return is greater than or equal to @size, the resulting
2814  * string is truncated.
2815  */
2816 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2817 {
2818         struct printf_spec spec = {0};
2819         char *str, *end;
2820         const char *args = (const char *)bin_buf;
2821
2822         if (WARN_ON_ONCE(size > INT_MAX))
2823                 return 0;
2824
2825         str = buf;
2826         end = buf + size;
2827
2828 #define get_arg(type)                                                   \
2829 ({                                                                      \
2830         typeof(type) value;                                             \
2831         if (sizeof(type) == 8) {                                        \
2832                 args = PTR_ALIGN(args, sizeof(u32));                    \
2833                 *(u32 *)&value = *(u32 *)args;                          \
2834                 *((u32 *)&value + 1) = *(u32 *)(args + 4);              \
2835         } else {                                                        \
2836                 args = PTR_ALIGN(args, sizeof(type));                   \
2837                 value = *(typeof(type) *)args;                          \
2838         }                                                               \
2839         args += sizeof(type);                                           \
2840         value;                                                          \
2841 })
2842
2843         /* Make sure end is always >= buf */
2844         if (end < buf) {
2845                 end = ((void *)-1);
2846                 size = end - buf;
2847         }
2848
2849         while (*fmt) {
2850                 const char *old_fmt = fmt;
2851                 int read = format_decode(fmt, &spec);
2852
2853                 fmt += read;
2854
2855                 switch (spec.type) {
2856                 case FORMAT_TYPE_NONE: {
2857                         int copy = read;
2858                         if (str < end) {
2859                                 if (copy > end - str)
2860                                         copy = end - str;
2861                                 memcpy(str, old_fmt, copy);
2862                         }
2863                         str += read;
2864                         break;
2865                 }
2866
2867                 case FORMAT_TYPE_WIDTH:
2868                         set_field_width(&spec, get_arg(int));
2869                         break;
2870
2871                 case FORMAT_TYPE_PRECISION:
2872                         set_precision(&spec, get_arg(int));
2873                         break;
2874
2875                 case FORMAT_TYPE_CHAR: {
2876                         char c;
2877
2878                         if (!(spec.flags & LEFT)) {
2879                                 while (--spec.field_width > 0) {
2880                                         if (str < end)
2881                                                 *str = ' ';
2882                                         ++str;
2883                                 }
2884                         }
2885                         c = (unsigned char) get_arg(char);
2886                         if (str < end)
2887                                 *str = c;
2888                         ++str;
2889                         while (--spec.field_width > 0) {
2890                                 if (str < end)
2891                                         *str = ' ';
2892                                 ++str;
2893                         }
2894                         break;
2895                 }
2896
2897                 case FORMAT_TYPE_STR: {
2898                         const char *str_arg = args;
2899                         args += strlen(str_arg) + 1;
2900                         str = string(str, end, (char *)str_arg, spec);
2901                         break;
2902                 }
2903
2904                 case FORMAT_TYPE_PTR: {
2905                         bool process = false;
2906                         int copy, len;
2907                         /* Non function dereferences were already done */
2908                         switch (*fmt) {
2909                         case 'S':
2910                         case 's':
2911                         case 'F':
2912                         case 'f':
2913                         case 'x':
2914                         case 'K':
2915                                 process = true;
2916                                 break;
2917                         default:
2918                                 if (!isalnum(*fmt)) {
2919                                         process = true;
2920                                         break;
2921                                 }
2922                                 /* Pointer dereference was already processed */
2923                                 if (str < end) {
2924                                         len = copy = strlen(args);
2925                                         if (copy > end - str)
2926                                                 copy = end - str;
2927                                         memcpy(str, args, copy);
2928                                         str += len;
2929                                         args += len + 1;
2930                                 }
2931                         }
2932                         if (process)
2933                                 str = pointer(fmt, str, end, get_arg(void *), spec);
2934
2935                         while (isalnum(*fmt))
2936                                 fmt++;
2937                         break;
2938                 }
2939
2940                 case FORMAT_TYPE_PERCENT_CHAR:
2941                         if (str < end)
2942                                 *str = '%';
2943                         ++str;
2944                         break;
2945
2946                 case FORMAT_TYPE_INVALID:
2947                         goto out;
2948
2949                 default: {
2950                         unsigned long long num;
2951
2952                         switch (spec.type) {
2953
2954                         case FORMAT_TYPE_LONG_LONG:
2955                                 num = get_arg(long long);
2956                                 break;
2957                         case FORMAT_TYPE_ULONG:
2958                         case FORMAT_TYPE_LONG:
2959                                 num = get_arg(unsigned long);
2960                                 break;
2961                         case FORMAT_TYPE_SIZE_T:
2962                                 num = get_arg(size_t);
2963                                 break;
2964                         case FORMAT_TYPE_PTRDIFF:
2965                                 num = get_arg(ptrdiff_t);
2966                                 break;
2967                         case FORMAT_TYPE_UBYTE:
2968                                 num = get_arg(unsigned char);
2969                                 break;
2970                         case FORMAT_TYPE_BYTE:
2971                                 num = get_arg(signed char);
2972                                 break;
2973                         case FORMAT_TYPE_USHORT:
2974                                 num = get_arg(unsigned short);
2975                                 break;
2976                         case FORMAT_TYPE_SHORT:
2977                                 num = get_arg(short);
2978                                 break;
2979                         case FORMAT_TYPE_UINT:
2980                                 num = get_arg(unsigned int);
2981                                 break;
2982                         default:
2983                                 num = get_arg(int);
2984                         }
2985
2986                         str = number(str, end, num, spec);
2987                 } /* default: */
2988                 } /* switch(spec.type) */
2989         } /* while(*fmt) */
2990
2991 out:
2992         if (size > 0) {
2993                 if (str < end)
2994                         *str = '\0';
2995                 else
2996                         end[-1] = '\0';
2997         }
2998
2999 #undef get_arg
3000
3001         /* the trailing null byte doesn't count towards the total */
3002         return str - buf;
3003 }
3004 EXPORT_SYMBOL_GPL(bstr_printf);
3005
3006 /**
3007  * bprintf - Parse a format string and place args' binary value in a buffer
3008  * @bin_buf: The buffer to place args' binary value
3009  * @size: The size of the buffer(by words(32bits), not characters)
3010  * @fmt: The format string to use
3011  * @...: Arguments for the format string
3012  *
3013  * The function returns the number of words(u32) written
3014  * into @bin_buf.
3015  */
3016 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
3017 {
3018         va_list args;
3019         int ret;
3020
3021         va_start(args, fmt);
3022         ret = vbin_printf(bin_buf, size, fmt, args);
3023         va_end(args);
3024
3025         return ret;
3026 }
3027 EXPORT_SYMBOL_GPL(bprintf);
3028
3029 #endif /* CONFIG_BINARY_PRINTF */
3030
3031 /**
3032  * vsscanf - Unformat a buffer into a list of arguments
3033  * @buf:        input buffer
3034  * @fmt:        format of buffer
3035  * @args:       arguments
3036  */
3037 int vsscanf(const char *buf, const char *fmt, va_list args)
3038 {
3039         const char *str = buf;
3040         char *next;
3041         char digit;
3042         int num = 0;
3043         u8 qualifier;
3044         unsigned int base;
3045         union {
3046                 long long s;
3047                 unsigned long long u;
3048         } val;
3049         s16 field_width;
3050         bool is_sign;
3051
3052         while (*fmt) {
3053                 /* skip any white space in format */
3054                 /* white space in format matchs any amount of
3055                  * white space, including none, in the input.
3056                  */
3057                 if (isspace(*fmt)) {
3058                         fmt = skip_spaces(++fmt);
3059                         str = skip_spaces(str);
3060                 }
3061
3062                 /* anything that is not a conversion must match exactly */
3063                 if (*fmt != '%' && *fmt) {
3064                         if (*fmt++ != *str++)
3065                                 break;
3066                         continue;
3067                 }
3068
3069                 if (!*fmt)
3070                         break;
3071                 ++fmt;
3072
3073                 /* skip this conversion.
3074                  * advance both strings to next white space
3075                  */
3076                 if (*fmt == '*') {
3077                         if (!*str)
3078                                 break;
3079                         while (!isspace(*fmt) && *fmt != '%' && *fmt) {
3080                                 /* '%*[' not yet supported, invalid format */
3081                                 if (*fmt == '[')
3082                                         return num;
3083                                 fmt++;
3084                         }
3085                         while (!isspace(*str) && *str)
3086                                 str++;
3087                         continue;
3088                 }
3089
3090                 /* get field width */
3091                 field_width = -1;
3092                 if (isdigit(*fmt)) {
3093                         field_width = skip_atoi(&fmt);
3094                         if (field_width <= 0)
3095                                 break;
3096                 }
3097
3098                 /* get conversion qualifier */
3099                 qualifier = -1;
3100                 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
3101                     *fmt == 'z') {
3102                         qualifier = *fmt++;
3103                         if (unlikely(qualifier == *fmt)) {
3104                                 if (qualifier == 'h') {
3105                                         qualifier = 'H';
3106                                         fmt++;
3107                                 } else if (qualifier == 'l') {
3108                                         qualifier = 'L';
3109                                         fmt++;
3110                                 }
3111                         }
3112                 }
3113
3114                 if (!*fmt)
3115                         break;
3116
3117                 if (*fmt == 'n') {
3118                         /* return number of characters read so far */
3119                         *va_arg(args, int *) = str - buf;
3120                         ++fmt;
3121                         continue;
3122                 }
3123
3124                 if (!*str)
3125                         break;
3126
3127                 base = 10;
3128                 is_sign = false;
3129
3130                 switch (*fmt++) {
3131                 case 'c':
3132                 {
3133                         char *s = (char *)va_arg(args, char*);
3134                         if (field_width == -1)
3135                                 field_width = 1;
3136                         do {
3137                                 *s++ = *str++;
3138                         } while (--field_width > 0 && *str);
3139                         num++;
3140                 }
3141                 continue;
3142                 case 's':
3143                 {
3144                         char *s = (char *)va_arg(args, char *);
3145                         if (field_width == -1)
3146                                 field_width = SHRT_MAX;
3147                         /* first, skip leading white space in buffer */
3148                         str = skip_spaces(str);
3149
3150                         /* now copy until next white space */
3151                         while (*str && !isspace(*str) && field_width--)
3152                                 *s++ = *str++;
3153                         *s = '\0';
3154                         num++;
3155                 }
3156                 continue;
3157                 /*
3158                  * Warning: This implementation of the '[' conversion specifier
3159                  * deviates from its glibc counterpart in the following ways:
3160                  * (1) It does NOT support ranges i.e. '-' is NOT a special
3161                  *     character
3162                  * (2) It cannot match the closing bracket ']' itself
3163                  * (3) A field width is required
3164                  * (4) '%*[' (discard matching input) is currently not supported
3165                  *
3166                  * Example usage:
3167                  * ret = sscanf("00:0a:95","%2[^:]:%2[^:]:%2[^:]",
3168                  *              buf1, buf2, buf3);
3169                  * if (ret < 3)
3170                  *    // etc..
3171                  */
3172                 case '[':
3173                 {
3174                         char *s = (char *)va_arg(args, char *);
3175                         DECLARE_BITMAP(set, 256) = {0};
3176                         unsigned int len = 0;
3177                         bool negate = (*fmt == '^');
3178
3179                         /* field width is required */
3180                         if (field_width == -1)
3181                                 return num;
3182
3183                         if (negate)
3184                                 ++fmt;
3185
3186                         for ( ; *fmt && *fmt != ']'; ++fmt, ++len)
3187                                 set_bit((u8)*fmt, set);
3188
3189                         /* no ']' or no character set found */
3190                         if (!*fmt || !len)
3191                                 return num;
3192                         ++fmt;
3193
3194                         if (negate) {
3195                                 bitmap_complement(set, set, 256);
3196                                 /* exclude null '\0' byte */
3197                                 clear_bit(0, set);
3198                         }
3199
3200                         /* match must be non-empty */
3201                         if (!test_bit((u8)*str, set))
3202                                 return num;
3203
3204                         while (test_bit((u8)*str, set) && field_width--)
3205                                 *s++ = *str++;
3206                         *s = '\0';
3207                         ++num;
3208                 }
3209                 continue;
3210                 case 'o':
3211                         base = 8;
3212                         break;
3213                 case 'x':
3214                 case 'X':
3215                         base = 16;
3216                         break;
3217                 case 'i':
3218                         base = 0;
3219                         /* fall through */
3220                 case 'd':
3221                         is_sign = true;
3222                         /* fall through */
3223                 case 'u':
3224                         break;
3225                 case '%':
3226                         /* looking for '%' in str */
3227                         if (*str++ != '%')
3228                                 return num;
3229                         continue;
3230                 default:
3231                         /* invalid format; stop here */
3232                         return num;
3233                 }
3234
3235                 /* have some sort of integer conversion.
3236                  * first, skip white space in buffer.
3237                  */
3238                 str = skip_spaces(str);
3239
3240                 digit = *str;
3241                 if (is_sign && digit == '-')
3242                         digit = *(str + 1);
3243
3244                 if (!digit
3245                     || (base == 16 && !isxdigit(digit))
3246                     || (base == 10 && !isdigit(digit))
3247                     || (base == 8 && (!isdigit(digit) || digit > '7'))
3248                     || (base == 0 && !isdigit(digit)))
3249                         break;
3250
3251                 if (is_sign)
3252                         val.s = qualifier != 'L' ?
3253                                 simple_strtol(str, &next, base) :
3254                                 simple_strtoll(str, &next, base);
3255                 else
3256                         val.u = qualifier != 'L' ?
3257                                 simple_strtoul(str, &next, base) :
3258                                 simple_strtoull(str, &next, base);
3259
3260                 if (field_width > 0 && next - str > field_width) {
3261                         if (base == 0)
3262                                 _parse_integer_fixup_radix(str, &base);
3263                         while (next - str > field_width) {
3264                                 if (is_sign)
3265                                         val.s = div_s64(val.s, base);
3266                                 else
3267                                         val.u = div_u64(val.u, base);
3268                                 --next;
3269                         }
3270                 }
3271
3272                 switch (qualifier) {
3273                 case 'H':       /* that's 'hh' in format */
3274                         if (is_sign)
3275                                 *va_arg(args, signed char *) = val.s;
3276                         else
3277                                 *va_arg(args, unsigned char *) = val.u;
3278                         break;
3279                 case 'h':
3280                         if (is_sign)
3281                                 *va_arg(args, short *) = val.s;
3282                         else
3283                                 *va_arg(args, unsigned short *) = val.u;
3284                         break;
3285                 case 'l':
3286                         if (is_sign)
3287                                 *va_arg(args, long *) = val.s;
3288                         else
3289                                 *va_arg(args, unsigned long *) = val.u;
3290                         break;
3291                 case 'L':
3292                         if (is_sign)
3293                                 *va_arg(args, long long *) = val.s;
3294                         else
3295                                 *va_arg(args, unsigned long long *) = val.u;
3296                         break;
3297                 case 'z':
3298                         *va_arg(args, size_t *) = val.u;
3299                         break;
3300                 default:
3301                         if (is_sign)
3302                                 *va_arg(args, int *) = val.s;
3303                         else
3304                                 *va_arg(args, unsigned int *) = val.u;
3305                         break;
3306                 }
3307                 num++;
3308
3309                 if (!next)
3310                         break;
3311                 str = next;
3312         }
3313
3314         return num;
3315 }
3316 EXPORT_SYMBOL(vsscanf);
3317
3318 /**
3319  * sscanf - Unformat a buffer into a list of arguments
3320  * @buf:        input buffer
3321  * @fmt:        formatting of buffer
3322  * @...:        resulting arguments
3323  */
3324 int sscanf(const char *buf, const char *fmt, ...)
3325 {
3326         va_list args;
3327         int i;
3328
3329         va_start(args, fmt);
3330         i = vsscanf(buf, fmt, args);
3331         va_end(args);
3332
3333         return i;
3334 }
3335 EXPORT_SYMBOL(sscanf);