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