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