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