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