File Index
Files and directories
Sign in
FILE

vsprintf.c

File preview with syntax highlighting.

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