• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #undef CREATE_TRACE_POINTS
58 #include <trace/hooks/printk.h>
59 #include <trace/hooks/logbuf.h>
60 
61 #include "printk_ringbuffer.h"
62 #include "console_cmdline.h"
63 #include "braille.h"
64 #include "internal.h"
65 
66 int console_printk[4] = {
67 	CONSOLE_LOGLEVEL_DEFAULT,	/* console_loglevel */
68 	MESSAGE_LOGLEVEL_DEFAULT,	/* default_message_loglevel */
69 	CONSOLE_LOGLEVEL_MIN,		/* minimum_console_loglevel */
70 	CONSOLE_LOGLEVEL_DEFAULT,	/* default_console_loglevel */
71 };
72 EXPORT_SYMBOL_GPL(console_printk);
73 
74 atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
75 EXPORT_SYMBOL(ignore_console_lock_warning);
76 
77 /*
78  * Low level drivers may need that to know if they can schedule in
79  * their unblank() callback or not. So let's export it.
80  */
81 int oops_in_progress;
82 EXPORT_SYMBOL(oops_in_progress);
83 
84 /*
85  * console_sem protects the console_drivers list, and also
86  * provides serialisation for access to the entire console
87  * driver system.
88  */
89 static DEFINE_SEMAPHORE(console_sem);
90 struct console *console_drivers;
91 EXPORT_SYMBOL_GPL(console_drivers);
92 
93 /*
94  * System may need to suppress printk message under certain
95  * circumstances, like after kernel panic happens.
96  */
97 int __read_mostly suppress_printk;
98 
99 #ifdef CONFIG_LOCKDEP
100 static struct lockdep_map console_lock_dep_map = {
101 	.name = "console_lock"
102 };
103 #endif
104 
105 enum devkmsg_log_bits {
106 	__DEVKMSG_LOG_BIT_ON = 0,
107 	__DEVKMSG_LOG_BIT_OFF,
108 	__DEVKMSG_LOG_BIT_LOCK,
109 };
110 
111 enum devkmsg_log_masks {
112 	DEVKMSG_LOG_MASK_ON             = BIT(__DEVKMSG_LOG_BIT_ON),
113 	DEVKMSG_LOG_MASK_OFF            = BIT(__DEVKMSG_LOG_BIT_OFF),
114 	DEVKMSG_LOG_MASK_LOCK           = BIT(__DEVKMSG_LOG_BIT_LOCK),
115 };
116 
117 /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
118 #define DEVKMSG_LOG_MASK_DEFAULT	0
119 
120 static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
121 
__control_devkmsg(char * str)122 static int __control_devkmsg(char *str)
123 {
124 	size_t len;
125 
126 	if (!str)
127 		return -EINVAL;
128 
129 	len = str_has_prefix(str, "on");
130 	if (len) {
131 		devkmsg_log = DEVKMSG_LOG_MASK_ON;
132 		return len;
133 	}
134 
135 	len = str_has_prefix(str, "off");
136 	if (len) {
137 		devkmsg_log = DEVKMSG_LOG_MASK_OFF;
138 		return len;
139 	}
140 
141 	len = str_has_prefix(str, "ratelimit");
142 	if (len) {
143 		devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
144 		return len;
145 	}
146 
147 	return -EINVAL;
148 }
149 
control_devkmsg(char * str)150 static int __init control_devkmsg(char *str)
151 {
152 	if (__control_devkmsg(str) < 0) {
153 		pr_warn("printk.devkmsg: bad option string '%s'\n", str);
154 		return 1;
155 	}
156 
157 	/*
158 	 * Set sysctl string accordingly:
159 	 */
160 	if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
161 		strcpy(devkmsg_log_str, "on");
162 	else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
163 		strcpy(devkmsg_log_str, "off");
164 	/* else "ratelimit" which is set by default. */
165 
166 	/*
167 	 * Sysctl cannot change it anymore. The kernel command line setting of
168 	 * this parameter is to force the setting to be permanent throughout the
169 	 * runtime of the system. This is a precation measure against userspace
170 	 * trying to be a smarta** and attempting to change it up on us.
171 	 */
172 	devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
173 
174 	return 1;
175 }
176 __setup("printk.devkmsg=", control_devkmsg);
177 
178 char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
179 
devkmsg_sysctl_set_loglvl(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)180 int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
181 			      void *buffer, size_t *lenp, loff_t *ppos)
182 {
183 	char old_str[DEVKMSG_STR_MAX_SIZE];
184 	unsigned int old;
185 	int err;
186 
187 	if (write) {
188 		if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
189 			return -EINVAL;
190 
191 		old = devkmsg_log;
192 		strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
193 	}
194 
195 	err = proc_dostring(table, write, buffer, lenp, ppos);
196 	if (err)
197 		return err;
198 
199 	if (write) {
200 		err = __control_devkmsg(devkmsg_log_str);
201 
202 		/*
203 		 * Do not accept an unknown string OR a known string with
204 		 * trailing crap...
205 		 */
206 		if (err < 0 || (err + 1 != *lenp)) {
207 
208 			/* ... and restore old setting. */
209 			devkmsg_log = old;
210 			strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
211 
212 			return -EINVAL;
213 		}
214 	}
215 
216 	return 0;
217 }
218 
219 /* Number of registered extended console drivers. */
220 static int nr_ext_console_drivers;
221 
222 /*
223  * Helper macros to handle lockdep when locking/unlocking console_sem. We use
224  * macros instead of functions so that _RET_IP_ contains useful information.
225  */
226 #define down_console_sem() do { \
227 	down(&console_sem);\
228 	mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
229 } while (0)
230 
__down_trylock_console_sem(unsigned long ip)231 static int __down_trylock_console_sem(unsigned long ip)
232 {
233 	int lock_failed;
234 	unsigned long flags;
235 
236 	/*
237 	 * Here and in __up_console_sem() we need to be in safe mode,
238 	 * because spindump/WARN/etc from under console ->lock will
239 	 * deadlock in printk()->down_trylock_console_sem() otherwise.
240 	 */
241 	printk_safe_enter_irqsave(flags);
242 	lock_failed = down_trylock(&console_sem);
243 	printk_safe_exit_irqrestore(flags);
244 
245 	if (lock_failed)
246 		return 1;
247 	mutex_acquire(&console_lock_dep_map, 0, 1, ip);
248 	return 0;
249 }
250 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
251 
__up_console_sem(unsigned long ip)252 static void __up_console_sem(unsigned long ip)
253 {
254 	unsigned long flags;
255 
256 	mutex_release(&console_lock_dep_map, ip);
257 
258 	printk_safe_enter_irqsave(flags);
259 	up(&console_sem);
260 	printk_safe_exit_irqrestore(flags);
261 }
262 #define up_console_sem() __up_console_sem(_RET_IP_)
263 
264 /*
265  * This is used for debugging the mess that is the VT code by
266  * keeping track if we have the console semaphore held. It's
267  * definitely not the perfect debug tool (we don't know if _WE_
268  * hold it and are racing, but it helps tracking those weird code
269  * paths in the console code where we end up in places I want
270  * locked without the console sempahore held).
271  */
272 static int console_locked, console_suspended;
273 
274 /*
275  * If exclusive_console is non-NULL then only this console is to be printed to.
276  */
277 static struct console *exclusive_console;
278 
279 /*
280  *	Array of consoles built from command line options (console=)
281  */
282 
283 #define MAX_CMDLINECONSOLES 8
284 
285 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
286 
287 static int preferred_console = -1;
288 static bool has_preferred_console;
289 int console_set_on_cmdline;
290 EXPORT_SYMBOL(console_set_on_cmdline);
291 
292 /* Flag: console code may call schedule() */
293 static int console_may_schedule;
294 
295 enum con_msg_format_flags {
296 	MSG_FORMAT_DEFAULT	= 0,
297 	MSG_FORMAT_SYSLOG	= (1 << 0),
298 };
299 
300 static int console_msg_format = MSG_FORMAT_DEFAULT;
301 
302 /*
303  * The printk log buffer consists of a sequenced collection of records, each
304  * containing variable length message text. Every record also contains its
305  * own meta-data (@info).
306  *
307  * Every record meta-data carries the timestamp in microseconds, as well as
308  * the standard userspace syslog level and syslog facility. The usual kernel
309  * messages use LOG_KERN; userspace-injected messages always carry a matching
310  * syslog facility, by default LOG_USER. The origin of every message can be
311  * reliably determined that way.
312  *
313  * The human readable log message of a record is available in @text, the
314  * length of the message text in @text_len. The stored message is not
315  * terminated.
316  *
317  * Optionally, a record can carry a dictionary of properties (key/value
318  * pairs), to provide userspace with a machine-readable message context.
319  *
320  * Examples for well-defined, commonly used property names are:
321  *   DEVICE=b12:8               device identifier
322  *                                b12:8         block dev_t
323  *                                c127:3        char dev_t
324  *                                n8            netdev ifindex
325  *                                +sound:card0  subsystem:devname
326  *   SUBSYSTEM=pci              driver-core subsystem name
327  *
328  * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
329  * and values are terminated by a '\0' character.
330  *
331  * Example of record values:
332  *   record.text_buf                = "it's a line" (unterminated)
333  *   record.info.seq                = 56
334  *   record.info.ts_nsec            = 36863
335  *   record.info.text_len           = 11
336  *   record.info.facility           = 0 (LOG_KERN)
337  *   record.info.flags              = 0
338  *   record.info.level              = 3 (LOG_ERR)
339  *   record.info.caller_id          = 299 (task 299)
340  *   record.info.dev_info.subsystem = "pci" (terminated)
341  *   record.info.dev_info.device    = "+pci:0000:00:01.0" (terminated)
342  *
343  * The 'struct printk_info' buffer must never be directly exported to
344  * userspace, it is a kernel-private implementation detail that might
345  * need to be changed in the future, when the requirements change.
346  *
347  * /dev/kmsg exports the structured data in the following line format:
348  *   "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
349  *
350  * Users of the export format should ignore possible additional values
351  * separated by ',', and find the message after the ';' character.
352  *
353  * The optional key/value pairs are attached as continuation lines starting
354  * with a space character and terminated by a newline. All possible
355  * non-prinatable characters are escaped in the "\xff" notation.
356  */
357 
358 enum log_flags {
359 	LOG_NEWLINE	= 2,	/* text ended with a newline */
360 	LOG_CONT	= 8,	/* text is a fragment of a continuation line */
361 };
362 
363 /*
364  * The logbuf_lock protects kmsg buffer, indices, counters.  This can be taken
365  * within the scheduler's rq lock. It must be released before calling
366  * console_unlock() or anything else that might wake up a process.
367  */
368 DEFINE_RAW_SPINLOCK(logbuf_lock);
369 
370 /*
371  * Helper macros to lock/unlock logbuf_lock and switch between
372  * printk-safe/unsafe modes.
373  */
374 #define logbuf_lock_irq()				\
375 	do {						\
376 		printk_safe_enter_irq();		\
377 		raw_spin_lock(&logbuf_lock);		\
378 	} while (0)
379 
380 #define logbuf_unlock_irq()				\
381 	do {						\
382 		raw_spin_unlock(&logbuf_lock);		\
383 		printk_safe_exit_irq();			\
384 	} while (0)
385 
386 #define logbuf_lock_irqsave(flags)			\
387 	do {						\
388 		printk_safe_enter_irqsave(flags);	\
389 		raw_spin_lock(&logbuf_lock);		\
390 	} while (0)
391 
392 #define logbuf_unlock_irqrestore(flags)		\
393 	do {						\
394 		raw_spin_unlock(&logbuf_lock);		\
395 		printk_safe_exit_irqrestore(flags);	\
396 	} while (0)
397 
398 #ifdef CONFIG_PRINTK
399 DECLARE_WAIT_QUEUE_HEAD(log_wait);
400 /* the next printk record to read by syslog(READ) or /proc/kmsg */
401 static u64 syslog_seq;
402 static size_t syslog_partial;
403 static bool syslog_time;
404 
405 /* the next printk record to write to the console */
406 static u64 console_seq;
407 static u64 exclusive_console_stop_seq;
408 static unsigned long console_dropped;
409 
410 /* the next printk record to read after the last 'clear' command */
411 static u64 clear_seq;
412 
413 #ifdef CONFIG_PRINTK_CALLER
414 #define PREFIX_MAX		48
415 #else
416 #define PREFIX_MAX		32
417 #endif
418 #define LOG_LINE_MAX		(1024 - PREFIX_MAX)
419 
420 #define LOG_LEVEL(v)		((v) & 0x07)
421 #define LOG_FACILITY(v)		((v) >> 3 & 0xff)
422 
423 /* record buffer */
424 #define LOG_ALIGN __alignof__(unsigned long)
425 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
426 #define LOG_BUF_LEN_MAX (u32)(1 << 31)
427 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
428 static char *log_buf = __log_buf;
429 static u32 log_buf_len = __LOG_BUF_LEN;
430 
431 /*
432  * Define the average message size. This only affects the number of
433  * descriptors that will be available. Underestimating is better than
434  * overestimating (too many available descriptors is better than not enough).
435  */
436 #define PRB_AVGBITS 5	/* 32 character average length */
437 
438 #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
439 #error CONFIG_LOG_BUF_SHIFT value too small.
440 #endif
441 _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
442 		 PRB_AVGBITS, &__log_buf[0]);
443 
444 static struct printk_ringbuffer printk_rb_dynamic;
445 
446 static struct printk_ringbuffer *prb = &printk_rb_static;
447 
448 /*
449  * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
450  * per_cpu_areas are initialised. This variable is set to true when
451  * it's safe to access per-CPU data.
452  */
453 static bool __printk_percpu_data_ready __read_mostly;
454 
printk_percpu_data_ready(void)455 bool printk_percpu_data_ready(void)
456 {
457 	return __printk_percpu_data_ready;
458 }
459 
460 /* Return log buffer address */
log_buf_addr_get(void)461 char *log_buf_addr_get(void)
462 {
463 	return log_buf;
464 }
465 EXPORT_SYMBOL_GPL(log_buf_addr_get);
466 
467 /* Return log buffer size */
log_buf_len_get(void)468 u32 log_buf_len_get(void)
469 {
470 	return log_buf_len;
471 }
472 EXPORT_SYMBOL_GPL(log_buf_len_get);
473 
474 /*
475  * Define how much of the log buffer we could take at maximum. The value
476  * must be greater than two. Note that only half of the buffer is available
477  * when the index points to the middle.
478  */
479 #define MAX_LOG_TAKE_PART 4
480 static const char trunc_msg[] = "<truncated>";
481 
truncate_msg(u16 * text_len,u16 * trunc_msg_len)482 static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
483 {
484 	/*
485 	 * The message should not take the whole buffer. Otherwise, it might
486 	 * get removed too soon.
487 	 */
488 	u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
489 
490 	if (*text_len > max_text_len)
491 		*text_len = max_text_len;
492 
493 	/* enable the warning message (if there is room) */
494 	*trunc_msg_len = strlen(trunc_msg);
495 	if (*text_len >= *trunc_msg_len)
496 		*text_len -= *trunc_msg_len;
497 	else
498 		*trunc_msg_len = 0;
499 }
500 
501 /* insert record into the buffer, discard old ones, update heads */
log_store(u32 caller_id,int facility,int level,enum log_flags flags,u64 ts_nsec,const struct dev_printk_info * dev_info,const char * text,u16 text_len)502 static int log_store(u32 caller_id, int facility, int level,
503 		     enum log_flags flags, u64 ts_nsec,
504 		     const struct dev_printk_info *dev_info,
505 		     const char *text, u16 text_len)
506 {
507 	struct prb_reserved_entry e;
508 	struct printk_record r;
509 	u16 trunc_msg_len = 0;
510 
511 	prb_rec_init_wr(&r, text_len);
512 
513 	if (!prb_reserve(&e, prb, &r)) {
514 		/* truncate the message if it is too long for empty buffer */
515 		truncate_msg(&text_len, &trunc_msg_len);
516 		prb_rec_init_wr(&r, text_len + trunc_msg_len);
517 		/* survive when the log buffer is too small for trunc_msg */
518 		if (!prb_reserve(&e, prb, &r))
519 			return 0;
520 	}
521 
522 	/* fill message */
523 	memcpy(&r.text_buf[0], text, text_len);
524 	if (trunc_msg_len)
525 		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
526 	r.info->text_len = text_len + trunc_msg_len;
527 	r.info->facility = facility;
528 	r.info->level = level & 7;
529 	r.info->flags = flags & 0x1f;
530 	if (ts_nsec > 0)
531 		r.info->ts_nsec = ts_nsec;
532 	else
533 		r.info->ts_nsec = local_clock();
534 	r.info->caller_id = caller_id;
535 	if (dev_info)
536 		memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
537 
538 	/* A message without a trailing newline can be continued. */
539 	if (!(flags & LOG_NEWLINE))
540 		prb_commit(&e);
541 	else
542 		prb_final_commit(&e);
543 
544 	trace_android_vh_logbuf(prb, &r);
545 
546 	return (text_len + trunc_msg_len);
547 }
548 
549 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
550 
syslog_action_restricted(int type)551 static int syslog_action_restricted(int type)
552 {
553 	if (dmesg_restrict)
554 		return 1;
555 	/*
556 	 * Unless restricted, we allow "read all" and "get buffer size"
557 	 * for everybody.
558 	 */
559 	return type != SYSLOG_ACTION_READ_ALL &&
560 	       type != SYSLOG_ACTION_SIZE_BUFFER;
561 }
562 
check_syslog_permissions(int type,int source)563 static int check_syslog_permissions(int type, int source)
564 {
565 	/*
566 	 * If this is from /proc/kmsg and we've already opened it, then we've
567 	 * already done the capabilities checks at open time.
568 	 */
569 	if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
570 		goto ok;
571 
572 	if (syslog_action_restricted(type)) {
573 		if (capable(CAP_SYSLOG))
574 			goto ok;
575 		/*
576 		 * For historical reasons, accept CAP_SYS_ADMIN too, with
577 		 * a warning.
578 		 */
579 		if (capable(CAP_SYS_ADMIN)) {
580 			pr_warn_once("%s (%d): Attempt to access syslog with "
581 				     "CAP_SYS_ADMIN but no CAP_SYSLOG "
582 				     "(deprecated).\n",
583 				 current->comm, task_pid_nr(current));
584 			goto ok;
585 		}
586 		return -EPERM;
587 	}
588 ok:
589 	return security_syslog(type);
590 }
591 
append_char(char ** pp,char * e,char c)592 static void append_char(char **pp, char *e, char c)
593 {
594 	if (*pp < e)
595 		*(*pp)++ = c;
596 }
597 
info_print_ext_header(char * buf,size_t size,struct printk_info * info)598 static ssize_t info_print_ext_header(char *buf, size_t size,
599 				     struct printk_info *info)
600 {
601 	u64 ts_usec = info->ts_nsec;
602 	char caller[20];
603 #ifdef CONFIG_PRINTK_CALLER
604 	u32 id = info->caller_id;
605 
606 	snprintf(caller, sizeof(caller), ",caller=%c%u",
607 		 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
608 #else
609 	caller[0] = '\0';
610 #endif
611 
612 	do_div(ts_usec, 1000);
613 
614 	return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
615 			 (info->facility << 3) | info->level, info->seq,
616 			 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
617 }
618 
msg_add_ext_text(char * buf,size_t size,const char * text,size_t text_len,unsigned char endc)619 static ssize_t msg_add_ext_text(char *buf, size_t size,
620 				const char *text, size_t text_len,
621 				unsigned char endc)
622 {
623 	char *p = buf, *e = buf + size;
624 	size_t i;
625 
626 	/* escape non-printable characters */
627 	for (i = 0; i < text_len; i++) {
628 		unsigned char c = text[i];
629 
630 		if (c < ' ' || c >= 127 || c == '\\')
631 			p += scnprintf(p, e - p, "\\x%02x", c);
632 		else
633 			append_char(&p, e, c);
634 	}
635 	append_char(&p, e, endc);
636 
637 	return p - buf;
638 }
639 
msg_add_dict_text(char * buf,size_t size,const char * key,const char * val)640 static ssize_t msg_add_dict_text(char *buf, size_t size,
641 				 const char *key, const char *val)
642 {
643 	size_t val_len = strlen(val);
644 	ssize_t len;
645 
646 	if (!val_len)
647 		return 0;
648 
649 	len = msg_add_ext_text(buf, size, "", 0, ' ');	/* dict prefix */
650 	len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
651 	len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
652 
653 	return len;
654 }
655 
msg_print_ext_body(char * buf,size_t size,char * text,size_t text_len,struct dev_printk_info * dev_info)656 static ssize_t msg_print_ext_body(char *buf, size_t size,
657 				  char *text, size_t text_len,
658 				  struct dev_printk_info *dev_info)
659 {
660 	ssize_t len;
661 
662 	len = msg_add_ext_text(buf, size, text, text_len, '\n');
663 
664 	if (!dev_info)
665 		goto out;
666 
667 	len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
668 				 dev_info->subsystem);
669 	len += msg_add_dict_text(buf + len, size - len, "DEVICE",
670 				 dev_info->device);
671 out:
672 	return len;
673 }
674 
675 /* /dev/kmsg - userspace message inject/listen interface */
676 struct devkmsg_user {
677 	u64 seq;
678 	struct ratelimit_state rs;
679 	struct mutex lock;
680 	char buf[CONSOLE_EXT_LOG_MAX];
681 
682 	struct printk_info info;
683 	char text_buf[CONSOLE_EXT_LOG_MAX];
684 	struct printk_record record;
685 };
686 
687 static __printf(3, 4) __cold
devkmsg_emit(int facility,int level,const char * fmt,...)688 int devkmsg_emit(int facility, int level, const char *fmt, ...)
689 {
690 	va_list args;
691 	int r;
692 
693 	va_start(args, fmt);
694 	r = vprintk_emit(facility, level, NULL, fmt, args);
695 	va_end(args);
696 
697 	return r;
698 }
699 
devkmsg_write(struct kiocb * iocb,struct iov_iter * from)700 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
701 {
702 	char *buf, *line;
703 	int level = default_message_loglevel;
704 	int facility = 1;	/* LOG_USER */
705 	struct file *file = iocb->ki_filp;
706 	struct devkmsg_user *user = file->private_data;
707 	size_t len = iov_iter_count(from);
708 	ssize_t ret = len;
709 
710 	if (!user || len > LOG_LINE_MAX)
711 		return -EINVAL;
712 
713 	/* Ignore when user logging is disabled. */
714 	if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
715 		return len;
716 
717 	/* Ratelimit when not explicitly enabled. */
718 	if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
719 		if (!___ratelimit(&user->rs, current->comm))
720 			return ret;
721 	}
722 
723 	buf = kmalloc(len+1, GFP_KERNEL);
724 	if (buf == NULL)
725 		return -ENOMEM;
726 
727 	buf[len] = '\0';
728 	if (!copy_from_iter_full(buf, len, from)) {
729 		kfree(buf);
730 		return -EFAULT;
731 	}
732 
733 	/*
734 	 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
735 	 * the decimal value represents 32bit, the lower 3 bit are the log
736 	 * level, the rest are the log facility.
737 	 *
738 	 * If no prefix or no userspace facility is specified, we
739 	 * enforce LOG_USER, to be able to reliably distinguish
740 	 * kernel-generated messages from userspace-injected ones.
741 	 */
742 	line = buf;
743 	if (line[0] == '<') {
744 		char *endp = NULL;
745 		unsigned int u;
746 
747 		u = simple_strtoul(line + 1, &endp, 10);
748 		if (endp && endp[0] == '>') {
749 			level = LOG_LEVEL(u);
750 			if (LOG_FACILITY(u) != 0)
751 				facility = LOG_FACILITY(u);
752 			endp++;
753 			len -= endp - line;
754 			line = endp;
755 		}
756 	}
757 
758 	devkmsg_emit(facility, level, "%s", line);
759 	kfree(buf);
760 	return ret;
761 }
762 
devkmsg_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)763 static ssize_t devkmsg_read(struct file *file, char __user *buf,
764 			    size_t count, loff_t *ppos)
765 {
766 	struct devkmsg_user *user = file->private_data;
767 	struct printk_record *r = &user->record;
768 	size_t len;
769 	ssize_t ret;
770 
771 	if (!user)
772 		return -EBADF;
773 
774 	ret = mutex_lock_interruptible(&user->lock);
775 	if (ret)
776 		return ret;
777 
778 	logbuf_lock_irq();
779 	if (!prb_read_valid(prb, user->seq, r)) {
780 		if (file->f_flags & O_NONBLOCK) {
781 			ret = -EAGAIN;
782 			logbuf_unlock_irq();
783 			goto out;
784 		}
785 
786 		logbuf_unlock_irq();
787 		ret = wait_event_interruptible(log_wait,
788 					prb_read_valid(prb, user->seq, r));
789 		if (ret)
790 			goto out;
791 		logbuf_lock_irq();
792 	}
793 
794 	if (r->info->seq != user->seq) {
795 		/* our last seen message is gone, return error and reset */
796 		user->seq = r->info->seq;
797 		ret = -EPIPE;
798 		logbuf_unlock_irq();
799 		goto out;
800 	}
801 
802 	len = info_print_ext_header(user->buf, sizeof(user->buf), r->info);
803 	len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
804 				  &r->text_buf[0], r->info->text_len,
805 				  &r->info->dev_info);
806 
807 	user->seq = r->info->seq + 1;
808 	logbuf_unlock_irq();
809 
810 	if (len > count) {
811 		ret = -EINVAL;
812 		goto out;
813 	}
814 
815 	if (copy_to_user(buf, user->buf, len)) {
816 		ret = -EFAULT;
817 		goto out;
818 	}
819 	ret = len;
820 out:
821 	mutex_unlock(&user->lock);
822 	return ret;
823 }
824 
825 /*
826  * Be careful when modifying this function!!!
827  *
828  * Only few operations are supported because the device works only with the
829  * entire variable length messages (records). Non-standard values are
830  * returned in the other cases and has been this way for quite some time.
831  * User space applications might depend on this behavior.
832  */
devkmsg_llseek(struct file * file,loff_t offset,int whence)833 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
834 {
835 	struct devkmsg_user *user = file->private_data;
836 	loff_t ret = 0;
837 
838 	if (!user)
839 		return -EBADF;
840 	if (offset)
841 		return -ESPIPE;
842 
843 	logbuf_lock_irq();
844 	switch (whence) {
845 	case SEEK_SET:
846 		/* the first record */
847 		user->seq = prb_first_valid_seq(prb);
848 		break;
849 	case SEEK_DATA:
850 		/*
851 		 * The first record after the last SYSLOG_ACTION_CLEAR,
852 		 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
853 		 * changes no global state, and does not clear anything.
854 		 */
855 		user->seq = clear_seq;
856 		break;
857 	case SEEK_END:
858 		/* after the last record */
859 		user->seq = prb_next_seq(prb);
860 		break;
861 	default:
862 		ret = -EINVAL;
863 	}
864 	logbuf_unlock_irq();
865 	return ret;
866 }
867 
devkmsg_poll(struct file * file,poll_table * wait)868 static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
869 {
870 	struct devkmsg_user *user = file->private_data;
871 	struct printk_info info;
872 	__poll_t ret = 0;
873 
874 	if (!user)
875 		return EPOLLERR|EPOLLNVAL;
876 
877 	poll_wait(file, &log_wait, wait);
878 
879 	logbuf_lock_irq();
880 	if (prb_read_valid_info(prb, user->seq, &info, NULL)) {
881 		/* return error when data has vanished underneath us */
882 		if (info.seq != user->seq)
883 			ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
884 		else
885 			ret = EPOLLIN|EPOLLRDNORM;
886 	}
887 	logbuf_unlock_irq();
888 
889 	return ret;
890 }
891 
devkmsg_open(struct inode * inode,struct file * file)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 = kmalloc(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 	prb_rec_init_rd(&user->record, &user->info,
918 			&user->text_buf[0], sizeof(user->text_buf));
919 
920 	logbuf_lock_irq();
921 	user->seq = prb_first_valid_seq(prb);
922 	logbuf_unlock_irq();
923 
924 	file->private_data = user;
925 	return 0;
926 }
927 
devkmsg_release(struct inode * inode,struct file * file)928 static int devkmsg_release(struct inode *inode, struct file *file)
929 {
930 	struct devkmsg_user *user = file->private_data;
931 
932 	if (!user)
933 		return 0;
934 
935 	ratelimit_state_exit(&user->rs);
936 
937 	mutex_destroy(&user->lock);
938 	kfree(user);
939 	return 0;
940 }
941 
942 const struct file_operations kmsg_fops = {
943 	.open = devkmsg_open,
944 	.read = devkmsg_read,
945 	.write_iter = devkmsg_write,
946 	.llseek = devkmsg_llseek,
947 	.poll = devkmsg_poll,
948 	.release = devkmsg_release,
949 };
950 
951 #ifdef CONFIG_CRASH_CORE
952 /*
953  * This appends the listed symbols to /proc/vmcore
954  *
955  * /proc/vmcore is used by various utilities, like crash and makedumpfile to
956  * obtain access to symbols that are otherwise very difficult to locate.  These
957  * symbols are specifically used so that utilities can access and extract the
958  * dmesg log from a vmcore file after a crash.
959  */
log_buf_vmcoreinfo_setup(void)960 void log_buf_vmcoreinfo_setup(void)
961 {
962 	struct dev_printk_info *dev_info = NULL;
963 
964 	VMCOREINFO_SYMBOL(prb);
965 	VMCOREINFO_SYMBOL(printk_rb_static);
966 	VMCOREINFO_SYMBOL(clear_seq);
967 
968 	/*
969 	 * Export struct size and field offsets. User space tools can
970 	 * parse it and detect any changes to structure down the line.
971 	 */
972 
973 	VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
974 	VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
975 	VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
976 	VMCOREINFO_OFFSET(printk_ringbuffer, fail);
977 
978 	VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
979 	VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
980 	VMCOREINFO_OFFSET(prb_desc_ring, descs);
981 	VMCOREINFO_OFFSET(prb_desc_ring, infos);
982 	VMCOREINFO_OFFSET(prb_desc_ring, head_id);
983 	VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
984 
985 	VMCOREINFO_STRUCT_SIZE(prb_desc);
986 	VMCOREINFO_OFFSET(prb_desc, state_var);
987 	VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
988 
989 	VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
990 	VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
991 	VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
992 
993 	VMCOREINFO_STRUCT_SIZE(printk_info);
994 	VMCOREINFO_OFFSET(printk_info, seq);
995 	VMCOREINFO_OFFSET(printk_info, ts_nsec);
996 	VMCOREINFO_OFFSET(printk_info, text_len);
997 	VMCOREINFO_OFFSET(printk_info, caller_id);
998 	VMCOREINFO_OFFSET(printk_info, dev_info);
999 
1000 	VMCOREINFO_STRUCT_SIZE(dev_printk_info);
1001 	VMCOREINFO_OFFSET(dev_printk_info, subsystem);
1002 	VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
1003 	VMCOREINFO_OFFSET(dev_printk_info, device);
1004 	VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
1005 
1006 	VMCOREINFO_STRUCT_SIZE(prb_data_ring);
1007 	VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1008 	VMCOREINFO_OFFSET(prb_data_ring, data);
1009 	VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1010 	VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1011 
1012 	VMCOREINFO_SIZE(atomic_long_t);
1013 	VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
1014 }
1015 #endif
1016 
1017 /* requested log_buf_len from kernel cmdline */
1018 static unsigned long __initdata new_log_buf_len;
1019 
1020 /* we practice scaling the ring buffer by powers of 2 */
log_buf_len_update(u64 size)1021 static void __init log_buf_len_update(u64 size)
1022 {
1023 	if (size > (u64)LOG_BUF_LEN_MAX) {
1024 		size = (u64)LOG_BUF_LEN_MAX;
1025 		pr_err("log_buf over 2G is not supported.\n");
1026 	}
1027 
1028 	if (size)
1029 		size = roundup_pow_of_two(size);
1030 	if (size > log_buf_len)
1031 		new_log_buf_len = (unsigned long)size;
1032 }
1033 
1034 /* save requested log_buf_len since it's too early to process it */
log_buf_len_setup(char * str)1035 static int __init log_buf_len_setup(char *str)
1036 {
1037 	u64 size;
1038 
1039 	if (!str)
1040 		return -EINVAL;
1041 
1042 	size = memparse(str, &str);
1043 
1044 	log_buf_len_update(size);
1045 
1046 	return 0;
1047 }
1048 early_param("log_buf_len", log_buf_len_setup);
1049 
1050 #ifdef CONFIG_SMP
1051 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
1052 
log_buf_add_cpu(void)1053 static void __init log_buf_add_cpu(void)
1054 {
1055 	unsigned int cpu_extra;
1056 
1057 	/*
1058 	 * archs should set up cpu_possible_bits properly with
1059 	 * set_cpu_possible() after setup_arch() but just in
1060 	 * case lets ensure this is valid.
1061 	 */
1062 	if (num_possible_cpus() == 1)
1063 		return;
1064 
1065 	cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
1066 
1067 	/* by default this will only continue through for large > 64 CPUs */
1068 	if (cpu_extra <= __LOG_BUF_LEN / 2)
1069 		return;
1070 
1071 	pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
1072 		__LOG_CPU_MAX_BUF_LEN);
1073 	pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
1074 		cpu_extra);
1075 	pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1076 
1077 	log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1078 }
1079 #else /* !CONFIG_SMP */
log_buf_add_cpu(void)1080 static inline void log_buf_add_cpu(void) {}
1081 #endif /* CONFIG_SMP */
1082 
set_percpu_data_ready(void)1083 static void __init set_percpu_data_ready(void)
1084 {
1085 	printk_safe_init();
1086 	/* Make sure we set this flag only after printk_safe() init is done */
1087 	barrier();
1088 	__printk_percpu_data_ready = true;
1089 }
1090 
add_to_rb(struct printk_ringbuffer * rb,struct printk_record * r)1091 static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1092 				     struct printk_record *r)
1093 {
1094 	struct prb_reserved_entry e;
1095 	struct printk_record dest_r;
1096 
1097 	prb_rec_init_wr(&dest_r, r->info->text_len);
1098 
1099 	if (!prb_reserve(&e, rb, &dest_r))
1100 		return 0;
1101 
1102 	memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1103 	dest_r.info->text_len = r->info->text_len;
1104 	dest_r.info->facility = r->info->facility;
1105 	dest_r.info->level = r->info->level;
1106 	dest_r.info->flags = r->info->flags;
1107 	dest_r.info->ts_nsec = r->info->ts_nsec;
1108 	dest_r.info->caller_id = r->info->caller_id;
1109 	memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1110 
1111 	prb_final_commit(&e);
1112 
1113 	return prb_record_text_space(&e);
1114 }
1115 
1116 static char setup_text_buf[LOG_LINE_MAX] __initdata;
1117 
setup_log_buf(int early)1118 void __init setup_log_buf(int early)
1119 {
1120 	struct printk_info *new_infos;
1121 	unsigned int new_descs_count;
1122 	struct prb_desc *new_descs;
1123 	struct printk_info info;
1124 	struct printk_record r;
1125 	size_t new_descs_size;
1126 	size_t new_infos_size;
1127 	unsigned long flags;
1128 	char *new_log_buf;
1129 	unsigned int free;
1130 	u64 seq;
1131 
1132 	/*
1133 	 * Some archs call setup_log_buf() multiple times - first is very
1134 	 * early, e.g. from setup_arch(), and second - when percpu_areas
1135 	 * are initialised.
1136 	 */
1137 	if (!early)
1138 		set_percpu_data_ready();
1139 
1140 	if (log_buf != __log_buf)
1141 		return;
1142 
1143 	if (!early && !new_log_buf_len)
1144 		log_buf_add_cpu();
1145 
1146 	if (!new_log_buf_len)
1147 		return;
1148 
1149 	new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1150 	if (new_descs_count == 0) {
1151 		pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1152 		return;
1153 	}
1154 
1155 	new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1156 	if (unlikely(!new_log_buf)) {
1157 		pr_err("log_buf_len: %lu text bytes not available\n",
1158 		       new_log_buf_len);
1159 		return;
1160 	}
1161 
1162 	new_descs_size = new_descs_count * sizeof(struct prb_desc);
1163 	new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1164 	if (unlikely(!new_descs)) {
1165 		pr_err("log_buf_len: %zu desc bytes not available\n",
1166 		       new_descs_size);
1167 		goto err_free_log_buf;
1168 	}
1169 
1170 	new_infos_size = new_descs_count * sizeof(struct printk_info);
1171 	new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1172 	if (unlikely(!new_infos)) {
1173 		pr_err("log_buf_len: %zu info bytes not available\n",
1174 		       new_infos_size);
1175 		goto err_free_descs;
1176 	}
1177 
1178 	prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1179 
1180 	prb_init(&printk_rb_dynamic,
1181 		 new_log_buf, ilog2(new_log_buf_len),
1182 		 new_descs, ilog2(new_descs_count),
1183 		 new_infos);
1184 
1185 	logbuf_lock_irqsave(flags);
1186 
1187 	log_buf_len = new_log_buf_len;
1188 	log_buf = new_log_buf;
1189 	new_log_buf_len = 0;
1190 
1191 	free = __LOG_BUF_LEN;
1192 	prb_for_each_record(0, &printk_rb_static, seq, &r)
1193 		free -= add_to_rb(&printk_rb_dynamic, &r);
1194 
1195 	/*
1196 	 * This is early enough that everything is still running on the
1197 	 * boot CPU and interrupts are disabled. So no new messages will
1198 	 * appear during the transition to the dynamic buffer.
1199 	 */
1200 	prb = &printk_rb_dynamic;
1201 
1202 	logbuf_unlock_irqrestore(flags);
1203 
1204 	if (seq != prb_next_seq(&printk_rb_static)) {
1205 		pr_err("dropped %llu messages\n",
1206 		       prb_next_seq(&printk_rb_static) - seq);
1207 	}
1208 
1209 	pr_info("log_buf_len: %u bytes\n", log_buf_len);
1210 	pr_info("early log buf free: %u(%u%%)\n",
1211 		free, (free * 100) / __LOG_BUF_LEN);
1212 	return;
1213 
1214 err_free_descs:
1215 	memblock_free(__pa(new_descs), new_descs_size);
1216 err_free_log_buf:
1217 	memblock_free(__pa(new_log_buf), new_log_buf_len);
1218 }
1219 
1220 static bool __read_mostly ignore_loglevel;
1221 
ignore_loglevel_setup(char * str)1222 static int __init ignore_loglevel_setup(char *str)
1223 {
1224 	ignore_loglevel = true;
1225 	pr_info("debug: ignoring loglevel setting.\n");
1226 
1227 	return 0;
1228 }
1229 
1230 early_param("ignore_loglevel", ignore_loglevel_setup);
1231 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1232 MODULE_PARM_DESC(ignore_loglevel,
1233 		 "ignore loglevel setting (prints all kernel messages to the console)");
1234 
suppress_message_printing(int level)1235 static bool suppress_message_printing(int level)
1236 {
1237 	return (level >= console_loglevel && !ignore_loglevel);
1238 }
1239 
1240 #ifdef CONFIG_BOOT_PRINTK_DELAY
1241 
1242 static int boot_delay; /* msecs delay after each printk during bootup */
1243 static unsigned long long loops_per_msec;	/* based on boot_delay */
1244 
boot_delay_setup(char * str)1245 static int __init boot_delay_setup(char *str)
1246 {
1247 	unsigned long lpj;
1248 
1249 	lpj = preset_lpj ? preset_lpj : 1000000;	/* some guess */
1250 	loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1251 
1252 	get_option(&str, &boot_delay);
1253 	if (boot_delay > 10 * 1000)
1254 		boot_delay = 0;
1255 
1256 	pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1257 		"HZ: %d, loops_per_msec: %llu\n",
1258 		boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1259 	return 0;
1260 }
1261 early_param("boot_delay", boot_delay_setup);
1262 
boot_delay_msec(int level)1263 static void boot_delay_msec(int level)
1264 {
1265 	unsigned long long k;
1266 	unsigned long timeout;
1267 
1268 	if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1269 		|| suppress_message_printing(level)) {
1270 		return;
1271 	}
1272 
1273 	k = (unsigned long long)loops_per_msec * boot_delay;
1274 
1275 	timeout = jiffies + msecs_to_jiffies(boot_delay);
1276 	while (k) {
1277 		k--;
1278 		cpu_relax();
1279 		/*
1280 		 * use (volatile) jiffies to prevent
1281 		 * compiler reduction; loop termination via jiffies
1282 		 * is secondary and may or may not happen.
1283 		 */
1284 		if (time_after(jiffies, timeout))
1285 			break;
1286 		touch_nmi_watchdog();
1287 	}
1288 }
1289 #else
boot_delay_msec(int level)1290 static inline void boot_delay_msec(int level)
1291 {
1292 }
1293 #endif
1294 
1295 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1296 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1297 
print_syslog(unsigned int level,char * buf)1298 static size_t print_syslog(unsigned int level, char *buf)
1299 {
1300 	return sprintf(buf, "<%u>", level);
1301 }
1302 
print_time(u64 ts,char * buf)1303 static size_t print_time(u64 ts, char *buf)
1304 {
1305 	unsigned long rem_nsec = do_div(ts, 1000000000);
1306 
1307 	return sprintf(buf, "[%5lu.%06lu]",
1308 		       (unsigned long)ts, rem_nsec / 1000);
1309 }
1310 
1311 #ifdef CONFIG_PRINTK_CALLER
print_caller(u32 id,char * buf)1312 static size_t print_caller(u32 id, char *buf)
1313 {
1314 	char caller[12];
1315 
1316 	snprintf(caller, sizeof(caller), "%c%u",
1317 		 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1318 	return sprintf(buf, "[%6s]", caller);
1319 }
1320 #else
1321 #define print_caller(id, buf) 0
1322 #endif
1323 
info_print_prefix(const struct printk_info * info,bool syslog,bool time,char * buf)1324 static size_t info_print_prefix(const struct printk_info  *info, bool syslog,
1325 				bool time, char *buf)
1326 {
1327 	size_t len = 0;
1328 
1329 	if (syslog)
1330 		len = print_syslog((info->facility << 3) | info->level, buf);
1331 
1332 	if (time)
1333 		len += print_time(info->ts_nsec, buf + len);
1334 
1335 	len += print_caller(info->caller_id, buf + len);
1336 
1337 	if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1338 		buf[len++] = ' ';
1339 		buf[len] = '\0';
1340 	}
1341 
1342 	return len;
1343 }
1344 
1345 /*
1346  * Prepare the record for printing. The text is shifted within the given
1347  * buffer to avoid a need for another one. The following operations are
1348  * done:
1349  *
1350  *   - Add prefix for each line.
1351  *   - Drop truncated lines that no longer fit into the buffer.
1352  *   - Add the trailing newline that has been removed in vprintk_store().
1353  *   - Add a string terminator.
1354  *
1355  * Since the produced string is always terminated, the maximum possible
1356  * return value is @r->text_buf_size - 1;
1357  *
1358  * Return: The length of the updated/prepared text, including the added
1359  * prefixes and the newline. The terminator is not counted. The dropped
1360  * line(s) are not counted.
1361  */
record_print_text(struct printk_record * r,bool syslog,bool time)1362 static size_t record_print_text(struct printk_record *r, bool syslog,
1363 				bool time)
1364 {
1365 	size_t text_len = r->info->text_len;
1366 	size_t buf_size = r->text_buf_size;
1367 	char *text = r->text_buf;
1368 	char prefix[PREFIX_MAX];
1369 	bool truncated = false;
1370 	size_t prefix_len;
1371 	size_t line_len;
1372 	size_t len = 0;
1373 	char *next;
1374 
1375 	/*
1376 	 * If the message was truncated because the buffer was not large
1377 	 * enough, treat the available text as if it were the full text.
1378 	 */
1379 	if (text_len > buf_size)
1380 		text_len = buf_size;
1381 
1382 	prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1383 
1384 	/*
1385 	 * @text_len: bytes of unprocessed text
1386 	 * @line_len: bytes of current line _without_ newline
1387 	 * @text:     pointer to beginning of current line
1388 	 * @len:      number of bytes prepared in r->text_buf
1389 	 */
1390 	for (;;) {
1391 		next = memchr(text, '\n', text_len);
1392 		if (next) {
1393 			line_len = next - text;
1394 		} else {
1395 			/* Drop truncated line(s). */
1396 			if (truncated)
1397 				break;
1398 			line_len = text_len;
1399 		}
1400 
1401 		/*
1402 		 * Truncate the text if there is not enough space to add the
1403 		 * prefix and a trailing newline and a terminator.
1404 		 */
1405 		if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1406 			/* Drop even the current line if no space. */
1407 			if (len + prefix_len + line_len + 1 + 1 > buf_size)
1408 				break;
1409 
1410 			text_len = buf_size - len - prefix_len - 1 - 1;
1411 			truncated = true;
1412 		}
1413 
1414 		memmove(text + prefix_len, text, text_len);
1415 		memcpy(text, prefix, prefix_len);
1416 
1417 		/*
1418 		 * Increment the prepared length to include the text and
1419 		 * prefix that were just moved+copied. Also increment for the
1420 		 * newline at the end of this line. If this is the last line,
1421 		 * there is no newline, but it will be added immediately below.
1422 		 */
1423 		len += prefix_len + line_len + 1;
1424 		if (text_len == line_len) {
1425 			/*
1426 			 * This is the last line. Add the trailing newline
1427 			 * removed in vprintk_store().
1428 			 */
1429 			text[prefix_len + line_len] = '\n';
1430 			break;
1431 		}
1432 
1433 		/*
1434 		 * Advance beyond the added prefix and the related line with
1435 		 * its newline.
1436 		 */
1437 		text += prefix_len + line_len + 1;
1438 
1439 		/*
1440 		 * The remaining text has only decreased by the line with its
1441 		 * newline.
1442 		 *
1443 		 * Note that @text_len can become zero. It happens when @text
1444 		 * ended with a newline (either due to truncation or the
1445 		 * original string ending with "\n\n"). The loop is correctly
1446 		 * repeated and (if not truncated) an empty line with a prefix
1447 		 * will be prepared.
1448 		 */
1449 		text_len -= line_len + 1;
1450 	}
1451 
1452 	/*
1453 	 * If a buffer was provided, it will be terminated. Space for the
1454 	 * string terminator is guaranteed to be available. The terminator is
1455 	 * not counted in the return value.
1456 	 */
1457 	if (buf_size > 0)
1458 		r->text_buf[len] = 0;
1459 
1460 	return len;
1461 }
1462 
get_record_print_text_size(struct printk_info * info,unsigned int line_count,bool syslog,bool time)1463 static size_t get_record_print_text_size(struct printk_info *info,
1464 					 unsigned int line_count,
1465 					 bool syslog, bool time)
1466 {
1467 	char prefix[PREFIX_MAX];
1468 	size_t prefix_len;
1469 
1470 	prefix_len = info_print_prefix(info, syslog, time, prefix);
1471 
1472 	/*
1473 	 * Each line will be preceded with a prefix. The intermediate
1474 	 * newlines are already within the text, but a final trailing
1475 	 * newline will be added.
1476 	 */
1477 	return ((prefix_len * line_count) + info->text_len + 1);
1478 }
1479 
syslog_print(char __user * buf,int size)1480 static int syslog_print(char __user *buf, int size)
1481 {
1482 	struct printk_info info;
1483 	struct printk_record r;
1484 	char *text;
1485 	int len = 0;
1486 
1487 	text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1488 	if (!text)
1489 		return -ENOMEM;
1490 
1491 	prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
1492 
1493 	while (size > 0) {
1494 		size_t n;
1495 		size_t skip;
1496 
1497 		logbuf_lock_irq();
1498 		if (!prb_read_valid(prb, syslog_seq, &r)) {
1499 			logbuf_unlock_irq();
1500 			break;
1501 		}
1502 		if (r.info->seq != syslog_seq) {
1503 			/* message is gone, move to next valid one */
1504 			syslog_seq = r.info->seq;
1505 			syslog_partial = 0;
1506 		}
1507 
1508 		/*
1509 		 * To keep reading/counting partial line consistent,
1510 		 * use printk_time value as of the beginning of a line.
1511 		 */
1512 		if (!syslog_partial)
1513 			syslog_time = printk_time;
1514 
1515 		skip = syslog_partial;
1516 		n = record_print_text(&r, true, syslog_time);
1517 		if (n - syslog_partial <= size) {
1518 			/* message fits into buffer, move forward */
1519 			syslog_seq = r.info->seq + 1;
1520 			n -= syslog_partial;
1521 			syslog_partial = 0;
1522 		} else if (!len){
1523 			/* partial read(), remember position */
1524 			n = size;
1525 			syslog_partial += n;
1526 		} else
1527 			n = 0;
1528 		logbuf_unlock_irq();
1529 
1530 		if (!n)
1531 			break;
1532 
1533 		if (copy_to_user(buf, text + skip, n)) {
1534 			if (!len)
1535 				len = -EFAULT;
1536 			break;
1537 		}
1538 
1539 		len += n;
1540 		size -= n;
1541 		buf += n;
1542 	}
1543 
1544 	kfree(text);
1545 	return len;
1546 }
1547 
syslog_print_all(char __user * buf,int size,bool clear)1548 static int syslog_print_all(char __user *buf, int size, bool clear)
1549 {
1550 	struct printk_info info;
1551 	unsigned int line_count;
1552 	struct printk_record r;
1553 	char *text;
1554 	int len = 0;
1555 	u64 seq;
1556 	bool time;
1557 
1558 	text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1559 	if (!text)
1560 		return -ENOMEM;
1561 
1562 	time = printk_time;
1563 	logbuf_lock_irq();
1564 	/*
1565 	 * Find first record that fits, including all following records,
1566 	 * into the user-provided buffer for this dump.
1567 	 */
1568 	prb_for_each_info(clear_seq, prb, seq, &info, &line_count)
1569 		len += get_record_print_text_size(&info, line_count, true, time);
1570 
1571 	/* move first record forward until length fits into the buffer */
1572 	prb_for_each_info(clear_seq, prb, seq, &info, &line_count) {
1573 		if (len <= size)
1574 			break;
1575 		len -= get_record_print_text_size(&info, line_count, true, time);
1576 	}
1577 
1578 	prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
1579 
1580 	len = 0;
1581 	prb_for_each_record(seq, prb, seq, &r) {
1582 		int textlen;
1583 
1584 		textlen = record_print_text(&r, true, time);
1585 
1586 		if (len + textlen > size) {
1587 			seq--;
1588 			break;
1589 		}
1590 
1591 		logbuf_unlock_irq();
1592 		if (copy_to_user(buf + len, text, textlen))
1593 			len = -EFAULT;
1594 		else
1595 			len += textlen;
1596 		logbuf_lock_irq();
1597 
1598 		if (len < 0)
1599 			break;
1600 	}
1601 
1602 	if (clear)
1603 		clear_seq = seq;
1604 	logbuf_unlock_irq();
1605 
1606 	kfree(text);
1607 	return len;
1608 }
1609 
syslog_clear(void)1610 static void syslog_clear(void)
1611 {
1612 	logbuf_lock_irq();
1613 	clear_seq = prb_next_seq(prb);
1614 	logbuf_unlock_irq();
1615 }
1616 
do_syslog(int type,char __user * buf,int len,int source)1617 int do_syslog(int type, char __user *buf, int len, int source)
1618 {
1619 	struct printk_info info;
1620 	bool clear = false;
1621 	static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1622 	int error;
1623 
1624 	error = check_syslog_permissions(type, source);
1625 	if (error)
1626 		return error;
1627 
1628 	switch (type) {
1629 	case SYSLOG_ACTION_CLOSE:	/* Close log */
1630 		break;
1631 	case SYSLOG_ACTION_OPEN:	/* Open log */
1632 		break;
1633 	case SYSLOG_ACTION_READ:	/* Read from log */
1634 		if (!buf || len < 0)
1635 			return -EINVAL;
1636 		if (!len)
1637 			return 0;
1638 		if (!access_ok(buf, len))
1639 			return -EFAULT;
1640 		error = wait_event_interruptible(log_wait,
1641 				prb_read_valid(prb, syslog_seq, NULL));
1642 		if (error)
1643 			return error;
1644 		error = syslog_print(buf, len);
1645 		break;
1646 	/* Read/clear last kernel messages */
1647 	case SYSLOG_ACTION_READ_CLEAR:
1648 		clear = true;
1649 		fallthrough;
1650 	/* Read last kernel messages */
1651 	case SYSLOG_ACTION_READ_ALL:
1652 		if (!buf || len < 0)
1653 			return -EINVAL;
1654 		if (!len)
1655 			return 0;
1656 		if (!access_ok(buf, len))
1657 			return -EFAULT;
1658 		error = syslog_print_all(buf, len, clear);
1659 		break;
1660 	/* Clear ring buffer */
1661 	case SYSLOG_ACTION_CLEAR:
1662 		syslog_clear();
1663 		break;
1664 	/* Disable logging to console */
1665 	case SYSLOG_ACTION_CONSOLE_OFF:
1666 		if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1667 			saved_console_loglevel = console_loglevel;
1668 		console_loglevel = minimum_console_loglevel;
1669 		break;
1670 	/* Enable logging to console */
1671 	case SYSLOG_ACTION_CONSOLE_ON:
1672 		if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1673 			console_loglevel = saved_console_loglevel;
1674 			saved_console_loglevel = LOGLEVEL_DEFAULT;
1675 		}
1676 		break;
1677 	/* Set level of messages printed to console */
1678 	case SYSLOG_ACTION_CONSOLE_LEVEL:
1679 		if (len < 1 || len > 8)
1680 			return -EINVAL;
1681 		if (len < minimum_console_loglevel)
1682 			len = minimum_console_loglevel;
1683 		console_loglevel = len;
1684 		/* Implicitly re-enable logging to console */
1685 		saved_console_loglevel = LOGLEVEL_DEFAULT;
1686 		break;
1687 	/* Number of chars in the log buffer */
1688 	case SYSLOG_ACTION_SIZE_UNREAD:
1689 		logbuf_lock_irq();
1690 		if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1691 			/* No unread messages. */
1692 			logbuf_unlock_irq();
1693 			return 0;
1694 		}
1695 		if (info.seq != syslog_seq) {
1696 			/* messages are gone, move to first one */
1697 			syslog_seq = info.seq;
1698 			syslog_partial = 0;
1699 		}
1700 		if (source == SYSLOG_FROM_PROC) {
1701 			/*
1702 			 * Short-cut for poll(/"proc/kmsg") which simply checks
1703 			 * for pending data, not the size; return the count of
1704 			 * records, not the length.
1705 			 */
1706 			error = prb_next_seq(prb) - syslog_seq;
1707 		} else {
1708 			bool time = syslog_partial ? syslog_time : printk_time;
1709 			unsigned int line_count;
1710 			u64 seq;
1711 
1712 			prb_for_each_info(syslog_seq, prb, seq, &info,
1713 					  &line_count) {
1714 				error += get_record_print_text_size(&info, line_count,
1715 								    true, time);
1716 				time = printk_time;
1717 			}
1718 			error -= syslog_partial;
1719 		}
1720 		logbuf_unlock_irq();
1721 		break;
1722 	/* Size of the log buffer */
1723 	case SYSLOG_ACTION_SIZE_BUFFER:
1724 		error = log_buf_len;
1725 		break;
1726 	default:
1727 		error = -EINVAL;
1728 		break;
1729 	}
1730 
1731 	return error;
1732 }
1733 
SYSCALL_DEFINE3(syslog,int,type,char __user *,buf,int,len)1734 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1735 {
1736 	return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1737 }
1738 
1739 /*
1740  * Special console_lock variants that help to reduce the risk of soft-lockups.
1741  * They allow to pass console_lock to another printk() call using a busy wait.
1742  */
1743 
1744 #ifdef CONFIG_LOCKDEP
1745 static struct lockdep_map console_owner_dep_map = {
1746 	.name = "console_owner"
1747 };
1748 #endif
1749 
1750 static DEFINE_RAW_SPINLOCK(console_owner_lock);
1751 static struct task_struct *console_owner;
1752 static bool console_waiter;
1753 
1754 /**
1755  * console_lock_spinning_enable - mark beginning of code where another
1756  *	thread might safely busy wait
1757  *
1758  * This basically converts console_lock into a spinlock. This marks
1759  * the section where the console_lock owner can not sleep, because
1760  * there may be a waiter spinning (like a spinlock). Also it must be
1761  * ready to hand over the lock at the end of the section.
1762  */
console_lock_spinning_enable(void)1763 static void console_lock_spinning_enable(void)
1764 {
1765 	raw_spin_lock(&console_owner_lock);
1766 	console_owner = current;
1767 	raw_spin_unlock(&console_owner_lock);
1768 
1769 	/* The waiter may spin on us after setting console_owner */
1770 	spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1771 }
1772 
1773 /**
1774  * console_lock_spinning_disable_and_check - mark end of code where another
1775  *	thread was able to busy wait and check if there is a waiter
1776  *
1777  * This is called at the end of the section where spinning is allowed.
1778  * It has two functions. First, it is a signal that it is no longer
1779  * safe to start busy waiting for the lock. Second, it checks if
1780  * there is a busy waiter and passes the lock rights to her.
1781  *
1782  * Important: Callers lose the lock if there was a busy waiter.
1783  *	They must not touch items synchronized by console_lock
1784  *	in this case.
1785  *
1786  * Return: 1 if the lock rights were passed, 0 otherwise.
1787  */
console_lock_spinning_disable_and_check(void)1788 static int console_lock_spinning_disable_and_check(void)
1789 {
1790 	int waiter;
1791 
1792 	raw_spin_lock(&console_owner_lock);
1793 	waiter = READ_ONCE(console_waiter);
1794 	console_owner = NULL;
1795 	raw_spin_unlock(&console_owner_lock);
1796 
1797 	if (!waiter) {
1798 		spin_release(&console_owner_dep_map, _THIS_IP_);
1799 		return 0;
1800 	}
1801 
1802 	/* The waiter is now free to continue */
1803 	WRITE_ONCE(console_waiter, false);
1804 
1805 	spin_release(&console_owner_dep_map, _THIS_IP_);
1806 
1807 	/*
1808 	 * Hand off console_lock to waiter. The waiter will perform
1809 	 * the up(). After this, the waiter is the console_lock owner.
1810 	 */
1811 	mutex_release(&console_lock_dep_map, _THIS_IP_);
1812 	return 1;
1813 }
1814 
1815 /**
1816  * console_trylock_spinning - try to get console_lock by busy waiting
1817  *
1818  * This allows to busy wait for the console_lock when the current
1819  * owner is running in specially marked sections. It means that
1820  * the current owner is running and cannot reschedule until it
1821  * is ready to lose the lock.
1822  *
1823  * Return: 1 if we got the lock, 0 othrewise
1824  */
console_trylock_spinning(void)1825 static int console_trylock_spinning(void)
1826 {
1827 	struct task_struct *owner = NULL;
1828 	bool waiter;
1829 	bool spin = false;
1830 	unsigned long flags;
1831 
1832 	if (console_trylock())
1833 		return 1;
1834 
1835 	printk_safe_enter_irqsave(flags);
1836 
1837 	raw_spin_lock(&console_owner_lock);
1838 	owner = READ_ONCE(console_owner);
1839 	waiter = READ_ONCE(console_waiter);
1840 	if (!waiter && owner && owner != current) {
1841 		WRITE_ONCE(console_waiter, true);
1842 		spin = true;
1843 	}
1844 	raw_spin_unlock(&console_owner_lock);
1845 
1846 	/*
1847 	 * If there is an active printk() writing to the
1848 	 * consoles, instead of having it write our data too,
1849 	 * see if we can offload that load from the active
1850 	 * printer, and do some printing ourselves.
1851 	 * Go into a spin only if there isn't already a waiter
1852 	 * spinning, and there is an active printer, and
1853 	 * that active printer isn't us (recursive printk?).
1854 	 */
1855 	if (!spin) {
1856 		printk_safe_exit_irqrestore(flags);
1857 		return 0;
1858 	}
1859 
1860 	/* We spin waiting for the owner to release us */
1861 	spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1862 	/* Owner will clear console_waiter on hand off */
1863 	while (READ_ONCE(console_waiter))
1864 		cpu_relax();
1865 	spin_release(&console_owner_dep_map, _THIS_IP_);
1866 
1867 	printk_safe_exit_irqrestore(flags);
1868 	/*
1869 	 * The owner passed the console lock to us.
1870 	 * Since we did not spin on console lock, annotate
1871 	 * this as a trylock. Otherwise lockdep will
1872 	 * complain.
1873 	 */
1874 	mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
1875 
1876 	return 1;
1877 }
1878 
1879 /*
1880  * Call the console drivers, asking them to write out
1881  * log_buf[start] to log_buf[end - 1].
1882  * The console_lock must be held.
1883  */
call_console_drivers(const char * ext_text,size_t ext_len,const char * text,size_t len)1884 static void call_console_drivers(const char *ext_text, size_t ext_len,
1885 				 const char *text, size_t len)
1886 {
1887 	static char dropped_text[64];
1888 	size_t dropped_len = 0;
1889 	struct console *con;
1890 
1891 	trace_console_rcuidle(text, len);
1892 
1893 	if (!console_drivers)
1894 		return;
1895 
1896 	if (console_dropped) {
1897 		dropped_len = snprintf(dropped_text, sizeof(dropped_text),
1898 				       "** %lu printk messages dropped **\n",
1899 				       console_dropped);
1900 		console_dropped = 0;
1901 	}
1902 
1903 	for_each_console(con) {
1904 		if (exclusive_console && con != exclusive_console)
1905 			continue;
1906 		if (!(con->flags & CON_ENABLED))
1907 			continue;
1908 		if (!con->write)
1909 			continue;
1910 		if (!cpu_online(smp_processor_id()) &&
1911 		    !(con->flags & CON_ANYTIME))
1912 			continue;
1913 		if (con->flags & CON_EXTENDED)
1914 			con->write(con, ext_text, ext_len);
1915 		else {
1916 			if (dropped_len)
1917 				con->write(con, dropped_text, dropped_len);
1918 			con->write(con, text, len);
1919 		}
1920 	}
1921 }
1922 
1923 int printk_delay_msec __read_mostly;
1924 
printk_delay(void)1925 static inline void printk_delay(void)
1926 {
1927 	if (unlikely(printk_delay_msec)) {
1928 		int m = printk_delay_msec;
1929 
1930 		while (m--) {
1931 			mdelay(1);
1932 			touch_nmi_watchdog();
1933 		}
1934 	}
1935 }
1936 
printk_caller_id(void)1937 static inline u32 printk_caller_id(void)
1938 {
1939 	return in_task() ? task_pid_nr(current) :
1940 		0x80000000 + raw_smp_processor_id();
1941 }
1942 
log_output(int facility,int level,enum log_flags lflags,const struct dev_printk_info * dev_info,char * text,size_t text_len)1943 static size_t log_output(int facility, int level, enum log_flags lflags,
1944 			 const struct dev_printk_info *dev_info,
1945 			 char *text, size_t text_len)
1946 {
1947 	const u32 caller_id = printk_caller_id();
1948 
1949 	if (lflags & LOG_CONT) {
1950 		struct prb_reserved_entry e;
1951 		struct printk_record r;
1952 
1953 		prb_rec_init_wr(&r, text_len);
1954 		if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
1955 			memcpy(&r.text_buf[r.info->text_len], text, text_len);
1956 			r.info->text_len += text_len;
1957 			if (lflags & LOG_NEWLINE) {
1958 				r.info->flags |= LOG_NEWLINE;
1959 				prb_final_commit(&e);
1960 			} else {
1961 				prb_commit(&e);
1962 			}
1963 
1964 			trace_android_vh_logbuf_pr_cont(&r, text_len);
1965 			return text_len;
1966 		}
1967 	}
1968 
1969 	/* Store it in the record log */
1970 	return log_store(caller_id, facility, level, lflags, 0,
1971 			 dev_info, text, text_len);
1972 }
1973 
1974 /* Must be called under logbuf_lock. */
vprintk_store(int facility,int level,const struct dev_printk_info * dev_info,const char * fmt,va_list args)1975 int vprintk_store(int facility, int level,
1976 		  const struct dev_printk_info *dev_info,
1977 		  const char *fmt, va_list args)
1978 {
1979 	static char textbuf[LOG_LINE_MAX];
1980 	char *text = textbuf;
1981 	size_t text_len;
1982 	enum log_flags lflags = 0;
1983 
1984 	/*
1985 	 * The printf needs to come first; we need the syslog
1986 	 * prefix which might be passed-in as a parameter.
1987 	 */
1988 	text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
1989 
1990 	/* mark and strip a trailing newline */
1991 	if (text_len && text[text_len-1] == '\n') {
1992 		text_len--;
1993 		lflags |= LOG_NEWLINE;
1994 	}
1995 
1996 	/* strip kernel syslog prefix and extract log level or control flags */
1997 	if (facility == 0) {
1998 		int kern_level;
1999 
2000 		while ((kern_level = printk_get_level(text)) != 0) {
2001 			switch (kern_level) {
2002 			case '0' ... '7':
2003 				if (level == LOGLEVEL_DEFAULT)
2004 					level = kern_level - '0';
2005 				break;
2006 			case 'c':	/* KERN_CONT */
2007 				lflags |= LOG_CONT;
2008 			}
2009 
2010 			text_len -= 2;
2011 			text += 2;
2012 		}
2013 	}
2014 
2015 	if (level == LOGLEVEL_DEFAULT)
2016 		level = default_message_loglevel;
2017 
2018 	if (dev_info)
2019 		lflags |= LOG_NEWLINE;
2020 
2021 	return log_output(facility, level, lflags, dev_info, text, text_len);
2022 }
2023 
vprintk_emit(int facility,int level,const struct dev_printk_info * dev_info,const char * fmt,va_list args)2024 asmlinkage int vprintk_emit(int facility, int level,
2025 			    const struct dev_printk_info *dev_info,
2026 			    const char *fmt, va_list args)
2027 {
2028 	int printed_len;
2029 	bool in_sched = false;
2030 	unsigned long flags;
2031 
2032 	/* Suppress unimportant messages after panic happens */
2033 	if (unlikely(suppress_printk))
2034 		return 0;
2035 
2036 	if (level == LOGLEVEL_SCHED) {
2037 		level = LOGLEVEL_DEFAULT;
2038 		in_sched = true;
2039 	}
2040 
2041 	boot_delay_msec(level);
2042 	printk_delay();
2043 
2044 	/* This stops the holder of console_sem just where we want him */
2045 	logbuf_lock_irqsave(flags);
2046 	printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2047 	logbuf_unlock_irqrestore(flags);
2048 
2049 	/* If called from the scheduler, we can not call up(). */
2050 	if (!in_sched) {
2051 		/*
2052 		 * Disable preemption to avoid being preempted while holding
2053 		 * console_sem which would prevent anyone from printing to
2054 		 * console
2055 		 */
2056 		preempt_disable();
2057 		/*
2058 		 * Try to acquire and then immediately release the console
2059 		 * semaphore.  The release will print out buffers and wake up
2060 		 * /dev/kmsg and syslog() users.
2061 		 */
2062 		if (console_trylock_spinning())
2063 			console_unlock();
2064 		preempt_enable();
2065 	}
2066 
2067 	wake_up_klogd();
2068 	return printed_len;
2069 }
2070 EXPORT_SYMBOL(vprintk_emit);
2071 
vprintk(const char * fmt,va_list args)2072 asmlinkage int vprintk(const char *fmt, va_list args)
2073 {
2074 	return vprintk_func(fmt, args);
2075 }
2076 EXPORT_SYMBOL(vprintk);
2077 
vprintk_default(const char * fmt,va_list args)2078 int vprintk_default(const char *fmt, va_list args)
2079 {
2080 	return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2081 }
2082 EXPORT_SYMBOL_GPL(vprintk_default);
2083 
2084 /**
2085  * printk - print a kernel message
2086  * @fmt: format string
2087  *
2088  * This is printk(). It can be called from any context. We want it to work.
2089  *
2090  * We try to grab the console_lock. If we succeed, it's easy - we log the
2091  * output and call the console drivers.  If we fail to get the semaphore, we
2092  * place the output into the log buffer and return. The current holder of
2093  * the console_sem will notice the new output in console_unlock(); and will
2094  * send it to the consoles before releasing the lock.
2095  *
2096  * One effect of this deferred printing is that code which calls printk() and
2097  * then changes console_loglevel may break. This is because console_loglevel
2098  * is inspected when the actual printing occurs.
2099  *
2100  * See also:
2101  * printf(3)
2102  *
2103  * See the vsnprintf() documentation for format string extensions over C99.
2104  */
printk(const char * fmt,...)2105 asmlinkage __visible int printk(const char *fmt, ...)
2106 {
2107 	va_list args;
2108 	int r;
2109 
2110 	va_start(args, fmt);
2111 	r = vprintk_func(fmt, args);
2112 	va_end(args);
2113 
2114 	return r;
2115 }
2116 EXPORT_SYMBOL(printk);
2117 
2118 #else /* CONFIG_PRINTK */
2119 
2120 #define LOG_LINE_MAX		0
2121 #define PREFIX_MAX		0
2122 #define printk_time		false
2123 
2124 #define prb_read_valid(rb, seq, r)	false
2125 #define prb_first_valid_seq(rb)		0
2126 
2127 static u64 syslog_seq;
2128 static u64 console_seq;
2129 static u64 exclusive_console_stop_seq;
2130 static unsigned long console_dropped;
2131 
record_print_text(const struct printk_record * r,bool syslog,bool time)2132 static size_t record_print_text(const struct printk_record *r,
2133 				bool syslog, bool time)
2134 {
2135 	return 0;
2136 }
info_print_ext_header(char * buf,size_t size,struct printk_info * info)2137 static ssize_t info_print_ext_header(char *buf, size_t size,
2138 				     struct printk_info *info)
2139 {
2140 	return 0;
2141 }
msg_print_ext_body(char * buf,size_t size,char * text,size_t text_len,struct dev_printk_info * dev_info)2142 static ssize_t msg_print_ext_body(char *buf, size_t size,
2143 				  char *text, size_t text_len,
2144 				  struct dev_printk_info *dev_info) { return 0; }
console_lock_spinning_enable(void)2145 static void console_lock_spinning_enable(void) { }
console_lock_spinning_disable_and_check(void)2146 static int console_lock_spinning_disable_and_check(void) { return 0; }
call_console_drivers(const char * ext_text,size_t ext_len,const char * text,size_t len)2147 static void call_console_drivers(const char *ext_text, size_t ext_len,
2148 				 const char *text, size_t len) {}
suppress_message_printing(int level)2149 static bool suppress_message_printing(int level) { return false; }
2150 
2151 #endif /* CONFIG_PRINTK */
2152 
2153 #ifdef CONFIG_EARLY_PRINTK
2154 struct console *early_console;
2155 
early_printk(const char * fmt,...)2156 asmlinkage __visible void early_printk(const char *fmt, ...)
2157 {
2158 	va_list ap;
2159 	char buf[512];
2160 	int n;
2161 
2162 	if (!early_console)
2163 		return;
2164 
2165 	va_start(ap, fmt);
2166 	n = vscnprintf(buf, sizeof(buf), fmt, ap);
2167 	va_end(ap);
2168 
2169 	early_console->write(early_console, buf, n);
2170 }
2171 #endif
2172 
__add_preferred_console(char * name,int idx,char * options,char * brl_options,bool user_specified)2173 static int __add_preferred_console(char *name, int idx, char *options,
2174 				   char *brl_options, bool user_specified)
2175 {
2176 	struct console_cmdline *c;
2177 	int i;
2178 
2179 	/*
2180 	 *	See if this tty is not yet registered, and
2181 	 *	if we have a slot free.
2182 	 */
2183 	for (i = 0, c = console_cmdline;
2184 	     i < MAX_CMDLINECONSOLES && c->name[0];
2185 	     i++, c++) {
2186 		if (strcmp(c->name, name) == 0 && c->index == idx) {
2187 			if (!brl_options)
2188 				preferred_console = i;
2189 			if (user_specified)
2190 				c->user_specified = true;
2191 			return 0;
2192 		}
2193 	}
2194 	if (i == MAX_CMDLINECONSOLES)
2195 		return -E2BIG;
2196 	if (!brl_options)
2197 		preferred_console = i;
2198 	strlcpy(c->name, name, sizeof(c->name));
2199 	c->options = options;
2200 	c->user_specified = user_specified;
2201 	braille_set_options(c, brl_options);
2202 
2203 	c->index = idx;
2204 	return 0;
2205 }
2206 
console_msg_format_setup(char * str)2207 static int __init console_msg_format_setup(char *str)
2208 {
2209 	if (!strcmp(str, "syslog"))
2210 		console_msg_format = MSG_FORMAT_SYSLOG;
2211 	if (!strcmp(str, "default"))
2212 		console_msg_format = MSG_FORMAT_DEFAULT;
2213 	return 1;
2214 }
2215 __setup("console_msg_format=", console_msg_format_setup);
2216 
2217 /*
2218  * Set up a console.  Called via do_early_param() in init/main.c
2219  * for each "console=" parameter in the boot command line.
2220  */
console_setup(char * str)2221 static int __init console_setup(char *str)
2222 {
2223 	char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2224 	char *s, *options, *brl_options = NULL;
2225 	int idx;
2226 
2227 	/*
2228 	 * console="" or console=null have been suggested as a way to
2229 	 * disable console output. Use ttynull that has been created
2230 	 * for exacly this purpose.
2231 	 */
2232 	if (str[0] == 0 || strcmp(str, "null") == 0) {
2233 		__add_preferred_console("ttynull", 0, NULL, NULL, true);
2234 		return 1;
2235 	}
2236 
2237 	if (_braille_console_setup(&str, &brl_options))
2238 		return 1;
2239 
2240 	/*
2241 	 * Decode str into name, index, options.
2242 	 */
2243 	if (str[0] >= '0' && str[0] <= '9') {
2244 		strcpy(buf, "ttyS");
2245 		strncpy(buf + 4, str, sizeof(buf) - 5);
2246 	} else {
2247 		strncpy(buf, str, sizeof(buf) - 1);
2248 	}
2249 	buf[sizeof(buf) - 1] = 0;
2250 	options = strchr(str, ',');
2251 	if (options)
2252 		*(options++) = 0;
2253 #ifdef __sparc__
2254 	if (!strcmp(str, "ttya"))
2255 		strcpy(buf, "ttyS0");
2256 	if (!strcmp(str, "ttyb"))
2257 		strcpy(buf, "ttyS1");
2258 #endif
2259 	for (s = buf; *s; s++)
2260 		if (isdigit(*s) || *s == ',')
2261 			break;
2262 	idx = simple_strtoul(s, NULL, 10);
2263 	*s = 0;
2264 
2265 	__add_preferred_console(buf, idx, options, brl_options, true);
2266 	console_set_on_cmdline = 1;
2267 	return 1;
2268 }
2269 __setup("console=", console_setup);
2270 
2271 /**
2272  * add_preferred_console - add a device to the list of preferred consoles.
2273  * @name: device name
2274  * @idx: device index
2275  * @options: options for this console
2276  *
2277  * The last preferred console added will be used for kernel messages
2278  * and stdin/out/err for init.  Normally this is used by console_setup
2279  * above to handle user-supplied console arguments; however it can also
2280  * be used by arch-specific code either to override the user or more
2281  * commonly to provide a default console (ie from PROM variables) when
2282  * the user has not supplied one.
2283  */
add_preferred_console(char * name,int idx,char * options)2284 int add_preferred_console(char *name, int idx, char *options)
2285 {
2286 	return __add_preferred_console(name, idx, options, NULL, false);
2287 }
2288 
2289 bool console_suspend_enabled = true;
2290 EXPORT_SYMBOL(console_suspend_enabled);
2291 
console_suspend_disable(char * str)2292 static int __init console_suspend_disable(char *str)
2293 {
2294 	console_suspend_enabled = false;
2295 	return 1;
2296 }
2297 __setup("no_console_suspend", console_suspend_disable);
2298 module_param_named(console_suspend, console_suspend_enabled,
2299 		bool, S_IRUGO | S_IWUSR);
2300 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2301 	" and hibernate operations");
2302 
2303 /**
2304  * suspend_console - suspend the console subsystem
2305  *
2306  * This disables printk() while we go into suspend states
2307  */
suspend_console(void)2308 void suspend_console(void)
2309 {
2310 	if (!console_suspend_enabled)
2311 		return;
2312 	pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2313 	console_lock();
2314 	console_suspended = 1;
2315 	up_console_sem();
2316 }
2317 
resume_console(void)2318 void resume_console(void)
2319 {
2320 	if (!console_suspend_enabled)
2321 		return;
2322 	down_console_sem();
2323 	console_suspended = 0;
2324 	console_unlock();
2325 }
2326 
2327 /**
2328  * console_cpu_notify - print deferred console messages after CPU hotplug
2329  * @cpu: unused
2330  *
2331  * If printk() is called from a CPU that is not online yet, the messages
2332  * will be printed on the console only if there are CON_ANYTIME consoles.
2333  * This function is called when a new CPU comes online (or fails to come
2334  * up) or goes offline.
2335  */
console_cpu_notify(unsigned int cpu)2336 static int console_cpu_notify(unsigned int cpu)
2337 {
2338 	int flag = 0;
2339 
2340 	trace_android_vh_printk_hotplug(&flag);
2341 	if (flag)
2342 		return 0;
2343 
2344 	if (!cpuhp_tasks_frozen) {
2345 		/* If trylock fails, someone else is doing the printing */
2346 		if (console_trylock())
2347 			console_unlock();
2348 	}
2349 	return 0;
2350 }
2351 
2352 /**
2353  * console_lock - lock the console system for exclusive use.
2354  *
2355  * Acquires a lock which guarantees that the caller has
2356  * exclusive access to the console system and the console_drivers list.
2357  *
2358  * Can sleep, returns nothing.
2359  */
console_lock(void)2360 void console_lock(void)
2361 {
2362 	might_sleep();
2363 
2364 	down_console_sem();
2365 	if (console_suspended)
2366 		return;
2367 	console_locked = 1;
2368 	console_may_schedule = 1;
2369 }
2370 EXPORT_SYMBOL(console_lock);
2371 
2372 /**
2373  * console_trylock - try to lock the console system for exclusive use.
2374  *
2375  * Try to acquire a lock which guarantees that the caller has exclusive
2376  * access to the console system and the console_drivers list.
2377  *
2378  * returns 1 on success, and 0 on failure to acquire the lock.
2379  */
console_trylock(void)2380 int console_trylock(void)
2381 {
2382 	if (down_trylock_console_sem())
2383 		return 0;
2384 	if (console_suspended) {
2385 		up_console_sem();
2386 		return 0;
2387 	}
2388 	console_locked = 1;
2389 	console_may_schedule = 0;
2390 	return 1;
2391 }
2392 EXPORT_SYMBOL(console_trylock);
2393 
is_console_locked(void)2394 int is_console_locked(void)
2395 {
2396 	return console_locked;
2397 }
2398 EXPORT_SYMBOL(is_console_locked);
2399 
2400 /*
2401  * Check if we have any console that is capable of printing while cpu is
2402  * booting or shutting down. Requires console_sem.
2403  */
have_callable_console(void)2404 static int have_callable_console(void)
2405 {
2406 	struct console *con;
2407 
2408 	for_each_console(con)
2409 		if ((con->flags & CON_ENABLED) &&
2410 				(con->flags & CON_ANYTIME))
2411 			return 1;
2412 
2413 	return 0;
2414 }
2415 
2416 /*
2417  * Can we actually use the console at this time on this cpu?
2418  *
2419  * Console drivers may assume that per-cpu resources have been allocated. So
2420  * unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
2421  * call them until this CPU is officially up.
2422  */
can_use_console(void)2423 static inline int can_use_console(void)
2424 {
2425 	return cpu_online(raw_smp_processor_id()) || have_callable_console();
2426 }
2427 
2428 /**
2429  * console_unlock - unlock the console system
2430  *
2431  * Releases the console_lock which the caller holds on the console system
2432  * and the console driver list.
2433  *
2434  * While the console_lock was held, console output may have been buffered
2435  * by printk().  If this is the case, console_unlock(); emits
2436  * the output prior to releasing the lock.
2437  *
2438  * If there is output waiting, we wake /dev/kmsg and syslog() users.
2439  *
2440  * console_unlock(); may be called from any context.
2441  */
console_unlock(void)2442 void console_unlock(void)
2443 {
2444 	static char ext_text[CONSOLE_EXT_LOG_MAX];
2445 	static char text[LOG_LINE_MAX + PREFIX_MAX];
2446 	unsigned long flags;
2447 	bool do_cond_resched, retry;
2448 	struct printk_info info;
2449 	struct printk_record r;
2450 
2451 	if (console_suspended) {
2452 		up_console_sem();
2453 		return;
2454 	}
2455 
2456 	prb_rec_init_rd(&r, &info, text, sizeof(text));
2457 
2458 	/*
2459 	 * Console drivers are called with interrupts disabled, so
2460 	 * @console_may_schedule should be cleared before; however, we may
2461 	 * end up dumping a lot of lines, for example, if called from
2462 	 * console registration path, and should invoke cond_resched()
2463 	 * between lines if allowable.  Not doing so can cause a very long
2464 	 * scheduling stall on a slow console leading to RCU stall and
2465 	 * softlockup warnings which exacerbate the issue with more
2466 	 * messages practically incapacitating the system.
2467 	 *
2468 	 * console_trylock() is not able to detect the preemptive
2469 	 * context reliably. Therefore the value must be stored before
2470 	 * and cleared after the "again" goto label.
2471 	 */
2472 	do_cond_resched = console_may_schedule;
2473 again:
2474 	console_may_schedule = 0;
2475 
2476 	/*
2477 	 * We released the console_sem lock, so we need to recheck if
2478 	 * cpu is online and (if not) is there at least one CON_ANYTIME
2479 	 * console.
2480 	 */
2481 	if (!can_use_console()) {
2482 		console_locked = 0;
2483 		up_console_sem();
2484 		return;
2485 	}
2486 
2487 	for (;;) {
2488 		size_t ext_len = 0;
2489 		size_t len;
2490 
2491 		printk_safe_enter_irqsave(flags);
2492 		raw_spin_lock(&logbuf_lock);
2493 skip:
2494 		if (!prb_read_valid(prb, console_seq, &r))
2495 			break;
2496 
2497 		if (console_seq != r.info->seq) {
2498 			console_dropped += r.info->seq - console_seq;
2499 			console_seq = r.info->seq;
2500 		}
2501 
2502 		if (suppress_message_printing(r.info->level)) {
2503 			/*
2504 			 * Skip record we have buffered and already printed
2505 			 * directly to the console when we received it, and
2506 			 * record that has level above the console loglevel.
2507 			 */
2508 			console_seq++;
2509 			goto skip;
2510 		}
2511 
2512 		/* Output to all consoles once old messages replayed. */
2513 		if (unlikely(exclusive_console &&
2514 			     console_seq >= exclusive_console_stop_seq)) {
2515 			exclusive_console = NULL;
2516 		}
2517 
2518 		/*
2519 		 * Handle extended console text first because later
2520 		 * record_print_text() will modify the record buffer in-place.
2521 		 */
2522 		if (nr_ext_console_drivers) {
2523 			ext_len = info_print_ext_header(ext_text,
2524 						sizeof(ext_text),
2525 						r.info);
2526 			ext_len += msg_print_ext_body(ext_text + ext_len,
2527 						sizeof(ext_text) - ext_len,
2528 						&r.text_buf[0],
2529 						r.info->text_len,
2530 						&r.info->dev_info);
2531 		}
2532 		len = record_print_text(&r,
2533 				console_msg_format & MSG_FORMAT_SYSLOG,
2534 				printk_time);
2535 		console_seq++;
2536 		raw_spin_unlock(&logbuf_lock);
2537 
2538 		/*
2539 		 * While actively printing out messages, if another printk()
2540 		 * were to occur on another CPU, it may wait for this one to
2541 		 * finish. This task can not be preempted if there is a
2542 		 * waiter waiting to take over.
2543 		 */
2544 		console_lock_spinning_enable();
2545 
2546 		stop_critical_timings();	/* don't trace print latency */
2547 		call_console_drivers(ext_text, ext_len, text, len);
2548 		start_critical_timings();
2549 
2550 		if (console_lock_spinning_disable_and_check()) {
2551 			printk_safe_exit_irqrestore(flags);
2552 			return;
2553 		}
2554 
2555 		printk_safe_exit_irqrestore(flags);
2556 
2557 		if (do_cond_resched)
2558 			cond_resched();
2559 	}
2560 
2561 	console_locked = 0;
2562 
2563 	raw_spin_unlock(&logbuf_lock);
2564 
2565 	up_console_sem();
2566 
2567 	/*
2568 	 * Someone could have filled up the buffer again, so re-check if there's
2569 	 * something to flush. In case we cannot trylock the console_sem again,
2570 	 * there's a new owner and the console_unlock() from them will do the
2571 	 * flush, no worries.
2572 	 */
2573 	raw_spin_lock(&logbuf_lock);
2574 	retry = prb_read_valid(prb, console_seq, NULL);
2575 	raw_spin_unlock(&logbuf_lock);
2576 	printk_safe_exit_irqrestore(flags);
2577 
2578 	if (retry && console_trylock())
2579 		goto again;
2580 }
2581 EXPORT_SYMBOL(console_unlock);
2582 
2583 /**
2584  * console_conditional_schedule - yield the CPU if required
2585  *
2586  * If the console code is currently allowed to sleep, and
2587  * if this CPU should yield the CPU to another task, do
2588  * so here.
2589  *
2590  * Must be called within console_lock();.
2591  */
console_conditional_schedule(void)2592 void __sched console_conditional_schedule(void)
2593 {
2594 	if (console_may_schedule)
2595 		cond_resched();
2596 }
2597 EXPORT_SYMBOL(console_conditional_schedule);
2598 
console_unblank(void)2599 void console_unblank(void)
2600 {
2601 	struct console *c;
2602 
2603 	/*
2604 	 * console_unblank can no longer be called in interrupt context unless
2605 	 * oops_in_progress is set to 1..
2606 	 */
2607 	if (oops_in_progress) {
2608 		if (down_trylock_console_sem() != 0)
2609 			return;
2610 	} else
2611 		console_lock();
2612 
2613 	console_locked = 1;
2614 	console_may_schedule = 0;
2615 	for_each_console(c)
2616 		if ((c->flags & CON_ENABLED) && c->unblank)
2617 			c->unblank();
2618 	console_unlock();
2619 }
2620 
2621 /**
2622  * console_flush_on_panic - flush console content on panic
2623  * @mode: flush all messages in buffer or just the pending ones
2624  *
2625  * Immediately output all pending messages no matter what.
2626  */
console_flush_on_panic(enum con_flush_mode mode)2627 void console_flush_on_panic(enum con_flush_mode mode)
2628 {
2629 	/*
2630 	 * If someone else is holding the console lock, trylock will fail
2631 	 * and may_schedule may be set.  Ignore and proceed to unlock so
2632 	 * that messages are flushed out.  As this can be called from any
2633 	 * context and we don't want to get preempted while flushing,
2634 	 * ensure may_schedule is cleared.
2635 	 */
2636 	console_trylock();
2637 	console_may_schedule = 0;
2638 
2639 	if (mode == CONSOLE_REPLAY_ALL) {
2640 		unsigned long flags;
2641 
2642 		logbuf_lock_irqsave(flags);
2643 		console_seq = prb_first_valid_seq(prb);
2644 		logbuf_unlock_irqrestore(flags);
2645 	}
2646 	console_unlock();
2647 }
2648 
2649 /*
2650  * Return the console tty driver structure and its associated index
2651  */
console_device(int * index)2652 struct tty_driver *console_device(int *index)
2653 {
2654 	struct console *c;
2655 	struct tty_driver *driver = NULL;
2656 
2657 	console_lock();
2658 	for_each_console(c) {
2659 		if (!c->device)
2660 			continue;
2661 		driver = c->device(c, index);
2662 		if (driver)
2663 			break;
2664 	}
2665 	console_unlock();
2666 	return driver;
2667 }
2668 
2669 /*
2670  * Prevent further output on the passed console device so that (for example)
2671  * serial drivers can disable console output before suspending a port, and can
2672  * re-enable output afterwards.
2673  */
console_stop(struct console * console)2674 void console_stop(struct console *console)
2675 {
2676 	console_lock();
2677 	console->flags &= ~CON_ENABLED;
2678 	console_unlock();
2679 }
2680 EXPORT_SYMBOL(console_stop);
2681 
console_start(struct console * console)2682 void console_start(struct console *console)
2683 {
2684 	console_lock();
2685 	console->flags |= CON_ENABLED;
2686 	console_unlock();
2687 }
2688 EXPORT_SYMBOL(console_start);
2689 
2690 static int __read_mostly keep_bootcon;
2691 
keep_bootcon_setup(char * str)2692 static int __init keep_bootcon_setup(char *str)
2693 {
2694 	keep_bootcon = 1;
2695 	pr_info("debug: skip boot console de-registration.\n");
2696 
2697 	return 0;
2698 }
2699 
2700 early_param("keep_bootcon", keep_bootcon_setup);
2701 
2702 /*
2703  * This is called by register_console() to try to match
2704  * the newly registered console with any of the ones selected
2705  * by either the command line or add_preferred_console() and
2706  * setup/enable it.
2707  *
2708  * Care need to be taken with consoles that are statically
2709  * enabled such as netconsole
2710  */
try_enable_new_console(struct console * newcon,bool user_specified)2711 static int try_enable_new_console(struct console *newcon, bool user_specified)
2712 {
2713 	struct console_cmdline *c;
2714 	int i, err;
2715 
2716 	for (i = 0, c = console_cmdline;
2717 	     i < MAX_CMDLINECONSOLES && c->name[0];
2718 	     i++, c++) {
2719 		if (c->user_specified != user_specified)
2720 			continue;
2721 		if (!newcon->match ||
2722 		    newcon->match(newcon, c->name, c->index, c->options) != 0) {
2723 			/* default matching */
2724 			BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
2725 			if (strcmp(c->name, newcon->name) != 0)
2726 				continue;
2727 			if (newcon->index >= 0 &&
2728 			    newcon->index != c->index)
2729 				continue;
2730 			if (newcon->index < 0)
2731 				newcon->index = c->index;
2732 
2733 			if (_braille_register_console(newcon, c))
2734 				return 0;
2735 
2736 			if (newcon->setup &&
2737 			    (err = newcon->setup(newcon, c->options)) != 0)
2738 				return err;
2739 		}
2740 		newcon->flags |= CON_ENABLED;
2741 		if (i == preferred_console) {
2742 			newcon->flags |= CON_CONSDEV;
2743 			has_preferred_console = true;
2744 		}
2745 		return 0;
2746 	}
2747 
2748 	/*
2749 	 * Some consoles, such as pstore and netconsole, can be enabled even
2750 	 * without matching. Accept the pre-enabled consoles only when match()
2751 	 * and setup() had a chance to be called.
2752 	 */
2753 	if (newcon->flags & CON_ENABLED && c->user_specified ==	user_specified)
2754 		return 0;
2755 
2756 	return -ENOENT;
2757 }
2758 
2759 /*
2760  * The console driver calls this routine during kernel initialization
2761  * to register the console printing procedure with printk() and to
2762  * print any messages that were printed by the kernel before the
2763  * console driver was initialized.
2764  *
2765  * This can happen pretty early during the boot process (because of
2766  * early_printk) - sometimes before setup_arch() completes - be careful
2767  * of what kernel features are used - they may not be initialised yet.
2768  *
2769  * There are two types of consoles - bootconsoles (early_printk) and
2770  * "real" consoles (everything which is not a bootconsole) which are
2771  * handled differently.
2772  *  - Any number of bootconsoles can be registered at any time.
2773  *  - As soon as a "real" console is registered, all bootconsoles
2774  *    will be unregistered automatically.
2775  *  - Once a "real" console is registered, any attempt to register a
2776  *    bootconsoles will be rejected
2777  */
register_console(struct console * newcon)2778 void register_console(struct console *newcon)
2779 {
2780 	unsigned long flags;
2781 	struct console *bcon = NULL;
2782 	int err;
2783 
2784 	for_each_console(bcon) {
2785 		if (WARN(bcon == newcon, "console '%s%d' already registered\n",
2786 					 bcon->name, bcon->index))
2787 			return;
2788 	}
2789 
2790 	/*
2791 	 * before we register a new CON_BOOT console, make sure we don't
2792 	 * already have a valid console
2793 	 */
2794 	if (newcon->flags & CON_BOOT) {
2795 		for_each_console(bcon) {
2796 			if (!(bcon->flags & CON_BOOT)) {
2797 				pr_info("Too late to register bootconsole %s%d\n",
2798 					newcon->name, newcon->index);
2799 				return;
2800 			}
2801 		}
2802 	}
2803 
2804 	if (console_drivers && console_drivers->flags & CON_BOOT)
2805 		bcon = console_drivers;
2806 
2807 	if (!has_preferred_console || bcon || !console_drivers)
2808 		has_preferred_console = preferred_console >= 0;
2809 
2810 	/*
2811 	 *	See if we want to use this console driver. If we
2812 	 *	didn't select a console we take the first one
2813 	 *	that registers here.
2814 	 */
2815 	if (!has_preferred_console) {
2816 		if (newcon->index < 0)
2817 			newcon->index = 0;
2818 		if (newcon->setup == NULL ||
2819 		    newcon->setup(newcon, NULL) == 0) {
2820 			newcon->flags |= CON_ENABLED;
2821 			if (newcon->device) {
2822 				newcon->flags |= CON_CONSDEV;
2823 				has_preferred_console = true;
2824 			}
2825 		}
2826 	}
2827 
2828 	/* See if this console matches one we selected on the command line */
2829 	err = try_enable_new_console(newcon, true);
2830 
2831 	/* If not, try to match against the platform default(s) */
2832 	if (err == -ENOENT)
2833 		err = try_enable_new_console(newcon, false);
2834 
2835 	/* printk() messages are not printed to the Braille console. */
2836 	if (err || newcon->flags & CON_BRL)
2837 		return;
2838 
2839 	/*
2840 	 * If we have a bootconsole, and are switching to a real console,
2841 	 * don't print everything out again, since when the boot console, and
2842 	 * the real console are the same physical device, it's annoying to
2843 	 * see the beginning boot messages twice
2844 	 */
2845 	if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
2846 		newcon->flags &= ~CON_PRINTBUFFER;
2847 
2848 	/*
2849 	 *	Put this console in the list - keep the
2850 	 *	preferred driver at the head of the list.
2851 	 */
2852 	console_lock();
2853 	if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2854 		newcon->next = console_drivers;
2855 		console_drivers = newcon;
2856 		if (newcon->next)
2857 			newcon->next->flags &= ~CON_CONSDEV;
2858 		/* Ensure this flag is always set for the head of the list */
2859 		newcon->flags |= CON_CONSDEV;
2860 	} else {
2861 		newcon->next = console_drivers->next;
2862 		console_drivers->next = newcon;
2863 	}
2864 
2865 	if (newcon->flags & CON_EXTENDED)
2866 		nr_ext_console_drivers++;
2867 
2868 	if (newcon->flags & CON_PRINTBUFFER) {
2869 		/*
2870 		 * console_unlock(); will print out the buffered messages
2871 		 * for us.
2872 		 */
2873 		logbuf_lock_irqsave(flags);
2874 		/*
2875 		 * We're about to replay the log buffer.  Only do this to the
2876 		 * just-registered console to avoid excessive message spam to
2877 		 * the already-registered consoles.
2878 		 *
2879 		 * Set exclusive_console with disabled interrupts to reduce
2880 		 * race window with eventual console_flush_on_panic() that
2881 		 * ignores console_lock.
2882 		 */
2883 		exclusive_console = newcon;
2884 		exclusive_console_stop_seq = console_seq;
2885 		console_seq = syslog_seq;
2886 		logbuf_unlock_irqrestore(flags);
2887 	}
2888 	console_unlock();
2889 	console_sysfs_notify();
2890 
2891 	/*
2892 	 * By unregistering the bootconsoles after we enable the real console
2893 	 * we get the "console xxx enabled" message on all the consoles -
2894 	 * boot consoles, real consoles, etc - this is to ensure that end
2895 	 * users know there might be something in the kernel's log buffer that
2896 	 * went to the bootconsole (that they do not see on the real console)
2897 	 */
2898 	pr_info("%sconsole [%s%d] enabled\n",
2899 		(newcon->flags & CON_BOOT) ? "boot" : "" ,
2900 		newcon->name, newcon->index);
2901 	if (bcon &&
2902 	    ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2903 	    !keep_bootcon) {
2904 		/* We need to iterate through all boot consoles, to make
2905 		 * sure we print everything out, before we unregister them.
2906 		 */
2907 		for_each_console(bcon)
2908 			if (bcon->flags & CON_BOOT)
2909 				unregister_console(bcon);
2910 	}
2911 }
2912 EXPORT_SYMBOL(register_console);
2913 
unregister_console(struct console * console)2914 int unregister_console(struct console *console)
2915 {
2916 	struct console *con;
2917 	int res;
2918 
2919 	pr_info("%sconsole [%s%d] disabled\n",
2920 		(console->flags & CON_BOOT) ? "boot" : "" ,
2921 		console->name, console->index);
2922 
2923 	res = _braille_unregister_console(console);
2924 	if (res < 0)
2925 		return res;
2926 	if (res > 0)
2927 		return 0;
2928 
2929 	res = -ENODEV;
2930 	console_lock();
2931 	if (console_drivers == console) {
2932 		console_drivers=console->next;
2933 		res = 0;
2934 	} else {
2935 		for_each_console(con) {
2936 			if (con->next == console) {
2937 				con->next = console->next;
2938 				res = 0;
2939 				break;
2940 			}
2941 		}
2942 	}
2943 
2944 	if (res)
2945 		goto out_disable_unlock;
2946 
2947 	if (console->flags & CON_EXTENDED)
2948 		nr_ext_console_drivers--;
2949 
2950 	/*
2951 	 * If this isn't the last console and it has CON_CONSDEV set, we
2952 	 * need to set it on the next preferred console.
2953 	 */
2954 	if (console_drivers != NULL && console->flags & CON_CONSDEV)
2955 		console_drivers->flags |= CON_CONSDEV;
2956 
2957 	console->flags &= ~CON_ENABLED;
2958 	console_unlock();
2959 	console_sysfs_notify();
2960 
2961 	if (console->exit)
2962 		res = console->exit(console);
2963 
2964 	return res;
2965 
2966 out_disable_unlock:
2967 	console->flags &= ~CON_ENABLED;
2968 	console_unlock();
2969 
2970 	return res;
2971 }
2972 EXPORT_SYMBOL(unregister_console);
2973 
2974 /*
2975  * Initialize the console device. This is called *early*, so
2976  * we can't necessarily depend on lots of kernel help here.
2977  * Just do some early initializations, and do the complex setup
2978  * later.
2979  */
console_init(void)2980 void __init console_init(void)
2981 {
2982 	int ret;
2983 	initcall_t call;
2984 	initcall_entry_t *ce;
2985 
2986 	/* Setup the default TTY line discipline. */
2987 	n_tty_init();
2988 
2989 	/*
2990 	 * set up the console device so that later boot sequences can
2991 	 * inform about problems etc..
2992 	 */
2993 	ce = __con_initcall_start;
2994 	trace_initcall_level("console");
2995 	while (ce < __con_initcall_end) {
2996 		call = initcall_from_entry(ce);
2997 		trace_initcall_start(call);
2998 		ret = call();
2999 		trace_initcall_finish(call, ret);
3000 		ce++;
3001 	}
3002 }
3003 
3004 /*
3005  * Some boot consoles access data that is in the init section and which will
3006  * be discarded after the initcalls have been run. To make sure that no code
3007  * will access this data, unregister the boot consoles in a late initcall.
3008  *
3009  * If for some reason, such as deferred probe or the driver being a loadable
3010  * module, the real console hasn't registered yet at this point, there will
3011  * be a brief interval in which no messages are logged to the console, which
3012  * makes it difficult to diagnose problems that occur during this time.
3013  *
3014  * To mitigate this problem somewhat, only unregister consoles whose memory
3015  * intersects with the init section. Note that all other boot consoles will
3016  * get unregistred when the real preferred console is registered.
3017  */
printk_late_init(void)3018 static int __init printk_late_init(void)
3019 {
3020 	struct console *con;
3021 	int ret;
3022 
3023 	for_each_console(con) {
3024 		if (!(con->flags & CON_BOOT))
3025 			continue;
3026 
3027 		/* Check addresses that might be used for enabled consoles. */
3028 		if (init_section_intersects(con, sizeof(*con)) ||
3029 		    init_section_contains(con->write, 0) ||
3030 		    init_section_contains(con->read, 0) ||
3031 		    init_section_contains(con->device, 0) ||
3032 		    init_section_contains(con->unblank, 0) ||
3033 		    init_section_contains(con->data, 0)) {
3034 			/*
3035 			 * Please, consider moving the reported consoles out
3036 			 * of the init section.
3037 			 */
3038 			pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3039 				con->name, con->index);
3040 			unregister_console(con);
3041 		}
3042 	}
3043 	ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3044 					console_cpu_notify);
3045 	WARN_ON(ret < 0);
3046 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3047 					console_cpu_notify, NULL);
3048 	WARN_ON(ret < 0);
3049 	return 0;
3050 }
3051 late_initcall(printk_late_init);
3052 
3053 #if defined CONFIG_PRINTK
3054 /*
3055  * Delayed printk version, for scheduler-internal messages:
3056  */
3057 #define PRINTK_PENDING_WAKEUP	0x01
3058 #define PRINTK_PENDING_OUTPUT	0x02
3059 
3060 static DEFINE_PER_CPU(int, printk_pending);
3061 
wake_up_klogd_work_func(struct irq_work * irq_work)3062 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3063 {
3064 	int pending = __this_cpu_xchg(printk_pending, 0);
3065 
3066 	if (pending & PRINTK_PENDING_OUTPUT) {
3067 		/* If trylock fails, someone else is doing the printing */
3068 		if (console_trylock())
3069 			console_unlock();
3070 	}
3071 
3072 	if (pending & PRINTK_PENDING_WAKEUP)
3073 		wake_up_interruptible(&log_wait);
3074 }
3075 
3076 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
3077 	.func = wake_up_klogd_work_func,
3078 	.flags = ATOMIC_INIT(IRQ_WORK_LAZY),
3079 };
3080 
wake_up_klogd(void)3081 void wake_up_klogd(void)
3082 {
3083 	if (!printk_percpu_data_ready())
3084 		return;
3085 
3086 	preempt_disable();
3087 	if (waitqueue_active(&log_wait)) {
3088 		this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
3089 		irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3090 	}
3091 	preempt_enable();
3092 }
3093 
defer_console_output(void)3094 void defer_console_output(void)
3095 {
3096 	if (!printk_percpu_data_ready())
3097 		return;
3098 
3099 	preempt_disable();
3100 	__this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
3101 	irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3102 	preempt_enable();
3103 }
3104 
vprintk_deferred(const char * fmt,va_list args)3105 int vprintk_deferred(const char *fmt, va_list args)
3106 {
3107 	int r;
3108 
3109 	r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
3110 	defer_console_output();
3111 
3112 	return r;
3113 }
3114 
printk_deferred(const char * fmt,...)3115 int printk_deferred(const char *fmt, ...)
3116 {
3117 	va_list args;
3118 	int r;
3119 
3120 	va_start(args, fmt);
3121 	r = vprintk_deferred(fmt, args);
3122 	va_end(args);
3123 
3124 	return r;
3125 }
3126 EXPORT_SYMBOL_GPL(printk_deferred);
3127 
3128 /*
3129  * printk rate limiting, lifted from the networking subsystem.
3130  *
3131  * This enforces a rate limit: not more than 10 kernel messages
3132  * every 5s to make a denial-of-service attack impossible.
3133  */
3134 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3135 
__printk_ratelimit(const char * func)3136 int __printk_ratelimit(const char *func)
3137 {
3138 	return ___ratelimit(&printk_ratelimit_state, func);
3139 }
3140 EXPORT_SYMBOL(__printk_ratelimit);
3141 
3142 /**
3143  * printk_timed_ratelimit - caller-controlled printk ratelimiting
3144  * @caller_jiffies: pointer to caller's state
3145  * @interval_msecs: minimum interval between prints
3146  *
3147  * printk_timed_ratelimit() returns true if more than @interval_msecs
3148  * milliseconds have elapsed since the last time printk_timed_ratelimit()
3149  * returned true.
3150  */
printk_timed_ratelimit(unsigned long * caller_jiffies,unsigned int interval_msecs)3151 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
3152 			unsigned int interval_msecs)
3153 {
3154 	unsigned long elapsed = jiffies - *caller_jiffies;
3155 
3156 	if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
3157 		return false;
3158 
3159 	*caller_jiffies = jiffies;
3160 	return true;
3161 }
3162 EXPORT_SYMBOL(printk_timed_ratelimit);
3163 
3164 static DEFINE_SPINLOCK(dump_list_lock);
3165 static LIST_HEAD(dump_list);
3166 
3167 /**
3168  * kmsg_dump_register - register a kernel log dumper.
3169  * @dumper: pointer to the kmsg_dumper structure
3170  *
3171  * Adds a kernel log dumper to the system. The dump callback in the
3172  * structure will be called when the kernel oopses or panics and must be
3173  * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
3174  */
kmsg_dump_register(struct kmsg_dumper * dumper)3175 int kmsg_dump_register(struct kmsg_dumper *dumper)
3176 {
3177 	unsigned long flags;
3178 	int err = -EBUSY;
3179 
3180 	/* The dump callback needs to be set */
3181 	if (!dumper->dump)
3182 		return -EINVAL;
3183 
3184 	spin_lock_irqsave(&dump_list_lock, flags);
3185 	/* Don't allow registering multiple times */
3186 	if (!dumper->registered) {
3187 		dumper->registered = 1;
3188 		list_add_tail_rcu(&dumper->list, &dump_list);
3189 		err = 0;
3190 	}
3191 	spin_unlock_irqrestore(&dump_list_lock, flags);
3192 
3193 	return err;
3194 }
3195 EXPORT_SYMBOL_GPL(kmsg_dump_register);
3196 
3197 /**
3198  * kmsg_dump_unregister - unregister a kmsg dumper.
3199  * @dumper: pointer to the kmsg_dumper structure
3200  *
3201  * Removes a dump device from the system. Returns zero on success and
3202  * %-EINVAL otherwise.
3203  */
kmsg_dump_unregister(struct kmsg_dumper * dumper)3204 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
3205 {
3206 	unsigned long flags;
3207 	int err = -EINVAL;
3208 
3209 	spin_lock_irqsave(&dump_list_lock, flags);
3210 	if (dumper->registered) {
3211 		dumper->registered = 0;
3212 		list_del_rcu(&dumper->list);
3213 		err = 0;
3214 	}
3215 	spin_unlock_irqrestore(&dump_list_lock, flags);
3216 	synchronize_rcu();
3217 
3218 	return err;
3219 }
3220 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
3221 
3222 static bool always_kmsg_dump;
3223 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
3224 
kmsg_dump_reason_str(enum kmsg_dump_reason reason)3225 const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
3226 {
3227 	switch (reason) {
3228 	case KMSG_DUMP_PANIC:
3229 		return "Panic";
3230 	case KMSG_DUMP_OOPS:
3231 		return "Oops";
3232 	case KMSG_DUMP_EMERG:
3233 		return "Emergency";
3234 	case KMSG_DUMP_SHUTDOWN:
3235 		return "Shutdown";
3236 	default:
3237 		return "Unknown";
3238 	}
3239 }
3240 EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
3241 
3242 /**
3243  * kmsg_dump - dump kernel log to kernel message dumpers.
3244  * @reason: the reason (oops, panic etc) for dumping
3245  *
3246  * Call each of the registered dumper's dump() callback, which can
3247  * retrieve the kmsg records with kmsg_dump_get_line() or
3248  * kmsg_dump_get_buffer().
3249  */
kmsg_dump(enum kmsg_dump_reason reason)3250 void kmsg_dump(enum kmsg_dump_reason reason)
3251 {
3252 	struct kmsg_dumper *dumper;
3253 	unsigned long flags;
3254 
3255 	rcu_read_lock();
3256 	list_for_each_entry_rcu(dumper, &dump_list, list) {
3257 		enum kmsg_dump_reason max_reason = dumper->max_reason;
3258 
3259 		/*
3260 		 * If client has not provided a specific max_reason, default
3261 		 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
3262 		 */
3263 		if (max_reason == KMSG_DUMP_UNDEF) {
3264 			max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
3265 							KMSG_DUMP_OOPS;
3266 		}
3267 		if (reason > max_reason)
3268 			continue;
3269 
3270 		/* initialize iterator with data about the stored records */
3271 		dumper->active = true;
3272 
3273 		logbuf_lock_irqsave(flags);
3274 		dumper->cur_seq = clear_seq;
3275 		dumper->next_seq = prb_next_seq(prb);
3276 		logbuf_unlock_irqrestore(flags);
3277 
3278 		/* invoke dumper which will iterate over records */
3279 		dumper->dump(dumper, reason);
3280 
3281 		/* reset iterator */
3282 		dumper->active = false;
3283 	}
3284 	rcu_read_unlock();
3285 }
3286 
3287 /**
3288  * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
3289  * @dumper: registered kmsg dumper
3290  * @syslog: include the "<4>" prefixes
3291  * @line: buffer to copy the line to
3292  * @size: maximum size of the buffer
3293  * @len: length of line placed into buffer
3294  *
3295  * Start at the beginning of the kmsg buffer, with the oldest kmsg
3296  * record, and copy one record into the provided buffer.
3297  *
3298  * Consecutive calls will return the next available record moving
3299  * towards the end of the buffer with the youngest messages.
3300  *
3301  * A return value of FALSE indicates that there are no more records to
3302  * read.
3303  *
3304  * The function is similar to kmsg_dump_get_line(), but grabs no locks.
3305  */
kmsg_dump_get_line_nolock(struct kmsg_dumper * dumper,bool syslog,char * line,size_t size,size_t * len)3306 bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
3307 			       char *line, size_t size, size_t *len)
3308 {
3309 	struct printk_info info;
3310 	unsigned int line_count;
3311 	struct printk_record r;
3312 	size_t l = 0;
3313 	bool ret = false;
3314 
3315 	prb_rec_init_rd(&r, &info, line, size);
3316 
3317 	if (!dumper->active)
3318 		goto out;
3319 
3320 	/* Read text or count text lines? */
3321 	if (line) {
3322 		if (!prb_read_valid(prb, dumper->cur_seq, &r))
3323 			goto out;
3324 		l = record_print_text(&r, syslog, printk_time);
3325 	} else {
3326 		if (!prb_read_valid_info(prb, dumper->cur_seq,
3327 					 &info, &line_count)) {
3328 			goto out;
3329 		}
3330 		l = get_record_print_text_size(&info, line_count, syslog,
3331 					       printk_time);
3332 
3333 	}
3334 
3335 	dumper->cur_seq = r.info->seq + 1;
3336 	ret = true;
3337 out:
3338 	if (len)
3339 		*len = l;
3340 	return ret;
3341 }
3342 
3343 /**
3344  * kmsg_dump_get_line - retrieve one kmsg log line
3345  * @dumper: registered kmsg dumper
3346  * @syslog: include the "<4>" prefixes
3347  * @line: buffer to copy the line to
3348  * @size: maximum size of the buffer
3349  * @len: length of line placed into buffer
3350  *
3351  * Start at the beginning of the kmsg buffer, with the oldest kmsg
3352  * record, and copy one record into the provided buffer.
3353  *
3354  * Consecutive calls will return the next available record moving
3355  * towards the end of the buffer with the youngest messages.
3356  *
3357  * A return value of FALSE indicates that there are no more records to
3358  * read.
3359  */
kmsg_dump_get_line(struct kmsg_dumper * dumper,bool syslog,char * line,size_t size,size_t * len)3360 bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
3361 			char *line, size_t size, size_t *len)
3362 {
3363 	unsigned long flags;
3364 	bool ret;
3365 
3366 	logbuf_lock_irqsave(flags);
3367 	ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
3368 	logbuf_unlock_irqrestore(flags);
3369 
3370 	return ret;
3371 }
3372 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
3373 
3374 /**
3375  * kmsg_dump_get_buffer - copy kmsg log lines
3376  * @dumper: registered kmsg dumper
3377  * @syslog: include the "<4>" prefixes
3378  * @buf: buffer to copy the line to
3379  * @size: maximum size of the buffer
3380  * @len: length of line placed into buffer
3381  *
3382  * Start at the end of the kmsg buffer and fill the provided buffer
3383  * with as many of the *youngest* kmsg records that fit into it.
3384  * If the buffer is large enough, all available kmsg records will be
3385  * copied with a single call.
3386  *
3387  * Consecutive calls will fill the buffer with the next block of
3388  * available older records, not including the earlier retrieved ones.
3389  *
3390  * A return value of FALSE indicates that there are no more records to
3391  * read.
3392  */
kmsg_dump_get_buffer(struct kmsg_dumper * dumper,bool syslog,char * buf,size_t size,size_t * len)3393 bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
3394 			  char *buf, size_t size, size_t *len)
3395 {
3396 	struct printk_info info;
3397 	unsigned int line_count;
3398 	struct printk_record r;
3399 	unsigned long flags;
3400 	u64 seq;
3401 	u64 next_seq;
3402 	size_t l = 0;
3403 	bool ret = false;
3404 	bool time = printk_time;
3405 
3406 	prb_rec_init_rd(&r, &info, buf, size);
3407 
3408 	if (!dumper->active || !buf || !size)
3409 		goto out;
3410 
3411 	logbuf_lock_irqsave(flags);
3412 	if (prb_read_valid_info(prb, dumper->cur_seq, &info, NULL)) {
3413 		if (info.seq != dumper->cur_seq) {
3414 			/* messages are gone, move to first available one */
3415 			dumper->cur_seq = info.seq;
3416 		}
3417 	}
3418 
3419 	/* last entry */
3420 	if (dumper->cur_seq >= dumper->next_seq) {
3421 		logbuf_unlock_irqrestore(flags);
3422 		goto out;
3423 	}
3424 
3425 	/* calculate length of entire buffer */
3426 	seq = dumper->cur_seq;
3427 	while (prb_read_valid_info(prb, seq, &info, &line_count)) {
3428 		if (r.info->seq >= dumper->next_seq)
3429 			break;
3430 		l += get_record_print_text_size(&info, line_count, syslog, time);
3431 		seq = r.info->seq + 1;
3432 	}
3433 
3434 	/* move first record forward until length fits into the buffer */
3435 	seq = dumper->cur_seq;
3436 	while (l >= size && prb_read_valid_info(prb, seq,
3437 						&info, &line_count)) {
3438 		if (r.info->seq >= dumper->next_seq)
3439 			break;
3440 		l -= get_record_print_text_size(&info, line_count, syslog, time);
3441 		seq = r.info->seq + 1;
3442 	}
3443 
3444 	/* last message in next interation */
3445 	next_seq = seq;
3446 
3447 	/* actually read text into the buffer now */
3448 	l = 0;
3449 	while (prb_read_valid(prb, seq, &r)) {
3450 		if (r.info->seq >= dumper->next_seq)
3451 			break;
3452 
3453 		l += record_print_text(&r, syslog, time);
3454 
3455 		/* adjust record to store to remaining buffer space */
3456 		prb_rec_init_rd(&r, &info, buf + l, size - l);
3457 
3458 		seq = r.info->seq + 1;
3459 	}
3460 
3461 	dumper->next_seq = next_seq;
3462 	ret = true;
3463 	logbuf_unlock_irqrestore(flags);
3464 out:
3465 	if (len)
3466 		*len = l;
3467 	return ret;
3468 }
3469 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
3470 
3471 /**
3472  * kmsg_dump_rewind_nolock - reset the iterator (unlocked version)
3473  * @dumper: registered kmsg dumper
3474  *
3475  * Reset the dumper's iterator so that kmsg_dump_get_line() and
3476  * kmsg_dump_get_buffer() can be called again and used multiple
3477  * times within the same dumper.dump() callback.
3478  *
3479  * The function is similar to kmsg_dump_rewind(), but grabs no locks.
3480  */
kmsg_dump_rewind_nolock(struct kmsg_dumper * dumper)3481 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
3482 {
3483 	dumper->cur_seq = clear_seq;
3484 	dumper->next_seq = prb_next_seq(prb);
3485 }
3486 
3487 /**
3488  * kmsg_dump_rewind - reset the iterator
3489  * @dumper: registered kmsg dumper
3490  *
3491  * Reset the dumper's iterator so that kmsg_dump_get_line() and
3492  * kmsg_dump_get_buffer() can be called again and used multiple
3493  * times within the same dumper.dump() callback.
3494  */
kmsg_dump_rewind(struct kmsg_dumper * dumper)3495 void kmsg_dump_rewind(struct kmsg_dumper *dumper)
3496 {
3497 	unsigned long flags;
3498 
3499 	logbuf_lock_irqsave(flags);
3500 	kmsg_dump_rewind_nolock(dumper);
3501 	logbuf_unlock_irqrestore(flags);
3502 }
3503 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
3504 
3505 #endif
3506