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