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