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