util_macros.h: add find_closest() macro
[cascardo/linux.git] / lib / vsprintf.c
1 /*
2  *  linux/lib/vsprintf.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
8 /*
9  * Wirzenius wrote this portably, Torvalds fucked it up :-)
10  */
11
12 /*
13  * Fri Jul 13 2001 Crutcher Dunnavant <crutcher+kernel@datastacks.com>
14  * - changed to provide snprintf and vsnprintf functions
15  * So Feb  1 16:51:32 CET 2004 Juergen Quade <quade@hsnr.de>
16  * - scnprintf and vscnprintf
17  */
18
19 #include <stdarg.h>
20 #include <linux/clk-provider.h>
21 #include <linux/module.h>       /* for KSYM_SYMBOL_LEN */
22 #include <linux/types.h>
23 #include <linux/string.h>
24 #include <linux/ctype.h>
25 #include <linux/kernel.h>
26 #include <linux/kallsyms.h>
27 #include <linux/math64.h>
28 #include <linux/uaccess.h>
29 #include <linux/ioport.h>
30 #include <linux/dcache.h>
31 #include <linux/cred.h>
32 #include <net/addrconf.h>
33
34 #include <asm/page.h>           /* for PAGE_SIZE */
35 #include <asm/sections.h>       /* for dereference_function_descriptor() */
36 #include <asm/byteorder.h>      /* cpu_to_le16 */
37
38 #include <linux/string_helpers.h>
39 #include "kstrtox.h"
40
41 /**
42  * simple_strtoull - convert a string to an unsigned long long
43  * @cp: The start of the string
44  * @endp: A pointer to the end of the parsed string will be placed here
45  * @base: The number base to use
46  *
47  * This function is obsolete. Please use kstrtoull instead.
48  */
49 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
50 {
51         unsigned long long result;
52         unsigned int rv;
53
54         cp = _parse_integer_fixup_radix(cp, &base);
55         rv = _parse_integer(cp, base, &result);
56         /* FIXME */
57         cp += (rv & ~KSTRTOX_OVERFLOW);
58
59         if (endp)
60                 *endp = (char *)cp;
61
62         return result;
63 }
64 EXPORT_SYMBOL(simple_strtoull);
65
66 /**
67  * simple_strtoul - convert a string to an unsigned long
68  * @cp: The start of the string
69  * @endp: A pointer to the end of the parsed string will be placed here
70  * @base: The number base to use
71  *
72  * This function is obsolete. Please use kstrtoul instead.
73  */
74 unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
75 {
76         return simple_strtoull(cp, endp, base);
77 }
78 EXPORT_SYMBOL(simple_strtoul);
79
80 /**
81  * simple_strtol - convert a string to a signed long
82  * @cp: The start of the string
83  * @endp: A pointer to the end of the parsed string will be placed here
84  * @base: The number base to use
85  *
86  * This function is obsolete. Please use kstrtol instead.
87  */
88 long simple_strtol(const char *cp, char **endp, unsigned int base)
89 {
90         if (*cp == '-')
91                 return -simple_strtoul(cp + 1, endp, base);
92
93         return simple_strtoul(cp, endp, base);
94 }
95 EXPORT_SYMBOL(simple_strtol);
96
97 /**
98  * simple_strtoll - convert a string to a signed long long
99  * @cp: The start of the string
100  * @endp: A pointer to the end of the parsed string will be placed here
101  * @base: The number base to use
102  *
103  * This function is obsolete. Please use kstrtoll instead.
104  */
105 long long simple_strtoll(const char *cp, char **endp, unsigned int base)
106 {
107         if (*cp == '-')
108                 return -simple_strtoull(cp + 1, endp, base);
109
110         return simple_strtoull(cp, endp, base);
111 }
112 EXPORT_SYMBOL(simple_strtoll);
113
114 static noinline_for_stack
115 int skip_atoi(const char **s)
116 {
117         int i = 0;
118
119         do {
120                 i = i*10 + *((*s)++) - '0';
121         } while (isdigit(**s));
122
123         return i;
124 }
125
126 /*
127  * Decimal conversion is by far the most typical, and is used for
128  * /proc and /sys data. This directly impacts e.g. top performance
129  * with many processes running. We optimize it for speed by emitting
130  * two characters at a time, using a 200 byte lookup table. This
131  * roughly halves the number of multiplications compared to computing
132  * the digits one at a time. Implementation strongly inspired by the
133  * previous version, which in turn used ideas described at
134  * <http://www.cs.uiowa.edu/~jones/bcd/divide.html> (with permission
135  * from the author, Douglas W. Jones).
136  *
137  * It turns out there is precisely one 26 bit fixed-point
138  * approximation a of 64/100 for which x/100 == (x * (u64)a) >> 32
139  * holds for all x in [0, 10^8-1], namely a = 0x28f5c29. The actual
140  * range happens to be somewhat larger (x <= 1073741898), but that's
141  * irrelevant for our purpose.
142  *
143  * For dividing a number in the range [10^4, 10^6-1] by 100, we still
144  * need a 32x32->64 bit multiply, so we simply use the same constant.
145  *
146  * For dividing a number in the range [100, 10^4-1] by 100, there are
147  * several options. The simplest is (x * 0x147b) >> 19, which is valid
148  * for all x <= 43698.
149  */
150
151 static const u16 decpair[100] = {
152 #define _(x) (__force u16) cpu_to_le16(((x % 10) | ((x / 10) << 8)) + 0x3030)
153         _( 0), _( 1), _( 2), _( 3), _( 4), _( 5), _( 6), _( 7), _( 8), _( 9),
154         _(10), _(11), _(12), _(13), _(14), _(15), _(16), _(17), _(18), _(19),
155         _(20), _(21), _(22), _(23), _(24), _(25), _(26), _(27), _(28), _(29),
156         _(30), _(31), _(32), _(33), _(34), _(35), _(36), _(37), _(38), _(39),
157         _(40), _(41), _(42), _(43), _(44), _(45), _(46), _(47), _(48), _(49),
158         _(50), _(51), _(52), _(53), _(54), _(55), _(56), _(57), _(58), _(59),
159         _(60), _(61), _(62), _(63), _(64), _(65), _(66), _(67), _(68), _(69),
160         _(70), _(71), _(72), _(73), _(74), _(75), _(76), _(77), _(78), _(79),
161         _(80), _(81), _(82), _(83), _(84), _(85), _(86), _(87), _(88), _(89),
162         _(90), _(91), _(92), _(93), _(94), _(95), _(96), _(97), _(98), _(99),
163 #undef _
164 };
165
166 /*
167  * This will print a single '0' even if r == 0, since we would
168  * immediately jump to out_r where two 0s would be written and one of
169  * them then discarded. This is needed by ip4_string below. All other
170  * callers pass a non-zero value of r.
171 */
172 static noinline_for_stack
173 char *put_dec_trunc8(char *buf, unsigned r)
174 {
175         unsigned q;
176
177         /* 1 <= r < 10^8 */
178         if (r < 100)
179                 goto out_r;
180
181         /* 100 <= r < 10^8 */
182         q = (r * (u64)0x28f5c29) >> 32;
183         *((u16 *)buf) = decpair[r - 100*q];
184         buf += 2;
185
186         /* 1 <= q < 10^6 */
187         if (q < 100)
188                 goto out_q;
189
190         /*  100 <= q < 10^6 */
191         r = (q * (u64)0x28f5c29) >> 32;
192         *((u16 *)buf) = decpair[q - 100*r];
193         buf += 2;
194
195         /* 1 <= r < 10^4 */
196         if (r < 100)
197                 goto out_r;
198
199         /* 100 <= r < 10^4 */
200         q = (r * 0x147b) >> 19;
201         *((u16 *)buf) = decpair[r - 100*q];
202         buf += 2;
203 out_q:
204         /* 1 <= q < 100 */
205         r = q;
206 out_r:
207         /* 1 <= r < 100 */
208         *((u16 *)buf) = decpair[r];
209         buf += 2;
210         if (buf[-1] == '0')
211                 buf--;
212         return buf;
213 }
214
215 #if BITS_PER_LONG == 64 && BITS_PER_LONG_LONG == 64
216 static noinline_for_stack
217 char *put_dec_full8(char *buf, unsigned r)
218 {
219         unsigned q;
220
221         /* 0 <= r < 10^8 */
222         q = (r * (u64)0x28f5c29) >> 32;
223         *((u16 *)buf) = decpair[r - 100*q];
224         buf += 2;
225
226         /* 0 <= q < 10^6 */
227         r = (q * (u64)0x28f5c29) >> 32;
228         *((u16 *)buf) = decpair[q - 100*r];
229         buf += 2;
230
231         /* 0 <= r < 10^4 */
232         q = (r * 0x147b) >> 19;
233         *((u16 *)buf) = decpair[r - 100*q];
234         buf += 2;
235
236         /* 0 <= q < 100 */
237         *((u16 *)buf) = decpair[q];
238         buf += 2;
239         return buf;
240 }
241
242 static noinline_for_stack
243 char *put_dec(char *buf, unsigned long long n)
244 {
245         if (n >= 100*1000*1000)
246                 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
247         /* 1 <= n <= 1.6e11 */
248         if (n >= 100*1000*1000)
249                 buf = put_dec_full8(buf, do_div(n, 100*1000*1000));
250         /* 1 <= n < 1e8 */
251         return put_dec_trunc8(buf, n);
252 }
253
254 #elif BITS_PER_LONG == 32 && BITS_PER_LONG_LONG == 64
255
256 static void
257 put_dec_full4(char *buf, unsigned r)
258 {
259         unsigned q;
260
261         /* 0 <= r < 10^4 */
262         q = (r * 0x147b) >> 19;
263         *((u16 *)buf) = decpair[r - 100*q];
264         buf += 2;
265         /* 0 <= q < 100 */
266         *((u16 *)buf) = decpair[q];
267 }
268
269 /*
270  * Call put_dec_full4 on x % 10000, return x / 10000.
271  * The approximation x/10000 == (x * 0x346DC5D7) >> 43
272  * holds for all x < 1,128,869,999.  The largest value this
273  * helper will ever be asked to convert is 1,125,520,955.
274  * (second call in the put_dec code, assuming n is all-ones).
275  */
276 static noinline_for_stack
277 unsigned put_dec_helper4(char *buf, unsigned x)
278 {
279         uint32_t q = (x * (uint64_t)0x346DC5D7) >> 43;
280
281         put_dec_full4(buf, x - q * 10000);
282         return q;
283 }
284
285 /* Based on code by Douglas W. Jones found at
286  * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour>
287  * (with permission from the author).
288  * Performs no 64-bit division and hence should be fast on 32-bit machines.
289  */
290 static
291 char *put_dec(char *buf, unsigned long long n)
292 {
293         uint32_t d3, d2, d1, q, h;
294
295         if (n < 100*1000*1000)
296                 return put_dec_trunc8(buf, n);
297
298         d1  = ((uint32_t)n >> 16); /* implicit "& 0xffff" */
299         h   = (n >> 32);
300         d2  = (h      ) & 0xffff;
301         d3  = (h >> 16); /* implicit "& 0xffff" */
302
303         /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0
304              = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */
305         q   = 656 * d3 + 7296 * d2 + 5536 * d1 + ((uint32_t)n & 0xffff);
306         q = put_dec_helper4(buf, q);
307
308         q += 7671 * d3 + 9496 * d2 + 6 * d1;
309         q = put_dec_helper4(buf+4, q);
310
311         q += 4749 * d3 + 42 * d2;
312         q = put_dec_helper4(buf+8, q);
313
314         q += 281 * d3;
315         buf += 12;
316         if (q)
317                 buf = put_dec_trunc8(buf, q);
318         else while (buf[-1] == '0')
319                 --buf;
320
321         return buf;
322 }
323
324 #endif
325
326 /*
327  * Convert passed number to decimal string.
328  * Returns the length of string.  On buffer overflow, returns 0.
329  *
330  * If speed is not important, use snprintf(). It's easy to read the code.
331  */
332 int num_to_str(char *buf, int size, unsigned long long num)
333 {
334         /* put_dec requires 2-byte alignment of the buffer. */
335         char tmp[sizeof(num) * 3] __aligned(2);
336         int idx, len;
337
338         /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
339         if (num <= 9) {
340                 tmp[0] = '0' + num;
341                 len = 1;
342         } else {
343                 len = put_dec(tmp, num) - tmp;
344         }
345
346         if (len > size)
347                 return 0;
348         for (idx = 0; idx < len; ++idx)
349                 buf[idx] = tmp[len - idx - 1];
350         return len;
351 }
352
353 #define SIGN    1               /* unsigned/signed, must be 1 */
354 #define LEFT    2               /* left justified */
355 #define PLUS    4               /* show plus */
356 #define SPACE   8               /* space if plus */
357 #define ZEROPAD 16              /* pad with zero, must be 16 == '0' - ' ' */
358 #define SMALL   32              /* use lowercase in hex (must be 32 == 0x20) */
359 #define SPECIAL 64              /* prefix hex with "0x", octal with "0" */
360
361 enum format_type {
362         FORMAT_TYPE_NONE, /* Just a string part */
363         FORMAT_TYPE_WIDTH,
364         FORMAT_TYPE_PRECISION,
365         FORMAT_TYPE_CHAR,
366         FORMAT_TYPE_STR,
367         FORMAT_TYPE_PTR,
368         FORMAT_TYPE_PERCENT_CHAR,
369         FORMAT_TYPE_INVALID,
370         FORMAT_TYPE_LONG_LONG,
371         FORMAT_TYPE_ULONG,
372         FORMAT_TYPE_LONG,
373         FORMAT_TYPE_UBYTE,
374         FORMAT_TYPE_BYTE,
375         FORMAT_TYPE_USHORT,
376         FORMAT_TYPE_SHORT,
377         FORMAT_TYPE_UINT,
378         FORMAT_TYPE_INT,
379         FORMAT_TYPE_SIZE_T,
380         FORMAT_TYPE_PTRDIFF
381 };
382
383 struct printf_spec {
384         u8      type;           /* format_type enum */
385         u8      flags;          /* flags to number() */
386         u8      base;           /* number base, 8, 10 or 16 only */
387         u8      qualifier;      /* number qualifier, one of 'hHlLtzZ' */
388         s16     field_width;    /* width of output field */
389         s16     precision;      /* # of digits/chars */
390 };
391
392 static noinline_for_stack
393 char *number(char *buf, char *end, unsigned long long num,
394              struct printf_spec spec)
395 {
396         /* put_dec requires 2-byte alignment of the buffer. */
397         char tmp[3 * sizeof(num)] __aligned(2);
398         char sign;
399         char locase;
400         int need_pfx = ((spec.flags & SPECIAL) && spec.base != 10);
401         int i;
402         bool is_zero = num == 0LL;
403
404         /* locase = 0 or 0x20. ORing digits or letters with 'locase'
405          * produces same digits or (maybe lowercased) letters */
406         locase = (spec.flags & SMALL);
407         if (spec.flags & LEFT)
408                 spec.flags &= ~ZEROPAD;
409         sign = 0;
410         if (spec.flags & SIGN) {
411                 if ((signed long long)num < 0) {
412                         sign = '-';
413                         num = -(signed long long)num;
414                         spec.field_width--;
415                 } else if (spec.flags & PLUS) {
416                         sign = '+';
417                         spec.field_width--;
418                 } else if (spec.flags & SPACE) {
419                         sign = ' ';
420                         spec.field_width--;
421                 }
422         }
423         if (need_pfx) {
424                 if (spec.base == 16)
425                         spec.field_width -= 2;
426                 else if (!is_zero)
427                         spec.field_width--;
428         }
429
430         /* generate full string in tmp[], in reverse order */
431         i = 0;
432         if (num < spec.base)
433                 tmp[i++] = hex_asc_upper[num] | locase;
434         else if (spec.base != 10) { /* 8 or 16 */
435                 int mask = spec.base - 1;
436                 int shift = 3;
437
438                 if (spec.base == 16)
439                         shift = 4;
440                 do {
441                         tmp[i++] = (hex_asc_upper[((unsigned char)num) & mask] | locase);
442                         num >>= shift;
443                 } while (num);
444         } else { /* base 10 */
445                 i = put_dec(tmp, num) - tmp;
446         }
447
448         /* printing 100 using %2d gives "100", not "00" */
449         if (i > spec.precision)
450                 spec.precision = i;
451         /* leading space padding */
452         spec.field_width -= spec.precision;
453         if (!(spec.flags & (ZEROPAD | LEFT))) {
454                 while (--spec.field_width >= 0) {
455                         if (buf < end)
456                                 *buf = ' ';
457                         ++buf;
458                 }
459         }
460         /* sign */
461         if (sign) {
462                 if (buf < end)
463                         *buf = sign;
464                 ++buf;
465         }
466         /* "0x" / "0" prefix */
467         if (need_pfx) {
468                 if (spec.base == 16 || !is_zero) {
469                         if (buf < end)
470                                 *buf = '0';
471                         ++buf;
472                 }
473                 if (spec.base == 16) {
474                         if (buf < end)
475                                 *buf = ('X' | locase);
476                         ++buf;
477                 }
478         }
479         /* zero or space padding */
480         if (!(spec.flags & LEFT)) {
481                 char c = ' ' + (spec.flags & ZEROPAD);
482                 BUILD_BUG_ON(' ' + ZEROPAD != '0');
483                 while (--spec.field_width >= 0) {
484                         if (buf < end)
485                                 *buf = c;
486                         ++buf;
487                 }
488         }
489         /* hmm even more zero padding? */
490         while (i <= --spec.precision) {
491                 if (buf < end)
492                         *buf = '0';
493                 ++buf;
494         }
495         /* actual digits of result */
496         while (--i >= 0) {
497                 if (buf < end)
498                         *buf = tmp[i];
499                 ++buf;
500         }
501         /* trailing space padding */
502         while (--spec.field_width >= 0) {
503                 if (buf < end)
504                         *buf = ' ';
505                 ++buf;
506         }
507
508         return buf;
509 }
510
511 static noinline_for_stack
512 char *string(char *buf, char *end, const char *s, struct printf_spec spec)
513 {
514         int len, i;
515
516         if ((unsigned long)s < PAGE_SIZE)
517                 s = "(null)";
518
519         len = strnlen(s, spec.precision);
520
521         if (!(spec.flags & LEFT)) {
522                 while (len < spec.field_width--) {
523                         if (buf < end)
524                                 *buf = ' ';
525                         ++buf;
526                 }
527         }
528         for (i = 0; i < len; ++i) {
529                 if (buf < end)
530                         *buf = *s;
531                 ++buf; ++s;
532         }
533         while (len < spec.field_width--) {
534                 if (buf < end)
535                         *buf = ' ';
536                 ++buf;
537         }
538
539         return buf;
540 }
541
542 static void widen(char *buf, char *end, unsigned len, unsigned spaces)
543 {
544         size_t size;
545         if (buf >= end) /* nowhere to put anything */
546                 return;
547         size = end - buf;
548         if (size <= spaces) {
549                 memset(buf, ' ', size);
550                 return;
551         }
552         if (len) {
553                 if (len > size - spaces)
554                         len = size - spaces;
555                 memmove(buf + spaces, buf, len);
556         }
557         memset(buf, ' ', spaces);
558 }
559
560 static noinline_for_stack
561 char *dentry_name(char *buf, char *end, const struct dentry *d, struct printf_spec spec,
562                   const char *fmt)
563 {
564         const char *array[4], *s;
565         const struct dentry *p;
566         int depth;
567         int i, n;
568
569         switch (fmt[1]) {
570                 case '2': case '3': case '4':
571                         depth = fmt[1] - '0';
572                         break;
573                 default:
574                         depth = 1;
575         }
576
577         rcu_read_lock();
578         for (i = 0; i < depth; i++, d = p) {
579                 p = ACCESS_ONCE(d->d_parent);
580                 array[i] = ACCESS_ONCE(d->d_name.name);
581                 if (p == d) {
582                         if (i)
583                                 array[i] = "";
584                         i++;
585                         break;
586                 }
587         }
588         s = array[--i];
589         for (n = 0; n != spec.precision; n++, buf++) {
590                 char c = *s++;
591                 if (!c) {
592                         if (!i)
593                                 break;
594                         c = '/';
595                         s = array[--i];
596                 }
597                 if (buf < end)
598                         *buf = c;
599         }
600         rcu_read_unlock();
601         if (n < spec.field_width) {
602                 /* we want to pad the sucker */
603                 unsigned spaces = spec.field_width - n;
604                 if (!(spec.flags & LEFT)) {
605                         widen(buf - n, end, n, spaces);
606                         return buf + spaces;
607                 }
608                 while (spaces--) {
609                         if (buf < end)
610                                 *buf = ' ';
611                         ++buf;
612                 }
613         }
614         return buf;
615 }
616
617 static noinline_for_stack
618 char *symbol_string(char *buf, char *end, void *ptr,
619                     struct printf_spec spec, const char *fmt)
620 {
621         unsigned long value;
622 #ifdef CONFIG_KALLSYMS
623         char sym[KSYM_SYMBOL_LEN];
624 #endif
625
626         if (fmt[1] == 'R')
627                 ptr = __builtin_extract_return_addr(ptr);
628         value = (unsigned long)ptr;
629
630 #ifdef CONFIG_KALLSYMS
631         if (*fmt == 'B')
632                 sprint_backtrace(sym, value);
633         else if (*fmt != 'f' && *fmt != 's')
634                 sprint_symbol(sym, value);
635         else
636                 sprint_symbol_no_offset(sym, value);
637
638         return string(buf, end, sym, spec);
639 #else
640         spec.field_width = 2 * sizeof(void *);
641         spec.flags |= SPECIAL | SMALL | ZEROPAD;
642         spec.base = 16;
643
644         return number(buf, end, value, spec);
645 #endif
646 }
647
648 static noinline_for_stack
649 char *resource_string(char *buf, char *end, struct resource *res,
650                       struct printf_spec spec, const char *fmt)
651 {
652 #ifndef IO_RSRC_PRINTK_SIZE
653 #define IO_RSRC_PRINTK_SIZE     6
654 #endif
655
656 #ifndef MEM_RSRC_PRINTK_SIZE
657 #define MEM_RSRC_PRINTK_SIZE    10
658 #endif
659         static const struct printf_spec io_spec = {
660                 .base = 16,
661                 .field_width = IO_RSRC_PRINTK_SIZE,
662                 .precision = -1,
663                 .flags = SPECIAL | SMALL | ZEROPAD,
664         };
665         static const struct printf_spec mem_spec = {
666                 .base = 16,
667                 .field_width = MEM_RSRC_PRINTK_SIZE,
668                 .precision = -1,
669                 .flags = SPECIAL | SMALL | ZEROPAD,
670         };
671         static const struct printf_spec bus_spec = {
672                 .base = 16,
673                 .field_width = 2,
674                 .precision = -1,
675                 .flags = SMALL | ZEROPAD,
676         };
677         static const struct printf_spec dec_spec = {
678                 .base = 10,
679                 .precision = -1,
680                 .flags = 0,
681         };
682         static const struct printf_spec str_spec = {
683                 .field_width = -1,
684                 .precision = 10,
685                 .flags = LEFT,
686         };
687         static const struct printf_spec flag_spec = {
688                 .base = 16,
689                 .precision = -1,
690                 .flags = SPECIAL | SMALL,
691         };
692
693         /* 32-bit res (sizeof==4): 10 chars in dec, 10 in hex ("0x" + 8)
694          * 64-bit res (sizeof==8): 20 chars in dec, 18 in hex ("0x" + 16) */
695 #define RSRC_BUF_SIZE           ((2 * sizeof(resource_size_t)) + 4)
696 #define FLAG_BUF_SIZE           (2 * sizeof(res->flags))
697 #define DECODED_BUF_SIZE        sizeof("[mem - 64bit pref window disabled]")
698 #define RAW_BUF_SIZE            sizeof("[mem - flags 0x]")
699         char sym[max(2*RSRC_BUF_SIZE + DECODED_BUF_SIZE,
700                      2*RSRC_BUF_SIZE + FLAG_BUF_SIZE + RAW_BUF_SIZE)];
701
702         char *p = sym, *pend = sym + sizeof(sym);
703         int decode = (fmt[0] == 'R') ? 1 : 0;
704         const struct printf_spec *specp;
705
706         *p++ = '[';
707         if (res->flags & IORESOURCE_IO) {
708                 p = string(p, pend, "io  ", str_spec);
709                 specp = &io_spec;
710         } else if (res->flags & IORESOURCE_MEM) {
711                 p = string(p, pend, "mem ", str_spec);
712                 specp = &mem_spec;
713         } else if (res->flags & IORESOURCE_IRQ) {
714                 p = string(p, pend, "irq ", str_spec);
715                 specp = &dec_spec;
716         } else if (res->flags & IORESOURCE_DMA) {
717                 p = string(p, pend, "dma ", str_spec);
718                 specp = &dec_spec;
719         } else if (res->flags & IORESOURCE_BUS) {
720                 p = string(p, pend, "bus ", str_spec);
721                 specp = &bus_spec;
722         } else {
723                 p = string(p, pend, "??? ", str_spec);
724                 specp = &mem_spec;
725                 decode = 0;
726         }
727         if (decode && res->flags & IORESOURCE_UNSET) {
728                 p = string(p, pend, "size ", str_spec);
729                 p = number(p, pend, resource_size(res), *specp);
730         } else {
731                 p = number(p, pend, res->start, *specp);
732                 if (res->start != res->end) {
733                         *p++ = '-';
734                         p = number(p, pend, res->end, *specp);
735                 }
736         }
737         if (decode) {
738                 if (res->flags & IORESOURCE_MEM_64)
739                         p = string(p, pend, " 64bit", str_spec);
740                 if (res->flags & IORESOURCE_PREFETCH)
741                         p = string(p, pend, " pref", str_spec);
742                 if (res->flags & IORESOURCE_WINDOW)
743                         p = string(p, pend, " window", str_spec);
744                 if (res->flags & IORESOURCE_DISABLED)
745                         p = string(p, pend, " disabled", str_spec);
746         } else {
747                 p = string(p, pend, " flags ", str_spec);
748                 p = number(p, pend, res->flags, flag_spec);
749         }
750         *p++ = ']';
751         *p = '\0';
752
753         return string(buf, end, sym, spec);
754 }
755
756 static noinline_for_stack
757 char *hex_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
758                  const char *fmt)
759 {
760         int i, len = 1;         /* if we pass '%ph[CDN]', field width remains
761                                    negative value, fallback to the default */
762         char separator;
763
764         if (spec.field_width == 0)
765                 /* nothing to print */
766                 return buf;
767
768         if (ZERO_OR_NULL_PTR(addr))
769                 /* NULL pointer */
770                 return string(buf, end, NULL, spec);
771
772         switch (fmt[1]) {
773         case 'C':
774                 separator = ':';
775                 break;
776         case 'D':
777                 separator = '-';
778                 break;
779         case 'N':
780                 separator = 0;
781                 break;
782         default:
783                 separator = ' ';
784                 break;
785         }
786
787         if (spec.field_width > 0)
788                 len = min_t(int, spec.field_width, 64);
789
790         for (i = 0; i < len; ++i) {
791                 if (buf < end)
792                         *buf = hex_asc_hi(addr[i]);
793                 ++buf;
794                 if (buf < end)
795                         *buf = hex_asc_lo(addr[i]);
796                 ++buf;
797
798                 if (separator && i != len - 1) {
799                         if (buf < end)
800                                 *buf = separator;
801                         ++buf;
802                 }
803         }
804
805         return buf;
806 }
807
808 static noinline_for_stack
809 char *bitmap_string(char *buf, char *end, unsigned long *bitmap,
810                     struct printf_spec spec, const char *fmt)
811 {
812         const int CHUNKSZ = 32;
813         int nr_bits = max_t(int, spec.field_width, 0);
814         int i, chunksz;
815         bool first = true;
816
817         /* reused to print numbers */
818         spec = (struct printf_spec){ .flags = SMALL | ZEROPAD, .base = 16 };
819
820         chunksz = nr_bits & (CHUNKSZ - 1);
821         if (chunksz == 0)
822                 chunksz = CHUNKSZ;
823
824         i = ALIGN(nr_bits, CHUNKSZ) - CHUNKSZ;
825         for (; i >= 0; i -= CHUNKSZ) {
826                 u32 chunkmask, val;
827                 int word, bit;
828
829                 chunkmask = ((1ULL << chunksz) - 1);
830                 word = i / BITS_PER_LONG;
831                 bit = i % BITS_PER_LONG;
832                 val = (bitmap[word] >> bit) & chunkmask;
833
834                 if (!first) {
835                         if (buf < end)
836                                 *buf = ',';
837                         buf++;
838                 }
839                 first = false;
840
841                 spec.field_width = DIV_ROUND_UP(chunksz, 4);
842                 buf = number(buf, end, val, spec);
843
844                 chunksz = CHUNKSZ;
845         }
846         return buf;
847 }
848
849 static noinline_for_stack
850 char *bitmap_list_string(char *buf, char *end, unsigned long *bitmap,
851                          struct printf_spec spec, const char *fmt)
852 {
853         int nr_bits = max_t(int, spec.field_width, 0);
854         /* current bit is 'cur', most recently seen range is [rbot, rtop] */
855         int cur, rbot, rtop;
856         bool first = true;
857
858         /* reused to print numbers */
859         spec = (struct printf_spec){ .base = 10 };
860
861         rbot = cur = find_first_bit(bitmap, nr_bits);
862         while (cur < nr_bits) {
863                 rtop = cur;
864                 cur = find_next_bit(bitmap, nr_bits, cur + 1);
865                 if (cur < nr_bits && cur <= rtop + 1)
866                         continue;
867
868                 if (!first) {
869                         if (buf < end)
870                                 *buf = ',';
871                         buf++;
872                 }
873                 first = false;
874
875                 buf = number(buf, end, rbot, spec);
876                 if (rbot < rtop) {
877                         if (buf < end)
878                                 *buf = '-';
879                         buf++;
880
881                         buf = number(buf, end, rtop, spec);
882                 }
883
884                 rbot = cur;
885         }
886         return buf;
887 }
888
889 static noinline_for_stack
890 char *mac_address_string(char *buf, char *end, u8 *addr,
891                          struct printf_spec spec, const char *fmt)
892 {
893         char mac_addr[sizeof("xx:xx:xx:xx:xx:xx")];
894         char *p = mac_addr;
895         int i;
896         char separator;
897         bool reversed = false;
898
899         switch (fmt[1]) {
900         case 'F':
901                 separator = '-';
902                 break;
903
904         case 'R':
905                 reversed = true;
906                 /* fall through */
907
908         default:
909                 separator = ':';
910                 break;
911         }
912
913         for (i = 0; i < 6; i++) {
914                 if (reversed)
915                         p = hex_byte_pack(p, addr[5 - i]);
916                 else
917                         p = hex_byte_pack(p, addr[i]);
918
919                 if (fmt[0] == 'M' && i != 5)
920                         *p++ = separator;
921         }
922         *p = '\0';
923
924         return string(buf, end, mac_addr, spec);
925 }
926
927 static noinline_for_stack
928 char *ip4_string(char *p, const u8 *addr, const char *fmt)
929 {
930         int i;
931         bool leading_zeros = (fmt[0] == 'i');
932         int index;
933         int step;
934
935         switch (fmt[2]) {
936         case 'h':
937 #ifdef __BIG_ENDIAN
938                 index = 0;
939                 step = 1;
940 #else
941                 index = 3;
942                 step = -1;
943 #endif
944                 break;
945         case 'l':
946                 index = 3;
947                 step = -1;
948                 break;
949         case 'n':
950         case 'b':
951         default:
952                 index = 0;
953                 step = 1;
954                 break;
955         }
956         for (i = 0; i < 4; i++) {
957                 char temp[4] __aligned(2);      /* hold each IP quad in reverse order */
958                 int digits = put_dec_trunc8(temp, addr[index]) - temp;
959                 if (leading_zeros) {
960                         if (digits < 3)
961                                 *p++ = '0';
962                         if (digits < 2)
963                                 *p++ = '0';
964                 }
965                 /* reverse the digits in the quad */
966                 while (digits--)
967                         *p++ = temp[digits];
968                 if (i < 3)
969                         *p++ = '.';
970                 index += step;
971         }
972         *p = '\0';
973
974         return p;
975 }
976
977 static noinline_for_stack
978 char *ip6_compressed_string(char *p, const char *addr)
979 {
980         int i, j, range;
981         unsigned char zerolength[8];
982         int longest = 1;
983         int colonpos = -1;
984         u16 word;
985         u8 hi, lo;
986         bool needcolon = false;
987         bool useIPv4;
988         struct in6_addr in6;
989
990         memcpy(&in6, addr, sizeof(struct in6_addr));
991
992         useIPv4 = ipv6_addr_v4mapped(&in6) || ipv6_addr_is_isatap(&in6);
993
994         memset(zerolength, 0, sizeof(zerolength));
995
996         if (useIPv4)
997                 range = 6;
998         else
999                 range = 8;
1000
1001         /* find position of longest 0 run */
1002         for (i = 0; i < range; i++) {
1003                 for (j = i; j < range; j++) {
1004                         if (in6.s6_addr16[j] != 0)
1005                                 break;
1006                         zerolength[i]++;
1007                 }
1008         }
1009         for (i = 0; i < range; i++) {
1010                 if (zerolength[i] > longest) {
1011                         longest = zerolength[i];
1012                         colonpos = i;
1013                 }
1014         }
1015         if (longest == 1)               /* don't compress a single 0 */
1016                 colonpos = -1;
1017
1018         /* emit address */
1019         for (i = 0; i < range; i++) {
1020                 if (i == colonpos) {
1021                         if (needcolon || i == 0)
1022                                 *p++ = ':';
1023                         *p++ = ':';
1024                         needcolon = false;
1025                         i += longest - 1;
1026                         continue;
1027                 }
1028                 if (needcolon) {
1029                         *p++ = ':';
1030                         needcolon = false;
1031                 }
1032                 /* hex u16 without leading 0s */
1033                 word = ntohs(in6.s6_addr16[i]);
1034                 hi = word >> 8;
1035                 lo = word & 0xff;
1036                 if (hi) {
1037                         if (hi > 0x0f)
1038                                 p = hex_byte_pack(p, hi);
1039                         else
1040                                 *p++ = hex_asc_lo(hi);
1041                         p = hex_byte_pack(p, lo);
1042                 }
1043                 else if (lo > 0x0f)
1044                         p = hex_byte_pack(p, lo);
1045                 else
1046                         *p++ = hex_asc_lo(lo);
1047                 needcolon = true;
1048         }
1049
1050         if (useIPv4) {
1051                 if (needcolon)
1052                         *p++ = ':';
1053                 p = ip4_string(p, &in6.s6_addr[12], "I4");
1054         }
1055         *p = '\0';
1056
1057         return p;
1058 }
1059
1060 static noinline_for_stack
1061 char *ip6_string(char *p, const char *addr, const char *fmt)
1062 {
1063         int i;
1064
1065         for (i = 0; i < 8; i++) {
1066                 p = hex_byte_pack(p, *addr++);
1067                 p = hex_byte_pack(p, *addr++);
1068                 if (fmt[0] == 'I' && i != 7)
1069                         *p++ = ':';
1070         }
1071         *p = '\0';
1072
1073         return p;
1074 }
1075
1076 static noinline_for_stack
1077 char *ip6_addr_string(char *buf, char *end, const u8 *addr,
1078                       struct printf_spec spec, const char *fmt)
1079 {
1080         char ip6_addr[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255")];
1081
1082         if (fmt[0] == 'I' && fmt[2] == 'c')
1083                 ip6_compressed_string(ip6_addr, addr);
1084         else
1085                 ip6_string(ip6_addr, addr, fmt);
1086
1087         return string(buf, end, ip6_addr, spec);
1088 }
1089
1090 static noinline_for_stack
1091 char *ip4_addr_string(char *buf, char *end, const u8 *addr,
1092                       struct printf_spec spec, const char *fmt)
1093 {
1094         char ip4_addr[sizeof("255.255.255.255")];
1095
1096         ip4_string(ip4_addr, addr, fmt);
1097
1098         return string(buf, end, ip4_addr, spec);
1099 }
1100
1101 static noinline_for_stack
1102 char *ip6_addr_string_sa(char *buf, char *end, const struct sockaddr_in6 *sa,
1103                          struct printf_spec spec, const char *fmt)
1104 {
1105         bool have_p = false, have_s = false, have_f = false, have_c = false;
1106         char ip6_addr[sizeof("[xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255]") +
1107                       sizeof(":12345") + sizeof("/123456789") +
1108                       sizeof("%1234567890")];
1109         char *p = ip6_addr, *pend = ip6_addr + sizeof(ip6_addr);
1110         const u8 *addr = (const u8 *) &sa->sin6_addr;
1111         char fmt6[2] = { fmt[0], '6' };
1112         u8 off = 0;
1113
1114         fmt++;
1115         while (isalpha(*++fmt)) {
1116                 switch (*fmt) {
1117                 case 'p':
1118                         have_p = true;
1119                         break;
1120                 case 'f':
1121                         have_f = true;
1122                         break;
1123                 case 's':
1124                         have_s = true;
1125                         break;
1126                 case 'c':
1127                         have_c = true;
1128                         break;
1129                 }
1130         }
1131
1132         if (have_p || have_s || have_f) {
1133                 *p = '[';
1134                 off = 1;
1135         }
1136
1137         if (fmt6[0] == 'I' && have_c)
1138                 p = ip6_compressed_string(ip6_addr + off, addr);
1139         else
1140                 p = ip6_string(ip6_addr + off, addr, fmt6);
1141
1142         if (have_p || have_s || have_f)
1143                 *p++ = ']';
1144
1145         if (have_p) {
1146                 *p++ = ':';
1147                 p = number(p, pend, ntohs(sa->sin6_port), spec);
1148         }
1149         if (have_f) {
1150                 *p++ = '/';
1151                 p = number(p, pend, ntohl(sa->sin6_flowinfo &
1152                                           IPV6_FLOWINFO_MASK), spec);
1153         }
1154         if (have_s) {
1155                 *p++ = '%';
1156                 p = number(p, pend, sa->sin6_scope_id, spec);
1157         }
1158         *p = '\0';
1159
1160         return string(buf, end, ip6_addr, spec);
1161 }
1162
1163 static noinline_for_stack
1164 char *ip4_addr_string_sa(char *buf, char *end, const struct sockaddr_in *sa,
1165                          struct printf_spec spec, const char *fmt)
1166 {
1167         bool have_p = false;
1168         char *p, ip4_addr[sizeof("255.255.255.255") + sizeof(":12345")];
1169         char *pend = ip4_addr + sizeof(ip4_addr);
1170         const u8 *addr = (const u8 *) &sa->sin_addr.s_addr;
1171         char fmt4[3] = { fmt[0], '4', 0 };
1172
1173         fmt++;
1174         while (isalpha(*++fmt)) {
1175                 switch (*fmt) {
1176                 case 'p':
1177                         have_p = true;
1178                         break;
1179                 case 'h':
1180                 case 'l':
1181                 case 'n':
1182                 case 'b':
1183                         fmt4[2] = *fmt;
1184                         break;
1185                 }
1186         }
1187
1188         p = ip4_string(ip4_addr, addr, fmt4);
1189         if (have_p) {
1190                 *p++ = ':';
1191                 p = number(p, pend, ntohs(sa->sin_port), spec);
1192         }
1193         *p = '\0';
1194
1195         return string(buf, end, ip4_addr, spec);
1196 }
1197
1198 static noinline_for_stack
1199 char *escaped_string(char *buf, char *end, u8 *addr, struct printf_spec spec,
1200                      const char *fmt)
1201 {
1202         bool found = true;
1203         int count = 1;
1204         unsigned int flags = 0;
1205         int len;
1206
1207         if (spec.field_width == 0)
1208                 return buf;                             /* nothing to print */
1209
1210         if (ZERO_OR_NULL_PTR(addr))
1211                 return string(buf, end, NULL, spec);    /* NULL pointer */
1212
1213
1214         do {
1215                 switch (fmt[count++]) {
1216                 case 'a':
1217                         flags |= ESCAPE_ANY;
1218                         break;
1219                 case 'c':
1220                         flags |= ESCAPE_SPECIAL;
1221                         break;
1222                 case 'h':
1223                         flags |= ESCAPE_HEX;
1224                         break;
1225                 case 'n':
1226                         flags |= ESCAPE_NULL;
1227                         break;
1228                 case 'o':
1229                         flags |= ESCAPE_OCTAL;
1230                         break;
1231                 case 'p':
1232                         flags |= ESCAPE_NP;
1233                         break;
1234                 case 's':
1235                         flags |= ESCAPE_SPACE;
1236                         break;
1237                 default:
1238                         found = false;
1239                         break;
1240                 }
1241         } while (found);
1242
1243         if (!flags)
1244                 flags = ESCAPE_ANY_NP;
1245
1246         len = spec.field_width < 0 ? 1 : spec.field_width;
1247
1248         /*
1249          * string_escape_mem() writes as many characters as it can to
1250          * the given buffer, and returns the total size of the output
1251          * had the buffer been big enough.
1252          */
1253         buf += string_escape_mem(addr, len, buf, buf < end ? end - buf : 0, flags, NULL);
1254
1255         return buf;
1256 }
1257
1258 static noinline_for_stack
1259 char *uuid_string(char *buf, char *end, const u8 *addr,
1260                   struct printf_spec spec, const char *fmt)
1261 {
1262         char uuid[sizeof("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")];
1263         char *p = uuid;
1264         int i;
1265         static const u8 be[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
1266         static const u8 le[16] = {3,2,1,0,5,4,7,6,8,9,10,11,12,13,14,15};
1267         const u8 *index = be;
1268         bool uc = false;
1269
1270         switch (*(++fmt)) {
1271         case 'L':
1272                 uc = true;              /* fall-through */
1273         case 'l':
1274                 index = le;
1275                 break;
1276         case 'B':
1277                 uc = true;
1278                 break;
1279         }
1280
1281         for (i = 0; i < 16; i++) {
1282                 p = hex_byte_pack(p, addr[index[i]]);
1283                 switch (i) {
1284                 case 3:
1285                 case 5:
1286                 case 7:
1287                 case 9:
1288                         *p++ = '-';
1289                         break;
1290                 }
1291         }
1292
1293         *p = 0;
1294
1295         if (uc) {
1296                 p = uuid;
1297                 do {
1298                         *p = toupper(*p);
1299                 } while (*(++p));
1300         }
1301
1302         return string(buf, end, uuid, spec);
1303 }
1304
1305 static
1306 char *netdev_feature_string(char *buf, char *end, const u8 *addr,
1307                       struct printf_spec spec)
1308 {
1309         spec.flags |= SPECIAL | SMALL | ZEROPAD;
1310         if (spec.field_width == -1)
1311                 spec.field_width = 2 + 2 * sizeof(netdev_features_t);
1312         spec.base = 16;
1313
1314         return number(buf, end, *(const netdev_features_t *)addr, spec);
1315 }
1316
1317 static noinline_for_stack
1318 char *address_val(char *buf, char *end, const void *addr,
1319                   struct printf_spec spec, const char *fmt)
1320 {
1321         unsigned long long num;
1322
1323         spec.flags |= SPECIAL | SMALL | ZEROPAD;
1324         spec.base = 16;
1325
1326         switch (fmt[1]) {
1327         case 'd':
1328                 num = *(const dma_addr_t *)addr;
1329                 spec.field_width = sizeof(dma_addr_t) * 2 + 2;
1330                 break;
1331         case 'p':
1332         default:
1333                 num = *(const phys_addr_t *)addr;
1334                 spec.field_width = sizeof(phys_addr_t) * 2 + 2;
1335                 break;
1336         }
1337
1338         return number(buf, end, num, spec);
1339 }
1340
1341 static noinline_for_stack
1342 char *clock(char *buf, char *end, struct clk *clk, struct printf_spec spec,
1343             const char *fmt)
1344 {
1345         if (!IS_ENABLED(CONFIG_HAVE_CLK) || !clk)
1346                 return string(buf, end, NULL, spec);
1347
1348         switch (fmt[1]) {
1349         case 'r':
1350                 return number(buf, end, clk_get_rate(clk), spec);
1351
1352         case 'n':
1353         default:
1354 #ifdef CONFIG_COMMON_CLK
1355                 return string(buf, end, __clk_get_name(clk), spec);
1356 #else
1357                 spec.base = 16;
1358                 spec.field_width = sizeof(unsigned long) * 2 + 2;
1359                 spec.flags |= SPECIAL | SMALL | ZEROPAD;
1360                 return number(buf, end, (unsigned long)clk, spec);
1361 #endif
1362         }
1363 }
1364
1365 int kptr_restrict __read_mostly;
1366
1367 /*
1368  * Show a '%p' thing.  A kernel extension is that the '%p' is followed
1369  * by an extra set of alphanumeric characters that are extended format
1370  * specifiers.
1371  *
1372  * Right now we handle:
1373  *
1374  * - 'F' For symbolic function descriptor pointers with offset
1375  * - 'f' For simple symbolic function names without offset
1376  * - 'S' For symbolic direct pointers with offset
1377  * - 's' For symbolic direct pointers without offset
1378  * - '[FfSs]R' as above with __builtin_extract_return_addr() translation
1379  * - 'B' For backtraced symbolic direct pointers with offset
1380  * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref]
1381  * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201]
1382  * - 'b[l]' For a bitmap, the number of bits is determined by the field
1383  *       width which must be explicitly specified either as part of the
1384  *       format string '%32b[l]' or through '%*b[l]', [l] selects
1385  *       range-list format instead of hex format
1386  * - 'M' For a 6-byte MAC address, it prints the address in the
1387  *       usual colon-separated hex notation
1388  * - 'm' For a 6-byte MAC address, it prints the hex address without colons
1389  * - 'MF' For a 6-byte MAC FDDI address, it prints the address
1390  *       with a dash-separated hex notation
1391  * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth)
1392  * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way
1393  *       IPv4 uses dot-separated decimal without leading 0's (1.2.3.4)
1394  *       IPv6 uses colon separated network-order 16 bit hex with leading 0's
1395  *       [S][pfs]
1396  *       Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1397  *       [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1398  * - 'i' [46] for 'raw' IPv4/IPv6 addresses
1399  *       IPv6 omits the colons (01020304...0f)
1400  *       IPv4 uses dot-separated decimal with leading 0's (010.123.045.006)
1401  *       [S][pfs]
1402  *       Generic IPv4/IPv6 address (struct sockaddr *) that falls back to
1403  *       [4] or [6] and is able to print port [p], flowinfo [f], scope [s]
1404  * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order
1405  * - 'I[6S]c' for IPv6 addresses printed as specified by
1406  *       http://tools.ietf.org/html/rfc5952
1407  * - 'E[achnops]' For an escaped buffer, where rules are defined by combination
1408  *                of the following flags (see string_escape_mem() for the
1409  *                details):
1410  *                  a - ESCAPE_ANY
1411  *                  c - ESCAPE_SPECIAL
1412  *                  h - ESCAPE_HEX
1413  *                  n - ESCAPE_NULL
1414  *                  o - ESCAPE_OCTAL
1415  *                  p - ESCAPE_NP
1416  *                  s - ESCAPE_SPACE
1417  *                By default ESCAPE_ANY_NP is used.
1418  * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form
1419  *       "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
1420  *       Options for %pU are:
1421  *         b big endian lower case hex (default)
1422  *         B big endian UPPER case hex
1423  *         l little endian lower case hex
1424  *         L little endian UPPER case hex
1425  *           big endian output byte order is:
1426  *             [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15]
1427  *           little endian output byte order is:
1428  *             [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15]
1429  * - 'V' For a struct va_format which contains a format string * and va_list *,
1430  *       call vsnprintf(->format, *->va_list).
1431  *       Implements a "recursive vsnprintf".
1432  *       Do not use this feature without some mechanism to verify the
1433  *       correctness of the format string and va_list arguments.
1434  * - 'K' For a kernel pointer that should be hidden from unprivileged users
1435  * - 'NF' For a netdev_features_t
1436  * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with
1437  *            a certain separator (' ' by default):
1438  *              C colon
1439  *              D dash
1440  *              N no separator
1441  *            The maximum supported length is 64 bytes of the input. Consider
1442  *            to use print_hex_dump() for the larger input.
1443  * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives
1444  *           (default assumed to be phys_addr_t, passed by reference)
1445  * - 'd[234]' For a dentry name (optionally 2-4 last components)
1446  * - 'D[234]' Same as 'd' but for a struct file
1447  * - 'C' For a clock, it prints the name (Common Clock Framework) or address
1448  *       (legacy clock framework) of the clock
1449  * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address
1450  *        (legacy clock framework) of the clock
1451  * - 'Cr' For a clock, it prints the current rate of the clock
1452  *
1453  * Note: The difference between 'S' and 'F' is that on ia64 and ppc64
1454  * function pointers are really function descriptors, which contain a
1455  * pointer to the real address.
1456  */
1457 static noinline_for_stack
1458 char *pointer(const char *fmt, char *buf, char *end, void *ptr,
1459               struct printf_spec spec)
1460 {
1461         int default_width = 2 * sizeof(void *) + (spec.flags & SPECIAL ? 2 : 0);
1462
1463         if (!ptr && *fmt != 'K') {
1464                 /*
1465                  * Print (null) with the same width as a pointer so it makes
1466                  * tabular output look nice.
1467                  */
1468                 if (spec.field_width == -1)
1469                         spec.field_width = default_width;
1470                 return string(buf, end, "(null)", spec);
1471         }
1472
1473         switch (*fmt) {
1474         case 'F':
1475         case 'f':
1476                 ptr = dereference_function_descriptor(ptr);
1477                 /* Fallthrough */
1478         case 'S':
1479         case 's':
1480         case 'B':
1481                 return symbol_string(buf, end, ptr, spec, fmt);
1482         case 'R':
1483         case 'r':
1484                 return resource_string(buf, end, ptr, spec, fmt);
1485         case 'h':
1486                 return hex_string(buf, end, ptr, spec, fmt);
1487         case 'b':
1488                 switch (fmt[1]) {
1489                 case 'l':
1490                         return bitmap_list_string(buf, end, ptr, spec, fmt);
1491                 default:
1492                         return bitmap_string(buf, end, ptr, spec, fmt);
1493                 }
1494         case 'M':                       /* Colon separated: 00:01:02:03:04:05 */
1495         case 'm':                       /* Contiguous: 000102030405 */
1496                                         /* [mM]F (FDDI) */
1497                                         /* [mM]R (Reverse order; Bluetooth) */
1498                 return mac_address_string(buf, end, ptr, spec, fmt);
1499         case 'I':                       /* Formatted IP supported
1500                                          * 4:   1.2.3.4
1501                                          * 6:   0001:0203:...:0708
1502                                          * 6c:  1::708 or 1::1.2.3.4
1503                                          */
1504         case 'i':                       /* Contiguous:
1505                                          * 4:   001.002.003.004
1506                                          * 6:   000102...0f
1507                                          */
1508                 switch (fmt[1]) {
1509                 case '6':
1510                         return ip6_addr_string(buf, end, ptr, spec, fmt);
1511                 case '4':
1512                         return ip4_addr_string(buf, end, ptr, spec, fmt);
1513                 case 'S': {
1514                         const union {
1515                                 struct sockaddr         raw;
1516                                 struct sockaddr_in      v4;
1517                                 struct sockaddr_in6     v6;
1518                         } *sa = ptr;
1519
1520                         switch (sa->raw.sa_family) {
1521                         case AF_INET:
1522                                 return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt);
1523                         case AF_INET6:
1524                                 return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt);
1525                         default:
1526                                 return string(buf, end, "(invalid address)", spec);
1527                         }}
1528                 }
1529                 break;
1530         case 'E':
1531                 return escaped_string(buf, end, ptr, spec, fmt);
1532         case 'U':
1533                 return uuid_string(buf, end, ptr, spec, fmt);
1534         case 'V':
1535                 {
1536                         va_list va;
1537
1538                         va_copy(va, *((struct va_format *)ptr)->va);
1539                         buf += vsnprintf(buf, end > buf ? end - buf : 0,
1540                                          ((struct va_format *)ptr)->fmt, va);
1541                         va_end(va);
1542                         return buf;
1543                 }
1544         case 'K':
1545                 /*
1546                  * %pK cannot be used in IRQ context because its test
1547                  * for CAP_SYSLOG would be meaningless.
1548                  */
1549                 if (kptr_restrict && (in_irq() || in_serving_softirq() ||
1550                                       in_nmi())) {
1551                         if (spec.field_width == -1)
1552                                 spec.field_width = default_width;
1553                         return string(buf, end, "pK-error", spec);
1554                 }
1555
1556                 switch (kptr_restrict) {
1557                 case 0:
1558                         /* Always print %pK values */
1559                         break;
1560                 case 1: {
1561                         /*
1562                          * Only print the real pointer value if the current
1563                          * process has CAP_SYSLOG and is running with the
1564                          * same credentials it started with. This is because
1565                          * access to files is checked at open() time, but %pK
1566                          * checks permission at read() time. We don't want to
1567                          * leak pointer values if a binary opens a file using
1568                          * %pK and then elevates privileges before reading it.
1569                          */
1570                         const struct cred *cred = current_cred();
1571
1572                         if (!has_capability_noaudit(current, CAP_SYSLOG) ||
1573                             !uid_eq(cred->euid, cred->uid) ||
1574                             !gid_eq(cred->egid, cred->gid))
1575                                 ptr = NULL;
1576                         break;
1577                 }
1578                 case 2:
1579                 default:
1580                         /* Always print 0's for %pK */
1581                         ptr = NULL;
1582                         break;
1583                 }
1584                 break;
1585
1586         case 'N':
1587                 switch (fmt[1]) {
1588                 case 'F':
1589                         return netdev_feature_string(buf, end, ptr, spec);
1590                 }
1591                 break;
1592         case 'a':
1593                 return address_val(buf, end, ptr, spec, fmt);
1594         case 'd':
1595                 return dentry_name(buf, end, ptr, spec, fmt);
1596         case 'C':
1597                 return clock(buf, end, ptr, spec, fmt);
1598         case 'D':
1599                 return dentry_name(buf, end,
1600                                    ((const struct file *)ptr)->f_path.dentry,
1601                                    spec, fmt);
1602         }
1603         spec.flags |= SMALL;
1604         if (spec.field_width == -1) {
1605                 spec.field_width = default_width;
1606                 spec.flags |= ZEROPAD;
1607         }
1608         spec.base = 16;
1609
1610         return number(buf, end, (unsigned long) ptr, spec);
1611 }
1612
1613 /*
1614  * Helper function to decode printf style format.
1615  * Each call decode a token from the format and return the
1616  * number of characters read (or likely the delta where it wants
1617  * to go on the next call).
1618  * The decoded token is returned through the parameters
1619  *
1620  * 'h', 'l', or 'L' for integer fields
1621  * 'z' support added 23/7/1999 S.H.
1622  * 'z' changed to 'Z' --davidm 1/25/99
1623  * 't' added for ptrdiff_t
1624  *
1625  * @fmt: the format string
1626  * @type of the token returned
1627  * @flags: various flags such as +, -, # tokens..
1628  * @field_width: overwritten width
1629  * @base: base of the number (octal, hex, ...)
1630  * @precision: precision of a number
1631  * @qualifier: qualifier of a number (long, size_t, ...)
1632  */
1633 static noinline_for_stack
1634 int format_decode(const char *fmt, struct printf_spec *spec)
1635 {
1636         const char *start = fmt;
1637
1638         /* we finished early by reading the field width */
1639         if (spec->type == FORMAT_TYPE_WIDTH) {
1640                 if (spec->field_width < 0) {
1641                         spec->field_width = -spec->field_width;
1642                         spec->flags |= LEFT;
1643                 }
1644                 spec->type = FORMAT_TYPE_NONE;
1645                 goto precision;
1646         }
1647
1648         /* we finished early by reading the precision */
1649         if (spec->type == FORMAT_TYPE_PRECISION) {
1650                 if (spec->precision < 0)
1651                         spec->precision = 0;
1652
1653                 spec->type = FORMAT_TYPE_NONE;
1654                 goto qualifier;
1655         }
1656
1657         /* By default */
1658         spec->type = FORMAT_TYPE_NONE;
1659
1660         for (; *fmt ; ++fmt) {
1661                 if (*fmt == '%')
1662                         break;
1663         }
1664
1665         /* Return the current non-format string */
1666         if (fmt != start || !*fmt)
1667                 return fmt - start;
1668
1669         /* Process flags */
1670         spec->flags = 0;
1671
1672         while (1) { /* this also skips first '%' */
1673                 bool found = true;
1674
1675                 ++fmt;
1676
1677                 switch (*fmt) {
1678                 case '-': spec->flags |= LEFT;    break;
1679                 case '+': spec->flags |= PLUS;    break;
1680                 case ' ': spec->flags |= SPACE;   break;
1681                 case '#': spec->flags |= SPECIAL; break;
1682                 case '0': spec->flags |= ZEROPAD; break;
1683                 default:  found = false;
1684                 }
1685
1686                 if (!found)
1687                         break;
1688         }
1689
1690         /* get field width */
1691         spec->field_width = -1;
1692
1693         if (isdigit(*fmt))
1694                 spec->field_width = skip_atoi(&fmt);
1695         else if (*fmt == '*') {
1696                 /* it's the next argument */
1697                 spec->type = FORMAT_TYPE_WIDTH;
1698                 return ++fmt - start;
1699         }
1700
1701 precision:
1702         /* get the precision */
1703         spec->precision = -1;
1704         if (*fmt == '.') {
1705                 ++fmt;
1706                 if (isdigit(*fmt)) {
1707                         spec->precision = skip_atoi(&fmt);
1708                         if (spec->precision < 0)
1709                                 spec->precision = 0;
1710                 } else if (*fmt == '*') {
1711                         /* it's the next argument */
1712                         spec->type = FORMAT_TYPE_PRECISION;
1713                         return ++fmt - start;
1714                 }
1715         }
1716
1717 qualifier:
1718         /* get the conversion qualifier */
1719         spec->qualifier = -1;
1720         if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
1721             _tolower(*fmt) == 'z' || *fmt == 't') {
1722                 spec->qualifier = *fmt++;
1723                 if (unlikely(spec->qualifier == *fmt)) {
1724                         if (spec->qualifier == 'l') {
1725                                 spec->qualifier = 'L';
1726                                 ++fmt;
1727                         } else if (spec->qualifier == 'h') {
1728                                 spec->qualifier = 'H';
1729                                 ++fmt;
1730                         }
1731                 }
1732         }
1733
1734         /* default base */
1735         spec->base = 10;
1736         switch (*fmt) {
1737         case 'c':
1738                 spec->type = FORMAT_TYPE_CHAR;
1739                 return ++fmt - start;
1740
1741         case 's':
1742                 spec->type = FORMAT_TYPE_STR;
1743                 return ++fmt - start;
1744
1745         case 'p':
1746                 spec->type = FORMAT_TYPE_PTR;
1747                 return ++fmt - start;
1748
1749         case '%':
1750                 spec->type = FORMAT_TYPE_PERCENT_CHAR;
1751                 return ++fmt - start;
1752
1753         /* integer number formats - set up the flags and "break" */
1754         case 'o':
1755                 spec->base = 8;
1756                 break;
1757
1758         case 'x':
1759                 spec->flags |= SMALL;
1760
1761         case 'X':
1762                 spec->base = 16;
1763                 break;
1764
1765         case 'd':
1766         case 'i':
1767                 spec->flags |= SIGN;
1768         case 'u':
1769                 break;
1770
1771         case 'n':
1772                 /*
1773                  * Since %n poses a greater security risk than utility, treat
1774                  * it as an invalid format specifier. Warn about its use so
1775                  * that new instances don't get added.
1776                  */
1777                 WARN_ONCE(1, "Please remove ignored %%n in '%s'\n", fmt);
1778                 /* Fall-through */
1779
1780         default:
1781                 spec->type = FORMAT_TYPE_INVALID;
1782                 return fmt - start;
1783         }
1784
1785         if (spec->qualifier == 'L')
1786                 spec->type = FORMAT_TYPE_LONG_LONG;
1787         else if (spec->qualifier == 'l') {
1788                 BUILD_BUG_ON(FORMAT_TYPE_ULONG + SIGN != FORMAT_TYPE_LONG);
1789                 spec->type = FORMAT_TYPE_ULONG + (spec->flags & SIGN);
1790         } else if (_tolower(spec->qualifier) == 'z') {
1791                 spec->type = FORMAT_TYPE_SIZE_T;
1792         } else if (spec->qualifier == 't') {
1793                 spec->type = FORMAT_TYPE_PTRDIFF;
1794         } else if (spec->qualifier == 'H') {
1795                 BUILD_BUG_ON(FORMAT_TYPE_UBYTE + SIGN != FORMAT_TYPE_BYTE);
1796                 spec->type = FORMAT_TYPE_UBYTE + (spec->flags & SIGN);
1797         } else if (spec->qualifier == 'h') {
1798                 BUILD_BUG_ON(FORMAT_TYPE_USHORT + SIGN != FORMAT_TYPE_SHORT);
1799                 spec->type = FORMAT_TYPE_USHORT + (spec->flags & SIGN);
1800         } else {
1801                 BUILD_BUG_ON(FORMAT_TYPE_UINT + SIGN != FORMAT_TYPE_INT);
1802                 spec->type = FORMAT_TYPE_UINT + (spec->flags & SIGN);
1803         }
1804
1805         return ++fmt - start;
1806 }
1807
1808 /**
1809  * vsnprintf - Format a string and place it in a buffer
1810  * @buf: The buffer to place the result into
1811  * @size: The size of the buffer, including the trailing null space
1812  * @fmt: The format string to use
1813  * @args: Arguments for the format string
1814  *
1815  * This function follows C99 vsnprintf, but has some extensions:
1816  * %pS output the name of a text symbol with offset
1817  * %ps output the name of a text symbol without offset
1818  * %pF output the name of a function pointer with its offset
1819  * %pf output the name of a function pointer without its offset
1820  * %pB output the name of a backtrace symbol with its offset
1821  * %pR output the address range in a struct resource with decoded flags
1822  * %pr output the address range in a struct resource with raw flags
1823  * %pb output the bitmap with field width as the number of bits
1824  * %pbl output the bitmap as range list with field width as the number of bits
1825  * %pM output a 6-byte MAC address with colons
1826  * %pMR output a 6-byte MAC address with colons in reversed order
1827  * %pMF output a 6-byte MAC address with dashes
1828  * %pm output a 6-byte MAC address without colons
1829  * %pmR output a 6-byte MAC address without colons in reversed order
1830  * %pI4 print an IPv4 address without leading zeros
1831  * %pi4 print an IPv4 address with leading zeros
1832  * %pI6 print an IPv6 address with colons
1833  * %pi6 print an IPv6 address without colons
1834  * %pI6c print an IPv6 address as specified by RFC 5952
1835  * %pIS depending on sa_family of 'struct sockaddr *' print IPv4/IPv6 address
1836  * %piS depending on sa_family of 'struct sockaddr *' print IPv4/IPv6 address
1837  * %pU[bBlL] print a UUID/GUID in big or little endian using lower or upper
1838  *   case.
1839  * %*pE[achnops] print an escaped buffer
1840  * %*ph[CDN] a variable-length hex string with a separator (supports up to 64
1841  *           bytes of the input)
1842  * %pC output the name (Common Clock Framework) or address (legacy clock
1843  *     framework) of a clock
1844  * %pCn output the name (Common Clock Framework) or address (legacy clock
1845  *      framework) of a clock
1846  * %pCr output the current rate of a clock
1847  * %n is ignored
1848  *
1849  * ** Please update Documentation/printk-formats.txt when making changes **
1850  *
1851  * The return value is the number of characters which would
1852  * be generated for the given input, excluding the trailing
1853  * '\0', as per ISO C99. If you want to have the exact
1854  * number of characters written into @buf as return value
1855  * (not including the trailing '\0'), use vscnprintf(). If the
1856  * return is greater than or equal to @size, the resulting
1857  * string is truncated.
1858  *
1859  * If you're not already dealing with a va_list consider using snprintf().
1860  */
1861 int vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
1862 {
1863         unsigned long long num;
1864         char *str, *end;
1865         struct printf_spec spec = {0};
1866
1867         /* Reject out-of-range values early.  Large positive sizes are
1868            used for unknown buffer sizes. */
1869         if (WARN_ON_ONCE(size > INT_MAX))
1870                 return 0;
1871
1872         str = buf;
1873         end = buf + size;
1874
1875         /* Make sure end is always >= buf */
1876         if (end < buf) {
1877                 end = ((void *)-1);
1878                 size = end - buf;
1879         }
1880
1881         while (*fmt) {
1882                 const char *old_fmt = fmt;
1883                 int read = format_decode(fmt, &spec);
1884
1885                 fmt += read;
1886
1887                 switch (spec.type) {
1888                 case FORMAT_TYPE_NONE: {
1889                         int copy = read;
1890                         if (str < end) {
1891                                 if (copy > end - str)
1892                                         copy = end - str;
1893                                 memcpy(str, old_fmt, copy);
1894                         }
1895                         str += read;
1896                         break;
1897                 }
1898
1899                 case FORMAT_TYPE_WIDTH:
1900                         spec.field_width = va_arg(args, int);
1901                         break;
1902
1903                 case FORMAT_TYPE_PRECISION:
1904                         spec.precision = va_arg(args, int);
1905                         break;
1906
1907                 case FORMAT_TYPE_CHAR: {
1908                         char c;
1909
1910                         if (!(spec.flags & LEFT)) {
1911                                 while (--spec.field_width > 0) {
1912                                         if (str < end)
1913                                                 *str = ' ';
1914                                         ++str;
1915
1916                                 }
1917                         }
1918                         c = (unsigned char) va_arg(args, int);
1919                         if (str < end)
1920                                 *str = c;
1921                         ++str;
1922                         while (--spec.field_width > 0) {
1923                                 if (str < end)
1924                                         *str = ' ';
1925                                 ++str;
1926                         }
1927                         break;
1928                 }
1929
1930                 case FORMAT_TYPE_STR:
1931                         str = string(str, end, va_arg(args, char *), spec);
1932                         break;
1933
1934                 case FORMAT_TYPE_PTR:
1935                         str = pointer(fmt, str, end, va_arg(args, void *),
1936                                       spec);
1937                         while (isalnum(*fmt))
1938                                 fmt++;
1939                         break;
1940
1941                 case FORMAT_TYPE_PERCENT_CHAR:
1942                         if (str < end)
1943                                 *str = '%';
1944                         ++str;
1945                         break;
1946
1947                 case FORMAT_TYPE_INVALID:
1948                         if (str < end)
1949                                 *str = '%';
1950                         ++str;
1951                         break;
1952
1953                 default:
1954                         switch (spec.type) {
1955                         case FORMAT_TYPE_LONG_LONG:
1956                                 num = va_arg(args, long long);
1957                                 break;
1958                         case FORMAT_TYPE_ULONG:
1959                                 num = va_arg(args, unsigned long);
1960                                 break;
1961                         case FORMAT_TYPE_LONG:
1962                                 num = va_arg(args, long);
1963                                 break;
1964                         case FORMAT_TYPE_SIZE_T:
1965                                 if (spec.flags & SIGN)
1966                                         num = va_arg(args, ssize_t);
1967                                 else
1968                                         num = va_arg(args, size_t);
1969                                 break;
1970                         case FORMAT_TYPE_PTRDIFF:
1971                                 num = va_arg(args, ptrdiff_t);
1972                                 break;
1973                         case FORMAT_TYPE_UBYTE:
1974                                 num = (unsigned char) va_arg(args, int);
1975                                 break;
1976                         case FORMAT_TYPE_BYTE:
1977                                 num = (signed char) va_arg(args, int);
1978                                 break;
1979                         case FORMAT_TYPE_USHORT:
1980                                 num = (unsigned short) va_arg(args, int);
1981                                 break;
1982                         case FORMAT_TYPE_SHORT:
1983                                 num = (short) va_arg(args, int);
1984                                 break;
1985                         case FORMAT_TYPE_INT:
1986                                 num = (int) va_arg(args, int);
1987                                 break;
1988                         default:
1989                                 num = va_arg(args, unsigned int);
1990                         }
1991
1992                         str = number(str, end, num, spec);
1993                 }
1994         }
1995
1996         if (size > 0) {
1997                 if (str < end)
1998                         *str = '\0';
1999                 else
2000                         end[-1] = '\0';
2001         }
2002
2003         /* the trailing null byte doesn't count towards the total */
2004         return str-buf;
2005
2006 }
2007 EXPORT_SYMBOL(vsnprintf);
2008
2009 /**
2010  * vscnprintf - Format a string and place it in a buffer
2011  * @buf: The buffer to place the result into
2012  * @size: The size of the buffer, including the trailing null space
2013  * @fmt: The format string to use
2014  * @args: Arguments for the format string
2015  *
2016  * The return value is the number of characters which have been written into
2017  * the @buf not including the trailing '\0'. If @size is == 0 the function
2018  * returns 0.
2019  *
2020  * If you're not already dealing with a va_list consider using scnprintf().
2021  *
2022  * See the vsnprintf() documentation for format string extensions over C99.
2023  */
2024 int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
2025 {
2026         int i;
2027
2028         i = vsnprintf(buf, size, fmt, args);
2029
2030         if (likely(i < size))
2031                 return i;
2032         if (size != 0)
2033                 return size - 1;
2034         return 0;
2035 }
2036 EXPORT_SYMBOL(vscnprintf);
2037
2038 /**
2039  * snprintf - Format a string and place it in a buffer
2040  * @buf: The buffer to place the result into
2041  * @size: The size of the buffer, including the trailing null space
2042  * @fmt: The format string to use
2043  * @...: Arguments for the format string
2044  *
2045  * The return value is the number of characters which would be
2046  * generated for the given input, excluding the trailing null,
2047  * as per ISO C99.  If the return is greater than or equal to
2048  * @size, the resulting string is truncated.
2049  *
2050  * See the vsnprintf() documentation for format string extensions over C99.
2051  */
2052 int snprintf(char *buf, size_t size, const char *fmt, ...)
2053 {
2054         va_list args;
2055         int i;
2056
2057         va_start(args, fmt);
2058         i = vsnprintf(buf, size, fmt, args);
2059         va_end(args);
2060
2061         return i;
2062 }
2063 EXPORT_SYMBOL(snprintf);
2064
2065 /**
2066  * scnprintf - Format a string and place it in a buffer
2067  * @buf: The buffer to place the result into
2068  * @size: The size of the buffer, including the trailing null space
2069  * @fmt: The format string to use
2070  * @...: Arguments for the format string
2071  *
2072  * The return value is the number of characters written into @buf not including
2073  * the trailing '\0'. If @size is == 0 the function returns 0.
2074  */
2075
2076 int scnprintf(char *buf, size_t size, const char *fmt, ...)
2077 {
2078         va_list args;
2079         int i;
2080
2081         va_start(args, fmt);
2082         i = vscnprintf(buf, size, fmt, args);
2083         va_end(args);
2084
2085         return i;
2086 }
2087 EXPORT_SYMBOL(scnprintf);
2088
2089 /**
2090  * vsprintf - Format a string and place it in a buffer
2091  * @buf: The buffer to place the result into
2092  * @fmt: The format string to use
2093  * @args: Arguments for the format string
2094  *
2095  * The function returns the number of characters written
2096  * into @buf. Use vsnprintf() or vscnprintf() in order to avoid
2097  * buffer overflows.
2098  *
2099  * If you're not already dealing with a va_list consider using sprintf().
2100  *
2101  * See the vsnprintf() documentation for format string extensions over C99.
2102  */
2103 int vsprintf(char *buf, const char *fmt, va_list args)
2104 {
2105         return vsnprintf(buf, INT_MAX, fmt, args);
2106 }
2107 EXPORT_SYMBOL(vsprintf);
2108
2109 /**
2110  * sprintf - Format a string and place it in a buffer
2111  * @buf: The buffer to place the result into
2112  * @fmt: The format string to use
2113  * @...: Arguments for the format string
2114  *
2115  * The function returns the number of characters written
2116  * into @buf. Use snprintf() or scnprintf() in order to avoid
2117  * buffer overflows.
2118  *
2119  * See the vsnprintf() documentation for format string extensions over C99.
2120  */
2121 int sprintf(char *buf, const char *fmt, ...)
2122 {
2123         va_list args;
2124         int i;
2125
2126         va_start(args, fmt);
2127         i = vsnprintf(buf, INT_MAX, fmt, args);
2128         va_end(args);
2129
2130         return i;
2131 }
2132 EXPORT_SYMBOL(sprintf);
2133
2134 #ifdef CONFIG_BINARY_PRINTF
2135 /*
2136  * bprintf service:
2137  * vbin_printf() - VA arguments to binary data
2138  * bstr_printf() - Binary data to text string
2139  */
2140
2141 /**
2142  * vbin_printf - Parse a format string and place args' binary value in a buffer
2143  * @bin_buf: The buffer to place args' binary value
2144  * @size: The size of the buffer(by words(32bits), not characters)
2145  * @fmt: The format string to use
2146  * @args: Arguments for the format string
2147  *
2148  * The format follows C99 vsnprintf, except %n is ignored, and its argument
2149  * is skipped.
2150  *
2151  * The return value is the number of words(32bits) which would be generated for
2152  * the given input.
2153  *
2154  * NOTE:
2155  * If the return value is greater than @size, the resulting bin_buf is NOT
2156  * valid for bstr_printf().
2157  */
2158 int vbin_printf(u32 *bin_buf, size_t size, const char *fmt, va_list args)
2159 {
2160         struct printf_spec spec = {0};
2161         char *str, *end;
2162
2163         str = (char *)bin_buf;
2164         end = (char *)(bin_buf + size);
2165
2166 #define save_arg(type)                                                  \
2167 do {                                                                    \
2168         if (sizeof(type) == 8) {                                        \
2169                 unsigned long long value;                               \
2170                 str = PTR_ALIGN(str, sizeof(u32));                      \
2171                 value = va_arg(args, unsigned long long);               \
2172                 if (str + sizeof(type) <= end) {                        \
2173                         *(u32 *)str = *(u32 *)&value;                   \
2174                         *(u32 *)(str + 4) = *((u32 *)&value + 1);       \
2175                 }                                                       \
2176         } else {                                                        \
2177                 unsigned long value;                                    \
2178                 str = PTR_ALIGN(str, sizeof(type));                     \
2179                 value = va_arg(args, int);                              \
2180                 if (str + sizeof(type) <= end)                          \
2181                         *(typeof(type) *)str = (type)value;             \
2182         }                                                               \
2183         str += sizeof(type);                                            \
2184 } while (0)
2185
2186         while (*fmt) {
2187                 int read = format_decode(fmt, &spec);
2188
2189                 fmt += read;
2190
2191                 switch (spec.type) {
2192                 case FORMAT_TYPE_NONE:
2193                 case FORMAT_TYPE_INVALID:
2194                 case FORMAT_TYPE_PERCENT_CHAR:
2195                         break;
2196
2197                 case FORMAT_TYPE_WIDTH:
2198                 case FORMAT_TYPE_PRECISION:
2199                         save_arg(int);
2200                         break;
2201
2202                 case FORMAT_TYPE_CHAR:
2203                         save_arg(char);
2204                         break;
2205
2206                 case FORMAT_TYPE_STR: {
2207                         const char *save_str = va_arg(args, char *);
2208                         size_t len;
2209
2210                         if ((unsigned long)save_str > (unsigned long)-PAGE_SIZE
2211                                         || (unsigned long)save_str < PAGE_SIZE)
2212                                 save_str = "(null)";
2213                         len = strlen(save_str) + 1;
2214                         if (str + len < end)
2215                                 memcpy(str, save_str, len);
2216                         str += len;
2217                         break;
2218                 }
2219
2220                 case FORMAT_TYPE_PTR:
2221                         save_arg(void *);
2222                         /* skip all alphanumeric pointer suffixes */
2223                         while (isalnum(*fmt))
2224                                 fmt++;
2225                         break;
2226
2227                 default:
2228                         switch (spec.type) {
2229
2230                         case FORMAT_TYPE_LONG_LONG:
2231                                 save_arg(long long);
2232                                 break;
2233                         case FORMAT_TYPE_ULONG:
2234                         case FORMAT_TYPE_LONG:
2235                                 save_arg(unsigned long);
2236                                 break;
2237                         case FORMAT_TYPE_SIZE_T:
2238                                 save_arg(size_t);
2239                                 break;
2240                         case FORMAT_TYPE_PTRDIFF:
2241                                 save_arg(ptrdiff_t);
2242                                 break;
2243                         case FORMAT_TYPE_UBYTE:
2244                         case FORMAT_TYPE_BYTE:
2245                                 save_arg(char);
2246                                 break;
2247                         case FORMAT_TYPE_USHORT:
2248                         case FORMAT_TYPE_SHORT:
2249                                 save_arg(short);
2250                                 break;
2251                         default:
2252                                 save_arg(int);
2253                         }
2254                 }
2255         }
2256
2257         return (u32 *)(PTR_ALIGN(str, sizeof(u32))) - bin_buf;
2258 #undef save_arg
2259 }
2260 EXPORT_SYMBOL_GPL(vbin_printf);
2261
2262 /**
2263  * bstr_printf - Format a string from binary arguments and place it in a buffer
2264  * @buf: The buffer to place the result into
2265  * @size: The size of the buffer, including the trailing null space
2266  * @fmt: The format string to use
2267  * @bin_buf: Binary arguments for the format string
2268  *
2269  * This function like C99 vsnprintf, but the difference is that vsnprintf gets
2270  * arguments from stack, and bstr_printf gets arguments from @bin_buf which is
2271  * a binary buffer that generated by vbin_printf.
2272  *
2273  * The format follows C99 vsnprintf, but has some extensions:
2274  *  see vsnprintf comment for details.
2275  *
2276  * The return value is the number of characters which would
2277  * be generated for the given input, excluding the trailing
2278  * '\0', as per ISO C99. If you want to have the exact
2279  * number of characters written into @buf as return value
2280  * (not including the trailing '\0'), use vscnprintf(). If the
2281  * return is greater than or equal to @size, the resulting
2282  * string is truncated.
2283  */
2284 int bstr_printf(char *buf, size_t size, const char *fmt, const u32 *bin_buf)
2285 {
2286         struct printf_spec spec = {0};
2287         char *str, *end;
2288         const char *args = (const char *)bin_buf;
2289
2290         if (WARN_ON_ONCE((int) size < 0))
2291                 return 0;
2292
2293         str = buf;
2294         end = buf + size;
2295
2296 #define get_arg(type)                                                   \
2297 ({                                                                      \
2298         typeof(type) value;                                             \
2299         if (sizeof(type) == 8) {                                        \
2300                 args = PTR_ALIGN(args, sizeof(u32));                    \
2301                 *(u32 *)&value = *(u32 *)args;                          \
2302                 *((u32 *)&value + 1) = *(u32 *)(args + 4);              \
2303         } else {                                                        \
2304                 args = PTR_ALIGN(args, sizeof(type));                   \
2305                 value = *(typeof(type) *)args;                          \
2306         }                                                               \
2307         args += sizeof(type);                                           \
2308         value;                                                          \
2309 })
2310
2311         /* Make sure end is always >= buf */
2312         if (end < buf) {
2313                 end = ((void *)-1);
2314                 size = end - buf;
2315         }
2316
2317         while (*fmt) {
2318                 const char *old_fmt = fmt;
2319                 int read = format_decode(fmt, &spec);
2320
2321                 fmt += read;
2322
2323                 switch (spec.type) {
2324                 case FORMAT_TYPE_NONE: {
2325                         int copy = read;
2326                         if (str < end) {
2327                                 if (copy > end - str)
2328                                         copy = end - str;
2329                                 memcpy(str, old_fmt, copy);
2330                         }
2331                         str += read;
2332                         break;
2333                 }
2334
2335                 case FORMAT_TYPE_WIDTH:
2336                         spec.field_width = get_arg(int);
2337                         break;
2338
2339                 case FORMAT_TYPE_PRECISION:
2340                         spec.precision = get_arg(int);
2341                         break;
2342
2343                 case FORMAT_TYPE_CHAR: {
2344                         char c;
2345
2346                         if (!(spec.flags & LEFT)) {
2347                                 while (--spec.field_width > 0) {
2348                                         if (str < end)
2349                                                 *str = ' ';
2350                                         ++str;
2351                                 }
2352                         }
2353                         c = (unsigned char) get_arg(char);
2354                         if (str < end)
2355                                 *str = c;
2356                         ++str;
2357                         while (--spec.field_width > 0) {
2358                                 if (str < end)
2359                                         *str = ' ';
2360                                 ++str;
2361                         }
2362                         break;
2363                 }
2364
2365                 case FORMAT_TYPE_STR: {
2366                         const char *str_arg = args;
2367                         args += strlen(str_arg) + 1;
2368                         str = string(str, end, (char *)str_arg, spec);
2369                         break;
2370                 }
2371
2372                 case FORMAT_TYPE_PTR:
2373                         str = pointer(fmt, str, end, get_arg(void *), spec);
2374                         while (isalnum(*fmt))
2375                                 fmt++;
2376                         break;
2377
2378                 case FORMAT_TYPE_PERCENT_CHAR:
2379                 case FORMAT_TYPE_INVALID:
2380                         if (str < end)
2381                                 *str = '%';
2382                         ++str;
2383                         break;
2384
2385                 default: {
2386                         unsigned long long num;
2387
2388                         switch (spec.type) {
2389
2390                         case FORMAT_TYPE_LONG_LONG:
2391                                 num = get_arg(long long);
2392                                 break;
2393                         case FORMAT_TYPE_ULONG:
2394                         case FORMAT_TYPE_LONG:
2395                                 num = get_arg(unsigned long);
2396                                 break;
2397                         case FORMAT_TYPE_SIZE_T:
2398                                 num = get_arg(size_t);
2399                                 break;
2400                         case FORMAT_TYPE_PTRDIFF:
2401                                 num = get_arg(ptrdiff_t);
2402                                 break;
2403                         case FORMAT_TYPE_UBYTE:
2404                                 num = get_arg(unsigned char);
2405                                 break;
2406                         case FORMAT_TYPE_BYTE:
2407                                 num = get_arg(signed char);
2408                                 break;
2409                         case FORMAT_TYPE_USHORT:
2410                                 num = get_arg(unsigned short);
2411                                 break;
2412                         case FORMAT_TYPE_SHORT:
2413                                 num = get_arg(short);
2414                                 break;
2415                         case FORMAT_TYPE_UINT:
2416                                 num = get_arg(unsigned int);
2417                                 break;
2418                         default:
2419                                 num = get_arg(int);
2420                         }
2421
2422                         str = number(str, end, num, spec);
2423                 } /* default: */
2424                 } /* switch(spec.type) */
2425         } /* while(*fmt) */
2426
2427         if (size > 0) {
2428                 if (str < end)
2429                         *str = '\0';
2430                 else
2431                         end[-1] = '\0';
2432         }
2433
2434 #undef get_arg
2435
2436         /* the trailing null byte doesn't count towards the total */
2437         return str - buf;
2438 }
2439 EXPORT_SYMBOL_GPL(bstr_printf);
2440
2441 /**
2442  * bprintf - Parse a format string and place args' binary value in a buffer
2443  * @bin_buf: The buffer to place args' binary value
2444  * @size: The size of the buffer(by words(32bits), not characters)
2445  * @fmt: The format string to use
2446  * @...: Arguments for the format string
2447  *
2448  * The function returns the number of words(u32) written
2449  * into @bin_buf.
2450  */
2451 int bprintf(u32 *bin_buf, size_t size, const char *fmt, ...)
2452 {
2453         va_list args;
2454         int ret;
2455
2456         va_start(args, fmt);
2457         ret = vbin_printf(bin_buf, size, fmt, args);
2458         va_end(args);
2459
2460         return ret;
2461 }
2462 EXPORT_SYMBOL_GPL(bprintf);
2463
2464 #endif /* CONFIG_BINARY_PRINTF */
2465
2466 /**
2467  * vsscanf - Unformat a buffer into a list of arguments
2468  * @buf:        input buffer
2469  * @fmt:        format of buffer
2470  * @args:       arguments
2471  */
2472 int vsscanf(const char *buf, const char *fmt, va_list args)
2473 {
2474         const char *str = buf;
2475         char *next;
2476         char digit;
2477         int num = 0;
2478         u8 qualifier;
2479         unsigned int base;
2480         union {
2481                 long long s;
2482                 unsigned long long u;
2483         } val;
2484         s16 field_width;
2485         bool is_sign;
2486
2487         while (*fmt) {
2488                 /* skip any white space in format */
2489                 /* white space in format matchs any amount of
2490                  * white space, including none, in the input.
2491                  */
2492                 if (isspace(*fmt)) {
2493                         fmt = skip_spaces(++fmt);
2494                         str = skip_spaces(str);
2495                 }
2496
2497                 /* anything that is not a conversion must match exactly */
2498                 if (*fmt != '%' && *fmt) {
2499                         if (*fmt++ != *str++)
2500                                 break;
2501                         continue;
2502                 }
2503
2504                 if (!*fmt)
2505                         break;
2506                 ++fmt;
2507
2508                 /* skip this conversion.
2509                  * advance both strings to next white space
2510                  */
2511                 if (*fmt == '*') {
2512                         if (!*str)
2513                                 break;
2514                         while (!isspace(*fmt) && *fmt != '%' && *fmt)
2515                                 fmt++;
2516                         while (!isspace(*str) && *str)
2517                                 str++;
2518                         continue;
2519                 }
2520
2521                 /* get field width */
2522                 field_width = -1;
2523                 if (isdigit(*fmt)) {
2524                         field_width = skip_atoi(&fmt);
2525                         if (field_width <= 0)
2526                                 break;
2527                 }
2528
2529                 /* get conversion qualifier */
2530                 qualifier = -1;
2531                 if (*fmt == 'h' || _tolower(*fmt) == 'l' ||
2532                     _tolower(*fmt) == 'z') {
2533                         qualifier = *fmt++;
2534                         if (unlikely(qualifier == *fmt)) {
2535                                 if (qualifier == 'h') {
2536                                         qualifier = 'H';
2537                                         fmt++;
2538                                 } else if (qualifier == 'l') {
2539                                         qualifier = 'L';
2540                                         fmt++;
2541                                 }
2542                         }
2543                 }
2544
2545                 if (!*fmt)
2546                         break;
2547
2548                 if (*fmt == 'n') {
2549                         /* return number of characters read so far */
2550                         *va_arg(args, int *) = str - buf;
2551                         ++fmt;
2552                         continue;
2553                 }
2554
2555                 if (!*str)
2556                         break;
2557
2558                 base = 10;
2559                 is_sign = false;
2560
2561                 switch (*fmt++) {
2562                 case 'c':
2563                 {
2564                         char *s = (char *)va_arg(args, char*);
2565                         if (field_width == -1)
2566                                 field_width = 1;
2567                         do {
2568                                 *s++ = *str++;
2569                         } while (--field_width > 0 && *str);
2570                         num++;
2571                 }
2572                 continue;
2573                 case 's':
2574                 {
2575                         char *s = (char *)va_arg(args, char *);
2576                         if (field_width == -1)
2577                                 field_width = SHRT_MAX;
2578                         /* first, skip leading white space in buffer */
2579                         str = skip_spaces(str);
2580
2581                         /* now copy until next white space */
2582                         while (*str && !isspace(*str) && field_width--)
2583                                 *s++ = *str++;
2584                         *s = '\0';
2585                         num++;
2586                 }
2587                 continue;
2588                 case 'o':
2589                         base = 8;
2590                         break;
2591                 case 'x':
2592                 case 'X':
2593                         base = 16;
2594                         break;
2595                 case 'i':
2596                         base = 0;
2597                 case 'd':
2598                         is_sign = true;
2599                 case 'u':
2600                         break;
2601                 case '%':
2602                         /* looking for '%' in str */
2603                         if (*str++ != '%')
2604                                 return num;
2605                         continue;
2606                 default:
2607                         /* invalid format; stop here */
2608                         return num;
2609                 }
2610
2611                 /* have some sort of integer conversion.
2612                  * first, skip white space in buffer.
2613                  */
2614                 str = skip_spaces(str);
2615
2616                 digit = *str;
2617                 if (is_sign && digit == '-')
2618                         digit = *(str + 1);
2619
2620                 if (!digit
2621                     || (base == 16 && !isxdigit(digit))
2622                     || (base == 10 && !isdigit(digit))
2623                     || (base == 8 && (!isdigit(digit) || digit > '7'))
2624                     || (base == 0 && !isdigit(digit)))
2625                         break;
2626
2627                 if (is_sign)
2628                         val.s = qualifier != 'L' ?
2629                                 simple_strtol(str, &next, base) :
2630                                 simple_strtoll(str, &next, base);
2631                 else
2632                         val.u = qualifier != 'L' ?
2633                                 simple_strtoul(str, &next, base) :
2634                                 simple_strtoull(str, &next, base);
2635
2636                 if (field_width > 0 && next - str > field_width) {
2637                         if (base == 0)
2638                                 _parse_integer_fixup_radix(str, &base);
2639                         while (next - str > field_width) {
2640                                 if (is_sign)
2641                                         val.s = div_s64(val.s, base);
2642                                 else
2643                                         val.u = div_u64(val.u, base);
2644                                 --next;
2645                         }
2646                 }
2647
2648                 switch (qualifier) {
2649                 case 'H':       /* that's 'hh' in format */
2650                         if (is_sign)
2651                                 *va_arg(args, signed char *) = val.s;
2652                         else
2653                                 *va_arg(args, unsigned char *) = val.u;
2654                         break;
2655                 case 'h':
2656                         if (is_sign)
2657                                 *va_arg(args, short *) = val.s;
2658                         else
2659                                 *va_arg(args, unsigned short *) = val.u;
2660                         break;
2661                 case 'l':
2662                         if (is_sign)
2663                                 *va_arg(args, long *) = val.s;
2664                         else
2665                                 *va_arg(args, unsigned long *) = val.u;
2666                         break;
2667                 case 'L':
2668                         if (is_sign)
2669                                 *va_arg(args, long long *) = val.s;
2670                         else
2671                                 *va_arg(args, unsigned long long *) = val.u;
2672                         break;
2673                 case 'Z':
2674                 case 'z':
2675                         *va_arg(args, size_t *) = val.u;
2676                         break;
2677                 default:
2678                         if (is_sign)
2679                                 *va_arg(args, int *) = val.s;
2680                         else
2681                                 *va_arg(args, unsigned int *) = val.u;
2682                         break;
2683                 }
2684                 num++;
2685
2686                 if (!next)
2687                         break;
2688                 str = next;
2689         }
2690
2691         return num;
2692 }
2693 EXPORT_SYMBOL(vsscanf);
2694
2695 /**
2696  * sscanf - Unformat a buffer into a list of arguments
2697  * @buf:        input buffer
2698  * @fmt:        formatting of buffer
2699  * @...:        resulting arguments
2700  */
2701 int sscanf(const char *buf, const char *fmt, ...)
2702 {
2703         va_list args;
2704         int i;
2705
2706         va_start(args, fmt);
2707         i = vsscanf(buf, fmt, args);
2708         va_end(args);
2709
2710         return i;
2711 }
2712 EXPORT_SYMBOL(sscanf);