xref: /linux/kernel/printk/printk.c (revision f6e0a4984c2e7244689ea87b62b433bed9d07e94)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/kernel/printk.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  *
7  * Modified to make sys_syslog() more flexible: added commands to
8  * return the last 4k of kernel messages, regardless of whether
9  * they've been read or not.  Added option to suppress kernel printk's
10  * to the console.  Added hook for sending the console messages
11  * elsewhere, in preparation for a serial line console (someday).
12  * Ted Ts'o, 2/11/93.
13  * Modified for sysctl support, 1/8/97, Chris Horn.
14  * Fixed SMP synchronization, 08/08/99, Manfred Spraul
15  *     manfred@colorfullife.com
16  * Rewrote bits to get rid of console_lock
17  *	01Mar01 Andrew Morton
18  */
19 
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21 
22 #include <linux/kernel.h>
23 #include <linux/mm.h>
24 #include <linux/tty.h>
25 #include <linux/tty_driver.h>
26 #include <linux/console.h>
27 #include <linux/init.h>
28 #include <linux/jiffies.h>
29 #include <linux/nmi.h>
30 #include <linux/module.h>
31 #include <linux/moduleparam.h>
32 #include <linux/delay.h>
33 #include <linux/smp.h>
34 #include <linux/security.h>
35 #include <linux/memblock.h>
36 #include <linux/syscalls.h>
37 #include <linux/crash_core.h>
38 #include <linux/ratelimit.h>
39 #include <linux/kmsg_dump.h>
40 #include <linux/syslog.h>
41 #include <linux/cpu.h>
42 #include <linux/rculist.h>
43 #include <linux/poll.h>
44 #include <linux/irq_work.h>
45 #include <linux/ctype.h>
46 #include <linux/uio.h>
47 #include <linux/sched/clock.h>
48 #include <linux/sched/debug.h>
49 #include <linux/sched/task_stack.h>
50 
51 #include <linux/uaccess.h>
52 #include <asm/sections.h>
53 
54 #include <trace/events/initcall.h>
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/printk.h>
57 
58 #include "printk_ringbuffer.h"
59 #include "console_cmdline.h"
60 #include "braille.h"
61 #include "internal.h"
62 
63 int console_printk[4] = {
64 	CONSOLE_LOGLEVEL_DEFAULT,	/* console_loglevel */
65 	MESSAGE_LOGLEVEL_DEFAULT,	/* default_message_loglevel */
66 	CONSOLE_LOGLEVEL_MIN,		/* minimum_console_loglevel */
67 	CONSOLE_LOGLEVEL_DEFAULT,	/* default_console_loglevel */
68 };
69 EXPORT_SYMBOL_GPL(console_printk);
70 
71 atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
72 EXPORT_SYMBOL(ignore_console_lock_warning);
73 
74 EXPORT_TRACEPOINT_SYMBOL_GPL(console);
75 
76 /*
77  * Low level drivers may need that to know if they can schedule in
78  * their unblank() callback or not. So let's export it.
79  */
80 int oops_in_progress;
81 EXPORT_SYMBOL(oops_in_progress);
82 
83 /*
84  * console_mutex protects console_list updates and console->flags updates.
85  * The flags are synchronized only for consoles that are registered, i.e.
86  * accessible via the console list.
87  */
88 static DEFINE_MUTEX(console_mutex);
89 
90 /*
91  * console_sem protects updates to console->seq
92  * and also provides serialization for console printing.
93  */
94 static DEFINE_SEMAPHORE(console_sem, 1);
95 HLIST_HEAD(console_list);
96 EXPORT_SYMBOL_GPL(console_list);
97 DEFINE_STATIC_SRCU(console_srcu);
98 
99 /*
100  * System may need to suppress printk message under certain
101  * circumstances, like after kernel panic happens.
102  */
103 int __read_mostly suppress_printk;
104 
105 #ifdef CONFIG_LOCKDEP
106 static struct lockdep_map console_lock_dep_map = {
107 	.name = "console_lock"
108 };
109 
110 void lockdep_assert_console_list_lock_held(void)
111 {
112 	lockdep_assert_held(&console_mutex);
113 }
114 EXPORT_SYMBOL(lockdep_assert_console_list_lock_held);
115 #endif
116 
117 #ifdef CONFIG_DEBUG_LOCK_ALLOC
118 bool console_srcu_read_lock_is_held(void)
119 {
120 	return srcu_read_lock_held(&console_srcu);
121 }
122 EXPORT_SYMBOL(console_srcu_read_lock_is_held);
123 #endif
124 
125 enum devkmsg_log_bits {
126 	__DEVKMSG_LOG_BIT_ON = 0,
127 	__DEVKMSG_LOG_BIT_OFF,
128 	__DEVKMSG_LOG_BIT_LOCK,
129 };
130 
131 enum devkmsg_log_masks {
132 	DEVKMSG_LOG_MASK_ON             = BIT(__DEVKMSG_LOG_BIT_ON),
133 	DEVKMSG_LOG_MASK_OFF            = BIT(__DEVKMSG_LOG_BIT_OFF),
134 	DEVKMSG_LOG_MASK_LOCK           = BIT(__DEVKMSG_LOG_BIT_LOCK),
135 };
136 
137 /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
138 #define DEVKMSG_LOG_MASK_DEFAULT	0
139 
140 static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
141 
142 static int __control_devkmsg(char *str)
143 {
144 	size_t len;
145 
146 	if (!str)
147 		return -EINVAL;
148 
149 	len = str_has_prefix(str, "on");
150 	if (len) {
151 		devkmsg_log = DEVKMSG_LOG_MASK_ON;
152 		return len;
153 	}
154 
155 	len = str_has_prefix(str, "off");
156 	if (len) {
157 		devkmsg_log = DEVKMSG_LOG_MASK_OFF;
158 		return len;
159 	}
160 
161 	len = str_has_prefix(str, "ratelimit");
162 	if (len) {
163 		devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
164 		return len;
165 	}
166 
167 	return -EINVAL;
168 }
169 
170 static int __init control_devkmsg(char *str)
171 {
172 	if (__control_devkmsg(str) < 0) {
173 		pr_warn("printk.devkmsg: bad option string '%s'\n", str);
174 		return 1;
175 	}
176 
177 	/*
178 	 * Set sysctl string accordingly:
179 	 */
180 	if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
181 		strcpy(devkmsg_log_str, "on");
182 	else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
183 		strcpy(devkmsg_log_str, "off");
184 	/* else "ratelimit" which is set by default. */
185 
186 	/*
187 	 * Sysctl cannot change it anymore. The kernel command line setting of
188 	 * this parameter is to force the setting to be permanent throughout the
189 	 * runtime of the system. This is a precation measure against userspace
190 	 * trying to be a smarta** and attempting to change it up on us.
191 	 */
192 	devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
193 
194 	return 1;
195 }
196 __setup("printk.devkmsg=", control_devkmsg);
197 
198 char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
199 #if defined(CONFIG_PRINTK) && defined(CONFIG_SYSCTL)
200 int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
201 			      void *buffer, size_t *lenp, loff_t *ppos)
202 {
203 	char old_str[DEVKMSG_STR_MAX_SIZE];
204 	unsigned int old;
205 	int err;
206 
207 	if (write) {
208 		if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
209 			return -EINVAL;
210 
211 		old = devkmsg_log;
212 		strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
213 	}
214 
215 	err = proc_dostring(table, write, buffer, lenp, ppos);
216 	if (err)
217 		return err;
218 
219 	if (write) {
220 		err = __control_devkmsg(devkmsg_log_str);
221 
222 		/*
223 		 * Do not accept an unknown string OR a known string with
224 		 * trailing crap...
225 		 */
226 		if (err < 0 || (err + 1 != *lenp)) {
227 
228 			/* ... and restore old setting. */
229 			devkmsg_log = old;
230 			strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
231 
232 			return -EINVAL;
233 		}
234 	}
235 
236 	return 0;
237 }
238 #endif /* CONFIG_PRINTK && CONFIG_SYSCTL */
239 
240 /**
241  * console_list_lock - Lock the console list
242  *
243  * For console list or console->flags updates
244  */
245 void console_list_lock(void)
246 {
247 	/*
248 	 * In unregister_console() and console_force_preferred_locked(),
249 	 * synchronize_srcu() is called with the console_list_lock held.
250 	 * Therefore it is not allowed that the console_list_lock is taken
251 	 * with the srcu_lock held.
252 	 *
253 	 * Detecting if this context is really in the read-side critical
254 	 * section is only possible if the appropriate debug options are
255 	 * enabled.
256 	 */
257 	WARN_ON_ONCE(debug_lockdep_rcu_enabled() &&
258 		     srcu_read_lock_held(&console_srcu));
259 
260 	mutex_lock(&console_mutex);
261 }
262 EXPORT_SYMBOL(console_list_lock);
263 
264 /**
265  * console_list_unlock - Unlock the console list
266  *
267  * Counterpart to console_list_lock()
268  */
269 void console_list_unlock(void)
270 {
271 	mutex_unlock(&console_mutex);
272 }
273 EXPORT_SYMBOL(console_list_unlock);
274 
275 /**
276  * console_srcu_read_lock - Register a new reader for the
277  *	SRCU-protected console list
278  *
279  * Use for_each_console_srcu() to iterate the console list
280  *
281  * Context: Any context.
282  * Return: A cookie to pass to console_srcu_read_unlock().
283  */
284 int console_srcu_read_lock(void)
285 {
286 	return srcu_read_lock_nmisafe(&console_srcu);
287 }
288 EXPORT_SYMBOL(console_srcu_read_lock);
289 
290 /**
291  * console_srcu_read_unlock - Unregister an old reader from
292  *	the SRCU-protected console list
293  * @cookie: cookie returned from console_srcu_read_lock()
294  *
295  * Counterpart to console_srcu_read_lock()
296  */
297 void console_srcu_read_unlock(int cookie)
298 {
299 	srcu_read_unlock_nmisafe(&console_srcu, cookie);
300 }
301 EXPORT_SYMBOL(console_srcu_read_unlock);
302 
303 /*
304  * Helper macros to handle lockdep when locking/unlocking console_sem. We use
305  * macros instead of functions so that _RET_IP_ contains useful information.
306  */
307 #define down_console_sem() do { \
308 	down(&console_sem);\
309 	mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
310 } while (0)
311 
312 static int __down_trylock_console_sem(unsigned long ip)
313 {
314 	int lock_failed;
315 	unsigned long flags;
316 
317 	/*
318 	 * Here and in __up_console_sem() we need to be in safe mode,
319 	 * because spindump/WARN/etc from under console ->lock will
320 	 * deadlock in printk()->down_trylock_console_sem() otherwise.
321 	 */
322 	printk_safe_enter_irqsave(flags);
323 	lock_failed = down_trylock(&console_sem);
324 	printk_safe_exit_irqrestore(flags);
325 
326 	if (lock_failed)
327 		return 1;
328 	mutex_acquire(&console_lock_dep_map, 0, 1, ip);
329 	return 0;
330 }
331 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
332 
333 static void __up_console_sem(unsigned long ip)
334 {
335 	unsigned long flags;
336 
337 	mutex_release(&console_lock_dep_map, ip);
338 
339 	printk_safe_enter_irqsave(flags);
340 	up(&console_sem);
341 	printk_safe_exit_irqrestore(flags);
342 }
343 #define up_console_sem() __up_console_sem(_RET_IP_)
344 
345 static bool panic_in_progress(void)
346 {
347 	return unlikely(atomic_read(&panic_cpu) != PANIC_CPU_INVALID);
348 }
349 
350 /*
351  * This is used for debugging the mess that is the VT code by
352  * keeping track if we have the console semaphore held. It's
353  * definitely not the perfect debug tool (we don't know if _WE_
354  * hold it and are racing, but it helps tracking those weird code
355  * paths in the console code where we end up in places I want
356  * locked without the console semaphore held).
357  */
358 static int console_locked;
359 
360 /*
361  *	Array of consoles built from command line options (console=)
362  */
363 
364 #define MAX_CMDLINECONSOLES 8
365 
366 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
367 
368 static int preferred_console = -1;
369 int console_set_on_cmdline;
370 EXPORT_SYMBOL(console_set_on_cmdline);
371 
372 /* Flag: console code may call schedule() */
373 static int console_may_schedule;
374 
375 enum con_msg_format_flags {
376 	MSG_FORMAT_DEFAULT	= 0,
377 	MSG_FORMAT_SYSLOG	= (1 << 0),
378 };
379 
380 static int console_msg_format = MSG_FORMAT_DEFAULT;
381 
382 /*
383  * The printk log buffer consists of a sequenced collection of records, each
384  * containing variable length message text. Every record also contains its
385  * own meta-data (@info).
386  *
387  * Every record meta-data carries the timestamp in microseconds, as well as
388  * the standard userspace syslog level and syslog facility. The usual kernel
389  * messages use LOG_KERN; userspace-injected messages always carry a matching
390  * syslog facility, by default LOG_USER. The origin of every message can be
391  * reliably determined that way.
392  *
393  * The human readable log message of a record is available in @text, the
394  * length of the message text in @text_len. The stored message is not
395  * terminated.
396  *
397  * Optionally, a record can carry a dictionary of properties (key/value
398  * pairs), to provide userspace with a machine-readable message context.
399  *
400  * Examples for well-defined, commonly used property names are:
401  *   DEVICE=b12:8               device identifier
402  *                                b12:8         block dev_t
403  *                                c127:3        char dev_t
404  *                                n8            netdev ifindex
405  *                                +sound:card0  subsystem:devname
406  *   SUBSYSTEM=pci              driver-core subsystem name
407  *
408  * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
409  * and values are terminated by a '\0' character.
410  *
411  * Example of record values:
412  *   record.text_buf                = "it's a line" (unterminated)
413  *   record.info.seq                = 56
414  *   record.info.ts_nsec            = 36863
415  *   record.info.text_len           = 11
416  *   record.info.facility           = 0 (LOG_KERN)
417  *   record.info.flags              = 0
418  *   record.info.level              = 3 (LOG_ERR)
419  *   record.info.caller_id          = 299 (task 299)
420  *   record.info.dev_info.subsystem = "pci" (terminated)
421  *   record.info.dev_info.device    = "+pci:0000:00:01.0" (terminated)
422  *
423  * The 'struct printk_info' buffer must never be directly exported to
424  * userspace, it is a kernel-private implementation detail that might
425  * need to be changed in the future, when the requirements change.
426  *
427  * /dev/kmsg exports the structured data in the following line format:
428  *   "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
429  *
430  * Users of the export format should ignore possible additional values
431  * separated by ',', and find the message after the ';' character.
432  *
433  * The optional key/value pairs are attached as continuation lines starting
434  * with a space character and terminated by a newline. All possible
435  * non-prinatable characters are escaped in the "\xff" notation.
436  */
437 
438 /* syslog_lock protects syslog_* variables and write access to clear_seq. */
439 static DEFINE_MUTEX(syslog_lock);
440 
441 #ifdef CONFIG_PRINTK
442 /*
443  * During panic, heavy printk by other CPUs can delay the
444  * panic and risk deadlock on console resources.
445  */
446 static int __read_mostly suppress_panic_printk;
447 
448 DECLARE_WAIT_QUEUE_HEAD(log_wait);
449 /* All 3 protected by @syslog_lock. */
450 /* the next printk record to read by syslog(READ) or /proc/kmsg */
451 static u64 syslog_seq;
452 static size_t syslog_partial;
453 static bool syslog_time;
454 
455 struct latched_seq {
456 	seqcount_latch_t	latch;
457 	u64			val[2];
458 };
459 
460 /*
461  * The next printk record to read after the last 'clear' command. There are
462  * two copies (updated with seqcount_latch) so that reads can locklessly
463  * access a valid value. Writers are synchronized by @syslog_lock.
464  */
465 static struct latched_seq clear_seq = {
466 	.latch		= SEQCNT_LATCH_ZERO(clear_seq.latch),
467 	.val[0]		= 0,
468 	.val[1]		= 0,
469 };
470 
471 #define LOG_LEVEL(v)		((v) & 0x07)
472 #define LOG_FACILITY(v)		((v) >> 3 & 0xff)
473 
474 /* record buffer */
475 #define LOG_ALIGN __alignof__(unsigned long)
476 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
477 #define LOG_BUF_LEN_MAX (u32)(1 << 31)
478 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
479 static char *log_buf = __log_buf;
480 static u32 log_buf_len = __LOG_BUF_LEN;
481 
482 /*
483  * Define the average message size. This only affects the number of
484  * descriptors that will be available. Underestimating is better than
485  * overestimating (too many available descriptors is better than not enough).
486  */
487 #define PRB_AVGBITS 5	/* 32 character average length */
488 
489 #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
490 #error CONFIG_LOG_BUF_SHIFT value too small.
491 #endif
492 _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
493 		 PRB_AVGBITS, &__log_buf[0]);
494 
495 static struct printk_ringbuffer printk_rb_dynamic;
496 
497 struct printk_ringbuffer *prb = &printk_rb_static;
498 
499 /*
500  * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
501  * per_cpu_areas are initialised. This variable is set to true when
502  * it's safe to access per-CPU data.
503  */
504 static bool __printk_percpu_data_ready __ro_after_init;
505 
506 bool printk_percpu_data_ready(void)
507 {
508 	return __printk_percpu_data_ready;
509 }
510 
511 /* Must be called under syslog_lock. */
512 static void latched_seq_write(struct latched_seq *ls, u64 val)
513 {
514 	raw_write_seqcount_latch(&ls->latch);
515 	ls->val[0] = val;
516 	raw_write_seqcount_latch(&ls->latch);
517 	ls->val[1] = val;
518 }
519 
520 /* Can be called from any context. */
521 static u64 latched_seq_read_nolock(struct latched_seq *ls)
522 {
523 	unsigned int seq;
524 	unsigned int idx;
525 	u64 val;
526 
527 	do {
528 		seq = raw_read_seqcount_latch(&ls->latch);
529 		idx = seq & 0x1;
530 		val = ls->val[idx];
531 	} while (raw_read_seqcount_latch_retry(&ls->latch, seq));
532 
533 	return val;
534 }
535 
536 /* Return log buffer address */
537 char *log_buf_addr_get(void)
538 {
539 	return log_buf;
540 }
541 
542 /* Return log buffer size */
543 u32 log_buf_len_get(void)
544 {
545 	return log_buf_len;
546 }
547 
548 /*
549  * Define how much of the log buffer we could take at maximum. The value
550  * must be greater than two. Note that only half of the buffer is available
551  * when the index points to the middle.
552  */
553 #define MAX_LOG_TAKE_PART 4
554 static const char trunc_msg[] = "<truncated>";
555 
556 static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
557 {
558 	/*
559 	 * The message should not take the whole buffer. Otherwise, it might
560 	 * get removed too soon.
561 	 */
562 	u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
563 
564 	if (*text_len > max_text_len)
565 		*text_len = max_text_len;
566 
567 	/* enable the warning message (if there is room) */
568 	*trunc_msg_len = strlen(trunc_msg);
569 	if (*text_len >= *trunc_msg_len)
570 		*text_len -= *trunc_msg_len;
571 	else
572 		*trunc_msg_len = 0;
573 }
574 
575 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
576 
577 static int syslog_action_restricted(int type)
578 {
579 	if (dmesg_restrict)
580 		return 1;
581 	/*
582 	 * Unless restricted, we allow "read all" and "get buffer size"
583 	 * for everybody.
584 	 */
585 	return type != SYSLOG_ACTION_READ_ALL &&
586 	       type != SYSLOG_ACTION_SIZE_BUFFER;
587 }
588 
589 static int check_syslog_permissions(int type, int source)
590 {
591 	/*
592 	 * If this is from /proc/kmsg and we've already opened it, then we've
593 	 * already done the capabilities checks at open time.
594 	 */
595 	if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
596 		goto ok;
597 
598 	if (syslog_action_restricted(type)) {
599 		if (capable(CAP_SYSLOG))
600 			goto ok;
601 		return -EPERM;
602 	}
603 ok:
604 	return security_syslog(type);
605 }
606 
607 static void append_char(char **pp, char *e, char c)
608 {
609 	if (*pp < e)
610 		*(*pp)++ = c;
611 }
612 
613 static ssize_t info_print_ext_header(char *buf, size_t size,
614 				     struct printk_info *info)
615 {
616 	u64 ts_usec = info->ts_nsec;
617 	char caller[20];
618 #ifdef CONFIG_PRINTK_CALLER
619 	u32 id = info->caller_id;
620 
621 	snprintf(caller, sizeof(caller), ",caller=%c%u",
622 		 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
623 #else
624 	caller[0] = '\0';
625 #endif
626 
627 	do_div(ts_usec, 1000);
628 
629 	return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
630 			 (info->facility << 3) | info->level, info->seq,
631 			 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
632 }
633 
634 static ssize_t msg_add_ext_text(char *buf, size_t size,
635 				const char *text, size_t text_len,
636 				unsigned char endc)
637 {
638 	char *p = buf, *e = buf + size;
639 	size_t i;
640 
641 	/* escape non-printable characters */
642 	for (i = 0; i < text_len; i++) {
643 		unsigned char c = text[i];
644 
645 		if (c < ' ' || c >= 127 || c == '\\')
646 			p += scnprintf(p, e - p, "\\x%02x", c);
647 		else
648 			append_char(&p, e, c);
649 	}
650 	append_char(&p, e, endc);
651 
652 	return p - buf;
653 }
654 
655 static ssize_t msg_add_dict_text(char *buf, size_t size,
656 				 const char *key, const char *val)
657 {
658 	size_t val_len = strlen(val);
659 	ssize_t len;
660 
661 	if (!val_len)
662 		return 0;
663 
664 	len = msg_add_ext_text(buf, size, "", 0, ' ');	/* dict prefix */
665 	len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
666 	len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
667 
668 	return len;
669 }
670 
671 static ssize_t msg_print_ext_body(char *buf, size_t size,
672 				  char *text, size_t text_len,
673 				  struct dev_printk_info *dev_info)
674 {
675 	ssize_t len;
676 
677 	len = msg_add_ext_text(buf, size, text, text_len, '\n');
678 
679 	if (!dev_info)
680 		goto out;
681 
682 	len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
683 				 dev_info->subsystem);
684 	len += msg_add_dict_text(buf + len, size - len, "DEVICE",
685 				 dev_info->device);
686 out:
687 	return len;
688 }
689 
690 /* /dev/kmsg - userspace message inject/listen interface */
691 struct devkmsg_user {
692 	atomic64_t seq;
693 	struct ratelimit_state rs;
694 	struct mutex lock;
695 	struct printk_buffers pbufs;
696 };
697 
698 static __printf(3, 4) __cold
699 int devkmsg_emit(int facility, int level, const char *fmt, ...)
700 {
701 	va_list args;
702 	int r;
703 
704 	va_start(args, fmt);
705 	r = vprintk_emit(facility, level, NULL, fmt, args);
706 	va_end(args);
707 
708 	return r;
709 }
710 
711 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
712 {
713 	char *buf, *line;
714 	int level = default_message_loglevel;
715 	int facility = 1;	/* LOG_USER */
716 	struct file *file = iocb->ki_filp;
717 	struct devkmsg_user *user = file->private_data;
718 	size_t len = iov_iter_count(from);
719 	ssize_t ret = len;
720 
721 	if (len > PRINTKRB_RECORD_MAX)
722 		return -EINVAL;
723 
724 	/* Ignore when user logging is disabled. */
725 	if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
726 		return len;
727 
728 	/* Ratelimit when not explicitly enabled. */
729 	if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
730 		if (!___ratelimit(&user->rs, current->comm))
731 			return ret;
732 	}
733 
734 	buf = kmalloc(len+1, GFP_KERNEL);
735 	if (buf == NULL)
736 		return -ENOMEM;
737 
738 	buf[len] = '\0';
739 	if (!copy_from_iter_full(buf, len, from)) {
740 		kfree(buf);
741 		return -EFAULT;
742 	}
743 
744 	/*
745 	 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
746 	 * the decimal value represents 32bit, the lower 3 bit are the log
747 	 * level, the rest are the log facility.
748 	 *
749 	 * If no prefix or no userspace facility is specified, we
750 	 * enforce LOG_USER, to be able to reliably distinguish
751 	 * kernel-generated messages from userspace-injected ones.
752 	 */
753 	line = buf;
754 	if (line[0] == '<') {
755 		char *endp = NULL;
756 		unsigned int u;
757 
758 		u = simple_strtoul(line + 1, &endp, 10);
759 		if (endp && endp[0] == '>') {
760 			level = LOG_LEVEL(u);
761 			if (LOG_FACILITY(u) != 0)
762 				facility = LOG_FACILITY(u);
763 			endp++;
764 			line = endp;
765 		}
766 	}
767 
768 	devkmsg_emit(facility, level, "%s", line);
769 	kfree(buf);
770 	return ret;
771 }
772 
773 static ssize_t devkmsg_read(struct file *file, char __user *buf,
774 			    size_t count, loff_t *ppos)
775 {
776 	struct devkmsg_user *user = file->private_data;
777 	char *outbuf = &user->pbufs.outbuf[0];
778 	struct printk_message pmsg = {
779 		.pbufs = &user->pbufs,
780 	};
781 	ssize_t ret;
782 
783 	ret = mutex_lock_interruptible(&user->lock);
784 	if (ret)
785 		return ret;
786 
787 	if (!printk_get_next_message(&pmsg, atomic64_read(&user->seq), true, false)) {
788 		if (file->f_flags & O_NONBLOCK) {
789 			ret = -EAGAIN;
790 			goto out;
791 		}
792 
793 		/*
794 		 * Guarantee this task is visible on the waitqueue before
795 		 * checking the wake condition.
796 		 *
797 		 * The full memory barrier within set_current_state() of
798 		 * prepare_to_wait_event() pairs with the full memory barrier
799 		 * within wq_has_sleeper().
800 		 *
801 		 * This pairs with __wake_up_klogd:A.
802 		 */
803 		ret = wait_event_interruptible(log_wait,
804 				printk_get_next_message(&pmsg, atomic64_read(&user->seq), true,
805 							false)); /* LMM(devkmsg_read:A) */
806 		if (ret)
807 			goto out;
808 	}
809 
810 	if (pmsg.dropped) {
811 		/* our last seen message is gone, return error and reset */
812 		atomic64_set(&user->seq, pmsg.seq);
813 		ret = -EPIPE;
814 		goto out;
815 	}
816 
817 	atomic64_set(&user->seq, pmsg.seq + 1);
818 
819 	if (pmsg.outbuf_len > count) {
820 		ret = -EINVAL;
821 		goto out;
822 	}
823 
824 	if (copy_to_user(buf, outbuf, pmsg.outbuf_len)) {
825 		ret = -EFAULT;
826 		goto out;
827 	}
828 	ret = pmsg.outbuf_len;
829 out:
830 	mutex_unlock(&user->lock);
831 	return ret;
832 }
833 
834 /*
835  * Be careful when modifying this function!!!
836  *
837  * Only few operations are supported because the device works only with the
838  * entire variable length messages (records). Non-standard values are
839  * returned in the other cases and has been this way for quite some time.
840  * User space applications might depend on this behavior.
841  */
842 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
843 {
844 	struct devkmsg_user *user = file->private_data;
845 	loff_t ret = 0;
846 
847 	if (offset)
848 		return -ESPIPE;
849 
850 	switch (whence) {
851 	case SEEK_SET:
852 		/* the first record */
853 		atomic64_set(&user->seq, prb_first_valid_seq(prb));
854 		break;
855 	case SEEK_DATA:
856 		/*
857 		 * The first record after the last SYSLOG_ACTION_CLEAR,
858 		 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
859 		 * changes no global state, and does not clear anything.
860 		 */
861 		atomic64_set(&user->seq, latched_seq_read_nolock(&clear_seq));
862 		break;
863 	case SEEK_END:
864 		/* after the last record */
865 		atomic64_set(&user->seq, prb_next_seq(prb));
866 		break;
867 	default:
868 		ret = -EINVAL;
869 	}
870 	return ret;
871 }
872 
873 static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
874 {
875 	struct devkmsg_user *user = file->private_data;
876 	struct printk_info info;
877 	__poll_t ret = 0;
878 
879 	poll_wait(file, &log_wait, wait);
880 
881 	if (prb_read_valid_info(prb, atomic64_read(&user->seq), &info, NULL)) {
882 		/* return error when data has vanished underneath us */
883 		if (info.seq != atomic64_read(&user->seq))
884 			ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
885 		else
886 			ret = EPOLLIN|EPOLLRDNORM;
887 	}
888 
889 	return ret;
890 }
891 
892 static int devkmsg_open(struct inode *inode, struct file *file)
893 {
894 	struct devkmsg_user *user;
895 	int err;
896 
897 	if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
898 		return -EPERM;
899 
900 	/* write-only does not need any file context */
901 	if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
902 		err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
903 					       SYSLOG_FROM_READER);
904 		if (err)
905 			return err;
906 	}
907 
908 	user = kvmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
909 	if (!user)
910 		return -ENOMEM;
911 
912 	ratelimit_default_init(&user->rs);
913 	ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
914 
915 	mutex_init(&user->lock);
916 
917 	atomic64_set(&user->seq, prb_first_valid_seq(prb));
918 
919 	file->private_data = user;
920 	return 0;
921 }
922 
923 static int devkmsg_release(struct inode *inode, struct file *file)
924 {
925 	struct devkmsg_user *user = file->private_data;
926 
927 	ratelimit_state_exit(&user->rs);
928 
929 	mutex_destroy(&user->lock);
930 	kvfree(user);
931 	return 0;
932 }
933 
934 const struct file_operations kmsg_fops = {
935 	.open = devkmsg_open,
936 	.read = devkmsg_read,
937 	.write_iter = devkmsg_write,
938 	.llseek = devkmsg_llseek,
939 	.poll = devkmsg_poll,
940 	.release = devkmsg_release,
941 };
942 
943 #ifdef CONFIG_CRASH_CORE
944 /*
945  * This appends the listed symbols to /proc/vmcore
946  *
947  * /proc/vmcore is used by various utilities, like crash and makedumpfile to
948  * obtain access to symbols that are otherwise very difficult to locate.  These
949  * symbols are specifically used so that utilities can access and extract the
950  * dmesg log from a vmcore file after a crash.
951  */
952 void log_buf_vmcoreinfo_setup(void)
953 {
954 	struct dev_printk_info *dev_info = NULL;
955 
956 	VMCOREINFO_SYMBOL(prb);
957 	VMCOREINFO_SYMBOL(printk_rb_static);
958 	VMCOREINFO_SYMBOL(clear_seq);
959 
960 	/*
961 	 * Export struct size and field offsets. User space tools can
962 	 * parse it and detect any changes to structure down the line.
963 	 */
964 
965 	VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
966 	VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
967 	VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
968 	VMCOREINFO_OFFSET(printk_ringbuffer, fail);
969 
970 	VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
971 	VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
972 	VMCOREINFO_OFFSET(prb_desc_ring, descs);
973 	VMCOREINFO_OFFSET(prb_desc_ring, infos);
974 	VMCOREINFO_OFFSET(prb_desc_ring, head_id);
975 	VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
976 
977 	VMCOREINFO_STRUCT_SIZE(prb_desc);
978 	VMCOREINFO_OFFSET(prb_desc, state_var);
979 	VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
980 
981 	VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
982 	VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
983 	VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
984 
985 	VMCOREINFO_STRUCT_SIZE(printk_info);
986 	VMCOREINFO_OFFSET(printk_info, seq);
987 	VMCOREINFO_OFFSET(printk_info, ts_nsec);
988 	VMCOREINFO_OFFSET(printk_info, text_len);
989 	VMCOREINFO_OFFSET(printk_info, caller_id);
990 	VMCOREINFO_OFFSET(printk_info, dev_info);
991 
992 	VMCOREINFO_STRUCT_SIZE(dev_printk_info);
993 	VMCOREINFO_OFFSET(dev_printk_info, subsystem);
994 	VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
995 	VMCOREINFO_OFFSET(dev_printk_info, device);
996 	VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
997 
998 	VMCOREINFO_STRUCT_SIZE(prb_data_ring);
999 	VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1000 	VMCOREINFO_OFFSET(prb_data_ring, data);
1001 	VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1002 	VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1003 
1004 	VMCOREINFO_SIZE(atomic_long_t);
1005 	VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
1006 
1007 	VMCOREINFO_STRUCT_SIZE(latched_seq);
1008 	VMCOREINFO_OFFSET(latched_seq, val);
1009 }
1010 #endif
1011 
1012 /* requested log_buf_len from kernel cmdline */
1013 static unsigned long __initdata new_log_buf_len;
1014 
1015 /* we practice scaling the ring buffer by powers of 2 */
1016 static void __init log_buf_len_update(u64 size)
1017 {
1018 	if (size > (u64)LOG_BUF_LEN_MAX) {
1019 		size = (u64)LOG_BUF_LEN_MAX;
1020 		pr_err("log_buf over 2G is not supported.\n");
1021 	}
1022 
1023 	if (size)
1024 		size = roundup_pow_of_two(size);
1025 	if (size > log_buf_len)
1026 		new_log_buf_len = (unsigned long)size;
1027 }
1028 
1029 /* save requested log_buf_len since it's too early to process it */
1030 static int __init log_buf_len_setup(char *str)
1031 {
1032 	u64 size;
1033 
1034 	if (!str)
1035 		return -EINVAL;
1036 
1037 	size = memparse(str, &str);
1038 
1039 	log_buf_len_update(size);
1040 
1041 	return 0;
1042 }
1043 early_param("log_buf_len", log_buf_len_setup);
1044 
1045 #ifdef CONFIG_SMP
1046 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
1047 
1048 static void __init log_buf_add_cpu(void)
1049 {
1050 	unsigned int cpu_extra;
1051 
1052 	/*
1053 	 * archs should set up cpu_possible_bits properly with
1054 	 * set_cpu_possible() after setup_arch() but just in
1055 	 * case lets ensure this is valid.
1056 	 */
1057 	if (num_possible_cpus() == 1)
1058 		return;
1059 
1060 	cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
1061 
1062 	/* by default this will only continue through for large > 64 CPUs */
1063 	if (cpu_extra <= __LOG_BUF_LEN / 2)
1064 		return;
1065 
1066 	pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
1067 		__LOG_CPU_MAX_BUF_LEN);
1068 	pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
1069 		cpu_extra);
1070 	pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1071 
1072 	log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1073 }
1074 #else /* !CONFIG_SMP */
1075 static inline void log_buf_add_cpu(void) {}
1076 #endif /* CONFIG_SMP */
1077 
1078 static void __init set_percpu_data_ready(void)
1079 {
1080 	__printk_percpu_data_ready = true;
1081 }
1082 
1083 static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1084 				     struct printk_record *r)
1085 {
1086 	struct prb_reserved_entry e;
1087 	struct printk_record dest_r;
1088 
1089 	prb_rec_init_wr(&dest_r, r->info->text_len);
1090 
1091 	if (!prb_reserve(&e, rb, &dest_r))
1092 		return 0;
1093 
1094 	memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1095 	dest_r.info->text_len = r->info->text_len;
1096 	dest_r.info->facility = r->info->facility;
1097 	dest_r.info->level = r->info->level;
1098 	dest_r.info->flags = r->info->flags;
1099 	dest_r.info->ts_nsec = r->info->ts_nsec;
1100 	dest_r.info->caller_id = r->info->caller_id;
1101 	memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1102 
1103 	prb_final_commit(&e);
1104 
1105 	return prb_record_text_space(&e);
1106 }
1107 
1108 static char setup_text_buf[PRINTKRB_RECORD_MAX] __initdata;
1109 
1110 void __init setup_log_buf(int early)
1111 {
1112 	struct printk_info *new_infos;
1113 	unsigned int new_descs_count;
1114 	struct prb_desc *new_descs;
1115 	struct printk_info info;
1116 	struct printk_record r;
1117 	unsigned int text_size;
1118 	size_t new_descs_size;
1119 	size_t new_infos_size;
1120 	unsigned long flags;
1121 	char *new_log_buf;
1122 	unsigned int free;
1123 	u64 seq;
1124 
1125 	/*
1126 	 * Some archs call setup_log_buf() multiple times - first is very
1127 	 * early, e.g. from setup_arch(), and second - when percpu_areas
1128 	 * are initialised.
1129 	 */
1130 	if (!early)
1131 		set_percpu_data_ready();
1132 
1133 	if (log_buf != __log_buf)
1134 		return;
1135 
1136 	if (!early && !new_log_buf_len)
1137 		log_buf_add_cpu();
1138 
1139 	if (!new_log_buf_len)
1140 		return;
1141 
1142 	new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1143 	if (new_descs_count == 0) {
1144 		pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1145 		return;
1146 	}
1147 
1148 	new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1149 	if (unlikely(!new_log_buf)) {
1150 		pr_err("log_buf_len: %lu text bytes not available\n",
1151 		       new_log_buf_len);
1152 		return;
1153 	}
1154 
1155 	new_descs_size = new_descs_count * sizeof(struct prb_desc);
1156 	new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1157 	if (unlikely(!new_descs)) {
1158 		pr_err("log_buf_len: %zu desc bytes not available\n",
1159 		       new_descs_size);
1160 		goto err_free_log_buf;
1161 	}
1162 
1163 	new_infos_size = new_descs_count * sizeof(struct printk_info);
1164 	new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1165 	if (unlikely(!new_infos)) {
1166 		pr_err("log_buf_len: %zu info bytes not available\n",
1167 		       new_infos_size);
1168 		goto err_free_descs;
1169 	}
1170 
1171 	prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1172 
1173 	prb_init(&printk_rb_dynamic,
1174 		 new_log_buf, ilog2(new_log_buf_len),
1175 		 new_descs, ilog2(new_descs_count),
1176 		 new_infos);
1177 
1178 	local_irq_save(flags);
1179 
1180 	log_buf_len = new_log_buf_len;
1181 	log_buf = new_log_buf;
1182 	new_log_buf_len = 0;
1183 
1184 	free = __LOG_BUF_LEN;
1185 	prb_for_each_record(0, &printk_rb_static, seq, &r) {
1186 		text_size = add_to_rb(&printk_rb_dynamic, &r);
1187 		if (text_size > free)
1188 			free = 0;
1189 		else
1190 			free -= text_size;
1191 	}
1192 
1193 	prb = &printk_rb_dynamic;
1194 
1195 	local_irq_restore(flags);
1196 
1197 	/*
1198 	 * Copy any remaining messages that might have appeared from
1199 	 * NMI context after copying but before switching to the
1200 	 * dynamic buffer.
1201 	 */
1202 	prb_for_each_record(seq, &printk_rb_static, seq, &r) {
1203 		text_size = add_to_rb(&printk_rb_dynamic, &r);
1204 		if (text_size > free)
1205 			free = 0;
1206 		else
1207 			free -= text_size;
1208 	}
1209 
1210 	if (seq != prb_next_seq(&printk_rb_static)) {
1211 		pr_err("dropped %llu messages\n",
1212 		       prb_next_seq(&printk_rb_static) - seq);
1213 	}
1214 
1215 	pr_info("log_buf_len: %u bytes\n", log_buf_len);
1216 	pr_info("early log buf free: %u(%u%%)\n",
1217 		free, (free * 100) / __LOG_BUF_LEN);
1218 	return;
1219 
1220 err_free_descs:
1221 	memblock_free(new_descs, new_descs_size);
1222 err_free_log_buf:
1223 	memblock_free(new_log_buf, new_log_buf_len);
1224 }
1225 
1226 static bool __read_mostly ignore_loglevel;
1227 
1228 static int __init ignore_loglevel_setup(char *str)
1229 {
1230 	ignore_loglevel = true;
1231 	pr_info("debug: ignoring loglevel setting.\n");
1232 
1233 	return 0;
1234 }
1235 
1236 early_param("ignore_loglevel", ignore_loglevel_setup);
1237 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1238 MODULE_PARM_DESC(ignore_loglevel,
1239 		 "ignore loglevel setting (prints all kernel messages to the console)");
1240 
1241 static bool suppress_message_printing(int level)
1242 {
1243 	return (level >= console_loglevel && !ignore_loglevel);
1244 }
1245 
1246 #ifdef CONFIG_BOOT_PRINTK_DELAY
1247 
1248 static int boot_delay; /* msecs delay after each printk during bootup */
1249 static unsigned long long loops_per_msec;	/* based on boot_delay */
1250 
1251 static int __init boot_delay_setup(char *str)
1252 {
1253 	unsigned long lpj;
1254 
1255 	lpj = preset_lpj ? preset_lpj : 1000000;	/* some guess */
1256 	loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1257 
1258 	get_option(&str, &boot_delay);
1259 	if (boot_delay > 10 * 1000)
1260 		boot_delay = 0;
1261 
1262 	pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1263 		"HZ: %d, loops_per_msec: %llu\n",
1264 		boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1265 	return 0;
1266 }
1267 early_param("boot_delay", boot_delay_setup);
1268 
1269 static void boot_delay_msec(int level)
1270 {
1271 	unsigned long long k;
1272 	unsigned long timeout;
1273 
1274 	if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1275 		|| suppress_message_printing(level)) {
1276 		return;
1277 	}
1278 
1279 	k = (unsigned long long)loops_per_msec * boot_delay;
1280 
1281 	timeout = jiffies + msecs_to_jiffies(boot_delay);
1282 	while (k) {
1283 		k--;
1284 		cpu_relax();
1285 		/*
1286 		 * use (volatile) jiffies to prevent
1287 		 * compiler reduction; loop termination via jiffies
1288 		 * is secondary and may or may not happen.
1289 		 */
1290 		if (time_after(jiffies, timeout))
1291 			break;
1292 		touch_nmi_watchdog();
1293 	}
1294 }
1295 #else
1296 static inline void boot_delay_msec(int level)
1297 {
1298 }
1299 #endif
1300 
1301 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1302 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1303 
1304 static size_t print_syslog(unsigned int level, char *buf)
1305 {
1306 	return sprintf(buf, "<%u>", level);
1307 }
1308 
1309 static size_t print_time(u64 ts, char *buf)
1310 {
1311 	unsigned long rem_nsec = do_div(ts, 1000000000);
1312 
1313 	return sprintf(buf, "[%5lu.%06lu]",
1314 		       (unsigned long)ts, rem_nsec / 1000);
1315 }
1316 
1317 #ifdef CONFIG_PRINTK_CALLER
1318 static size_t print_caller(u32 id, char *buf)
1319 {
1320 	char caller[12];
1321 
1322 	snprintf(caller, sizeof(caller), "%c%u",
1323 		 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1324 	return sprintf(buf, "[%6s]", caller);
1325 }
1326 #else
1327 #define print_caller(id, buf) 0
1328 #endif
1329 
1330 static size_t info_print_prefix(const struct printk_info  *info, bool syslog,
1331 				bool time, char *buf)
1332 {
1333 	size_t len = 0;
1334 
1335 	if (syslog)
1336 		len = print_syslog((info->facility << 3) | info->level, buf);
1337 
1338 	if (time)
1339 		len += print_time(info->ts_nsec, buf + len);
1340 
1341 	len += print_caller(info->caller_id, buf + len);
1342 
1343 	if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1344 		buf[len++] = ' ';
1345 		buf[len] = '\0';
1346 	}
1347 
1348 	return len;
1349 }
1350 
1351 /*
1352  * Prepare the record for printing. The text is shifted within the given
1353  * buffer to avoid a need for another one. The following operations are
1354  * done:
1355  *
1356  *   - Add prefix for each line.
1357  *   - Drop truncated lines that no longer fit into the buffer.
1358  *   - Add the trailing newline that has been removed in vprintk_store().
1359  *   - Add a string terminator.
1360  *
1361  * Since the produced string is always terminated, the maximum possible
1362  * return value is @r->text_buf_size - 1;
1363  *
1364  * Return: The length of the updated/prepared text, including the added
1365  * prefixes and the newline. The terminator is not counted. The dropped
1366  * line(s) are not counted.
1367  */
1368 static size_t record_print_text(struct printk_record *r, bool syslog,
1369 				bool time)
1370 {
1371 	size_t text_len = r->info->text_len;
1372 	size_t buf_size = r->text_buf_size;
1373 	char *text = r->text_buf;
1374 	char prefix[PRINTK_PREFIX_MAX];
1375 	bool truncated = false;
1376 	size_t prefix_len;
1377 	size_t line_len;
1378 	size_t len = 0;
1379 	char *next;
1380 
1381 	/*
1382 	 * If the message was truncated because the buffer was not large
1383 	 * enough, treat the available text as if it were the full text.
1384 	 */
1385 	if (text_len > buf_size)
1386 		text_len = buf_size;
1387 
1388 	prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1389 
1390 	/*
1391 	 * @text_len: bytes of unprocessed text
1392 	 * @line_len: bytes of current line _without_ newline
1393 	 * @text:     pointer to beginning of current line
1394 	 * @len:      number of bytes prepared in r->text_buf
1395 	 */
1396 	for (;;) {
1397 		next = memchr(text, '\n', text_len);
1398 		if (next) {
1399 			line_len = next - text;
1400 		} else {
1401 			/* Drop truncated line(s). */
1402 			if (truncated)
1403 				break;
1404 			line_len = text_len;
1405 		}
1406 
1407 		/*
1408 		 * Truncate the text if there is not enough space to add the
1409 		 * prefix and a trailing newline and a terminator.
1410 		 */
1411 		if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1412 			/* Drop even the current line if no space. */
1413 			if (len + prefix_len + line_len + 1 + 1 > buf_size)
1414 				break;
1415 
1416 			text_len = buf_size - len - prefix_len - 1 - 1;
1417 			truncated = true;
1418 		}
1419 
1420 		memmove(text + prefix_len, text, text_len);
1421 		memcpy(text, prefix, prefix_len);
1422 
1423 		/*
1424 		 * Increment the prepared length to include the text and
1425 		 * prefix that were just moved+copied. Also increment for the
1426 		 * newline at the end of this line. If this is the last line,
1427 		 * there is no newline, but it will be added immediately below.
1428 		 */
1429 		len += prefix_len + line_len + 1;
1430 		if (text_len == line_len) {
1431 			/*
1432 			 * This is the last line. Add the trailing newline
1433 			 * removed in vprintk_store().
1434 			 */
1435 			text[prefix_len + line_len] = '\n';
1436 			break;
1437 		}
1438 
1439 		/*
1440 		 * Advance beyond the added prefix and the related line with
1441 		 * its newline.
1442 		 */
1443 		text += prefix_len + line_len + 1;
1444 
1445 		/*
1446 		 * The remaining text has only decreased by the line with its
1447 		 * newline.
1448 		 *
1449 		 * Note that @text_len can become zero. It happens when @text
1450 		 * ended with a newline (either due to truncation or the
1451 		 * original string ending with "\n\n"). The loop is correctly
1452 		 * repeated and (if not truncated) an empty line with a prefix
1453 		 * will be prepared.
1454 		 */
1455 		text_len -= line_len + 1;
1456 	}
1457 
1458 	/*
1459 	 * If a buffer was provided, it will be terminated. Space for the
1460 	 * string terminator is guaranteed to be available. The terminator is
1461 	 * not counted in the return value.
1462 	 */
1463 	if (buf_size > 0)
1464 		r->text_buf[len] = 0;
1465 
1466 	return len;
1467 }
1468 
1469 static size_t get_record_print_text_size(struct printk_info *info,
1470 					 unsigned int line_count,
1471 					 bool syslog, bool time)
1472 {
1473 	char prefix[PRINTK_PREFIX_MAX];
1474 	size_t prefix_len;
1475 
1476 	prefix_len = info_print_prefix(info, syslog, time, prefix);
1477 
1478 	/*
1479 	 * Each line will be preceded with a prefix. The intermediate
1480 	 * newlines are already within the text, but a final trailing
1481 	 * newline will be added.
1482 	 */
1483 	return ((prefix_len * line_count) + info->text_len + 1);
1484 }
1485 
1486 /*
1487  * Beginning with @start_seq, find the first record where it and all following
1488  * records up to (but not including) @max_seq fit into @size.
1489  *
1490  * @max_seq is simply an upper bound and does not need to exist. If the caller
1491  * does not require an upper bound, -1 can be used for @max_seq.
1492  */
1493 static u64 find_first_fitting_seq(u64 start_seq, u64 max_seq, size_t size,
1494 				  bool syslog, bool time)
1495 {
1496 	struct printk_info info;
1497 	unsigned int line_count;
1498 	size_t len = 0;
1499 	u64 seq;
1500 
1501 	/* Determine the size of the records up to @max_seq. */
1502 	prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1503 		if (info.seq >= max_seq)
1504 			break;
1505 		len += get_record_print_text_size(&info, line_count, syslog, time);
1506 	}
1507 
1508 	/*
1509 	 * Adjust the upper bound for the next loop to avoid subtracting
1510 	 * lengths that were never added.
1511 	 */
1512 	if (seq < max_seq)
1513 		max_seq = seq;
1514 
1515 	/*
1516 	 * Move first record forward until length fits into the buffer. Ignore
1517 	 * newest messages that were not counted in the above cycle. Messages
1518 	 * might appear and get lost in the meantime. This is a best effort
1519 	 * that prevents an infinite loop that could occur with a retry.
1520 	 */
1521 	prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1522 		if (len <= size || info.seq >= max_seq)
1523 			break;
1524 		len -= get_record_print_text_size(&info, line_count, syslog, time);
1525 	}
1526 
1527 	return seq;
1528 }
1529 
1530 /* The caller is responsible for making sure @size is greater than 0. */
1531 static int syslog_print(char __user *buf, int size)
1532 {
1533 	struct printk_info info;
1534 	struct printk_record r;
1535 	char *text;
1536 	int len = 0;
1537 	u64 seq;
1538 
1539 	text = kmalloc(PRINTK_MESSAGE_MAX, GFP_KERNEL);
1540 	if (!text)
1541 		return -ENOMEM;
1542 
1543 	prb_rec_init_rd(&r, &info, text, PRINTK_MESSAGE_MAX);
1544 
1545 	mutex_lock(&syslog_lock);
1546 
1547 	/*
1548 	 * Wait for the @syslog_seq record to be available. @syslog_seq may
1549 	 * change while waiting.
1550 	 */
1551 	do {
1552 		seq = syslog_seq;
1553 
1554 		mutex_unlock(&syslog_lock);
1555 		/*
1556 		 * Guarantee this task is visible on the waitqueue before
1557 		 * checking the wake condition.
1558 		 *
1559 		 * The full memory barrier within set_current_state() of
1560 		 * prepare_to_wait_event() pairs with the full memory barrier
1561 		 * within wq_has_sleeper().
1562 		 *
1563 		 * This pairs with __wake_up_klogd:A.
1564 		 */
1565 		len = wait_event_interruptible(log_wait,
1566 				prb_read_valid(prb, seq, NULL)); /* LMM(syslog_print:A) */
1567 		mutex_lock(&syslog_lock);
1568 
1569 		if (len)
1570 			goto out;
1571 	} while (syslog_seq != seq);
1572 
1573 	/*
1574 	 * Copy records that fit into the buffer. The above cycle makes sure
1575 	 * that the first record is always available.
1576 	 */
1577 	do {
1578 		size_t n;
1579 		size_t skip;
1580 		int err;
1581 
1582 		if (!prb_read_valid(prb, syslog_seq, &r))
1583 			break;
1584 
1585 		if (r.info->seq != syslog_seq) {
1586 			/* message is gone, move to next valid one */
1587 			syslog_seq = r.info->seq;
1588 			syslog_partial = 0;
1589 		}
1590 
1591 		/*
1592 		 * To keep reading/counting partial line consistent,
1593 		 * use printk_time value as of the beginning of a line.
1594 		 */
1595 		if (!syslog_partial)
1596 			syslog_time = printk_time;
1597 
1598 		skip = syslog_partial;
1599 		n = record_print_text(&r, true, syslog_time);
1600 		if (n - syslog_partial <= size) {
1601 			/* message fits into buffer, move forward */
1602 			syslog_seq = r.info->seq + 1;
1603 			n -= syslog_partial;
1604 			syslog_partial = 0;
1605 		} else if (!len){
1606 			/* partial read(), remember position */
1607 			n = size;
1608 			syslog_partial += n;
1609 		} else
1610 			n = 0;
1611 
1612 		if (!n)
1613 			break;
1614 
1615 		mutex_unlock(&syslog_lock);
1616 		err = copy_to_user(buf, text + skip, n);
1617 		mutex_lock(&syslog_lock);
1618 
1619 		if (err) {
1620 			if (!len)
1621 				len = -EFAULT;
1622 			break;
1623 		}
1624 
1625 		len += n;
1626 		size -= n;
1627 		buf += n;
1628 	} while (size);
1629 out:
1630 	mutex_unlock(&syslog_lock);
1631 	kfree(text);
1632 	return len;
1633 }
1634 
1635 static int syslog_print_all(char __user *buf, int size, bool clear)
1636 {
1637 	struct printk_info info;
1638 	struct printk_record r;
1639 	char *text;
1640 	int len = 0;
1641 	u64 seq;
1642 	bool time;
1643 
1644 	text = kmalloc(PRINTK_MESSAGE_MAX, GFP_KERNEL);
1645 	if (!text)
1646 		return -ENOMEM;
1647 
1648 	time = printk_time;
1649 	/*
1650 	 * Find first record that fits, including all following records,
1651 	 * into the user-provided buffer for this dump.
1652 	 */
1653 	seq = find_first_fitting_seq(latched_seq_read_nolock(&clear_seq), -1,
1654 				     size, true, time);
1655 
1656 	prb_rec_init_rd(&r, &info, text, PRINTK_MESSAGE_MAX);
1657 
1658 	prb_for_each_record(seq, prb, seq, &r) {
1659 		int textlen;
1660 
1661 		textlen = record_print_text(&r, true, time);
1662 
1663 		if (len + textlen > size) {
1664 			seq--;
1665 			break;
1666 		}
1667 
1668 		if (copy_to_user(buf + len, text, textlen))
1669 			len = -EFAULT;
1670 		else
1671 			len += textlen;
1672 
1673 		if (len < 0)
1674 			break;
1675 	}
1676 
1677 	if (clear) {
1678 		mutex_lock(&syslog_lock);
1679 		latched_seq_write(&clear_seq, seq);
1680 		mutex_unlock(&syslog_lock);
1681 	}
1682 
1683 	kfree(text);
1684 	return len;
1685 }
1686 
1687 static void syslog_clear(void)
1688 {
1689 	mutex_lock(&syslog_lock);
1690 	latched_seq_write(&clear_seq, prb_next_seq(prb));
1691 	mutex_unlock(&syslog_lock);
1692 }
1693 
1694 int do_syslog(int type, char __user *buf, int len, int source)
1695 {
1696 	struct printk_info info;
1697 	bool clear = false;
1698 	static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1699 	int error;
1700 
1701 	error = check_syslog_permissions(type, source);
1702 	if (error)
1703 		return error;
1704 
1705 	switch (type) {
1706 	case SYSLOG_ACTION_CLOSE:	/* Close log */
1707 		break;
1708 	case SYSLOG_ACTION_OPEN:	/* Open log */
1709 		break;
1710 	case SYSLOG_ACTION_READ:	/* Read from log */
1711 		if (!buf || len < 0)
1712 			return -EINVAL;
1713 		if (!len)
1714 			return 0;
1715 		if (!access_ok(buf, len))
1716 			return -EFAULT;
1717 		error = syslog_print(buf, len);
1718 		break;
1719 	/* Read/clear last kernel messages */
1720 	case SYSLOG_ACTION_READ_CLEAR:
1721 		clear = true;
1722 		fallthrough;
1723 	/* Read last kernel messages */
1724 	case SYSLOG_ACTION_READ_ALL:
1725 		if (!buf || len < 0)
1726 			return -EINVAL;
1727 		if (!len)
1728 			return 0;
1729 		if (!access_ok(buf, len))
1730 			return -EFAULT;
1731 		error = syslog_print_all(buf, len, clear);
1732 		break;
1733 	/* Clear ring buffer */
1734 	case SYSLOG_ACTION_CLEAR:
1735 		syslog_clear();
1736 		break;
1737 	/* Disable logging to console */
1738 	case SYSLOG_ACTION_CONSOLE_OFF:
1739 		if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1740 			saved_console_loglevel = console_loglevel;
1741 		console_loglevel = minimum_console_loglevel;
1742 		break;
1743 	/* Enable logging to console */
1744 	case SYSLOG_ACTION_CONSOLE_ON:
1745 		if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1746 			console_loglevel = saved_console_loglevel;
1747 			saved_console_loglevel = LOGLEVEL_DEFAULT;
1748 		}
1749 		break;
1750 	/* Set level of messages printed to console */
1751 	case SYSLOG_ACTION_CONSOLE_LEVEL:
1752 		if (len < 1 || len > 8)
1753 			return -EINVAL;
1754 		if (len < minimum_console_loglevel)
1755 			len = minimum_console_loglevel;
1756 		console_loglevel = len;
1757 		/* Implicitly re-enable logging to console */
1758 		saved_console_loglevel = LOGLEVEL_DEFAULT;
1759 		break;
1760 	/* Number of chars in the log buffer */
1761 	case SYSLOG_ACTION_SIZE_UNREAD:
1762 		mutex_lock(&syslog_lock);
1763 		if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1764 			/* No unread messages. */
1765 			mutex_unlock(&syslog_lock);
1766 			return 0;
1767 		}
1768 		if (info.seq != syslog_seq) {
1769 			/* messages are gone, move to first one */
1770 			syslog_seq = info.seq;
1771 			syslog_partial = 0;
1772 		}
1773 		if (source == SYSLOG_FROM_PROC) {
1774 			/*
1775 			 * Short-cut for poll(/"proc/kmsg") which simply checks
1776 			 * for pending data, not the size; return the count of
1777 			 * records, not the length.
1778 			 */
1779 			error = prb_next_seq(prb) - syslog_seq;
1780 		} else {
1781 			bool time = syslog_partial ? syslog_time : printk_time;
1782 			unsigned int line_count;
1783 			u64 seq;
1784 
1785 			prb_for_each_info(syslog_seq, prb, seq, &info,
1786 					  &line_count) {
1787 				error += get_record_print_text_size(&info, line_count,
1788 								    true, time);
1789 				time = printk_time;
1790 			}
1791 			error -= syslog_partial;
1792 		}
1793 		mutex_unlock(&syslog_lock);
1794 		break;
1795 	/* Size of the log buffer */
1796 	case SYSLOG_ACTION_SIZE_BUFFER:
1797 		error = log_buf_len;
1798 		break;
1799 	default:
1800 		error = -EINVAL;
1801 		break;
1802 	}
1803 
1804 	return error;
1805 }
1806 
1807 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1808 {
1809 	return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1810 }
1811 
1812 /*
1813  * Special console_lock variants that help to reduce the risk of soft-lockups.
1814  * They allow to pass console_lock to another printk() call using a busy wait.
1815  */
1816 
1817 #ifdef CONFIG_LOCKDEP
1818 static struct lockdep_map console_owner_dep_map = {
1819 	.name = "console_owner"
1820 };
1821 #endif
1822 
1823 static DEFINE_RAW_SPINLOCK(console_owner_lock);
1824 static struct task_struct *console_owner;
1825 static bool console_waiter;
1826 
1827 /**
1828  * console_lock_spinning_enable - mark beginning of code where another
1829  *	thread might safely busy wait
1830  *
1831  * This basically converts console_lock into a spinlock. This marks
1832  * the section where the console_lock owner can not sleep, because
1833  * there may be a waiter spinning (like a spinlock). Also it must be
1834  * ready to hand over the lock at the end of the section.
1835  */
1836 static void console_lock_spinning_enable(void)
1837 {
1838 	raw_spin_lock(&console_owner_lock);
1839 	console_owner = current;
1840 	raw_spin_unlock(&console_owner_lock);
1841 
1842 	/* The waiter may spin on us after setting console_owner */
1843 	spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1844 }
1845 
1846 /**
1847  * console_lock_spinning_disable_and_check - mark end of code where another
1848  *	thread was able to busy wait and check if there is a waiter
1849  * @cookie: cookie returned from console_srcu_read_lock()
1850  *
1851  * This is called at the end of the section where spinning is allowed.
1852  * It has two functions. First, it is a signal that it is no longer
1853  * safe to start busy waiting for the lock. Second, it checks if
1854  * there is a busy waiter and passes the lock rights to her.
1855  *
1856  * Important: Callers lose both the console_lock and the SRCU read lock if
1857  *	there was a busy waiter. They must not touch items synchronized by
1858  *	console_lock or SRCU read lock in this case.
1859  *
1860  * Return: 1 if the lock rights were passed, 0 otherwise.
1861  */
1862 static int console_lock_spinning_disable_and_check(int cookie)
1863 {
1864 	int waiter;
1865 
1866 	raw_spin_lock(&console_owner_lock);
1867 	waiter = READ_ONCE(console_waiter);
1868 	console_owner = NULL;
1869 	raw_spin_unlock(&console_owner_lock);
1870 
1871 	if (!waiter) {
1872 		spin_release(&console_owner_dep_map, _THIS_IP_);
1873 		return 0;
1874 	}
1875 
1876 	/* The waiter is now free to continue */
1877 	WRITE_ONCE(console_waiter, false);
1878 
1879 	spin_release(&console_owner_dep_map, _THIS_IP_);
1880 
1881 	/*
1882 	 * Preserve lockdep lock ordering. Release the SRCU read lock before
1883 	 * releasing the console_lock.
1884 	 */
1885 	console_srcu_read_unlock(cookie);
1886 
1887 	/*
1888 	 * Hand off console_lock to waiter. The waiter will perform
1889 	 * the up(). After this, the waiter is the console_lock owner.
1890 	 */
1891 	mutex_release(&console_lock_dep_map, _THIS_IP_);
1892 	return 1;
1893 }
1894 
1895 /**
1896  * console_trylock_spinning - try to get console_lock by busy waiting
1897  *
1898  * This allows to busy wait for the console_lock when the current
1899  * owner is running in specially marked sections. It means that
1900  * the current owner is running and cannot reschedule until it
1901  * is ready to lose the lock.
1902  *
1903  * Return: 1 if we got the lock, 0 othrewise
1904  */
1905 static int console_trylock_spinning(void)
1906 {
1907 	struct task_struct *owner = NULL;
1908 	bool waiter;
1909 	bool spin = false;
1910 	unsigned long flags;
1911 
1912 	if (console_trylock())
1913 		return 1;
1914 
1915 	/*
1916 	 * It's unsafe to spin once a panic has begun. If we are the
1917 	 * panic CPU, we may have already halted the owner of the
1918 	 * console_sem. If we are not the panic CPU, then we should
1919 	 * avoid taking console_sem, so the panic CPU has a better
1920 	 * chance of cleanly acquiring it later.
1921 	 */
1922 	if (panic_in_progress())
1923 		return 0;
1924 
1925 	printk_safe_enter_irqsave(flags);
1926 
1927 	raw_spin_lock(&console_owner_lock);
1928 	owner = READ_ONCE(console_owner);
1929 	waiter = READ_ONCE(console_waiter);
1930 	if (!waiter && owner && owner != current) {
1931 		WRITE_ONCE(console_waiter, true);
1932 		spin = true;
1933 	}
1934 	raw_spin_unlock(&console_owner_lock);
1935 
1936 	/*
1937 	 * If there is an active printk() writing to the
1938 	 * consoles, instead of having it write our data too,
1939 	 * see if we can offload that load from the active
1940 	 * printer, and do some printing ourselves.
1941 	 * Go into a spin only if there isn't already a waiter
1942 	 * spinning, and there is an active printer, and
1943 	 * that active printer isn't us (recursive printk?).
1944 	 */
1945 	if (!spin) {
1946 		printk_safe_exit_irqrestore(flags);
1947 		return 0;
1948 	}
1949 
1950 	/* We spin waiting for the owner to release us */
1951 	spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1952 	/* Owner will clear console_waiter on hand off */
1953 	while (READ_ONCE(console_waiter))
1954 		cpu_relax();
1955 	spin_release(&console_owner_dep_map, _THIS_IP_);
1956 
1957 	printk_safe_exit_irqrestore(flags);
1958 	/*
1959 	 * The owner passed the console lock to us.
1960 	 * Since we did not spin on console lock, annotate
1961 	 * this as a trylock. Otherwise lockdep will
1962 	 * complain.
1963 	 */
1964 	mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
1965 
1966 	return 1;
1967 }
1968 
1969 /*
1970  * Recursion is tracked separately on each CPU. If NMIs are supported, an
1971  * additional NMI context per CPU is also separately tracked. Until per-CPU
1972  * is available, a separate "early tracking" is performed.
1973  */
1974 static DEFINE_PER_CPU(u8, printk_count);
1975 static u8 printk_count_early;
1976 #ifdef CONFIG_HAVE_NMI
1977 static DEFINE_PER_CPU(u8, printk_count_nmi);
1978 static u8 printk_count_nmi_early;
1979 #endif
1980 
1981 /*
1982  * Recursion is limited to keep the output sane. printk() should not require
1983  * more than 1 level of recursion (allowing, for example, printk() to trigger
1984  * a WARN), but a higher value is used in case some printk-internal errors
1985  * exist, such as the ringbuffer validation checks failing.
1986  */
1987 #define PRINTK_MAX_RECURSION 3
1988 
1989 /*
1990  * Return a pointer to the dedicated counter for the CPU+context of the
1991  * caller.
1992  */
1993 static u8 *__printk_recursion_counter(void)
1994 {
1995 #ifdef CONFIG_HAVE_NMI
1996 	if (in_nmi()) {
1997 		if (printk_percpu_data_ready())
1998 			return this_cpu_ptr(&printk_count_nmi);
1999 		return &printk_count_nmi_early;
2000 	}
2001 #endif
2002 	if (printk_percpu_data_ready())
2003 		return this_cpu_ptr(&printk_count);
2004 	return &printk_count_early;
2005 }
2006 
2007 /*
2008  * Enter recursion tracking. Interrupts are disabled to simplify tracking.
2009  * The caller must check the boolean return value to see if the recursion is
2010  * allowed. On failure, interrupts are not disabled.
2011  *
2012  * @recursion_ptr must be a variable of type (u8 *) and is the same variable
2013  * that is passed to printk_exit_irqrestore().
2014  */
2015 #define printk_enter_irqsave(recursion_ptr, flags)	\
2016 ({							\
2017 	bool success = true;				\
2018 							\
2019 	typecheck(u8 *, recursion_ptr);			\
2020 	local_irq_save(flags);				\
2021 	(recursion_ptr) = __printk_recursion_counter();	\
2022 	if (*(recursion_ptr) > PRINTK_MAX_RECURSION) {	\
2023 		local_irq_restore(flags);		\
2024 		success = false;			\
2025 	} else {					\
2026 		(*(recursion_ptr))++;			\
2027 	}						\
2028 	success;					\
2029 })
2030 
2031 /* Exit recursion tracking, restoring interrupts. */
2032 #define printk_exit_irqrestore(recursion_ptr, flags)	\
2033 	do {						\
2034 		typecheck(u8 *, recursion_ptr);		\
2035 		(*(recursion_ptr))--;			\
2036 		local_irq_restore(flags);		\
2037 	} while (0)
2038 
2039 int printk_delay_msec __read_mostly;
2040 
2041 static inline void printk_delay(int level)
2042 {
2043 	boot_delay_msec(level);
2044 
2045 	if (unlikely(printk_delay_msec)) {
2046 		int m = printk_delay_msec;
2047 
2048 		while (m--) {
2049 			mdelay(1);
2050 			touch_nmi_watchdog();
2051 		}
2052 	}
2053 }
2054 
2055 static inline u32 printk_caller_id(void)
2056 {
2057 	return in_task() ? task_pid_nr(current) :
2058 		0x80000000 + smp_processor_id();
2059 }
2060 
2061 /**
2062  * printk_parse_prefix - Parse level and control flags.
2063  *
2064  * @text:     The terminated text message.
2065  * @level:    A pointer to the current level value, will be updated.
2066  * @flags:    A pointer to the current printk_info flags, will be updated.
2067  *
2068  * @level may be NULL if the caller is not interested in the parsed value.
2069  * Otherwise the variable pointed to by @level must be set to
2070  * LOGLEVEL_DEFAULT in order to be updated with the parsed value.
2071  *
2072  * @flags may be NULL if the caller is not interested in the parsed value.
2073  * Otherwise the variable pointed to by @flags will be OR'd with the parsed
2074  * value.
2075  *
2076  * Return: The length of the parsed level and control flags.
2077  */
2078 u16 printk_parse_prefix(const char *text, int *level,
2079 			enum printk_info_flags *flags)
2080 {
2081 	u16 prefix_len = 0;
2082 	int kern_level;
2083 
2084 	while (*text) {
2085 		kern_level = printk_get_level(text);
2086 		if (!kern_level)
2087 			break;
2088 
2089 		switch (kern_level) {
2090 		case '0' ... '7':
2091 			if (level && *level == LOGLEVEL_DEFAULT)
2092 				*level = kern_level - '0';
2093 			break;
2094 		case 'c':	/* KERN_CONT */
2095 			if (flags)
2096 				*flags |= LOG_CONT;
2097 		}
2098 
2099 		prefix_len += 2;
2100 		text += 2;
2101 	}
2102 
2103 	return prefix_len;
2104 }
2105 
2106 __printf(5, 0)
2107 static u16 printk_sprint(char *text, u16 size, int facility,
2108 			 enum printk_info_flags *flags, const char *fmt,
2109 			 va_list args)
2110 {
2111 	u16 text_len;
2112 
2113 	text_len = vscnprintf(text, size, fmt, args);
2114 
2115 	/* Mark and strip a trailing newline. */
2116 	if (text_len && text[text_len - 1] == '\n') {
2117 		text_len--;
2118 		*flags |= LOG_NEWLINE;
2119 	}
2120 
2121 	/* Strip log level and control flags. */
2122 	if (facility == 0) {
2123 		u16 prefix_len;
2124 
2125 		prefix_len = printk_parse_prefix(text, NULL, NULL);
2126 		if (prefix_len) {
2127 			text_len -= prefix_len;
2128 			memmove(text, text + prefix_len, text_len);
2129 		}
2130 	}
2131 
2132 	trace_console(text, text_len);
2133 
2134 	return text_len;
2135 }
2136 
2137 __printf(4, 0)
2138 int vprintk_store(int facility, int level,
2139 		  const struct dev_printk_info *dev_info,
2140 		  const char *fmt, va_list args)
2141 {
2142 	struct prb_reserved_entry e;
2143 	enum printk_info_flags flags = 0;
2144 	struct printk_record r;
2145 	unsigned long irqflags;
2146 	u16 trunc_msg_len = 0;
2147 	char prefix_buf[8];
2148 	u8 *recursion_ptr;
2149 	u16 reserve_size;
2150 	va_list args2;
2151 	u32 caller_id;
2152 	u16 text_len;
2153 	int ret = 0;
2154 	u64 ts_nsec;
2155 
2156 	if (!printk_enter_irqsave(recursion_ptr, irqflags))
2157 		return 0;
2158 
2159 	/*
2160 	 * Since the duration of printk() can vary depending on the message
2161 	 * and state of the ringbuffer, grab the timestamp now so that it is
2162 	 * close to the call of printk(). This provides a more deterministic
2163 	 * timestamp with respect to the caller.
2164 	 */
2165 	ts_nsec = local_clock();
2166 
2167 	caller_id = printk_caller_id();
2168 
2169 	/*
2170 	 * The sprintf needs to come first since the syslog prefix might be
2171 	 * passed in as a parameter. An extra byte must be reserved so that
2172 	 * later the vscnprintf() into the reserved buffer has room for the
2173 	 * terminating '\0', which is not counted by vsnprintf().
2174 	 */
2175 	va_copy(args2, args);
2176 	reserve_size = vsnprintf(&prefix_buf[0], sizeof(prefix_buf), fmt, args2) + 1;
2177 	va_end(args2);
2178 
2179 	if (reserve_size > PRINTKRB_RECORD_MAX)
2180 		reserve_size = PRINTKRB_RECORD_MAX;
2181 
2182 	/* Extract log level or control flags. */
2183 	if (facility == 0)
2184 		printk_parse_prefix(&prefix_buf[0], &level, &flags);
2185 
2186 	if (level == LOGLEVEL_DEFAULT)
2187 		level = default_message_loglevel;
2188 
2189 	if (dev_info)
2190 		flags |= LOG_NEWLINE;
2191 
2192 	if (flags & LOG_CONT) {
2193 		prb_rec_init_wr(&r, reserve_size);
2194 		if (prb_reserve_in_last(&e, prb, &r, caller_id, PRINTKRB_RECORD_MAX)) {
2195 			text_len = printk_sprint(&r.text_buf[r.info->text_len], reserve_size,
2196 						 facility, &flags, fmt, args);
2197 			r.info->text_len += text_len;
2198 
2199 			if (flags & LOG_NEWLINE) {
2200 				r.info->flags |= LOG_NEWLINE;
2201 				prb_final_commit(&e);
2202 			} else {
2203 				prb_commit(&e);
2204 			}
2205 
2206 			ret = text_len;
2207 			goto out;
2208 		}
2209 	}
2210 
2211 	/*
2212 	 * Explicitly initialize the record before every prb_reserve() call.
2213 	 * prb_reserve_in_last() and prb_reserve() purposely invalidate the
2214 	 * structure when they fail.
2215 	 */
2216 	prb_rec_init_wr(&r, reserve_size);
2217 	if (!prb_reserve(&e, prb, &r)) {
2218 		/* truncate the message if it is too long for empty buffer */
2219 		truncate_msg(&reserve_size, &trunc_msg_len);
2220 
2221 		prb_rec_init_wr(&r, reserve_size + trunc_msg_len);
2222 		if (!prb_reserve(&e, prb, &r))
2223 			goto out;
2224 	}
2225 
2226 	/* fill message */
2227 	text_len = printk_sprint(&r.text_buf[0], reserve_size, facility, &flags, fmt, args);
2228 	if (trunc_msg_len)
2229 		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
2230 	r.info->text_len = text_len + trunc_msg_len;
2231 	r.info->facility = facility;
2232 	r.info->level = level & 7;
2233 	r.info->flags = flags & 0x1f;
2234 	r.info->ts_nsec = ts_nsec;
2235 	r.info->caller_id = caller_id;
2236 	if (dev_info)
2237 		memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
2238 
2239 	/* A message without a trailing newline can be continued. */
2240 	if (!(flags & LOG_NEWLINE))
2241 		prb_commit(&e);
2242 	else
2243 		prb_final_commit(&e);
2244 
2245 	ret = text_len + trunc_msg_len;
2246 out:
2247 	printk_exit_irqrestore(recursion_ptr, irqflags);
2248 	return ret;
2249 }
2250 
2251 asmlinkage int vprintk_emit(int facility, int level,
2252 			    const struct dev_printk_info *dev_info,
2253 			    const char *fmt, va_list args)
2254 {
2255 	int printed_len;
2256 	bool in_sched = false;
2257 
2258 	/* Suppress unimportant messages after panic happens */
2259 	if (unlikely(suppress_printk))
2260 		return 0;
2261 
2262 	if (unlikely(suppress_panic_printk) &&
2263 	    atomic_read(&panic_cpu) != raw_smp_processor_id())
2264 		return 0;
2265 
2266 	if (level == LOGLEVEL_SCHED) {
2267 		level = LOGLEVEL_DEFAULT;
2268 		in_sched = true;
2269 	}
2270 
2271 	printk_delay(level);
2272 
2273 	printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2274 
2275 	/* If called from the scheduler, we can not call up(). */
2276 	if (!in_sched) {
2277 		/*
2278 		 * The caller may be holding system-critical or
2279 		 * timing-sensitive locks. Disable preemption during
2280 		 * printing of all remaining records to all consoles so that
2281 		 * this context can return as soon as possible. Hopefully
2282 		 * another printk() caller will take over the printing.
2283 		 */
2284 		preempt_disable();
2285 		/*
2286 		 * Try to acquire and then immediately release the console
2287 		 * semaphore. The release will print out buffers. With the
2288 		 * spinning variant, this context tries to take over the
2289 		 * printing from another printing context.
2290 		 */
2291 		if (console_trylock_spinning())
2292 			console_unlock();
2293 		preempt_enable();
2294 	}
2295 
2296 	if (in_sched)
2297 		defer_console_output();
2298 	else
2299 		wake_up_klogd();
2300 
2301 	return printed_len;
2302 }
2303 EXPORT_SYMBOL(vprintk_emit);
2304 
2305 int vprintk_default(const char *fmt, va_list args)
2306 {
2307 	return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2308 }
2309 EXPORT_SYMBOL_GPL(vprintk_default);
2310 
2311 asmlinkage __visible int _printk(const char *fmt, ...)
2312 {
2313 	va_list args;
2314 	int r;
2315 
2316 	va_start(args, fmt);
2317 	r = vprintk(fmt, args);
2318 	va_end(args);
2319 
2320 	return r;
2321 }
2322 EXPORT_SYMBOL(_printk);
2323 
2324 static bool pr_flush(int timeout_ms, bool reset_on_progress);
2325 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress);
2326 
2327 #else /* CONFIG_PRINTK */
2328 
2329 #define printk_time		false
2330 
2331 #define prb_read_valid(rb, seq, r)	false
2332 #define prb_first_valid_seq(rb)		0
2333 #define prb_next_seq(rb)		0
2334 
2335 static u64 syslog_seq;
2336 
2337 static bool pr_flush(int timeout_ms, bool reset_on_progress) { return true; }
2338 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress) { return true; }
2339 
2340 #endif /* CONFIG_PRINTK */
2341 
2342 #ifdef CONFIG_EARLY_PRINTK
2343 struct console *early_console;
2344 
2345 asmlinkage __visible void early_printk(const char *fmt, ...)
2346 {
2347 	va_list ap;
2348 	char buf[512];
2349 	int n;
2350 
2351 	if (!early_console)
2352 		return;
2353 
2354 	va_start(ap, fmt);
2355 	n = vscnprintf(buf, sizeof(buf), fmt, ap);
2356 	va_end(ap);
2357 
2358 	early_console->write(early_console, buf, n);
2359 }
2360 #endif
2361 
2362 static void set_user_specified(struct console_cmdline *c, bool user_specified)
2363 {
2364 	if (!user_specified)
2365 		return;
2366 
2367 	/*
2368 	 * @c console was defined by the user on the command line.
2369 	 * Do not clear when added twice also by SPCR or the device tree.
2370 	 */
2371 	c->user_specified = true;
2372 	/* At least one console defined by the user on the command line. */
2373 	console_set_on_cmdline = 1;
2374 }
2375 
2376 static int __add_preferred_console(const char *name, const short idx, char *options,
2377 				   char *brl_options, bool user_specified)
2378 {
2379 	struct console_cmdline *c;
2380 	int i;
2381 
2382 	/*
2383 	 * We use a signed short index for struct console for device drivers to
2384 	 * indicate a not yet assigned index or port. However, a negative index
2385 	 * value is not valid for preferred console.
2386 	 */
2387 	if (idx < 0)
2388 		return -EINVAL;
2389 
2390 	/*
2391 	 *	See if this tty is not yet registered, and
2392 	 *	if we have a slot free.
2393 	 */
2394 	for (i = 0, c = console_cmdline;
2395 	     i < MAX_CMDLINECONSOLES && c->name[0];
2396 	     i++, c++) {
2397 		if (strcmp(c->name, name) == 0 && c->index == idx) {
2398 			if (!brl_options)
2399 				preferred_console = i;
2400 			set_user_specified(c, user_specified);
2401 			return 0;
2402 		}
2403 	}
2404 	if (i == MAX_CMDLINECONSOLES)
2405 		return -E2BIG;
2406 	if (!brl_options)
2407 		preferred_console = i;
2408 	strscpy(c->name, name, sizeof(c->name));
2409 	c->options = options;
2410 	set_user_specified(c, user_specified);
2411 	braille_set_options(c, brl_options);
2412 
2413 	c->index = idx;
2414 	return 0;
2415 }
2416 
2417 static int __init console_msg_format_setup(char *str)
2418 {
2419 	if (!strcmp(str, "syslog"))
2420 		console_msg_format = MSG_FORMAT_SYSLOG;
2421 	if (!strcmp(str, "default"))
2422 		console_msg_format = MSG_FORMAT_DEFAULT;
2423 	return 1;
2424 }
2425 __setup("console_msg_format=", console_msg_format_setup);
2426 
2427 /*
2428  * Set up a console.  Called via do_early_param() in init/main.c
2429  * for each "console=" parameter in the boot command line.
2430  */
2431 static int __init console_setup(char *str)
2432 {
2433 	char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2434 	char *s, *options, *brl_options = NULL;
2435 	int idx;
2436 
2437 	/*
2438 	 * console="" or console=null have been suggested as a way to
2439 	 * disable console output. Use ttynull that has been created
2440 	 * for exactly this purpose.
2441 	 */
2442 	if (str[0] == 0 || strcmp(str, "null") == 0) {
2443 		__add_preferred_console("ttynull", 0, NULL, NULL, true);
2444 		return 1;
2445 	}
2446 
2447 	if (_braille_console_setup(&str, &brl_options))
2448 		return 1;
2449 
2450 	/*
2451 	 * Decode str into name, index, options.
2452 	 */
2453 	if (str[0] >= '0' && str[0] <= '9') {
2454 		strcpy(buf, "ttyS");
2455 		strncpy(buf + 4, str, sizeof(buf) - 5);
2456 	} else {
2457 		strncpy(buf, str, sizeof(buf) - 1);
2458 	}
2459 	buf[sizeof(buf) - 1] = 0;
2460 	options = strchr(str, ',');
2461 	if (options)
2462 		*(options++) = 0;
2463 #ifdef __sparc__
2464 	if (!strcmp(str, "ttya"))
2465 		strcpy(buf, "ttyS0");
2466 	if (!strcmp(str, "ttyb"))
2467 		strcpy(buf, "ttyS1");
2468 #endif
2469 	for (s = buf; *s; s++)
2470 		if (isdigit(*s) || *s == ',')
2471 			break;
2472 	idx = simple_strtoul(s, NULL, 10);
2473 	*s = 0;
2474 
2475 	__add_preferred_console(buf, idx, options, brl_options, true);
2476 	return 1;
2477 }
2478 __setup("console=", console_setup);
2479 
2480 /**
2481  * add_preferred_console - add a device to the list of preferred consoles.
2482  * @name: device name
2483  * @idx: device index
2484  * @options: options for this console
2485  *
2486  * The last preferred console added will be used for kernel messages
2487  * and stdin/out/err for init.  Normally this is used by console_setup
2488  * above to handle user-supplied console arguments; however it can also
2489  * be used by arch-specific code either to override the user or more
2490  * commonly to provide a default console (ie from PROM variables) when
2491  * the user has not supplied one.
2492  */
2493 int add_preferred_console(const char *name, const short idx, char *options)
2494 {
2495 	return __add_preferred_console(name, idx, options, NULL, false);
2496 }
2497 
2498 bool console_suspend_enabled = true;
2499 EXPORT_SYMBOL(console_suspend_enabled);
2500 
2501 static int __init console_suspend_disable(char *str)
2502 {
2503 	console_suspend_enabled = false;
2504 	return 1;
2505 }
2506 __setup("no_console_suspend", console_suspend_disable);
2507 module_param_named(console_suspend, console_suspend_enabled,
2508 		bool, S_IRUGO | S_IWUSR);
2509 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2510 	" and hibernate operations");
2511 
2512 static bool printk_console_no_auto_verbose;
2513 
2514 void console_verbose(void)
2515 {
2516 	if (console_loglevel && !printk_console_no_auto_verbose)
2517 		console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
2518 }
2519 EXPORT_SYMBOL_GPL(console_verbose);
2520 
2521 module_param_named(console_no_auto_verbose, printk_console_no_auto_verbose, bool, 0644);
2522 MODULE_PARM_DESC(console_no_auto_verbose, "Disable console loglevel raise to highest on oops/panic/etc");
2523 
2524 /**
2525  * suspend_console - suspend the console subsystem
2526  *
2527  * This disables printk() while we go into suspend states
2528  */
2529 void suspend_console(void)
2530 {
2531 	struct console *con;
2532 
2533 	if (!console_suspend_enabled)
2534 		return;
2535 	pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2536 	pr_flush(1000, true);
2537 
2538 	console_list_lock();
2539 	for_each_console(con)
2540 		console_srcu_write_flags(con, con->flags | CON_SUSPENDED);
2541 	console_list_unlock();
2542 
2543 	/*
2544 	 * Ensure that all SRCU list walks have completed. All printing
2545 	 * contexts must be able to see that they are suspended so that it
2546 	 * is guaranteed that all printing has stopped when this function
2547 	 * completes.
2548 	 */
2549 	synchronize_srcu(&console_srcu);
2550 }
2551 
2552 void resume_console(void)
2553 {
2554 	struct console *con;
2555 
2556 	if (!console_suspend_enabled)
2557 		return;
2558 
2559 	console_list_lock();
2560 	for_each_console(con)
2561 		console_srcu_write_flags(con, con->flags & ~CON_SUSPENDED);
2562 	console_list_unlock();
2563 
2564 	/*
2565 	 * Ensure that all SRCU list walks have completed. All printing
2566 	 * contexts must be able to see they are no longer suspended so
2567 	 * that they are guaranteed to wake up and resume printing.
2568 	 */
2569 	synchronize_srcu(&console_srcu);
2570 
2571 	pr_flush(1000, true);
2572 }
2573 
2574 /**
2575  * console_cpu_notify - print deferred console messages after CPU hotplug
2576  * @cpu: unused
2577  *
2578  * If printk() is called from a CPU that is not online yet, the messages
2579  * will be printed on the console only if there are CON_ANYTIME consoles.
2580  * This function is called when a new CPU comes online (or fails to come
2581  * up) or goes offline.
2582  */
2583 static int console_cpu_notify(unsigned int cpu)
2584 {
2585 	if (!cpuhp_tasks_frozen) {
2586 		/* If trylock fails, someone else is doing the printing */
2587 		if (console_trylock())
2588 			console_unlock();
2589 	}
2590 	return 0;
2591 }
2592 
2593 /*
2594  * Return true if a panic is in progress on a remote CPU.
2595  *
2596  * On true, the local CPU should immediately release any printing resources
2597  * that may be needed by the panic CPU.
2598  */
2599 bool other_cpu_in_panic(void)
2600 {
2601 	if (!panic_in_progress())
2602 		return false;
2603 
2604 	/*
2605 	 * We can use raw_smp_processor_id() here because it is impossible for
2606 	 * the task to be migrated to the panic_cpu, or away from it. If
2607 	 * panic_cpu has already been set, and we're not currently executing on
2608 	 * that CPU, then we never will be.
2609 	 */
2610 	return atomic_read(&panic_cpu) != raw_smp_processor_id();
2611 }
2612 
2613 /**
2614  * console_lock - block the console subsystem from printing
2615  *
2616  * Acquires a lock which guarantees that no consoles will
2617  * be in or enter their write() callback.
2618  *
2619  * Can sleep, returns nothing.
2620  */
2621 void console_lock(void)
2622 {
2623 	might_sleep();
2624 
2625 	/* On panic, the console_lock must be left to the panic cpu. */
2626 	while (other_cpu_in_panic())
2627 		msleep(1000);
2628 
2629 	down_console_sem();
2630 	console_locked = 1;
2631 	console_may_schedule = 1;
2632 }
2633 EXPORT_SYMBOL(console_lock);
2634 
2635 /**
2636  * console_trylock - try to block the console subsystem from printing
2637  *
2638  * Try to acquire a lock which guarantees that no consoles will
2639  * be in or enter their write() callback.
2640  *
2641  * returns 1 on success, and 0 on failure to acquire the lock.
2642  */
2643 int console_trylock(void)
2644 {
2645 	/* On panic, the console_lock must be left to the panic cpu. */
2646 	if (other_cpu_in_panic())
2647 		return 0;
2648 	if (down_trylock_console_sem())
2649 		return 0;
2650 	console_locked = 1;
2651 	console_may_schedule = 0;
2652 	return 1;
2653 }
2654 EXPORT_SYMBOL(console_trylock);
2655 
2656 int is_console_locked(void)
2657 {
2658 	return console_locked;
2659 }
2660 EXPORT_SYMBOL(is_console_locked);
2661 
2662 /*
2663  * Check if the given console is currently capable and allowed to print
2664  * records.
2665  *
2666  * Requires the console_srcu_read_lock.
2667  */
2668 static inline bool console_is_usable(struct console *con)
2669 {
2670 	short flags = console_srcu_read_flags(con);
2671 
2672 	if (!(flags & CON_ENABLED))
2673 		return false;
2674 
2675 	if ((flags & CON_SUSPENDED))
2676 		return false;
2677 
2678 	if (!con->write)
2679 		return false;
2680 
2681 	/*
2682 	 * Console drivers may assume that per-cpu resources have been
2683 	 * allocated. So unless they're explicitly marked as being able to
2684 	 * cope (CON_ANYTIME) don't call them until this CPU is officially up.
2685 	 */
2686 	if (!cpu_online(raw_smp_processor_id()) && !(flags & CON_ANYTIME))
2687 		return false;
2688 
2689 	return true;
2690 }
2691 
2692 static void __console_unlock(void)
2693 {
2694 	console_locked = 0;
2695 	up_console_sem();
2696 }
2697 
2698 #ifdef CONFIG_PRINTK
2699 
2700 /*
2701  * Prepend the message in @pmsg->pbufs->outbuf with a "dropped message". This
2702  * is achieved by shifting the existing message over and inserting the dropped
2703  * message.
2704  *
2705  * @pmsg is the printk message to prepend.
2706  *
2707  * @dropped is the dropped count to report in the dropped message.
2708  *
2709  * If the message text in @pmsg->pbufs->outbuf does not have enough space for
2710  * the dropped message, the message text will be sufficiently truncated.
2711  *
2712  * If @pmsg->pbufs->outbuf is modified, @pmsg->outbuf_len is updated.
2713  */
2714 void console_prepend_dropped(struct printk_message *pmsg, unsigned long dropped)
2715 {
2716 	struct printk_buffers *pbufs = pmsg->pbufs;
2717 	const size_t scratchbuf_sz = sizeof(pbufs->scratchbuf);
2718 	const size_t outbuf_sz = sizeof(pbufs->outbuf);
2719 	char *scratchbuf = &pbufs->scratchbuf[0];
2720 	char *outbuf = &pbufs->outbuf[0];
2721 	size_t len;
2722 
2723 	len = scnprintf(scratchbuf, scratchbuf_sz,
2724 		       "** %lu printk messages dropped **\n", dropped);
2725 
2726 	/*
2727 	 * Make sure outbuf is sufficiently large before prepending.
2728 	 * Keep at least the prefix when the message must be truncated.
2729 	 * It is a rather theoretical problem when someone tries to
2730 	 * use a minimalist buffer.
2731 	 */
2732 	if (WARN_ON_ONCE(len + PRINTK_PREFIX_MAX >= outbuf_sz))
2733 		return;
2734 
2735 	if (pmsg->outbuf_len + len >= outbuf_sz) {
2736 		/* Truncate the message, but keep it terminated. */
2737 		pmsg->outbuf_len = outbuf_sz - (len + 1);
2738 		outbuf[pmsg->outbuf_len] = 0;
2739 	}
2740 
2741 	memmove(outbuf + len, outbuf, pmsg->outbuf_len + 1);
2742 	memcpy(outbuf, scratchbuf, len);
2743 	pmsg->outbuf_len += len;
2744 }
2745 
2746 /*
2747  * Read and format the specified record (or a later record if the specified
2748  * record is not available).
2749  *
2750  * @pmsg will contain the formatted result. @pmsg->pbufs must point to a
2751  * struct printk_buffers.
2752  *
2753  * @seq is the record to read and format. If it is not available, the next
2754  * valid record is read.
2755  *
2756  * @is_extended specifies if the message should be formatted for extended
2757  * console output.
2758  *
2759  * @may_supress specifies if records may be skipped based on loglevel.
2760  *
2761  * Returns false if no record is available. Otherwise true and all fields
2762  * of @pmsg are valid. (See the documentation of struct printk_message
2763  * for information about the @pmsg fields.)
2764  */
2765 bool printk_get_next_message(struct printk_message *pmsg, u64 seq,
2766 			     bool is_extended, bool may_suppress)
2767 {
2768 	static int panic_console_dropped;
2769 
2770 	struct printk_buffers *pbufs = pmsg->pbufs;
2771 	const size_t scratchbuf_sz = sizeof(pbufs->scratchbuf);
2772 	const size_t outbuf_sz = sizeof(pbufs->outbuf);
2773 	char *scratchbuf = &pbufs->scratchbuf[0];
2774 	char *outbuf = &pbufs->outbuf[0];
2775 	struct printk_info info;
2776 	struct printk_record r;
2777 	size_t len = 0;
2778 
2779 	/*
2780 	 * Formatting extended messages requires a separate buffer, so use the
2781 	 * scratch buffer to read in the ringbuffer text.
2782 	 *
2783 	 * Formatting normal messages is done in-place, so read the ringbuffer
2784 	 * text directly into the output buffer.
2785 	 */
2786 	if (is_extended)
2787 		prb_rec_init_rd(&r, &info, scratchbuf, scratchbuf_sz);
2788 	else
2789 		prb_rec_init_rd(&r, &info, outbuf, outbuf_sz);
2790 
2791 	if (!prb_read_valid(prb, seq, &r))
2792 		return false;
2793 
2794 	pmsg->seq = r.info->seq;
2795 	pmsg->dropped = r.info->seq - seq;
2796 
2797 	/*
2798 	 * Check for dropped messages in panic here so that printk
2799 	 * suppression can occur as early as possible if necessary.
2800 	 */
2801 	if (pmsg->dropped &&
2802 	    panic_in_progress() &&
2803 	    panic_console_dropped++ > 10) {
2804 		suppress_panic_printk = 1;
2805 		pr_warn_once("Too many dropped messages. Suppress messages on non-panic CPUs to prevent livelock.\n");
2806 	}
2807 
2808 	/* Skip record that has level above the console loglevel. */
2809 	if (may_suppress && suppress_message_printing(r.info->level))
2810 		goto out;
2811 
2812 	if (is_extended) {
2813 		len = info_print_ext_header(outbuf, outbuf_sz, r.info);
2814 		len += msg_print_ext_body(outbuf + len, outbuf_sz - len,
2815 					  &r.text_buf[0], r.info->text_len, &r.info->dev_info);
2816 	} else {
2817 		len = record_print_text(&r, console_msg_format & MSG_FORMAT_SYSLOG, printk_time);
2818 	}
2819 out:
2820 	pmsg->outbuf_len = len;
2821 	return true;
2822 }
2823 
2824 /*
2825  * Used as the printk buffers for non-panic, serialized console printing.
2826  * This is for legacy (!CON_NBCON) as well as all boot (CON_BOOT) consoles.
2827  * Its usage requires the console_lock held.
2828  */
2829 struct printk_buffers printk_shared_pbufs;
2830 
2831 /*
2832  * Print one record for the given console. The record printed is whatever
2833  * record is the next available record for the given console.
2834  *
2835  * @handover will be set to true if a printk waiter has taken over the
2836  * console_lock, in which case the caller is no longer holding both the
2837  * console_lock and the SRCU read lock. Otherwise it is set to false.
2838  *
2839  * @cookie is the cookie from the SRCU read lock.
2840  *
2841  * Returns false if the given console has no next record to print, otherwise
2842  * true.
2843  *
2844  * Requires the console_lock and the SRCU read lock.
2845  */
2846 static bool console_emit_next_record(struct console *con, bool *handover, int cookie)
2847 {
2848 	bool is_extended = console_srcu_read_flags(con) & CON_EXTENDED;
2849 	char *outbuf = &printk_shared_pbufs.outbuf[0];
2850 	struct printk_message pmsg = {
2851 		.pbufs = &printk_shared_pbufs,
2852 	};
2853 	unsigned long flags;
2854 
2855 	*handover = false;
2856 
2857 	if (!printk_get_next_message(&pmsg, con->seq, is_extended, true))
2858 		return false;
2859 
2860 	con->dropped += pmsg.dropped;
2861 
2862 	/* Skip messages of formatted length 0. */
2863 	if (pmsg.outbuf_len == 0) {
2864 		con->seq = pmsg.seq + 1;
2865 		goto skip;
2866 	}
2867 
2868 	if (con->dropped && !is_extended) {
2869 		console_prepend_dropped(&pmsg, con->dropped);
2870 		con->dropped = 0;
2871 	}
2872 
2873 	/*
2874 	 * While actively printing out messages, if another printk()
2875 	 * were to occur on another CPU, it may wait for this one to
2876 	 * finish. This task can not be preempted if there is a
2877 	 * waiter waiting to take over.
2878 	 *
2879 	 * Interrupts are disabled because the hand over to a waiter
2880 	 * must not be interrupted until the hand over is completed
2881 	 * (@console_waiter is cleared).
2882 	 */
2883 	printk_safe_enter_irqsave(flags);
2884 	console_lock_spinning_enable();
2885 
2886 	/* Do not trace print latency. */
2887 	stop_critical_timings();
2888 
2889 	/* Write everything out to the hardware. */
2890 	con->write(con, outbuf, pmsg.outbuf_len);
2891 
2892 	start_critical_timings();
2893 
2894 	con->seq = pmsg.seq + 1;
2895 
2896 	*handover = console_lock_spinning_disable_and_check(cookie);
2897 	printk_safe_exit_irqrestore(flags);
2898 skip:
2899 	return true;
2900 }
2901 
2902 #else
2903 
2904 static bool console_emit_next_record(struct console *con, bool *handover, int cookie)
2905 {
2906 	*handover = false;
2907 	return false;
2908 }
2909 
2910 #endif /* CONFIG_PRINTK */
2911 
2912 /*
2913  * Print out all remaining records to all consoles.
2914  *
2915  * @do_cond_resched is set by the caller. It can be true only in schedulable
2916  * context.
2917  *
2918  * @next_seq is set to the sequence number after the last available record.
2919  * The value is valid only when this function returns true. It means that all
2920  * usable consoles are completely flushed.
2921  *
2922  * @handover will be set to true if a printk waiter has taken over the
2923  * console_lock, in which case the caller is no longer holding the
2924  * console_lock. Otherwise it is set to false.
2925  *
2926  * Returns true when there was at least one usable console and all messages
2927  * were flushed to all usable consoles. A returned false informs the caller
2928  * that everything was not flushed (either there were no usable consoles or
2929  * another context has taken over printing or it is a panic situation and this
2930  * is not the panic CPU). Regardless the reason, the caller should assume it
2931  * is not useful to immediately try again.
2932  *
2933  * Requires the console_lock.
2934  */
2935 static bool console_flush_all(bool do_cond_resched, u64 *next_seq, bool *handover)
2936 {
2937 	bool any_usable = false;
2938 	struct console *con;
2939 	bool any_progress;
2940 	int cookie;
2941 
2942 	*next_seq = 0;
2943 	*handover = false;
2944 
2945 	do {
2946 		any_progress = false;
2947 
2948 		cookie = console_srcu_read_lock();
2949 		for_each_console_srcu(con) {
2950 			bool progress;
2951 
2952 			if (!console_is_usable(con))
2953 				continue;
2954 			any_usable = true;
2955 
2956 			progress = console_emit_next_record(con, handover, cookie);
2957 
2958 			/*
2959 			 * If a handover has occurred, the SRCU read lock
2960 			 * is already released.
2961 			 */
2962 			if (*handover)
2963 				return false;
2964 
2965 			/* Track the next of the highest seq flushed. */
2966 			if (con->seq > *next_seq)
2967 				*next_seq = con->seq;
2968 
2969 			if (!progress)
2970 				continue;
2971 			any_progress = true;
2972 
2973 			/* Allow panic_cpu to take over the consoles safely. */
2974 			if (other_cpu_in_panic())
2975 				goto abandon;
2976 
2977 			if (do_cond_resched)
2978 				cond_resched();
2979 		}
2980 		console_srcu_read_unlock(cookie);
2981 	} while (any_progress);
2982 
2983 	return any_usable;
2984 
2985 abandon:
2986 	console_srcu_read_unlock(cookie);
2987 	return false;
2988 }
2989 
2990 /**
2991  * console_unlock - unblock the console subsystem from printing
2992  *
2993  * Releases the console_lock which the caller holds to block printing of
2994  * the console subsystem.
2995  *
2996  * While the console_lock was held, console output may have been buffered
2997  * by printk().  If this is the case, console_unlock(); emits
2998  * the output prior to releasing the lock.
2999  *
3000  * console_unlock(); may be called from any context.
3001  */
3002 void console_unlock(void)
3003 {
3004 	bool do_cond_resched;
3005 	bool handover;
3006 	bool flushed;
3007 	u64 next_seq;
3008 
3009 	/*
3010 	 * Console drivers are called with interrupts disabled, so
3011 	 * @console_may_schedule should be cleared before; however, we may
3012 	 * end up dumping a lot of lines, for example, if called from
3013 	 * console registration path, and should invoke cond_resched()
3014 	 * between lines if allowable.  Not doing so can cause a very long
3015 	 * scheduling stall on a slow console leading to RCU stall and
3016 	 * softlockup warnings which exacerbate the issue with more
3017 	 * messages practically incapacitating the system. Therefore, create
3018 	 * a local to use for the printing loop.
3019 	 */
3020 	do_cond_resched = console_may_schedule;
3021 
3022 	do {
3023 		console_may_schedule = 0;
3024 
3025 		flushed = console_flush_all(do_cond_resched, &next_seq, &handover);
3026 		if (!handover)
3027 			__console_unlock();
3028 
3029 		/*
3030 		 * Abort if there was a failure to flush all messages to all
3031 		 * usable consoles. Either it is not possible to flush (in
3032 		 * which case it would be an infinite loop of retrying) or
3033 		 * another context has taken over printing.
3034 		 */
3035 		if (!flushed)
3036 			break;
3037 
3038 		/*
3039 		 * Some context may have added new records after
3040 		 * console_flush_all() but before unlocking the console.
3041 		 * Re-check if there is a new record to flush. If the trylock
3042 		 * fails, another context is already handling the printing.
3043 		 */
3044 	} while (prb_read_valid(prb, next_seq, NULL) && console_trylock());
3045 }
3046 EXPORT_SYMBOL(console_unlock);
3047 
3048 /**
3049  * console_conditional_schedule - yield the CPU if required
3050  *
3051  * If the console code is currently allowed to sleep, and
3052  * if this CPU should yield the CPU to another task, do
3053  * so here.
3054  *
3055  * Must be called within console_lock();.
3056  */
3057 void __sched console_conditional_schedule(void)
3058 {
3059 	if (console_may_schedule)
3060 		cond_resched();
3061 }
3062 EXPORT_SYMBOL(console_conditional_schedule);
3063 
3064 void console_unblank(void)
3065 {
3066 	bool found_unblank = false;
3067 	struct console *c;
3068 	int cookie;
3069 
3070 	/*
3071 	 * First check if there are any consoles implementing the unblank()
3072 	 * callback. If not, there is no reason to continue and take the
3073 	 * console lock, which in particular can be dangerous if
3074 	 * @oops_in_progress is set.
3075 	 */
3076 	cookie = console_srcu_read_lock();
3077 	for_each_console_srcu(c) {
3078 		if ((console_srcu_read_flags(c) & CON_ENABLED) && c->unblank) {
3079 			found_unblank = true;
3080 			break;
3081 		}
3082 	}
3083 	console_srcu_read_unlock(cookie);
3084 	if (!found_unblank)
3085 		return;
3086 
3087 	/*
3088 	 * Stop console printing because the unblank() callback may
3089 	 * assume the console is not within its write() callback.
3090 	 *
3091 	 * If @oops_in_progress is set, this may be an atomic context.
3092 	 * In that case, attempt a trylock as best-effort.
3093 	 */
3094 	if (oops_in_progress) {
3095 		/* Semaphores are not NMI-safe. */
3096 		if (in_nmi())
3097 			return;
3098 
3099 		/*
3100 		 * Attempting to trylock the console lock can deadlock
3101 		 * if another CPU was stopped while modifying the
3102 		 * semaphore. "Hope and pray" that this is not the
3103 		 * current situation.
3104 		 */
3105 		if (down_trylock_console_sem() != 0)
3106 			return;
3107 	} else
3108 		console_lock();
3109 
3110 	console_locked = 1;
3111 	console_may_schedule = 0;
3112 
3113 	cookie = console_srcu_read_lock();
3114 	for_each_console_srcu(c) {
3115 		if ((console_srcu_read_flags(c) & CON_ENABLED) && c->unblank)
3116 			c->unblank();
3117 	}
3118 	console_srcu_read_unlock(cookie);
3119 
3120 	console_unlock();
3121 
3122 	if (!oops_in_progress)
3123 		pr_flush(1000, true);
3124 }
3125 
3126 /**
3127  * console_flush_on_panic - flush console content on panic
3128  * @mode: flush all messages in buffer or just the pending ones
3129  *
3130  * Immediately output all pending messages no matter what.
3131  */
3132 void console_flush_on_panic(enum con_flush_mode mode)
3133 {
3134 	bool handover;
3135 	u64 next_seq;
3136 
3137 	/*
3138 	 * Ignore the console lock and flush out the messages. Attempting a
3139 	 * trylock would not be useful because:
3140 	 *
3141 	 *   - if it is contended, it must be ignored anyway
3142 	 *   - console_lock() and console_trylock() block and fail
3143 	 *     respectively in panic for non-panic CPUs
3144 	 *   - semaphores are not NMI-safe
3145 	 */
3146 
3147 	/*
3148 	 * If another context is holding the console lock,
3149 	 * @console_may_schedule might be set. Clear it so that
3150 	 * this context does not call cond_resched() while flushing.
3151 	 */
3152 	console_may_schedule = 0;
3153 
3154 	if (mode == CONSOLE_REPLAY_ALL) {
3155 		struct console *c;
3156 		short flags;
3157 		int cookie;
3158 		u64 seq;
3159 
3160 		seq = prb_first_valid_seq(prb);
3161 
3162 		cookie = console_srcu_read_lock();
3163 		for_each_console_srcu(c) {
3164 			flags = console_srcu_read_flags(c);
3165 
3166 			if (flags & CON_NBCON) {
3167 				nbcon_seq_force(c, seq);
3168 			} else {
3169 				/*
3170 				 * This is an unsynchronized assignment. On
3171 				 * panic legacy consoles are only best effort.
3172 				 */
3173 				c->seq = seq;
3174 			}
3175 		}
3176 		console_srcu_read_unlock(cookie);
3177 	}
3178 
3179 	console_flush_all(false, &next_seq, &handover);
3180 }
3181 
3182 /*
3183  * Return the console tty driver structure and its associated index
3184  */
3185 struct tty_driver *console_device(int *index)
3186 {
3187 	struct console *c;
3188 	struct tty_driver *driver = NULL;
3189 	int cookie;
3190 
3191 	/*
3192 	 * Take console_lock to serialize device() callback with
3193 	 * other console operations. For example, fg_console is
3194 	 * modified under console_lock when switching vt.
3195 	 */
3196 	console_lock();
3197 
3198 	cookie = console_srcu_read_lock();
3199 	for_each_console_srcu(c) {
3200 		if (!c->device)
3201 			continue;
3202 		driver = c->device(c, index);
3203 		if (driver)
3204 			break;
3205 	}
3206 	console_srcu_read_unlock(cookie);
3207 
3208 	console_unlock();
3209 	return driver;
3210 }
3211 
3212 /*
3213  * Prevent further output on the passed console device so that (for example)
3214  * serial drivers can disable console output before suspending a port, and can
3215  * re-enable output afterwards.
3216  */
3217 void console_stop(struct console *console)
3218 {
3219 	__pr_flush(console, 1000, true);
3220 	console_list_lock();
3221 	console_srcu_write_flags(console, console->flags & ~CON_ENABLED);
3222 	console_list_unlock();
3223 
3224 	/*
3225 	 * Ensure that all SRCU list walks have completed. All contexts must
3226 	 * be able to see that this console is disabled so that (for example)
3227 	 * the caller can suspend the port without risk of another context
3228 	 * using the port.
3229 	 */
3230 	synchronize_srcu(&console_srcu);
3231 }
3232 EXPORT_SYMBOL(console_stop);
3233 
3234 void console_start(struct console *console)
3235 {
3236 	console_list_lock();
3237 	console_srcu_write_flags(console, console->flags | CON_ENABLED);
3238 	console_list_unlock();
3239 	__pr_flush(console, 1000, true);
3240 }
3241 EXPORT_SYMBOL(console_start);
3242 
3243 static int __read_mostly keep_bootcon;
3244 
3245 static int __init keep_bootcon_setup(char *str)
3246 {
3247 	keep_bootcon = 1;
3248 	pr_info("debug: skip boot console de-registration.\n");
3249 
3250 	return 0;
3251 }
3252 
3253 early_param("keep_bootcon", keep_bootcon_setup);
3254 
3255 /*
3256  * This is called by register_console() to try to match
3257  * the newly registered console with any of the ones selected
3258  * by either the command line or add_preferred_console() and
3259  * setup/enable it.
3260  *
3261  * Care need to be taken with consoles that are statically
3262  * enabled such as netconsole
3263  */
3264 static int try_enable_preferred_console(struct console *newcon,
3265 					bool user_specified)
3266 {
3267 	struct console_cmdline *c;
3268 	int i, err;
3269 
3270 	for (i = 0, c = console_cmdline;
3271 	     i < MAX_CMDLINECONSOLES && c->name[0];
3272 	     i++, c++) {
3273 		if (c->user_specified != user_specified)
3274 			continue;
3275 		if (!newcon->match ||
3276 		    newcon->match(newcon, c->name, c->index, c->options) != 0) {
3277 			/* default matching */
3278 			BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
3279 			if (strcmp(c->name, newcon->name) != 0)
3280 				continue;
3281 			if (newcon->index >= 0 &&
3282 			    newcon->index != c->index)
3283 				continue;
3284 			if (newcon->index < 0)
3285 				newcon->index = c->index;
3286 
3287 			if (_braille_register_console(newcon, c))
3288 				return 0;
3289 
3290 			if (newcon->setup &&
3291 			    (err = newcon->setup(newcon, c->options)) != 0)
3292 				return err;
3293 		}
3294 		newcon->flags |= CON_ENABLED;
3295 		if (i == preferred_console)
3296 			newcon->flags |= CON_CONSDEV;
3297 		return 0;
3298 	}
3299 
3300 	/*
3301 	 * Some consoles, such as pstore and netconsole, can be enabled even
3302 	 * without matching. Accept the pre-enabled consoles only when match()
3303 	 * and setup() had a chance to be called.
3304 	 */
3305 	if (newcon->flags & CON_ENABLED && c->user_specified ==	user_specified)
3306 		return 0;
3307 
3308 	return -ENOENT;
3309 }
3310 
3311 /* Try to enable the console unconditionally */
3312 static void try_enable_default_console(struct console *newcon)
3313 {
3314 	if (newcon->index < 0)
3315 		newcon->index = 0;
3316 
3317 	if (newcon->setup && newcon->setup(newcon, NULL) != 0)
3318 		return;
3319 
3320 	newcon->flags |= CON_ENABLED;
3321 
3322 	if (newcon->device)
3323 		newcon->flags |= CON_CONSDEV;
3324 }
3325 
3326 static void console_init_seq(struct console *newcon, bool bootcon_registered)
3327 {
3328 	struct console *con;
3329 	bool handover;
3330 
3331 	if (newcon->flags & (CON_PRINTBUFFER | CON_BOOT)) {
3332 		/* Get a consistent copy of @syslog_seq. */
3333 		mutex_lock(&syslog_lock);
3334 		newcon->seq = syslog_seq;
3335 		mutex_unlock(&syslog_lock);
3336 	} else {
3337 		/* Begin with next message added to ringbuffer. */
3338 		newcon->seq = prb_next_seq(prb);
3339 
3340 		/*
3341 		 * If any enabled boot consoles are due to be unregistered
3342 		 * shortly, some may not be caught up and may be the same
3343 		 * device as @newcon. Since it is not known which boot console
3344 		 * is the same device, flush all consoles and, if necessary,
3345 		 * start with the message of the enabled boot console that is
3346 		 * the furthest behind.
3347 		 */
3348 		if (bootcon_registered && !keep_bootcon) {
3349 			/*
3350 			 * Hold the console_lock to stop console printing and
3351 			 * guarantee safe access to console->seq.
3352 			 */
3353 			console_lock();
3354 
3355 			/*
3356 			 * Flush all consoles and set the console to start at
3357 			 * the next unprinted sequence number.
3358 			 */
3359 			if (!console_flush_all(true, &newcon->seq, &handover)) {
3360 				/*
3361 				 * Flushing failed. Just choose the lowest
3362 				 * sequence of the enabled boot consoles.
3363 				 */
3364 
3365 				/*
3366 				 * If there was a handover, this context no
3367 				 * longer holds the console_lock.
3368 				 */
3369 				if (handover)
3370 					console_lock();
3371 
3372 				newcon->seq = prb_next_seq(prb);
3373 				for_each_console(con) {
3374 					if ((con->flags & CON_BOOT) &&
3375 					    (con->flags & CON_ENABLED) &&
3376 					    con->seq < newcon->seq) {
3377 						newcon->seq = con->seq;
3378 					}
3379 				}
3380 			}
3381 
3382 			console_unlock();
3383 		}
3384 	}
3385 }
3386 
3387 #define console_first()				\
3388 	hlist_entry(console_list.first, struct console, node)
3389 
3390 static int unregister_console_locked(struct console *console);
3391 
3392 /*
3393  * The console driver calls this routine during kernel initialization
3394  * to register the console printing procedure with printk() and to
3395  * print any messages that were printed by the kernel before the
3396  * console driver was initialized.
3397  *
3398  * This can happen pretty early during the boot process (because of
3399  * early_printk) - sometimes before setup_arch() completes - be careful
3400  * of what kernel features are used - they may not be initialised yet.
3401  *
3402  * There are two types of consoles - bootconsoles (early_printk) and
3403  * "real" consoles (everything which is not a bootconsole) which are
3404  * handled differently.
3405  *  - Any number of bootconsoles can be registered at any time.
3406  *  - As soon as a "real" console is registered, all bootconsoles
3407  *    will be unregistered automatically.
3408  *  - Once a "real" console is registered, any attempt to register a
3409  *    bootconsoles will be rejected
3410  */
3411 void register_console(struct console *newcon)
3412 {
3413 	struct console *con;
3414 	bool bootcon_registered = false;
3415 	bool realcon_registered = false;
3416 	int err;
3417 
3418 	console_list_lock();
3419 
3420 	for_each_console(con) {
3421 		if (WARN(con == newcon, "console '%s%d' already registered\n",
3422 					 con->name, con->index)) {
3423 			goto unlock;
3424 		}
3425 
3426 		if (con->flags & CON_BOOT)
3427 			bootcon_registered = true;
3428 		else
3429 			realcon_registered = true;
3430 	}
3431 
3432 	/* Do not register boot consoles when there already is a real one. */
3433 	if ((newcon->flags & CON_BOOT) && realcon_registered) {
3434 		pr_info("Too late to register bootconsole %s%d\n",
3435 			newcon->name, newcon->index);
3436 		goto unlock;
3437 	}
3438 
3439 	if (newcon->flags & CON_NBCON) {
3440 		/*
3441 		 * Ensure the nbcon console buffers can be allocated
3442 		 * before modifying any global data.
3443 		 */
3444 		if (!nbcon_alloc(newcon))
3445 			goto unlock;
3446 	}
3447 
3448 	/*
3449 	 * See if we want to enable this console driver by default.
3450 	 *
3451 	 * Nope when a console is preferred by the command line, device
3452 	 * tree, or SPCR.
3453 	 *
3454 	 * The first real console with tty binding (driver) wins. More
3455 	 * consoles might get enabled before the right one is found.
3456 	 *
3457 	 * Note that a console with tty binding will have CON_CONSDEV
3458 	 * flag set and will be first in the list.
3459 	 */
3460 	if (preferred_console < 0) {
3461 		if (hlist_empty(&console_list) || !console_first()->device ||
3462 		    console_first()->flags & CON_BOOT) {
3463 			try_enable_default_console(newcon);
3464 		}
3465 	}
3466 
3467 	/* See if this console matches one we selected on the command line */
3468 	err = try_enable_preferred_console(newcon, true);
3469 
3470 	/* If not, try to match against the platform default(s) */
3471 	if (err == -ENOENT)
3472 		err = try_enable_preferred_console(newcon, false);
3473 
3474 	/* printk() messages are not printed to the Braille console. */
3475 	if (err || newcon->flags & CON_BRL) {
3476 		if (newcon->flags & CON_NBCON)
3477 			nbcon_free(newcon);
3478 		goto unlock;
3479 	}
3480 
3481 	/*
3482 	 * If we have a bootconsole, and are switching to a real console,
3483 	 * don't print everything out again, since when the boot console, and
3484 	 * the real console are the same physical device, it's annoying to
3485 	 * see the beginning boot messages twice
3486 	 */
3487 	if (bootcon_registered &&
3488 	    ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
3489 		newcon->flags &= ~CON_PRINTBUFFER;
3490 	}
3491 
3492 	newcon->dropped = 0;
3493 	console_init_seq(newcon, bootcon_registered);
3494 
3495 	if (newcon->flags & CON_NBCON)
3496 		nbcon_init(newcon);
3497 
3498 	/*
3499 	 * Put this console in the list - keep the
3500 	 * preferred driver at the head of the list.
3501 	 */
3502 	if (hlist_empty(&console_list)) {
3503 		/* Ensure CON_CONSDEV is always set for the head. */
3504 		newcon->flags |= CON_CONSDEV;
3505 		hlist_add_head_rcu(&newcon->node, &console_list);
3506 
3507 	} else if (newcon->flags & CON_CONSDEV) {
3508 		/* Only the new head can have CON_CONSDEV set. */
3509 		console_srcu_write_flags(console_first(), console_first()->flags & ~CON_CONSDEV);
3510 		hlist_add_head_rcu(&newcon->node, &console_list);
3511 
3512 	} else {
3513 		hlist_add_behind_rcu(&newcon->node, console_list.first);
3514 	}
3515 
3516 	/*
3517 	 * No need to synchronize SRCU here! The caller does not rely
3518 	 * on all contexts being able to see the new console before
3519 	 * register_console() completes.
3520 	 */
3521 
3522 	console_sysfs_notify();
3523 
3524 	/*
3525 	 * By unregistering the bootconsoles after we enable the real console
3526 	 * we get the "console xxx enabled" message on all the consoles -
3527 	 * boot consoles, real consoles, etc - this is to ensure that end
3528 	 * users know there might be something in the kernel's log buffer that
3529 	 * went to the bootconsole (that they do not see on the real console)
3530 	 */
3531 	con_printk(KERN_INFO, newcon, "enabled\n");
3532 	if (bootcon_registered &&
3533 	    ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
3534 	    !keep_bootcon) {
3535 		struct hlist_node *tmp;
3536 
3537 		hlist_for_each_entry_safe(con, tmp, &console_list, node) {
3538 			if (con->flags & CON_BOOT)
3539 				unregister_console_locked(con);
3540 		}
3541 	}
3542 unlock:
3543 	console_list_unlock();
3544 }
3545 EXPORT_SYMBOL(register_console);
3546 
3547 /* Must be called under console_list_lock(). */
3548 static int unregister_console_locked(struct console *console)
3549 {
3550 	int res;
3551 
3552 	lockdep_assert_console_list_lock_held();
3553 
3554 	con_printk(KERN_INFO, console, "disabled\n");
3555 
3556 	res = _braille_unregister_console(console);
3557 	if (res < 0)
3558 		return res;
3559 	if (res > 0)
3560 		return 0;
3561 
3562 	/* Disable it unconditionally */
3563 	console_srcu_write_flags(console, console->flags & ~CON_ENABLED);
3564 
3565 	if (!console_is_registered_locked(console))
3566 		return -ENODEV;
3567 
3568 	hlist_del_init_rcu(&console->node);
3569 
3570 	/*
3571 	 * <HISTORICAL>
3572 	 * If this isn't the last console and it has CON_CONSDEV set, we
3573 	 * need to set it on the next preferred console.
3574 	 * </HISTORICAL>
3575 	 *
3576 	 * The above makes no sense as there is no guarantee that the next
3577 	 * console has any device attached. Oh well....
3578 	 */
3579 	if (!hlist_empty(&console_list) && console->flags & CON_CONSDEV)
3580 		console_srcu_write_flags(console_first(), console_first()->flags | CON_CONSDEV);
3581 
3582 	/*
3583 	 * Ensure that all SRCU list walks have completed. All contexts
3584 	 * must not be able to see this console in the list so that any
3585 	 * exit/cleanup routines can be performed safely.
3586 	 */
3587 	synchronize_srcu(&console_srcu);
3588 
3589 	if (console->flags & CON_NBCON)
3590 		nbcon_free(console);
3591 
3592 	console_sysfs_notify();
3593 
3594 	if (console->exit)
3595 		res = console->exit(console);
3596 
3597 	return res;
3598 }
3599 
3600 int unregister_console(struct console *console)
3601 {
3602 	int res;
3603 
3604 	console_list_lock();
3605 	res = unregister_console_locked(console);
3606 	console_list_unlock();
3607 	return res;
3608 }
3609 EXPORT_SYMBOL(unregister_console);
3610 
3611 /**
3612  * console_force_preferred_locked - force a registered console preferred
3613  * @con: The registered console to force preferred.
3614  *
3615  * Must be called under console_list_lock().
3616  */
3617 void console_force_preferred_locked(struct console *con)
3618 {
3619 	struct console *cur_pref_con;
3620 
3621 	if (!console_is_registered_locked(con))
3622 		return;
3623 
3624 	cur_pref_con = console_first();
3625 
3626 	/* Already preferred? */
3627 	if (cur_pref_con == con)
3628 		return;
3629 
3630 	/*
3631 	 * Delete, but do not re-initialize the entry. This allows the console
3632 	 * to continue to appear registered (via any hlist_unhashed_lockless()
3633 	 * checks), even though it was briefly removed from the console list.
3634 	 */
3635 	hlist_del_rcu(&con->node);
3636 
3637 	/*
3638 	 * Ensure that all SRCU list walks have completed so that the console
3639 	 * can be added to the beginning of the console list and its forward
3640 	 * list pointer can be re-initialized.
3641 	 */
3642 	synchronize_srcu(&console_srcu);
3643 
3644 	con->flags |= CON_CONSDEV;
3645 	WARN_ON(!con->device);
3646 
3647 	/* Only the new head can have CON_CONSDEV set. */
3648 	console_srcu_write_flags(cur_pref_con, cur_pref_con->flags & ~CON_CONSDEV);
3649 	hlist_add_head_rcu(&con->node, &console_list);
3650 }
3651 EXPORT_SYMBOL(console_force_preferred_locked);
3652 
3653 /*
3654  * Initialize the console device. This is called *early*, so
3655  * we can't necessarily depend on lots of kernel help here.
3656  * Just do some early initializations, and do the complex setup
3657  * later.
3658  */
3659 void __init console_init(void)
3660 {
3661 	int ret;
3662 	initcall_t call;
3663 	initcall_entry_t *ce;
3664 
3665 	/* Setup the default TTY line discipline. */
3666 	n_tty_init();
3667 
3668 	/*
3669 	 * set up the console device so that later boot sequences can
3670 	 * inform about problems etc..
3671 	 */
3672 	ce = __con_initcall_start;
3673 	trace_initcall_level("console");
3674 	while (ce < __con_initcall_end) {
3675 		call = initcall_from_entry(ce);
3676 		trace_initcall_start(call);
3677 		ret = call();
3678 		trace_initcall_finish(call, ret);
3679 		ce++;
3680 	}
3681 }
3682 
3683 /*
3684  * Some boot consoles access data that is in the init section and which will
3685  * be discarded after the initcalls have been run. To make sure that no code
3686  * will access this data, unregister the boot consoles in a late initcall.
3687  *
3688  * If for some reason, such as deferred probe or the driver being a loadable
3689  * module, the real console hasn't registered yet at this point, there will
3690  * be a brief interval in which no messages are logged to the console, which
3691  * makes it difficult to diagnose problems that occur during this time.
3692  *
3693  * To mitigate this problem somewhat, only unregister consoles whose memory
3694  * intersects with the init section. Note that all other boot consoles will
3695  * get unregistered when the real preferred console is registered.
3696  */
3697 static int __init printk_late_init(void)
3698 {
3699 	struct hlist_node *tmp;
3700 	struct console *con;
3701 	int ret;
3702 
3703 	console_list_lock();
3704 	hlist_for_each_entry_safe(con, tmp, &console_list, node) {
3705 		if (!(con->flags & CON_BOOT))
3706 			continue;
3707 
3708 		/* Check addresses that might be used for enabled consoles. */
3709 		if (init_section_intersects(con, sizeof(*con)) ||
3710 		    init_section_contains(con->write, 0) ||
3711 		    init_section_contains(con->read, 0) ||
3712 		    init_section_contains(con->device, 0) ||
3713 		    init_section_contains(con->unblank, 0) ||
3714 		    init_section_contains(con->data, 0)) {
3715 			/*
3716 			 * Please, consider moving the reported consoles out
3717 			 * of the init section.
3718 			 */
3719 			pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3720 				con->name, con->index);
3721 			unregister_console_locked(con);
3722 		}
3723 	}
3724 	console_list_unlock();
3725 
3726 	ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3727 					console_cpu_notify);
3728 	WARN_ON(ret < 0);
3729 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3730 					console_cpu_notify, NULL);
3731 	WARN_ON(ret < 0);
3732 	printk_sysctl_init();
3733 	return 0;
3734 }
3735 late_initcall(printk_late_init);
3736 
3737 #if defined CONFIG_PRINTK
3738 /* If @con is specified, only wait for that console. Otherwise wait for all. */
3739 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress)
3740 {
3741 	unsigned long timeout_jiffies = msecs_to_jiffies(timeout_ms);
3742 	unsigned long remaining_jiffies = timeout_jiffies;
3743 	struct console *c;
3744 	u64 last_diff = 0;
3745 	u64 printk_seq;
3746 	short flags;
3747 	int cookie;
3748 	u64 diff;
3749 	u64 seq;
3750 
3751 	might_sleep();
3752 
3753 	seq = prb_next_seq(prb);
3754 
3755 	/* Flush the consoles so that records up to @seq are printed. */
3756 	console_lock();
3757 	console_unlock();
3758 
3759 	for (;;) {
3760 		unsigned long begin_jiffies;
3761 		unsigned long slept_jiffies;
3762 
3763 		diff = 0;
3764 
3765 		/*
3766 		 * Hold the console_lock to guarantee safe access to
3767 		 * console->seq. Releasing console_lock flushes more
3768 		 * records in case @seq is still not printed on all
3769 		 * usable consoles.
3770 		 */
3771 		console_lock();
3772 
3773 		cookie = console_srcu_read_lock();
3774 		for_each_console_srcu(c) {
3775 			if (con && con != c)
3776 				continue;
3777 
3778 			flags = console_srcu_read_flags(c);
3779 
3780 			/*
3781 			 * If consoles are not usable, it cannot be expected
3782 			 * that they make forward progress, so only increment
3783 			 * @diff for usable consoles.
3784 			 */
3785 			if (!console_is_usable(c))
3786 				continue;
3787 
3788 			if (flags & CON_NBCON) {
3789 				printk_seq = nbcon_seq_read(c);
3790 			} else {
3791 				printk_seq = c->seq;
3792 			}
3793 
3794 			if (printk_seq < seq)
3795 				diff += seq - printk_seq;
3796 		}
3797 		console_srcu_read_unlock(cookie);
3798 
3799 		if (diff != last_diff && reset_on_progress)
3800 			remaining_jiffies = timeout_jiffies;
3801 
3802 		console_unlock();
3803 
3804 		/* Note: @diff is 0 if there are no usable consoles. */
3805 		if (diff == 0 || remaining_jiffies == 0)
3806 			break;
3807 
3808 		/* msleep(1) might sleep much longer. Check time by jiffies. */
3809 		begin_jiffies = jiffies;
3810 		msleep(1);
3811 		slept_jiffies = jiffies - begin_jiffies;
3812 
3813 		remaining_jiffies -= min(slept_jiffies, remaining_jiffies);
3814 
3815 		last_diff = diff;
3816 	}
3817 
3818 	return (diff == 0);
3819 }
3820 
3821 /**
3822  * pr_flush() - Wait for printing threads to catch up.
3823  *
3824  * @timeout_ms:        The maximum time (in ms) to wait.
3825  * @reset_on_progress: Reset the timeout if forward progress is seen.
3826  *
3827  * A value of 0 for @timeout_ms means no waiting will occur. A value of -1
3828  * represents infinite waiting.
3829  *
3830  * If @reset_on_progress is true, the timeout will be reset whenever any
3831  * printer has been seen to make some forward progress.
3832  *
3833  * Context: Process context. May sleep while acquiring console lock.
3834  * Return: true if all usable printers are caught up.
3835  */
3836 static bool pr_flush(int timeout_ms, bool reset_on_progress)
3837 {
3838 	return __pr_flush(NULL, timeout_ms, reset_on_progress);
3839 }
3840 
3841 /*
3842  * Delayed printk version, for scheduler-internal messages:
3843  */
3844 #define PRINTK_PENDING_WAKEUP	0x01
3845 #define PRINTK_PENDING_OUTPUT	0x02
3846 
3847 static DEFINE_PER_CPU(int, printk_pending);
3848 
3849 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3850 {
3851 	int pending = this_cpu_xchg(printk_pending, 0);
3852 
3853 	if (pending & PRINTK_PENDING_OUTPUT) {
3854 		/* If trylock fails, someone else is doing the printing */
3855 		if (console_trylock())
3856 			console_unlock();
3857 	}
3858 
3859 	if (pending & PRINTK_PENDING_WAKEUP)
3860 		wake_up_interruptible(&log_wait);
3861 }
3862 
3863 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) =
3864 	IRQ_WORK_INIT_LAZY(wake_up_klogd_work_func);
3865 
3866 static void __wake_up_klogd(int val)
3867 {
3868 	if (!printk_percpu_data_ready())
3869 		return;
3870 
3871 	preempt_disable();
3872 	/*
3873 	 * Guarantee any new records can be seen by tasks preparing to wait
3874 	 * before this context checks if the wait queue is empty.
3875 	 *
3876 	 * The full memory barrier within wq_has_sleeper() pairs with the full
3877 	 * memory barrier within set_current_state() of
3878 	 * prepare_to_wait_event(), which is called after ___wait_event() adds
3879 	 * the waiter but before it has checked the wait condition.
3880 	 *
3881 	 * This pairs with devkmsg_read:A and syslog_print:A.
3882 	 */
3883 	if (wq_has_sleeper(&log_wait) || /* LMM(__wake_up_klogd:A) */
3884 	    (val & PRINTK_PENDING_OUTPUT)) {
3885 		this_cpu_or(printk_pending, val);
3886 		irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3887 	}
3888 	preempt_enable();
3889 }
3890 
3891 /**
3892  * wake_up_klogd - Wake kernel logging daemon
3893  *
3894  * Use this function when new records have been added to the ringbuffer
3895  * and the console printing of those records has already occurred or is
3896  * known to be handled by some other context. This function will only
3897  * wake the logging daemon.
3898  *
3899  * Context: Any context.
3900  */
3901 void wake_up_klogd(void)
3902 {
3903 	__wake_up_klogd(PRINTK_PENDING_WAKEUP);
3904 }
3905 
3906 /**
3907  * defer_console_output - Wake kernel logging daemon and trigger
3908  *	console printing in a deferred context
3909  *
3910  * Use this function when new records have been added to the ringbuffer,
3911  * this context is responsible for console printing those records, but
3912  * the current context is not allowed to perform the console printing.
3913  * Trigger an irq_work context to perform the console printing. This
3914  * function also wakes the logging daemon.
3915  *
3916  * Context: Any context.
3917  */
3918 void defer_console_output(void)
3919 {
3920 	/*
3921 	 * New messages may have been added directly to the ringbuffer
3922 	 * using vprintk_store(), so wake any waiters as well.
3923 	 */
3924 	__wake_up_klogd(PRINTK_PENDING_WAKEUP | PRINTK_PENDING_OUTPUT);
3925 }
3926 
3927 void printk_trigger_flush(void)
3928 {
3929 	defer_console_output();
3930 }
3931 
3932 int vprintk_deferred(const char *fmt, va_list args)
3933 {
3934 	return vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
3935 }
3936 
3937 int _printk_deferred(const char *fmt, ...)
3938 {
3939 	va_list args;
3940 	int r;
3941 
3942 	va_start(args, fmt);
3943 	r = vprintk_deferred(fmt, args);
3944 	va_end(args);
3945 
3946 	return r;
3947 }
3948 
3949 /*
3950  * printk rate limiting, lifted from the networking subsystem.
3951  *
3952  * This enforces a rate limit: not more than 10 kernel messages
3953  * every 5s to make a denial-of-service attack impossible.
3954  */
3955 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3956 
3957 int __printk_ratelimit(const char *func)
3958 {
3959 	return ___ratelimit(&printk_ratelimit_state, func);
3960 }
3961 EXPORT_SYMBOL(__printk_ratelimit);
3962 
3963 /**
3964  * printk_timed_ratelimit - caller-controlled printk ratelimiting
3965  * @caller_jiffies: pointer to caller's state
3966  * @interval_msecs: minimum interval between prints
3967  *
3968  * printk_timed_ratelimit() returns true if more than @interval_msecs
3969  * milliseconds have elapsed since the last time printk_timed_ratelimit()
3970  * returned true.
3971  */
3972 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
3973 			unsigned int interval_msecs)
3974 {
3975 	unsigned long elapsed = jiffies - *caller_jiffies;
3976 
3977 	if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
3978 		return false;
3979 
3980 	*caller_jiffies = jiffies;
3981 	return true;
3982 }
3983 EXPORT_SYMBOL(printk_timed_ratelimit);
3984 
3985 static DEFINE_SPINLOCK(dump_list_lock);
3986 static LIST_HEAD(dump_list);
3987 
3988 /**
3989  * kmsg_dump_register - register a kernel log dumper.
3990  * @dumper: pointer to the kmsg_dumper structure
3991  *
3992  * Adds a kernel log dumper to the system. The dump callback in the
3993  * structure will be called when the kernel oopses or panics and must be
3994  * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
3995  */
3996 int kmsg_dump_register(struct kmsg_dumper *dumper)
3997 {
3998 	unsigned long flags;
3999 	int err = -EBUSY;
4000 
4001 	/* The dump callback needs to be set */
4002 	if (!dumper->dump)
4003 		return -EINVAL;
4004 
4005 	spin_lock_irqsave(&dump_list_lock, flags);
4006 	/* Don't allow registering multiple times */
4007 	if (!dumper->registered) {
4008 		dumper->registered = 1;
4009 		list_add_tail_rcu(&dumper->list, &dump_list);
4010 		err = 0;
4011 	}
4012 	spin_unlock_irqrestore(&dump_list_lock, flags);
4013 
4014 	return err;
4015 }
4016 EXPORT_SYMBOL_GPL(kmsg_dump_register);
4017 
4018 /**
4019  * kmsg_dump_unregister - unregister a kmsg dumper.
4020  * @dumper: pointer to the kmsg_dumper structure
4021  *
4022  * Removes a dump device from the system. Returns zero on success and
4023  * %-EINVAL otherwise.
4024  */
4025 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
4026 {
4027 	unsigned long flags;
4028 	int err = -EINVAL;
4029 
4030 	spin_lock_irqsave(&dump_list_lock, flags);
4031 	if (dumper->registered) {
4032 		dumper->registered = 0;
4033 		list_del_rcu(&dumper->list);
4034 		err = 0;
4035 	}
4036 	spin_unlock_irqrestore(&dump_list_lock, flags);
4037 	synchronize_rcu();
4038 
4039 	return err;
4040 }
4041 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
4042 
4043 static bool always_kmsg_dump;
4044 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
4045 
4046 const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
4047 {
4048 	switch (reason) {
4049 	case KMSG_DUMP_PANIC:
4050 		return "Panic";
4051 	case KMSG_DUMP_OOPS:
4052 		return "Oops";
4053 	case KMSG_DUMP_EMERG:
4054 		return "Emergency";
4055 	case KMSG_DUMP_SHUTDOWN:
4056 		return "Shutdown";
4057 	default:
4058 		return "Unknown";
4059 	}
4060 }
4061 EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
4062 
4063 /**
4064  * kmsg_dump - dump kernel log to kernel message dumpers.
4065  * @reason: the reason (oops, panic etc) for dumping
4066  *
4067  * Call each of the registered dumper's dump() callback, which can
4068  * retrieve the kmsg records with kmsg_dump_get_line() or
4069  * kmsg_dump_get_buffer().
4070  */
4071 void kmsg_dump(enum kmsg_dump_reason reason)
4072 {
4073 	struct kmsg_dumper *dumper;
4074 
4075 	rcu_read_lock();
4076 	list_for_each_entry_rcu(dumper, &dump_list, list) {
4077 		enum kmsg_dump_reason max_reason = dumper->max_reason;
4078 
4079 		/*
4080 		 * If client has not provided a specific max_reason, default
4081 		 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
4082 		 */
4083 		if (max_reason == KMSG_DUMP_UNDEF) {
4084 			max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
4085 							KMSG_DUMP_OOPS;
4086 		}
4087 		if (reason > max_reason)
4088 			continue;
4089 
4090 		/* invoke dumper which will iterate over records */
4091 		dumper->dump(dumper, reason);
4092 	}
4093 	rcu_read_unlock();
4094 }
4095 
4096 /**
4097  * kmsg_dump_get_line - retrieve one kmsg log line
4098  * @iter: kmsg dump iterator
4099  * @syslog: include the "<4>" prefixes
4100  * @line: buffer to copy the line to
4101  * @size: maximum size of the buffer
4102  * @len: length of line placed into buffer
4103  *
4104  * Start at the beginning of the kmsg buffer, with the oldest kmsg
4105  * record, and copy one record into the provided buffer.
4106  *
4107  * Consecutive calls will return the next available record moving
4108  * towards the end of the buffer with the youngest messages.
4109  *
4110  * A return value of FALSE indicates that there are no more records to
4111  * read.
4112  */
4113 bool kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog,
4114 			char *line, size_t size, size_t *len)
4115 {
4116 	u64 min_seq = latched_seq_read_nolock(&clear_seq);
4117 	struct printk_info info;
4118 	unsigned int line_count;
4119 	struct printk_record r;
4120 	size_t l = 0;
4121 	bool ret = false;
4122 
4123 	if (iter->cur_seq < min_seq)
4124 		iter->cur_seq = min_seq;
4125 
4126 	prb_rec_init_rd(&r, &info, line, size);
4127 
4128 	/* Read text or count text lines? */
4129 	if (line) {
4130 		if (!prb_read_valid(prb, iter->cur_seq, &r))
4131 			goto out;
4132 		l = record_print_text(&r, syslog, printk_time);
4133 	} else {
4134 		if (!prb_read_valid_info(prb, iter->cur_seq,
4135 					 &info, &line_count)) {
4136 			goto out;
4137 		}
4138 		l = get_record_print_text_size(&info, line_count, syslog,
4139 					       printk_time);
4140 
4141 	}
4142 
4143 	iter->cur_seq = r.info->seq + 1;
4144 	ret = true;
4145 out:
4146 	if (len)
4147 		*len = l;
4148 	return ret;
4149 }
4150 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
4151 
4152 /**
4153  * kmsg_dump_get_buffer - copy kmsg log lines
4154  * @iter: kmsg dump iterator
4155  * @syslog: include the "<4>" prefixes
4156  * @buf: buffer to copy the line to
4157  * @size: maximum size of the buffer
4158  * @len_out: length of line placed into buffer
4159  *
4160  * Start at the end of the kmsg buffer and fill the provided buffer
4161  * with as many of the *youngest* kmsg records that fit into it.
4162  * If the buffer is large enough, all available kmsg records will be
4163  * copied with a single call.
4164  *
4165  * Consecutive calls will fill the buffer with the next block of
4166  * available older records, not including the earlier retrieved ones.
4167  *
4168  * A return value of FALSE indicates that there are no more records to
4169  * read.
4170  */
4171 bool kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog,
4172 			  char *buf, size_t size, size_t *len_out)
4173 {
4174 	u64 min_seq = latched_seq_read_nolock(&clear_seq);
4175 	struct printk_info info;
4176 	struct printk_record r;
4177 	u64 seq;
4178 	u64 next_seq;
4179 	size_t len = 0;
4180 	bool ret = false;
4181 	bool time = printk_time;
4182 
4183 	if (!buf || !size)
4184 		goto out;
4185 
4186 	if (iter->cur_seq < min_seq)
4187 		iter->cur_seq = min_seq;
4188 
4189 	if (prb_read_valid_info(prb, iter->cur_seq, &info, NULL)) {
4190 		if (info.seq != iter->cur_seq) {
4191 			/* messages are gone, move to first available one */
4192 			iter->cur_seq = info.seq;
4193 		}
4194 	}
4195 
4196 	/* last entry */
4197 	if (iter->cur_seq >= iter->next_seq)
4198 		goto out;
4199 
4200 	/*
4201 	 * Find first record that fits, including all following records,
4202 	 * into the user-provided buffer for this dump. Pass in size-1
4203 	 * because this function (by way of record_print_text()) will
4204 	 * not write more than size-1 bytes of text into @buf.
4205 	 */
4206 	seq = find_first_fitting_seq(iter->cur_seq, iter->next_seq,
4207 				     size - 1, syslog, time);
4208 
4209 	/*
4210 	 * Next kmsg_dump_get_buffer() invocation will dump block of
4211 	 * older records stored right before this one.
4212 	 */
4213 	next_seq = seq;
4214 
4215 	prb_rec_init_rd(&r, &info, buf, size);
4216 
4217 	prb_for_each_record(seq, prb, seq, &r) {
4218 		if (r.info->seq >= iter->next_seq)
4219 			break;
4220 
4221 		len += record_print_text(&r, syslog, time);
4222 
4223 		/* Adjust record to store to remaining buffer space. */
4224 		prb_rec_init_rd(&r, &info, buf + len, size - len);
4225 	}
4226 
4227 	iter->next_seq = next_seq;
4228 	ret = true;
4229 out:
4230 	if (len_out)
4231 		*len_out = len;
4232 	return ret;
4233 }
4234 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
4235 
4236 /**
4237  * kmsg_dump_rewind - reset the iterator
4238  * @iter: kmsg dump iterator
4239  *
4240  * Reset the dumper's iterator so that kmsg_dump_get_line() and
4241  * kmsg_dump_get_buffer() can be called again and used multiple
4242  * times within the same dumper.dump() callback.
4243  */
4244 void kmsg_dump_rewind(struct kmsg_dump_iter *iter)
4245 {
4246 	iter->cur_seq = latched_seq_read_nolock(&clear_seq);
4247 	iter->next_seq = prb_next_seq(prb);
4248 }
4249 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
4250 
4251 #endif
4252 
4253 #ifdef CONFIG_SMP
4254 static atomic_t printk_cpu_sync_owner = ATOMIC_INIT(-1);
4255 static atomic_t printk_cpu_sync_nested = ATOMIC_INIT(0);
4256 
4257 /**
4258  * __printk_cpu_sync_wait() - Busy wait until the printk cpu-reentrant
4259  *                            spinning lock is not owned by any CPU.
4260  *
4261  * Context: Any context.
4262  */
4263 void __printk_cpu_sync_wait(void)
4264 {
4265 	do {
4266 		cpu_relax();
4267 	} while (atomic_read(&printk_cpu_sync_owner) != -1);
4268 }
4269 EXPORT_SYMBOL(__printk_cpu_sync_wait);
4270 
4271 /**
4272  * __printk_cpu_sync_try_get() - Try to acquire the printk cpu-reentrant
4273  *                               spinning lock.
4274  *
4275  * If no processor has the lock, the calling processor takes the lock and
4276  * becomes the owner. If the calling processor is already the owner of the
4277  * lock, this function succeeds immediately.
4278  *
4279  * Context: Any context. Expects interrupts to be disabled.
4280  * Return: 1 on success, otherwise 0.
4281  */
4282 int __printk_cpu_sync_try_get(void)
4283 {
4284 	int cpu;
4285 	int old;
4286 
4287 	cpu = smp_processor_id();
4288 
4289 	/*
4290 	 * Guarantee loads and stores from this CPU when it is the lock owner
4291 	 * are _not_ visible to the previous lock owner. This pairs with
4292 	 * __printk_cpu_sync_put:B.
4293 	 *
4294 	 * Memory barrier involvement:
4295 	 *
4296 	 * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4297 	 * then __printk_cpu_sync_put:A can never read from
4298 	 * __printk_cpu_sync_try_get:B.
4299 	 *
4300 	 * Relies on:
4301 	 *
4302 	 * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
4303 	 * of the previous CPU
4304 	 *    matching
4305 	 * ACQUIRE from __printk_cpu_sync_try_get:A to
4306 	 * __printk_cpu_sync_try_get:B of this CPU
4307 	 */
4308 	old = atomic_cmpxchg_acquire(&printk_cpu_sync_owner, -1,
4309 				     cpu); /* LMM(__printk_cpu_sync_try_get:A) */
4310 	if (old == -1) {
4311 		/*
4312 		 * This CPU is now the owner and begins loading/storing
4313 		 * data: LMM(__printk_cpu_sync_try_get:B)
4314 		 */
4315 		return 1;
4316 
4317 	} else if (old == cpu) {
4318 		/* This CPU is already the owner. */
4319 		atomic_inc(&printk_cpu_sync_nested);
4320 		return 1;
4321 	}
4322 
4323 	return 0;
4324 }
4325 EXPORT_SYMBOL(__printk_cpu_sync_try_get);
4326 
4327 /**
4328  * __printk_cpu_sync_put() - Release the printk cpu-reentrant spinning lock.
4329  *
4330  * The calling processor must be the owner of the lock.
4331  *
4332  * Context: Any context. Expects interrupts to be disabled.
4333  */
4334 void __printk_cpu_sync_put(void)
4335 {
4336 	if (atomic_read(&printk_cpu_sync_nested)) {
4337 		atomic_dec(&printk_cpu_sync_nested);
4338 		return;
4339 	}
4340 
4341 	/*
4342 	 * This CPU is finished loading/storing data:
4343 	 * LMM(__printk_cpu_sync_put:A)
4344 	 */
4345 
4346 	/*
4347 	 * Guarantee loads and stores from this CPU when it was the
4348 	 * lock owner are visible to the next lock owner. This pairs
4349 	 * with __printk_cpu_sync_try_get:A.
4350 	 *
4351 	 * Memory barrier involvement:
4352 	 *
4353 	 * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4354 	 * then __printk_cpu_sync_try_get:B reads from __printk_cpu_sync_put:A.
4355 	 *
4356 	 * Relies on:
4357 	 *
4358 	 * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
4359 	 * of this CPU
4360 	 *    matching
4361 	 * ACQUIRE from __printk_cpu_sync_try_get:A to
4362 	 * __printk_cpu_sync_try_get:B of the next CPU
4363 	 */
4364 	atomic_set_release(&printk_cpu_sync_owner,
4365 			   -1); /* LMM(__printk_cpu_sync_put:B) */
4366 }
4367 EXPORT_SYMBOL(__printk_cpu_sync_put);
4368 #endif /* CONFIG_SMP */
4369