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