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