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