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