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