1 // SPDX-License-Identifier: GPL-2.0-only
3 * linux/kernel/printk.c
5 * Copyright (C) 1991, 1992 Linus Torvalds
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).
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
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22 #include <linux/kernel.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>
51 #include <linux/uaccess.h>
52 #include <asm/sections.h>
54 #include <trace/events/initcall.h>
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/printk.h>
58 #include "printk_ringbuffer.h"
59 #include "console_cmdline.h"
63 int console_printk[4] = {
64 CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
65 MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
66 CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
67 CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
69 EXPORT_SYMBOL_GPL(console_printk);
71 atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
72 EXPORT_SYMBOL(ignore_console_lock_warning);
75 * Low level drivers may need that to know if they can schedule in
76 * their unblank() callback or not. So let's export it.
79 EXPORT_SYMBOL(oops_in_progress);
82 * console_sem protects the console_drivers list, and also
83 * provides serialisation for access to the entire console
86 static DEFINE_SEMAPHORE(console_sem);
87 struct console *console_drivers;
88 EXPORT_SYMBOL_GPL(console_drivers);
91 * System may need to suppress printk message under certain
92 * circumstances, like after kernel panic happens.
94 int __read_mostly suppress_printk;
97 * During panic, heavy printk by other CPUs can delay the
98 * panic and risk deadlock on console resources.
100 static int __read_mostly suppress_panic_printk;
102 #ifdef CONFIG_LOCKDEP
103 static struct lockdep_map console_lock_dep_map = {
104 .name = "console_lock"
108 enum devkmsg_log_bits {
109 __DEVKMSG_LOG_BIT_ON = 0,
110 __DEVKMSG_LOG_BIT_OFF,
111 __DEVKMSG_LOG_BIT_LOCK,
114 enum devkmsg_log_masks {
115 DEVKMSG_LOG_MASK_ON = BIT(__DEVKMSG_LOG_BIT_ON),
116 DEVKMSG_LOG_MASK_OFF = BIT(__DEVKMSG_LOG_BIT_OFF),
117 DEVKMSG_LOG_MASK_LOCK = BIT(__DEVKMSG_LOG_BIT_LOCK),
120 /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
121 #define DEVKMSG_LOG_MASK_DEFAULT 0
123 static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
125 static int __control_devkmsg(char *str)
132 len = str_has_prefix(str, "on");
134 devkmsg_log = DEVKMSG_LOG_MASK_ON;
138 len = str_has_prefix(str, "off");
140 devkmsg_log = DEVKMSG_LOG_MASK_OFF;
144 len = str_has_prefix(str, "ratelimit");
146 devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
153 static int __init control_devkmsg(char *str)
155 if (__control_devkmsg(str) < 0) {
156 pr_warn("printk.devkmsg: bad option string '%s'\n", str);
161 * Set sysctl string accordingly:
163 if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
164 strcpy(devkmsg_log_str, "on");
165 else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
166 strcpy(devkmsg_log_str, "off");
167 /* else "ratelimit" which is set by default. */
170 * Sysctl cannot change it anymore. The kernel command line setting of
171 * this parameter is to force the setting to be permanent throughout the
172 * runtime of the system. This is a precation measure against userspace
173 * trying to be a smarta** and attempting to change it up on us.
175 devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
179 __setup("printk.devkmsg=", control_devkmsg);
181 char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
182 #if defined(CONFIG_PRINTK) && defined(CONFIG_SYSCTL)
183 int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
184 void *buffer, size_t *lenp, loff_t *ppos)
186 char old_str[DEVKMSG_STR_MAX_SIZE];
191 if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
195 strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
198 err = proc_dostring(table, write, buffer, lenp, ppos);
203 err = __control_devkmsg(devkmsg_log_str);
206 * Do not accept an unknown string OR a known string with
209 if (err < 0 || (err + 1 != *lenp)) {
211 /* ... and restore old setting. */
213 strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
221 #endif /* CONFIG_PRINTK && CONFIG_SYSCTL */
223 /* Number of registered extended console drivers. */
224 static int nr_ext_console_drivers;
227 * Used to synchronize printing kthreads against direct printing via
228 * console_trylock/console_unlock.
231 * -1 = console kthreads atomically blocked (via global trylock)
232 * 0 = no kthread printing, console not locked (via trylock)
233 * >0 = kthread(s) actively printing
235 * Note: For synchronizing against direct printing via
236 * console_lock/console_unlock, see the @lock variable in
239 static atomic_t console_kthreads_active = ATOMIC_INIT(0);
241 #define console_kthreads_atomic_tryblock() \
242 (atomic_cmpxchg(&console_kthreads_active, 0, -1) == 0)
243 #define console_kthreads_atomic_unblock() \
244 atomic_cmpxchg(&console_kthreads_active, -1, 0)
245 #define console_kthreads_atomically_blocked() \
246 (atomic_read(&console_kthreads_active) == -1)
248 #define console_kthread_printing_tryenter() \
249 atomic_inc_unless_negative(&console_kthreads_active)
250 #define console_kthread_printing_exit() \
251 atomic_dec(&console_kthreads_active)
254 * Helper macros to handle lockdep when locking/unlocking console_sem. We use
255 * macros instead of functions so that _RET_IP_ contains useful information.
257 #define down_console_sem() do { \
259 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
262 static int __down_trylock_console_sem(unsigned long ip)
268 * Here and in __up_console_sem() we need to be in safe mode,
269 * because spindump/WARN/etc from under console ->lock will
270 * deadlock in printk()->down_trylock_console_sem() otherwise.
272 printk_safe_enter_irqsave(flags);
273 lock_failed = down_trylock(&console_sem);
274 printk_safe_exit_irqrestore(flags);
278 mutex_acquire(&console_lock_dep_map, 0, 1, ip);
281 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
283 static void __up_console_sem(unsigned long ip)
287 mutex_release(&console_lock_dep_map, ip);
289 printk_safe_enter_irqsave(flags);
291 printk_safe_exit_irqrestore(flags);
293 #define up_console_sem() __up_console_sem(_RET_IP_)
295 static bool panic_in_progress(void)
297 return unlikely(atomic_read(&panic_cpu) != PANIC_CPU_INVALID);
301 * Tracks whether kthread printers are all blocked. A value of true implies
302 * that the console is locked via console_lock() or the console is suspended.
303 * Writing to this variable requires holding @console_sem.
305 static bool console_kthreads_blocked;
308 * Block all kthread printers from a schedulable context.
310 * Requires holding @console_sem.
312 static void console_kthreads_block(void)
316 for_each_console(con) {
317 mutex_lock(&con->lock);
319 mutex_unlock(&con->lock);
322 console_kthreads_blocked = true;
326 * Unblock all kthread printers from a schedulable context.
328 * Requires holding @console_sem.
330 static void console_kthreads_unblock(void)
334 for_each_console(con) {
335 mutex_lock(&con->lock);
336 con->blocked = false;
337 mutex_unlock(&con->lock);
340 console_kthreads_blocked = false;
344 * This is used for debugging the mess that is the VT code by
345 * keeping track if we have the console semaphore held. It's
346 * definitely not the perfect debug tool (we don't know if _WE_
347 * hold it and are racing, but it helps tracking those weird code
348 * paths in the console code where we end up in places I want
349 * locked without the console semaphore held).
351 static int console_locked, console_suspended;
354 * Array of consoles built from command line options (console=)
357 #define MAX_CMDLINECONSOLES 8
359 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
361 static int preferred_console = -1;
362 int console_set_on_cmdline;
363 EXPORT_SYMBOL(console_set_on_cmdline);
365 /* Flag: console code may call schedule() */
366 static int console_may_schedule;
368 enum con_msg_format_flags {
369 MSG_FORMAT_DEFAULT = 0,
370 MSG_FORMAT_SYSLOG = (1 << 0),
373 static int console_msg_format = MSG_FORMAT_DEFAULT;
376 * The printk log buffer consists of a sequenced collection of records, each
377 * containing variable length message text. Every record also contains its
378 * own meta-data (@info).
380 * Every record meta-data carries the timestamp in microseconds, as well as
381 * the standard userspace syslog level and syslog facility. The usual kernel
382 * messages use LOG_KERN; userspace-injected messages always carry a matching
383 * syslog facility, by default LOG_USER. The origin of every message can be
384 * reliably determined that way.
386 * The human readable log message of a record is available in @text, the
387 * length of the message text in @text_len. The stored message is not
390 * Optionally, a record can carry a dictionary of properties (key/value
391 * pairs), to provide userspace with a machine-readable message context.
393 * Examples for well-defined, commonly used property names are:
394 * DEVICE=b12:8 device identifier
398 * +sound:card0 subsystem:devname
399 * SUBSYSTEM=pci driver-core subsystem name
401 * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
402 * and values are terminated by a '\0' character.
404 * Example of record values:
405 * record.text_buf = "it's a line" (unterminated)
406 * record.info.seq = 56
407 * record.info.ts_nsec = 36863
408 * record.info.text_len = 11
409 * record.info.facility = 0 (LOG_KERN)
410 * record.info.flags = 0
411 * record.info.level = 3 (LOG_ERR)
412 * record.info.caller_id = 299 (task 299)
413 * record.info.dev_info.subsystem = "pci" (terminated)
414 * record.info.dev_info.device = "+pci:0000:00:01.0" (terminated)
416 * The 'struct printk_info' buffer must never be directly exported to
417 * userspace, it is a kernel-private implementation detail that might
418 * need to be changed in the future, when the requirements change.
420 * /dev/kmsg exports the structured data in the following line format:
421 * "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
423 * Users of the export format should ignore possible additional values
424 * separated by ',', and find the message after the ';' character.
426 * The optional key/value pairs are attached as continuation lines starting
427 * with a space character and terminated by a newline. All possible
428 * non-prinatable characters are escaped in the "\xff" notation.
431 /* syslog_lock protects syslog_* variables and write access to clear_seq. */
432 static DEFINE_MUTEX(syslog_lock);
435 * A flag to signify if printk_activate_kthreads() has already started the
436 * kthread printers. If true, any later registered consoles must start their
437 * own kthread directly. The flag is write protected by the console_lock.
439 static bool printk_kthreads_available;
442 static atomic_t printk_prefer_direct = ATOMIC_INIT(0);
445 * printk_prefer_direct_enter - cause printk() calls to attempt direct
446 * printing to all enabled consoles
448 * Since it is not possible to call into the console printing code from any
449 * context, there is no guarantee that direct printing will occur.
451 * This globally effects all printk() callers.
453 * Context: Any context.
455 void printk_prefer_direct_enter(void)
457 atomic_inc(&printk_prefer_direct);
461 * printk_prefer_direct_exit - restore printk() behavior
463 * Context: Any context.
465 void printk_prefer_direct_exit(void)
467 WARN_ON(atomic_dec_if_positive(&printk_prefer_direct) < 0);
471 * Calling printk() always wakes kthread printers so that they can
472 * flush the new message to their respective consoles. Also, if direct
473 * printing is allowed, printk() tries to flush the messages directly.
475 * Direct printing is allowed in situations when the kthreads
476 * are not available or the system is in a problematic state.
478 * See the implementation about possible races.
480 static inline bool allow_direct_printing(void)
483 * Checking kthread availability is a possible race because the
484 * kthread printers can become permanently disabled during runtime.
485 * However, doing that requires holding the console_lock, so any
486 * pending messages will be direct printed by console_unlock().
488 if (!printk_kthreads_available)
492 * Prefer direct printing when the system is in a problematic state.
493 * The context that sets this state will always see the updated value.
494 * The other contexts do not care. Anyway, direct printing is just a
495 * best effort. The direct output is only possible when console_lock
496 * is not already taken and no kthread printers are actively printing.
498 return (system_state > SYSTEM_RUNNING ||
500 atomic_read(&printk_prefer_direct));
503 DECLARE_WAIT_QUEUE_HEAD(log_wait);
504 /* All 3 protected by @syslog_lock. */
505 /* the next printk record to read by syslog(READ) or /proc/kmsg */
506 static u64 syslog_seq;
507 static size_t syslog_partial;
508 static bool syslog_time;
511 seqcount_latch_t latch;
516 * The next printk record to read after the last 'clear' command. There are
517 * two copies (updated with seqcount_latch) so that reads can locklessly
518 * access a valid value. Writers are synchronized by @syslog_lock.
520 static struct latched_seq clear_seq = {
521 .latch = SEQCNT_LATCH_ZERO(clear_seq.latch),
526 #ifdef CONFIG_PRINTK_CALLER
527 #define PREFIX_MAX 48
529 #define PREFIX_MAX 32
532 /* the maximum size of a formatted record (i.e. with prefix added per line) */
533 #define CONSOLE_LOG_MAX 1024
535 /* the maximum size for a dropped text message */
536 #define DROPPED_TEXT_MAX 64
538 /* the maximum size allowed to be reserved for a record */
539 #define LOG_LINE_MAX (CONSOLE_LOG_MAX - PREFIX_MAX)
541 #define LOG_LEVEL(v) ((v) & 0x07)
542 #define LOG_FACILITY(v) ((v) >> 3 & 0xff)
545 #define LOG_ALIGN __alignof__(unsigned long)
546 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
547 #define LOG_BUF_LEN_MAX (u32)(1 << 31)
548 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
549 static char *log_buf = __log_buf;
550 static u32 log_buf_len = __LOG_BUF_LEN;
553 * Define the average message size. This only affects the number of
554 * descriptors that will be available. Underestimating is better than
555 * overestimating (too many available descriptors is better than not enough).
557 #define PRB_AVGBITS 5 /* 32 character average length */
559 #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
560 #error CONFIG_LOG_BUF_SHIFT value too small.
562 _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
563 PRB_AVGBITS, &__log_buf[0]);
565 static struct printk_ringbuffer printk_rb_dynamic;
567 static struct printk_ringbuffer *prb = &printk_rb_static;
570 * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
571 * per_cpu_areas are initialised. This variable is set to true when
572 * it's safe to access per-CPU data.
574 static bool __printk_percpu_data_ready __read_mostly;
576 bool printk_percpu_data_ready(void)
578 return __printk_percpu_data_ready;
581 /* Must be called under syslog_lock. */
582 static void latched_seq_write(struct latched_seq *ls, u64 val)
584 raw_write_seqcount_latch(&ls->latch);
586 raw_write_seqcount_latch(&ls->latch);
590 /* Can be called from any context. */
591 static u64 latched_seq_read_nolock(struct latched_seq *ls)
598 seq = raw_read_seqcount_latch(&ls->latch);
601 } while (read_seqcount_latch_retry(&ls->latch, seq));
606 /* Return log buffer address */
607 char *log_buf_addr_get(void)
612 /* Return log buffer size */
613 u32 log_buf_len_get(void)
619 * Define how much of the log buffer we could take at maximum. The value
620 * must be greater than two. Note that only half of the buffer is available
621 * when the index points to the middle.
623 #define MAX_LOG_TAKE_PART 4
624 static const char trunc_msg[] = "<truncated>";
626 static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
629 * The message should not take the whole buffer. Otherwise, it might
630 * get removed too soon.
632 u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
634 if (*text_len > max_text_len)
635 *text_len = max_text_len;
637 /* enable the warning message (if there is room) */
638 *trunc_msg_len = strlen(trunc_msg);
639 if (*text_len >= *trunc_msg_len)
640 *text_len -= *trunc_msg_len;
645 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
647 static int syslog_action_restricted(int type)
652 * Unless restricted, we allow "read all" and "get buffer size"
655 return type != SYSLOG_ACTION_READ_ALL &&
656 type != SYSLOG_ACTION_SIZE_BUFFER;
659 static int check_syslog_permissions(int type, int source)
662 * If this is from /proc/kmsg and we've already opened it, then we've
663 * already done the capabilities checks at open time.
665 if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
668 if (syslog_action_restricted(type)) {
669 if (capable(CAP_SYSLOG))
672 * For historical reasons, accept CAP_SYS_ADMIN too, with
675 if (capable(CAP_SYS_ADMIN)) {
676 pr_warn_once("%s (%d): Attempt to access syslog with "
677 "CAP_SYS_ADMIN but no CAP_SYSLOG "
679 current->comm, task_pid_nr(current));
685 return security_syslog(type);
688 static void append_char(char **pp, char *e, char c)
694 static ssize_t info_print_ext_header(char *buf, size_t size,
695 struct printk_info *info)
697 u64 ts_usec = info->ts_nsec;
699 #ifdef CONFIG_PRINTK_CALLER
700 u32 id = info->caller_id;
702 snprintf(caller, sizeof(caller), ",caller=%c%u",
703 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
708 do_div(ts_usec, 1000);
710 return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
711 (info->facility << 3) | info->level, info->seq,
712 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
715 static ssize_t msg_add_ext_text(char *buf, size_t size,
716 const char *text, size_t text_len,
719 char *p = buf, *e = buf + size;
722 /* escape non-printable characters */
723 for (i = 0; i < text_len; i++) {
724 unsigned char c = text[i];
726 if (c < ' ' || c >= 127 || c == '\\')
727 p += scnprintf(p, e - p, "\\x%02x", c);
729 append_char(&p, e, c);
731 append_char(&p, e, endc);
736 static ssize_t msg_add_dict_text(char *buf, size_t size,
737 const char *key, const char *val)
739 size_t val_len = strlen(val);
745 len = msg_add_ext_text(buf, size, "", 0, ' '); /* dict prefix */
746 len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
747 len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
752 static ssize_t msg_print_ext_body(char *buf, size_t size,
753 char *text, size_t text_len,
754 struct dev_printk_info *dev_info)
758 len = msg_add_ext_text(buf, size, text, text_len, '\n');
763 len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
764 dev_info->subsystem);
765 len += msg_add_dict_text(buf + len, size - len, "DEVICE",
771 /* /dev/kmsg - userspace message inject/listen interface */
772 struct devkmsg_user {
774 struct ratelimit_state rs;
776 char buf[CONSOLE_EXT_LOG_MAX];
778 struct printk_info info;
779 char text_buf[CONSOLE_EXT_LOG_MAX];
780 struct printk_record record;
783 static __printf(3, 4) __cold
784 int devkmsg_emit(int facility, int level, const char *fmt, ...)
790 r = vprintk_emit(facility, level, NULL, fmt, args);
796 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
799 int level = default_message_loglevel;
800 int facility = 1; /* LOG_USER */
801 struct file *file = iocb->ki_filp;
802 struct devkmsg_user *user = file->private_data;
803 size_t len = iov_iter_count(from);
806 if (!user || len > LOG_LINE_MAX)
809 /* Ignore when user logging is disabled. */
810 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
813 /* Ratelimit when not explicitly enabled. */
814 if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
815 if (!___ratelimit(&user->rs, current->comm))
819 buf = kmalloc(len+1, GFP_KERNEL);
824 if (!copy_from_iter_full(buf, len, from)) {
830 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
831 * the decimal value represents 32bit, the lower 3 bit are the log
832 * level, the rest are the log facility.
834 * If no prefix or no userspace facility is specified, we
835 * enforce LOG_USER, to be able to reliably distinguish
836 * kernel-generated messages from userspace-injected ones.
839 if (line[0] == '<') {
843 u = simple_strtoul(line + 1, &endp, 10);
844 if (endp && endp[0] == '>') {
845 level = LOG_LEVEL(u);
846 if (LOG_FACILITY(u) != 0)
847 facility = LOG_FACILITY(u);
853 devkmsg_emit(facility, level, "%s", line);
858 static ssize_t devkmsg_read(struct file *file, char __user *buf,
859 size_t count, loff_t *ppos)
861 struct devkmsg_user *user = file->private_data;
862 struct printk_record *r = &user->record;
869 ret = mutex_lock_interruptible(&user->lock);
873 if (!prb_read_valid(prb, atomic64_read(&user->seq), r)) {
874 if (file->f_flags & O_NONBLOCK) {
880 * Guarantee this task is visible on the waitqueue before
881 * checking the wake condition.
883 * The full memory barrier within set_current_state() of
884 * prepare_to_wait_event() pairs with the full memory barrier
885 * within wq_has_sleeper().
887 * This pairs with __wake_up_klogd:A.
889 ret = wait_event_interruptible(log_wait,
891 atomic64_read(&user->seq), r)); /* LMM(devkmsg_read:A) */
896 if (r->info->seq != atomic64_read(&user->seq)) {
897 /* our last seen message is gone, return error and reset */
898 atomic64_set(&user->seq, r->info->seq);
903 len = info_print_ext_header(user->buf, sizeof(user->buf), r->info);
904 len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
905 &r->text_buf[0], r->info->text_len,
908 atomic64_set(&user->seq, r->info->seq + 1);
915 if (copy_to_user(buf, user->buf, len)) {
921 mutex_unlock(&user->lock);
926 * Be careful when modifying this function!!!
928 * Only few operations are supported because the device works only with the
929 * entire variable length messages (records). Non-standard values are
930 * returned in the other cases and has been this way for quite some time.
931 * User space applications might depend on this behavior.
933 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
935 struct devkmsg_user *user = file->private_data;
945 /* the first record */
946 atomic64_set(&user->seq, prb_first_valid_seq(prb));
950 * The first record after the last SYSLOG_ACTION_CLEAR,
951 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
952 * changes no global state, and does not clear anything.
954 atomic64_set(&user->seq, latched_seq_read_nolock(&clear_seq));
957 /* after the last record */
958 atomic64_set(&user->seq, prb_next_seq(prb));
966 static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
968 struct devkmsg_user *user = file->private_data;
969 struct printk_info info;
973 return EPOLLERR|EPOLLNVAL;
975 poll_wait(file, &log_wait, wait);
977 if (prb_read_valid_info(prb, atomic64_read(&user->seq), &info, NULL)) {
978 /* return error when data has vanished underneath us */
979 if (info.seq != atomic64_read(&user->seq))
980 ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
982 ret = EPOLLIN|EPOLLRDNORM;
988 static int devkmsg_open(struct inode *inode, struct file *file)
990 struct devkmsg_user *user;
993 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
996 /* write-only does not need any file context */
997 if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
998 err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
1004 user = kvmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
1008 ratelimit_default_init(&user->rs);
1009 ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
1011 mutex_init(&user->lock);
1013 prb_rec_init_rd(&user->record, &user->info,
1014 &user->text_buf[0], sizeof(user->text_buf));
1016 atomic64_set(&user->seq, prb_first_valid_seq(prb));
1018 file->private_data = user;
1022 static int devkmsg_release(struct inode *inode, struct file *file)
1024 struct devkmsg_user *user = file->private_data;
1029 ratelimit_state_exit(&user->rs);
1031 mutex_destroy(&user->lock);
1036 const struct file_operations kmsg_fops = {
1037 .open = devkmsg_open,
1038 .read = devkmsg_read,
1039 .write_iter = devkmsg_write,
1040 .llseek = devkmsg_llseek,
1041 .poll = devkmsg_poll,
1042 .release = devkmsg_release,
1045 #ifdef CONFIG_CRASH_CORE
1047 * This appends the listed symbols to /proc/vmcore
1049 * /proc/vmcore is used by various utilities, like crash and makedumpfile to
1050 * obtain access to symbols that are otherwise very difficult to locate. These
1051 * symbols are specifically used so that utilities can access and extract the
1052 * dmesg log from a vmcore file after a crash.
1054 void log_buf_vmcoreinfo_setup(void)
1056 struct dev_printk_info *dev_info = NULL;
1058 VMCOREINFO_SYMBOL(prb);
1059 VMCOREINFO_SYMBOL(printk_rb_static);
1060 VMCOREINFO_SYMBOL(clear_seq);
1063 * Export struct size and field offsets. User space tools can
1064 * parse it and detect any changes to structure down the line.
1067 VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
1068 VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
1069 VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
1070 VMCOREINFO_OFFSET(printk_ringbuffer, fail);
1072 VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
1073 VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
1074 VMCOREINFO_OFFSET(prb_desc_ring, descs);
1075 VMCOREINFO_OFFSET(prb_desc_ring, infos);
1076 VMCOREINFO_OFFSET(prb_desc_ring, head_id);
1077 VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
1079 VMCOREINFO_STRUCT_SIZE(prb_desc);
1080 VMCOREINFO_OFFSET(prb_desc, state_var);
1081 VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
1083 VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
1084 VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
1085 VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
1087 VMCOREINFO_STRUCT_SIZE(printk_info);
1088 VMCOREINFO_OFFSET(printk_info, seq);
1089 VMCOREINFO_OFFSET(printk_info, ts_nsec);
1090 VMCOREINFO_OFFSET(printk_info, text_len);
1091 VMCOREINFO_OFFSET(printk_info, caller_id);
1092 VMCOREINFO_OFFSET(printk_info, dev_info);
1094 VMCOREINFO_STRUCT_SIZE(dev_printk_info);
1095 VMCOREINFO_OFFSET(dev_printk_info, subsystem);
1096 VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
1097 VMCOREINFO_OFFSET(dev_printk_info, device);
1098 VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
1100 VMCOREINFO_STRUCT_SIZE(prb_data_ring);
1101 VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1102 VMCOREINFO_OFFSET(prb_data_ring, data);
1103 VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1104 VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1106 VMCOREINFO_SIZE(atomic_long_t);
1107 VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
1109 VMCOREINFO_STRUCT_SIZE(latched_seq);
1110 VMCOREINFO_OFFSET(latched_seq, val);
1114 /* requested log_buf_len from kernel cmdline */
1115 static unsigned long __initdata new_log_buf_len;
1117 /* we practice scaling the ring buffer by powers of 2 */
1118 static void __init log_buf_len_update(u64 size)
1120 if (size > (u64)LOG_BUF_LEN_MAX) {
1121 size = (u64)LOG_BUF_LEN_MAX;
1122 pr_err("log_buf over 2G is not supported.\n");
1126 size = roundup_pow_of_two(size);
1127 if (size > log_buf_len)
1128 new_log_buf_len = (unsigned long)size;
1131 /* save requested log_buf_len since it's too early to process it */
1132 static int __init log_buf_len_setup(char *str)
1139 size = memparse(str, &str);
1141 log_buf_len_update(size);
1145 early_param("log_buf_len", log_buf_len_setup);
1148 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
1150 static void __init log_buf_add_cpu(void)
1152 unsigned int cpu_extra;
1155 * archs should set up cpu_possible_bits properly with
1156 * set_cpu_possible() after setup_arch() but just in
1157 * case lets ensure this is valid.
1159 if (num_possible_cpus() == 1)
1162 cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
1164 /* by default this will only continue through for large > 64 CPUs */
1165 if (cpu_extra <= __LOG_BUF_LEN / 2)
1168 pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
1169 __LOG_CPU_MAX_BUF_LEN);
1170 pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
1172 pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1174 log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1176 #else /* !CONFIG_SMP */
1177 static inline void log_buf_add_cpu(void) {}
1178 #endif /* CONFIG_SMP */
1180 static void __init set_percpu_data_ready(void)
1182 __printk_percpu_data_ready = true;
1185 static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1186 struct printk_record *r)
1188 struct prb_reserved_entry e;
1189 struct printk_record dest_r;
1191 prb_rec_init_wr(&dest_r, r->info->text_len);
1193 if (!prb_reserve(&e, rb, &dest_r))
1196 memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1197 dest_r.info->text_len = r->info->text_len;
1198 dest_r.info->facility = r->info->facility;
1199 dest_r.info->level = r->info->level;
1200 dest_r.info->flags = r->info->flags;
1201 dest_r.info->ts_nsec = r->info->ts_nsec;
1202 dest_r.info->caller_id = r->info->caller_id;
1203 memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1205 prb_final_commit(&e);
1207 return prb_record_text_space(&e);
1210 static char setup_text_buf[LOG_LINE_MAX] __initdata;
1212 void __init setup_log_buf(int early)
1214 struct printk_info *new_infos;
1215 unsigned int new_descs_count;
1216 struct prb_desc *new_descs;
1217 struct printk_info info;
1218 struct printk_record r;
1219 unsigned int text_size;
1220 size_t new_descs_size;
1221 size_t new_infos_size;
1222 unsigned long flags;
1228 * Some archs call setup_log_buf() multiple times - first is very
1229 * early, e.g. from setup_arch(), and second - when percpu_areas
1233 set_percpu_data_ready();
1235 if (log_buf != __log_buf)
1238 if (!early && !new_log_buf_len)
1241 if (!new_log_buf_len)
1244 new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1245 if (new_descs_count == 0) {
1246 pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1250 new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1251 if (unlikely(!new_log_buf)) {
1252 pr_err("log_buf_len: %lu text bytes not available\n",
1257 new_descs_size = new_descs_count * sizeof(struct prb_desc);
1258 new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1259 if (unlikely(!new_descs)) {
1260 pr_err("log_buf_len: %zu desc bytes not available\n",
1262 goto err_free_log_buf;
1265 new_infos_size = new_descs_count * sizeof(struct printk_info);
1266 new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1267 if (unlikely(!new_infos)) {
1268 pr_err("log_buf_len: %zu info bytes not available\n",
1270 goto err_free_descs;
1273 prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1275 prb_init(&printk_rb_dynamic,
1276 new_log_buf, ilog2(new_log_buf_len),
1277 new_descs, ilog2(new_descs_count),
1280 local_irq_save(flags);
1282 log_buf_len = new_log_buf_len;
1283 log_buf = new_log_buf;
1284 new_log_buf_len = 0;
1286 free = __LOG_BUF_LEN;
1287 prb_for_each_record(0, &printk_rb_static, seq, &r) {
1288 text_size = add_to_rb(&printk_rb_dynamic, &r);
1289 if (text_size > free)
1295 prb = &printk_rb_dynamic;
1297 local_irq_restore(flags);
1300 * Copy any remaining messages that might have appeared from
1301 * NMI context after copying but before switching to the
1304 prb_for_each_record(seq, &printk_rb_static, seq, &r) {
1305 text_size = add_to_rb(&printk_rb_dynamic, &r);
1306 if (text_size > free)
1312 if (seq != prb_next_seq(&printk_rb_static)) {
1313 pr_err("dropped %llu messages\n",
1314 prb_next_seq(&printk_rb_static) - seq);
1317 pr_info("log_buf_len: %u bytes\n", log_buf_len);
1318 pr_info("early log buf free: %u(%u%%)\n",
1319 free, (free * 100) / __LOG_BUF_LEN);
1323 memblock_free(new_descs, new_descs_size);
1325 memblock_free(new_log_buf, new_log_buf_len);
1328 static bool __read_mostly ignore_loglevel;
1330 static int __init ignore_loglevel_setup(char *str)
1332 ignore_loglevel = true;
1333 pr_info("debug: ignoring loglevel setting.\n");
1338 early_param("ignore_loglevel", ignore_loglevel_setup);
1339 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1340 MODULE_PARM_DESC(ignore_loglevel,
1341 "ignore loglevel setting (prints all kernel messages to the console)");
1343 static bool suppress_message_printing(int level)
1345 return (level >= console_loglevel && !ignore_loglevel);
1348 #ifdef CONFIG_BOOT_PRINTK_DELAY
1350 static int boot_delay; /* msecs delay after each printk during bootup */
1351 static unsigned long long loops_per_msec; /* based on boot_delay */
1353 static int __init boot_delay_setup(char *str)
1357 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
1358 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1360 get_option(&str, &boot_delay);
1361 if (boot_delay > 10 * 1000)
1364 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1365 "HZ: %d, loops_per_msec: %llu\n",
1366 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1369 early_param("boot_delay", boot_delay_setup);
1371 static void boot_delay_msec(int level)
1373 unsigned long long k;
1374 unsigned long timeout;
1376 if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1377 || suppress_message_printing(level)) {
1381 k = (unsigned long long)loops_per_msec * boot_delay;
1383 timeout = jiffies + msecs_to_jiffies(boot_delay);
1388 * use (volatile) jiffies to prevent
1389 * compiler reduction; loop termination via jiffies
1390 * is secondary and may or may not happen.
1392 if (time_after(jiffies, timeout))
1394 touch_nmi_watchdog();
1398 static inline void boot_delay_msec(int level)
1403 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1404 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1406 static size_t print_syslog(unsigned int level, char *buf)
1408 return sprintf(buf, "<%u>", level);
1411 static size_t print_time(u64 ts, char *buf)
1413 unsigned long rem_nsec = do_div(ts, 1000000000);
1415 return sprintf(buf, "[%5lu.%06lu]",
1416 (unsigned long)ts, rem_nsec / 1000);
1419 #ifdef CONFIG_PRINTK_CALLER
1420 static size_t print_caller(u32 id, char *buf)
1424 snprintf(caller, sizeof(caller), "%c%u",
1425 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1426 return sprintf(buf, "[%6s]", caller);
1429 #define print_caller(id, buf) 0
1432 static size_t info_print_prefix(const struct printk_info *info, bool syslog,
1433 bool time, char *buf)
1438 len = print_syslog((info->facility << 3) | info->level, buf);
1441 len += print_time(info->ts_nsec, buf + len);
1443 len += print_caller(info->caller_id, buf + len);
1445 if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1454 * Prepare the record for printing. The text is shifted within the given
1455 * buffer to avoid a need for another one. The following operations are
1458 * - Add prefix for each line.
1459 * - Drop truncated lines that no longer fit into the buffer.
1460 * - Add the trailing newline that has been removed in vprintk_store().
1461 * - Add a string terminator.
1463 * Since the produced string is always terminated, the maximum possible
1464 * return value is @r->text_buf_size - 1;
1466 * Return: The length of the updated/prepared text, including the added
1467 * prefixes and the newline. The terminator is not counted. The dropped
1468 * line(s) are not counted.
1470 static size_t record_print_text(struct printk_record *r, bool syslog,
1473 size_t text_len = r->info->text_len;
1474 size_t buf_size = r->text_buf_size;
1475 char *text = r->text_buf;
1476 char prefix[PREFIX_MAX];
1477 bool truncated = false;
1484 * If the message was truncated because the buffer was not large
1485 * enough, treat the available text as if it were the full text.
1487 if (text_len > buf_size)
1488 text_len = buf_size;
1490 prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1493 * @text_len: bytes of unprocessed text
1494 * @line_len: bytes of current line _without_ newline
1495 * @text: pointer to beginning of current line
1496 * @len: number of bytes prepared in r->text_buf
1499 next = memchr(text, '\n', text_len);
1501 line_len = next - text;
1503 /* Drop truncated line(s). */
1506 line_len = text_len;
1510 * Truncate the text if there is not enough space to add the
1511 * prefix and a trailing newline and a terminator.
1513 if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1514 /* Drop even the current line if no space. */
1515 if (len + prefix_len + line_len + 1 + 1 > buf_size)
1518 text_len = buf_size - len - prefix_len - 1 - 1;
1522 memmove(text + prefix_len, text, text_len);
1523 memcpy(text, prefix, prefix_len);
1526 * Increment the prepared length to include the text and
1527 * prefix that were just moved+copied. Also increment for the
1528 * newline at the end of this line. If this is the last line,
1529 * there is no newline, but it will be added immediately below.
1531 len += prefix_len + line_len + 1;
1532 if (text_len == line_len) {
1534 * This is the last line. Add the trailing newline
1535 * removed in vprintk_store().
1537 text[prefix_len + line_len] = '\n';
1542 * Advance beyond the added prefix and the related line with
1545 text += prefix_len + line_len + 1;
1548 * The remaining text has only decreased by the line with its
1551 * Note that @text_len can become zero. It happens when @text
1552 * ended with a newline (either due to truncation or the
1553 * original string ending with "\n\n"). The loop is correctly
1554 * repeated and (if not truncated) an empty line with a prefix
1557 text_len -= line_len + 1;
1561 * If a buffer was provided, it will be terminated. Space for the
1562 * string terminator is guaranteed to be available. The terminator is
1563 * not counted in the return value.
1566 r->text_buf[len] = 0;
1571 static size_t get_record_print_text_size(struct printk_info *info,
1572 unsigned int line_count,
1573 bool syslog, bool time)
1575 char prefix[PREFIX_MAX];
1578 prefix_len = info_print_prefix(info, syslog, time, prefix);
1581 * Each line will be preceded with a prefix. The intermediate
1582 * newlines are already within the text, but a final trailing
1583 * newline will be added.
1585 return ((prefix_len * line_count) + info->text_len + 1);
1589 * Beginning with @start_seq, find the first record where it and all following
1590 * records up to (but not including) @max_seq fit into @size.
1592 * @max_seq is simply an upper bound and does not need to exist. If the caller
1593 * does not require an upper bound, -1 can be used for @max_seq.
1595 static u64 find_first_fitting_seq(u64 start_seq, u64 max_seq, size_t size,
1596 bool syslog, bool time)
1598 struct printk_info info;
1599 unsigned int line_count;
1603 /* Determine the size of the records up to @max_seq. */
1604 prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1605 if (info.seq >= max_seq)
1607 len += get_record_print_text_size(&info, line_count, syslog, time);
1611 * Adjust the upper bound for the next loop to avoid subtracting
1612 * lengths that were never added.
1618 * Move first record forward until length fits into the buffer. Ignore
1619 * newest messages that were not counted in the above cycle. Messages
1620 * might appear and get lost in the meantime. This is a best effort
1621 * that prevents an infinite loop that could occur with a retry.
1623 prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1624 if (len <= size || info.seq >= max_seq)
1626 len -= get_record_print_text_size(&info, line_count, syslog, time);
1632 /* The caller is responsible for making sure @size is greater than 0. */
1633 static int syslog_print(char __user *buf, int size)
1635 struct printk_info info;
1636 struct printk_record r;
1641 text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
1645 prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
1647 mutex_lock(&syslog_lock);
1650 * Wait for the @syslog_seq record to be available. @syslog_seq may
1651 * change while waiting.
1656 mutex_unlock(&syslog_lock);
1658 * Guarantee this task is visible on the waitqueue before
1659 * checking the wake condition.
1661 * The full memory barrier within set_current_state() of
1662 * prepare_to_wait_event() pairs with the full memory barrier
1663 * within wq_has_sleeper().
1665 * This pairs with __wake_up_klogd:A.
1667 len = wait_event_interruptible(log_wait,
1668 prb_read_valid(prb, seq, NULL)); /* LMM(syslog_print:A) */
1669 mutex_lock(&syslog_lock);
1673 } while (syslog_seq != seq);
1676 * Copy records that fit into the buffer. The above cycle makes sure
1677 * that the first record is always available.
1684 if (!prb_read_valid(prb, syslog_seq, &r))
1687 if (r.info->seq != syslog_seq) {
1688 /* message is gone, move to next valid one */
1689 syslog_seq = r.info->seq;
1694 * To keep reading/counting partial line consistent,
1695 * use printk_time value as of the beginning of a line.
1697 if (!syslog_partial)
1698 syslog_time = printk_time;
1700 skip = syslog_partial;
1701 n = record_print_text(&r, true, syslog_time);
1702 if (n - syslog_partial <= size) {
1703 /* message fits into buffer, move forward */
1704 syslog_seq = r.info->seq + 1;
1705 n -= syslog_partial;
1708 /* partial read(), remember position */
1710 syslog_partial += n;
1717 mutex_unlock(&syslog_lock);
1718 err = copy_to_user(buf, text + skip, n);
1719 mutex_lock(&syslog_lock);
1732 mutex_unlock(&syslog_lock);
1737 static int syslog_print_all(char __user *buf, int size, bool clear)
1739 struct printk_info info;
1740 struct printk_record r;
1746 text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
1752 * Find first record that fits, including all following records,
1753 * into the user-provided buffer for this dump.
1755 seq = find_first_fitting_seq(latched_seq_read_nolock(&clear_seq), -1,
1758 prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
1761 prb_for_each_record(seq, prb, seq, &r) {
1764 textlen = record_print_text(&r, true, time);
1766 if (len + textlen > size) {
1771 if (copy_to_user(buf + len, text, textlen))
1781 mutex_lock(&syslog_lock);
1782 latched_seq_write(&clear_seq, seq);
1783 mutex_unlock(&syslog_lock);
1790 static void syslog_clear(void)
1792 mutex_lock(&syslog_lock);
1793 latched_seq_write(&clear_seq, prb_next_seq(prb));
1794 mutex_unlock(&syslog_lock);
1797 int do_syslog(int type, char __user *buf, int len, int source)
1799 struct printk_info info;
1801 static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1804 error = check_syslog_permissions(type, source);
1809 case SYSLOG_ACTION_CLOSE: /* Close log */
1811 case SYSLOG_ACTION_OPEN: /* Open log */
1813 case SYSLOG_ACTION_READ: /* Read from log */
1814 if (!buf || len < 0)
1818 if (!access_ok(buf, len))
1820 error = syslog_print(buf, len);
1822 /* Read/clear last kernel messages */
1823 case SYSLOG_ACTION_READ_CLEAR:
1826 /* Read last kernel messages */
1827 case SYSLOG_ACTION_READ_ALL:
1828 if (!buf || len < 0)
1832 if (!access_ok(buf, len))
1834 error = syslog_print_all(buf, len, clear);
1836 /* Clear ring buffer */
1837 case SYSLOG_ACTION_CLEAR:
1840 /* Disable logging to console */
1841 case SYSLOG_ACTION_CONSOLE_OFF:
1842 if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1843 saved_console_loglevel = console_loglevel;
1844 console_loglevel = minimum_console_loglevel;
1846 /* Enable logging to console */
1847 case SYSLOG_ACTION_CONSOLE_ON:
1848 if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1849 console_loglevel = saved_console_loglevel;
1850 saved_console_loglevel = LOGLEVEL_DEFAULT;
1853 /* Set level of messages printed to console */
1854 case SYSLOG_ACTION_CONSOLE_LEVEL:
1855 if (len < 1 || len > 8)
1857 if (len < minimum_console_loglevel)
1858 len = minimum_console_loglevel;
1859 console_loglevel = len;
1860 /* Implicitly re-enable logging to console */
1861 saved_console_loglevel = LOGLEVEL_DEFAULT;
1863 /* Number of chars in the log buffer */
1864 case SYSLOG_ACTION_SIZE_UNREAD:
1865 mutex_lock(&syslog_lock);
1866 if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1867 /* No unread messages. */
1868 mutex_unlock(&syslog_lock);
1871 if (info.seq != syslog_seq) {
1872 /* messages are gone, move to first one */
1873 syslog_seq = info.seq;
1876 if (source == SYSLOG_FROM_PROC) {
1878 * Short-cut for poll(/"proc/kmsg") which simply checks
1879 * for pending data, not the size; return the count of
1880 * records, not the length.
1882 error = prb_next_seq(prb) - syslog_seq;
1884 bool time = syslog_partial ? syslog_time : printk_time;
1885 unsigned int line_count;
1888 prb_for_each_info(syslog_seq, prb, seq, &info,
1890 error += get_record_print_text_size(&info, line_count,
1894 error -= syslog_partial;
1896 mutex_unlock(&syslog_lock);
1898 /* Size of the log buffer */
1899 case SYSLOG_ACTION_SIZE_BUFFER:
1900 error = log_buf_len;
1910 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1912 return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1916 * Special console_lock variants that help to reduce the risk of soft-lockups.
1917 * They allow to pass console_lock to another printk() call using a busy wait.
1920 #ifdef CONFIG_LOCKDEP
1921 static struct lockdep_map console_owner_dep_map = {
1922 .name = "console_owner"
1926 static DEFINE_RAW_SPINLOCK(console_owner_lock);
1927 static struct task_struct *console_owner;
1928 static bool console_waiter;
1931 * console_lock_spinning_enable - mark beginning of code where another
1932 * thread might safely busy wait
1934 * This basically converts console_lock into a spinlock. This marks
1935 * the section where the console_lock owner can not sleep, because
1936 * there may be a waiter spinning (like a spinlock). Also it must be
1937 * ready to hand over the lock at the end of the section.
1939 static void console_lock_spinning_enable(void)
1941 raw_spin_lock(&console_owner_lock);
1942 console_owner = current;
1943 raw_spin_unlock(&console_owner_lock);
1945 /* The waiter may spin on us after setting console_owner */
1946 spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1950 * console_lock_spinning_disable_and_check - mark end of code where another
1951 * thread was able to busy wait and check if there is a waiter
1953 * This is called at the end of the section where spinning is allowed.
1954 * It has two functions. First, it is a signal that it is no longer
1955 * safe to start busy waiting for the lock. Second, it checks if
1956 * there is a busy waiter and passes the lock rights to her.
1958 * Important: Callers lose the lock if there was a busy waiter.
1959 * They must not touch items synchronized by console_lock
1962 * Return: 1 if the lock rights were passed, 0 otherwise.
1964 static int console_lock_spinning_disable_and_check(void)
1968 raw_spin_lock(&console_owner_lock);
1969 waiter = READ_ONCE(console_waiter);
1970 console_owner = NULL;
1971 raw_spin_unlock(&console_owner_lock);
1974 spin_release(&console_owner_dep_map, _THIS_IP_);
1978 /* The waiter is now free to continue */
1979 WRITE_ONCE(console_waiter, false);
1981 spin_release(&console_owner_dep_map, _THIS_IP_);
1984 * Hand off console_lock to waiter. The waiter will perform
1985 * the up(). After this, the waiter is the console_lock owner.
1987 mutex_release(&console_lock_dep_map, _THIS_IP_);
1992 * console_trylock_spinning - try to get console_lock by busy waiting
1994 * This allows to busy wait for the console_lock when the current
1995 * owner is running in specially marked sections. It means that
1996 * the current owner is running and cannot reschedule until it
1997 * is ready to lose the lock.
1999 * Return: 1 if we got the lock, 0 othrewise
2001 static int console_trylock_spinning(void)
2003 struct task_struct *owner = NULL;
2006 unsigned long flags;
2008 if (console_trylock())
2012 * It's unsafe to spin once a panic has begun. If we are the
2013 * panic CPU, we may have already halted the owner of the
2014 * console_sem. If we are not the panic CPU, then we should
2015 * avoid taking console_sem, so the panic CPU has a better
2016 * chance of cleanly acquiring it later.
2018 if (panic_in_progress())
2021 printk_safe_enter_irqsave(flags);
2023 raw_spin_lock(&console_owner_lock);
2024 owner = READ_ONCE(console_owner);
2025 waiter = READ_ONCE(console_waiter);
2026 if (!waiter && owner && owner != current) {
2027 WRITE_ONCE(console_waiter, true);
2030 raw_spin_unlock(&console_owner_lock);
2033 * If there is an active printk() writing to the
2034 * consoles, instead of having it write our data too,
2035 * see if we can offload that load from the active
2036 * printer, and do some printing ourselves.
2037 * Go into a spin only if there isn't already a waiter
2038 * spinning, and there is an active printer, and
2039 * that active printer isn't us (recursive printk?).
2042 printk_safe_exit_irqrestore(flags);
2046 /* We spin waiting for the owner to release us */
2047 spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
2048 /* Owner will clear console_waiter on hand off */
2049 while (READ_ONCE(console_waiter))
2051 spin_release(&console_owner_dep_map, _THIS_IP_);
2053 printk_safe_exit_irqrestore(flags);
2055 * The owner passed the console lock to us.
2056 * Since we did not spin on console lock, annotate
2057 * this as a trylock. Otherwise lockdep will
2060 mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
2066 * Call the specified console driver, asking it to write out the specified
2067 * text and length. If @dropped_text is non-NULL and any records have been
2068 * dropped, a dropped message will be written out first.
2070 static void call_console_driver(struct console *con, const char *text, size_t len,
2075 if (con->dropped && dropped_text) {
2076 dropped_len = snprintf(dropped_text, DROPPED_TEXT_MAX,
2077 "** %lu printk messages dropped **\n",
2080 con->write(con, dropped_text, dropped_len);
2083 con->write(con, text, len);
2087 * Recursion is tracked separately on each CPU. If NMIs are supported, an
2088 * additional NMI context per CPU is also separately tracked. Until per-CPU
2089 * is available, a separate "early tracking" is performed.
2091 static DEFINE_PER_CPU(u8, printk_count);
2092 static u8 printk_count_early;
2093 #ifdef CONFIG_HAVE_NMI
2094 static DEFINE_PER_CPU(u8, printk_count_nmi);
2095 static u8 printk_count_nmi_early;
2099 * Recursion is limited to keep the output sane. printk() should not require
2100 * more than 1 level of recursion (allowing, for example, printk() to trigger
2101 * a WARN), but a higher value is used in case some printk-internal errors
2102 * exist, such as the ringbuffer validation checks failing.
2104 #define PRINTK_MAX_RECURSION 3
2107 * Return a pointer to the dedicated counter for the CPU+context of the
2110 static u8 *__printk_recursion_counter(void)
2112 #ifdef CONFIG_HAVE_NMI
2114 if (printk_percpu_data_ready())
2115 return this_cpu_ptr(&printk_count_nmi);
2116 return &printk_count_nmi_early;
2119 if (printk_percpu_data_ready())
2120 return this_cpu_ptr(&printk_count);
2121 return &printk_count_early;
2125 * Enter recursion tracking. Interrupts are disabled to simplify tracking.
2126 * The caller must check the boolean return value to see if the recursion is
2127 * allowed. On failure, interrupts are not disabled.
2129 * @recursion_ptr must be a variable of type (u8 *) and is the same variable
2130 * that is passed to printk_exit_irqrestore().
2132 #define printk_enter_irqsave(recursion_ptr, flags) \
2134 bool success = true; \
2136 typecheck(u8 *, recursion_ptr); \
2137 local_irq_save(flags); \
2138 (recursion_ptr) = __printk_recursion_counter(); \
2139 if (*(recursion_ptr) > PRINTK_MAX_RECURSION) { \
2140 local_irq_restore(flags); \
2143 (*(recursion_ptr))++; \
2148 /* Exit recursion tracking, restoring interrupts. */
2149 #define printk_exit_irqrestore(recursion_ptr, flags) \
2151 typecheck(u8 *, recursion_ptr); \
2152 (*(recursion_ptr))--; \
2153 local_irq_restore(flags); \
2156 int printk_delay_msec __read_mostly;
2158 static inline void printk_delay(int level)
2160 boot_delay_msec(level);
2162 if (unlikely(printk_delay_msec)) {
2163 int m = printk_delay_msec;
2167 touch_nmi_watchdog();
2172 static inline u32 printk_caller_id(void)
2174 return in_task() ? task_pid_nr(current) :
2175 0x80000000 + smp_processor_id();
2179 * printk_parse_prefix - Parse level and control flags.
2181 * @text: The terminated text message.
2182 * @level: A pointer to the current level value, will be updated.
2183 * @flags: A pointer to the current printk_info flags, will be updated.
2185 * @level may be NULL if the caller is not interested in the parsed value.
2186 * Otherwise the variable pointed to by @level must be set to
2187 * LOGLEVEL_DEFAULT in order to be updated with the parsed value.
2189 * @flags may be NULL if the caller is not interested in the parsed value.
2190 * Otherwise the variable pointed to by @flags will be OR'd with the parsed
2193 * Return: The length of the parsed level and control flags.
2195 u16 printk_parse_prefix(const char *text, int *level,
2196 enum printk_info_flags *flags)
2202 kern_level = printk_get_level(text);
2206 switch (kern_level) {
2208 if (level && *level == LOGLEVEL_DEFAULT)
2209 *level = kern_level - '0';
2211 case 'c': /* KERN_CONT */
2224 static u16 printk_sprint(char *text, u16 size, int facility,
2225 enum printk_info_flags *flags, const char *fmt,
2230 text_len = vscnprintf(text, size, fmt, args);
2232 /* Mark and strip a trailing newline. */
2233 if (text_len && text[text_len - 1] == '\n') {
2235 *flags |= LOG_NEWLINE;
2238 /* Strip log level and control flags. */
2239 if (facility == 0) {
2242 prefix_len = printk_parse_prefix(text, NULL, NULL);
2244 text_len -= prefix_len;
2245 memmove(text, text + prefix_len, text_len);
2249 trace_console_rcuidle(text, text_len);
2255 int vprintk_store(int facility, int level,
2256 const struct dev_printk_info *dev_info,
2257 const char *fmt, va_list args)
2259 struct prb_reserved_entry e;
2260 enum printk_info_flags flags = 0;
2261 struct printk_record r;
2262 unsigned long irqflags;
2263 u16 trunc_msg_len = 0;
2273 if (!printk_enter_irqsave(recursion_ptr, irqflags))
2277 * Since the duration of printk() can vary depending on the message
2278 * and state of the ringbuffer, grab the timestamp now so that it is
2279 * close to the call of printk(). This provides a more deterministic
2280 * timestamp with respect to the caller.
2282 ts_nsec = local_clock();
2284 caller_id = printk_caller_id();
2287 * The sprintf needs to come first since the syslog prefix might be
2288 * passed in as a parameter. An extra byte must be reserved so that
2289 * later the vscnprintf() into the reserved buffer has room for the
2290 * terminating '\0', which is not counted by vsnprintf().
2292 va_copy(args2, args);
2293 reserve_size = vsnprintf(&prefix_buf[0], sizeof(prefix_buf), fmt, args2) + 1;
2296 if (reserve_size > LOG_LINE_MAX)
2297 reserve_size = LOG_LINE_MAX;
2299 /* Extract log level or control flags. */
2301 printk_parse_prefix(&prefix_buf[0], &level, &flags);
2303 if (level == LOGLEVEL_DEFAULT)
2304 level = default_message_loglevel;
2307 flags |= LOG_NEWLINE;
2309 if (flags & LOG_CONT) {
2310 prb_rec_init_wr(&r, reserve_size);
2311 if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
2312 text_len = printk_sprint(&r.text_buf[r.info->text_len], reserve_size,
2313 facility, &flags, fmt, args);
2314 r.info->text_len += text_len;
2316 if (flags & LOG_NEWLINE) {
2317 r.info->flags |= LOG_NEWLINE;
2318 prb_final_commit(&e);
2329 * Explicitly initialize the record before every prb_reserve() call.
2330 * prb_reserve_in_last() and prb_reserve() purposely invalidate the
2331 * structure when they fail.
2333 prb_rec_init_wr(&r, reserve_size);
2334 if (!prb_reserve(&e, prb, &r)) {
2335 /* truncate the message if it is too long for empty buffer */
2336 truncate_msg(&reserve_size, &trunc_msg_len);
2338 prb_rec_init_wr(&r, reserve_size + trunc_msg_len);
2339 if (!prb_reserve(&e, prb, &r))
2344 text_len = printk_sprint(&r.text_buf[0], reserve_size, facility, &flags, fmt, args);
2346 memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
2347 r.info->text_len = text_len + trunc_msg_len;
2348 r.info->facility = facility;
2349 r.info->level = level & 7;
2350 r.info->flags = flags & 0x1f;
2351 r.info->ts_nsec = ts_nsec;
2352 r.info->caller_id = caller_id;
2354 memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
2356 /* A message without a trailing newline can be continued. */
2357 if (!(flags & LOG_NEWLINE))
2360 prb_final_commit(&e);
2362 ret = text_len + trunc_msg_len;
2364 printk_exit_irqrestore(recursion_ptr, irqflags);
2368 asmlinkage int vprintk_emit(int facility, int level,
2369 const struct dev_printk_info *dev_info,
2370 const char *fmt, va_list args)
2373 bool in_sched = false;
2375 /* Suppress unimportant messages after panic happens */
2376 if (unlikely(suppress_printk))
2379 if (unlikely(suppress_panic_printk) &&
2380 atomic_read(&panic_cpu) != raw_smp_processor_id())
2383 if (level == LOGLEVEL_SCHED) {
2384 level = LOGLEVEL_DEFAULT;
2388 printk_delay(level);
2390 printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2392 /* If called from the scheduler, we can not call up(). */
2393 if (!in_sched && allow_direct_printing()) {
2395 * The caller may be holding system-critical or
2396 * timing-sensitive locks. Disable preemption during direct
2397 * printing of all remaining records to all consoles so that
2398 * this context can return as soon as possible. Hopefully
2399 * another printk() caller will take over the printing.
2403 * Try to acquire and then immediately release the console
2404 * semaphore. The release will print out buffers. With the
2405 * spinning variant, this context tries to take over the
2406 * printing from another printing context.
2408 if (console_trylock_spinning())
2416 EXPORT_SYMBOL(vprintk_emit);
2418 int vprintk_default(const char *fmt, va_list args)
2420 return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2422 EXPORT_SYMBOL_GPL(vprintk_default);
2424 asmlinkage __visible int _printk(const char *fmt, ...)
2429 va_start(args, fmt);
2430 r = vprintk(fmt, args);
2435 EXPORT_SYMBOL(_printk);
2437 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress);
2439 static void printk_start_kthread(struct console *con);
2441 #else /* CONFIG_PRINTK */
2443 #define CONSOLE_LOG_MAX 0
2444 #define DROPPED_TEXT_MAX 0
2445 #define printk_time false
2447 #define prb_read_valid(rb, seq, r) false
2448 #define prb_first_valid_seq(rb) 0
2449 #define prb_next_seq(rb) 0
2451 static u64 syslog_seq;
2453 static size_t record_print_text(const struct printk_record *r,
2454 bool syslog, bool time)
2458 static ssize_t info_print_ext_header(char *buf, size_t size,
2459 struct printk_info *info)
2463 static ssize_t msg_print_ext_body(char *buf, size_t size,
2464 char *text, size_t text_len,
2465 struct dev_printk_info *dev_info) { return 0; }
2466 static void console_lock_spinning_enable(void) { }
2467 static int console_lock_spinning_disable_and_check(void) { return 0; }
2468 static void call_console_driver(struct console *con, const char *text, size_t len,
2472 static bool suppress_message_printing(int level) { return false; }
2473 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress) { return true; }
2474 static void printk_start_kthread(struct console *con) { }
2475 static bool allow_direct_printing(void) { return true; }
2477 #endif /* CONFIG_PRINTK */
2479 #ifdef CONFIG_EARLY_PRINTK
2480 struct console *early_console;
2482 asmlinkage __visible void early_printk(const char *fmt, ...)
2492 n = vscnprintf(buf, sizeof(buf), fmt, ap);
2495 early_console->write(early_console, buf, n);
2499 static void set_user_specified(struct console_cmdline *c, bool user_specified)
2501 if (!user_specified)
2505 * @c console was defined by the user on the command line.
2506 * Do not clear when added twice also by SPCR or the device tree.
2508 c->user_specified = true;
2509 /* At least one console defined by the user on the command line. */
2510 console_set_on_cmdline = 1;
2513 static int __add_preferred_console(char *name, int idx, char *options,
2514 char *brl_options, bool user_specified)
2516 struct console_cmdline *c;
2520 * See if this tty is not yet registered, and
2521 * if we have a slot free.
2523 for (i = 0, c = console_cmdline;
2524 i < MAX_CMDLINECONSOLES && c->name[0];
2526 if (strcmp(c->name, name) == 0 && c->index == idx) {
2528 preferred_console = i;
2529 set_user_specified(c, user_specified);
2533 if (i == MAX_CMDLINECONSOLES)
2536 preferred_console = i;
2537 strlcpy(c->name, name, sizeof(c->name));
2538 c->options = options;
2539 set_user_specified(c, user_specified);
2540 braille_set_options(c, brl_options);
2546 static int __init console_msg_format_setup(char *str)
2548 if (!strcmp(str, "syslog"))
2549 console_msg_format = MSG_FORMAT_SYSLOG;
2550 if (!strcmp(str, "default"))
2551 console_msg_format = MSG_FORMAT_DEFAULT;
2554 __setup("console_msg_format=", console_msg_format_setup);
2557 * Set up a console. Called via do_early_param() in init/main.c
2558 * for each "console=" parameter in the boot command line.
2560 static int __init console_setup(char *str)
2562 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2563 char *s, *options, *brl_options = NULL;
2567 * console="" or console=null have been suggested as a way to
2568 * disable console output. Use ttynull that has been created
2569 * for exactly this purpose.
2571 if (str[0] == 0 || strcmp(str, "null") == 0) {
2572 __add_preferred_console("ttynull", 0, NULL, NULL, true);
2576 if (_braille_console_setup(&str, &brl_options))
2580 * Decode str into name, index, options.
2582 if (str[0] >= '0' && str[0] <= '9') {
2583 strcpy(buf, "ttyS");
2584 strncpy(buf + 4, str, sizeof(buf) - 5);
2586 strncpy(buf, str, sizeof(buf) - 1);
2588 buf[sizeof(buf) - 1] = 0;
2589 options = strchr(str, ',');
2593 if (!strcmp(str, "ttya"))
2594 strcpy(buf, "ttyS0");
2595 if (!strcmp(str, "ttyb"))
2596 strcpy(buf, "ttyS1");
2598 for (s = buf; *s; s++)
2599 if (isdigit(*s) || *s == ',')
2601 idx = simple_strtoul(s, NULL, 10);
2604 __add_preferred_console(buf, idx, options, brl_options, true);
2607 __setup("console=", console_setup);
2610 * add_preferred_console - add a device to the list of preferred consoles.
2611 * @name: device name
2612 * @idx: device index
2613 * @options: options for this console
2615 * The last preferred console added will be used for kernel messages
2616 * and stdin/out/err for init. Normally this is used by console_setup
2617 * above to handle user-supplied console arguments; however it can also
2618 * be used by arch-specific code either to override the user or more
2619 * commonly to provide a default console (ie from PROM variables) when
2620 * the user has not supplied one.
2622 int add_preferred_console(char *name, int idx, char *options)
2624 return __add_preferred_console(name, idx, options, NULL, false);
2627 bool console_suspend_enabled = true;
2628 EXPORT_SYMBOL(console_suspend_enabled);
2630 static int __init console_suspend_disable(char *str)
2632 console_suspend_enabled = false;
2635 __setup("no_console_suspend", console_suspend_disable);
2636 module_param_named(console_suspend, console_suspend_enabled,
2637 bool, S_IRUGO | S_IWUSR);
2638 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2639 " and hibernate operations");
2641 static bool printk_console_no_auto_verbose;
2643 void console_verbose(void)
2645 if (console_loglevel && !printk_console_no_auto_verbose)
2646 console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
2648 EXPORT_SYMBOL_GPL(console_verbose);
2650 module_param_named(console_no_auto_verbose, printk_console_no_auto_verbose, bool, 0644);
2651 MODULE_PARM_DESC(console_no_auto_verbose, "Disable console loglevel raise to highest on oops/panic/etc");
2654 * suspend_console - suspend the console subsystem
2656 * This disables printk() while we go into suspend states
2658 void suspend_console(void)
2660 if (!console_suspend_enabled)
2662 pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2663 pr_flush(1000, true);
2665 console_suspended = 1;
2669 void resume_console(void)
2671 if (!console_suspend_enabled)
2674 console_suspended = 0;
2676 pr_flush(1000, true);
2680 * console_cpu_notify - print deferred console messages after CPU hotplug
2683 * If printk() is called from a CPU that is not online yet, the messages
2684 * will be printed on the console only if there are CON_ANYTIME consoles.
2685 * This function is called when a new CPU comes online (or fails to come
2686 * up) or goes offline.
2688 static int console_cpu_notify(unsigned int cpu)
2690 if (!cpuhp_tasks_frozen) {
2691 /* If trylock fails, someone else is doing the printing */
2692 if (console_trylock())
2696 * If a new CPU comes online, the conditions for
2697 * printer_should_wake() may have changed for some
2698 * kthread printer with !CON_ANYTIME.
2707 * console_lock - lock the console system for exclusive use.
2709 * Acquires a lock which guarantees that the caller has
2710 * exclusive access to the console system and the console_drivers list.
2712 * Can sleep, returns nothing.
2714 void console_lock(void)
2719 if (console_suspended)
2721 console_kthreads_block();
2723 console_may_schedule = 1;
2725 EXPORT_SYMBOL(console_lock);
2728 * console_trylock - try to lock the console system for exclusive use.
2730 * Try to acquire a lock which guarantees that the caller has exclusive
2731 * access to the console system and the console_drivers list.
2733 * returns 1 on success, and 0 on failure to acquire the lock.
2735 int console_trylock(void)
2737 if (down_trylock_console_sem())
2739 if (console_suspended) {
2743 if (!console_kthreads_atomic_tryblock()) {
2748 console_may_schedule = 0;
2751 EXPORT_SYMBOL(console_trylock);
2753 int is_console_locked(void)
2755 return (console_locked || atomic_read(&console_kthreads_active));
2757 EXPORT_SYMBOL(is_console_locked);
2760 * Return true when this CPU should unlock console_sem without pushing all
2761 * messages to the console. This reduces the chance that the console is
2762 * locked when the panic CPU tries to use it.
2764 static bool abandon_console_lock_in_panic(void)
2766 if (!panic_in_progress())
2770 * We can use raw_smp_processor_id() here because it is impossible for
2771 * the task to be migrated to the panic_cpu, or away from it. If
2772 * panic_cpu has already been set, and we're not currently executing on
2773 * that CPU, then we never will be.
2775 return atomic_read(&panic_cpu) != raw_smp_processor_id();
2778 static inline bool __console_is_usable(short flags)
2780 if (!(flags & CON_ENABLED))
2784 * Console drivers may assume that per-cpu resources have been
2785 * allocated. So unless they're explicitly marked as being able to
2786 * cope (CON_ANYTIME) don't call them until this CPU is officially up.
2788 if (!cpu_online(raw_smp_processor_id()) &&
2789 !(flags & CON_ANYTIME))
2796 * Check if the given console is currently capable and allowed to print
2799 * Requires holding the console_lock.
2801 static inline bool console_is_usable(struct console *con)
2806 return __console_is_usable(con->flags);
2809 static void __console_unlock(void)
2814 * Depending on whether console_lock() or console_trylock() was used,
2815 * appropriately allow the kthread printers to continue.
2817 if (console_kthreads_blocked)
2818 console_kthreads_unblock();
2820 console_kthreads_atomic_unblock();
2823 * New records may have arrived while the console was locked.
2824 * Wake the kthread printers to print them.
2832 * Print one record for the given console. The record printed is whatever
2833 * record is the next available record for the given console.
2835 * @text is a buffer of size CONSOLE_LOG_MAX.
2837 * If extended messages should be printed, @ext_text is a buffer of size
2838 * CONSOLE_EXT_LOG_MAX. Otherwise @ext_text must be NULL.
2840 * If dropped messages should be printed, @dropped_text is a buffer of size
2841 * DROPPED_TEXT_MAX. Otherwise @dropped_text must be NULL.
2843 * @handover will be set to true if a printk waiter has taken over the
2844 * console_lock, in which case the caller is no longer holding the
2845 * console_lock. Otherwise it is set to false. A NULL pointer may be provided
2846 * to disable allowing the console_lock to be taken over by a printk waiter.
2848 * Returns false if the given console has no next record to print, otherwise
2851 * Requires the console_lock if @handover is non-NULL.
2852 * Requires con->lock otherwise.
2854 static bool __console_emit_next_record(struct console *con, char *text, char *ext_text,
2855 char *dropped_text, bool *handover)
2857 static atomic_t panic_console_dropped = ATOMIC_INIT(0);
2858 struct printk_info info;
2859 struct printk_record r;
2860 unsigned long flags;
2864 prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
2869 if (!prb_read_valid(prb, con->seq, &r))
2872 if (con->seq != r.info->seq) {
2873 con->dropped += r.info->seq - con->seq;
2874 con->seq = r.info->seq;
2875 if (panic_in_progress() &&
2876 atomic_fetch_inc_relaxed(&panic_console_dropped) > 10) {
2877 suppress_panic_printk = 1;
2878 pr_warn_once("Too many dropped messages. Suppress messages on non-panic CPUs to prevent livelock.\n");
2882 /* Skip record that has level above the console loglevel. */
2883 if (suppress_message_printing(r.info->level)) {
2889 write_text = ext_text;
2890 len = info_print_ext_header(ext_text, CONSOLE_EXT_LOG_MAX, r.info);
2891 len += msg_print_ext_body(ext_text + len, CONSOLE_EXT_LOG_MAX - len,
2892 &r.text_buf[0], r.info->text_len, &r.info->dev_info);
2895 len = record_print_text(&r, console_msg_format & MSG_FORMAT_SYSLOG, printk_time);
2900 * While actively printing out messages, if another printk()
2901 * were to occur on another CPU, it may wait for this one to
2902 * finish. This task can not be preempted if there is a
2903 * waiter waiting to take over.
2905 * Interrupts are disabled because the hand over to a waiter
2906 * must not be interrupted until the hand over is completed
2907 * (@console_waiter is cleared).
2909 printk_safe_enter_irqsave(flags);
2910 console_lock_spinning_enable();
2912 /* don't trace irqsoff print latency */
2913 stop_critical_timings();
2916 call_console_driver(con, write_text, len, dropped_text);
2921 start_critical_timings();
2922 *handover = console_lock_spinning_disable_and_check();
2923 printk_safe_exit_irqrestore(flags);
2930 * Print a record for a given console, but allow another printk() caller to
2931 * take over the console_lock and continue printing.
2933 * Requires the console_lock, but depending on @handover after the call, the
2934 * caller may no longer have the console_lock.
2936 * See __console_emit_next_record() for argument and return details.
2938 static bool console_emit_next_record_transferable(struct console *con, char *text, char *ext_text,
2939 char *dropped_text, bool *handover)
2942 * Handovers are only supported if threaded printers are atomically
2943 * blocked. The context taking over the console_lock may be atomic.
2945 if (!console_kthreads_atomically_blocked()) {
2950 return __console_emit_next_record(con, text, ext_text, dropped_text, handover);
2954 * Print out all remaining records to all consoles.
2956 * @do_cond_resched is set by the caller. It can be true only in schedulable
2959 * @next_seq is set to the sequence number after the last available record.
2960 * The value is valid only when this function returns true. It means that all
2961 * usable consoles are completely flushed.
2963 * @handover will be set to true if a printk waiter has taken over the
2964 * console_lock, in which case the caller is no longer holding the
2965 * console_lock. Otherwise it is set to false.
2967 * Returns true when there was at least one usable console and all messages
2968 * were flushed to all usable consoles. A returned false informs the caller
2969 * that everything was not flushed (either there were no usable consoles or
2970 * another context has taken over printing or it is a panic situation and this
2971 * is not the panic CPU or direct printing is not preferred). Regardless the
2972 * reason, the caller should assume it is not useful to immediately try again.
2974 * Requires the console_lock.
2976 static bool console_flush_all(bool do_cond_resched, u64 *next_seq, bool *handover)
2978 static char dropped_text[DROPPED_TEXT_MAX];
2979 static char ext_text[CONSOLE_EXT_LOG_MAX];
2980 static char text[CONSOLE_LOG_MAX];
2981 bool any_usable = false;
2982 struct console *con;
2989 /* Let the kthread printers do the work if they can. */
2990 if (!allow_direct_printing())
2993 any_progress = false;
2995 for_each_console(con) {
2998 if (!console_is_usable(con))
3002 if (con->flags & CON_EXTENDED) {
3003 /* Extended consoles do not print "dropped messages". */
3004 progress = console_emit_next_record_transferable(con, &text[0],
3005 &ext_text[0], NULL, handover);
3007 progress = console_emit_next_record_transferable(con, &text[0],
3008 NULL, &dropped_text[0], handover);
3013 /* Track the next of the highest seq flushed. */
3014 if (con->seq > *next_seq)
3015 *next_seq = con->seq;
3019 any_progress = true;
3021 /* Allow panic_cpu to take over the consoles safely. */
3022 if (abandon_console_lock_in_panic())
3025 if (do_cond_resched)
3028 } while (any_progress);
3034 * console_unlock - unlock the console system
3036 * Releases the console_lock which the caller holds on the console system
3037 * and the console driver list.
3039 * While the console_lock was held, console output may have been buffered
3040 * by printk(). If this is the case, console_unlock(); emits
3041 * the output prior to releasing the lock.
3043 * console_unlock(); may be called from any context.
3045 void console_unlock(void)
3047 bool do_cond_resched;
3052 if (console_suspended) {
3058 * Console drivers are called with interrupts disabled, so
3059 * @console_may_schedule should be cleared before; however, we may
3060 * end up dumping a lot of lines, for example, if called from
3061 * console registration path, and should invoke cond_resched()
3062 * between lines if allowable. Not doing so can cause a very long
3063 * scheduling stall on a slow console leading to RCU stall and
3064 * softlockup warnings which exacerbate the issue with more
3065 * messages practically incapacitating the system. Therefore, create
3066 * a local to use for the printing loop.
3068 do_cond_resched = console_may_schedule;
3071 console_may_schedule = 0;
3073 flushed = console_flush_all(do_cond_resched, &next_seq, &handover);
3078 * Abort if there was a failure to flush all messages to all
3079 * usable consoles. Either it is not possible to flush (in
3080 * which case it would be an infinite loop of retrying) or
3081 * another context has taken over printing.
3087 * Some context may have added new records after
3088 * console_flush_all() but before unlocking the console.
3089 * Re-check if there is a new record to flush. If the trylock
3090 * fails, another context is already handling the printing.
3092 } while (prb_read_valid(prb, next_seq, NULL) && console_trylock());
3094 EXPORT_SYMBOL(console_unlock);
3097 * console_conditional_schedule - yield the CPU if required
3099 * If the console code is currently allowed to sleep, and
3100 * if this CPU should yield the CPU to another task, do
3103 * Must be called within console_lock();.
3105 void __sched console_conditional_schedule(void)
3107 if (console_may_schedule)
3110 EXPORT_SYMBOL(console_conditional_schedule);
3112 void console_unblank(void)
3117 * console_unblank can no longer be called in interrupt context unless
3118 * oops_in_progress is set to 1..
3120 if (oops_in_progress) {
3121 if (down_trylock_console_sem() != 0)
3123 if (!console_kthreads_atomic_tryblock()) {
3131 console_may_schedule = 0;
3133 if ((c->flags & CON_ENABLED) && c->unblank)
3137 if (!oops_in_progress)
3138 pr_flush(1000, true);
3142 * console_flush_on_panic - flush console content on panic
3143 * @mode: flush all messages in buffer or just the pending ones
3145 * Immediately output all pending messages no matter what.
3147 void console_flush_on_panic(enum con_flush_mode mode)
3150 * If someone else is holding the console lock, trylock will fail
3151 * and may_schedule may be set. Ignore and proceed to unlock so
3152 * that messages are flushed out. As this can be called from any
3153 * context and we don't want to get preempted while flushing,
3154 * ensure may_schedule is cleared.
3157 console_may_schedule = 0;
3159 if (mode == CONSOLE_REPLAY_ALL) {
3163 seq = prb_first_valid_seq(prb);
3171 * Return the console tty driver structure and its associated index
3173 struct tty_driver *console_device(int *index)
3176 struct tty_driver *driver = NULL;
3179 for_each_console(c) {
3182 driver = c->device(c, index);
3191 * Prevent further output on the passed console device so that (for example)
3192 * serial drivers can disable console output before suspending a port, and can
3193 * re-enable output afterwards.
3195 void console_stop(struct console *console)
3197 __pr_flush(console, 1000, true);
3199 console->flags &= ~CON_ENABLED;
3202 EXPORT_SYMBOL(console_stop);
3204 void console_start(struct console *console)
3207 console->flags |= CON_ENABLED;
3209 __pr_flush(console, 1000, true);
3211 EXPORT_SYMBOL(console_start);
3213 static int __read_mostly keep_bootcon;
3215 static int __init keep_bootcon_setup(char *str)
3218 pr_info("debug: skip boot console de-registration.\n");
3223 early_param("keep_bootcon", keep_bootcon_setup);
3226 * This is called by register_console() to try to match
3227 * the newly registered console with any of the ones selected
3228 * by either the command line or add_preferred_console() and
3231 * Care need to be taken with consoles that are statically
3232 * enabled such as netconsole
3234 static int try_enable_preferred_console(struct console *newcon,
3235 bool user_specified)
3237 struct console_cmdline *c;
3240 for (i = 0, c = console_cmdline;
3241 i < MAX_CMDLINECONSOLES && c->name[0];
3243 if (c->user_specified != user_specified)
3245 if (!newcon->match ||
3246 newcon->match(newcon, c->name, c->index, c->options) != 0) {
3247 /* default matching */
3248 BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
3249 if (strcmp(c->name, newcon->name) != 0)
3251 if (newcon->index >= 0 &&
3252 newcon->index != c->index)
3254 if (newcon->index < 0)
3255 newcon->index = c->index;
3257 if (_braille_register_console(newcon, c))
3260 if (newcon->setup &&
3261 (err = newcon->setup(newcon, c->options)) != 0)
3264 newcon->flags |= CON_ENABLED;
3265 if (i == preferred_console)
3266 newcon->flags |= CON_CONSDEV;
3271 * Some consoles, such as pstore and netconsole, can be enabled even
3272 * without matching. Accept the pre-enabled consoles only when match()
3273 * and setup() had a chance to be called.
3275 if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
3281 /* Try to enable the console unconditionally */
3282 static void try_enable_default_console(struct console *newcon)
3284 if (newcon->index < 0)
3287 if (newcon->setup && newcon->setup(newcon, NULL) != 0)
3290 newcon->flags |= CON_ENABLED;
3293 newcon->flags |= CON_CONSDEV;
3296 #define con_printk(lvl, con, fmt, ...) \
3297 printk(lvl pr_fmt("%sconsole [%s%d] " fmt), \
3298 (con->flags & CON_BOOT) ? "boot" : "", \
3299 con->name, con->index, ##__VA_ARGS__)
3302 * The console driver calls this routine during kernel initialization
3303 * to register the console printing procedure with printk() and to
3304 * print any messages that were printed by the kernel before the
3305 * console driver was initialized.
3307 * This can happen pretty early during the boot process (because of
3308 * early_printk) - sometimes before setup_arch() completes - be careful
3309 * of what kernel features are used - they may not be initialised yet.
3311 * There are two types of consoles - bootconsoles (early_printk) and
3312 * "real" consoles (everything which is not a bootconsole) which are
3313 * handled differently.
3314 * - Any number of bootconsoles can be registered at any time.
3315 * - As soon as a "real" console is registered, all bootconsoles
3316 * will be unregistered automatically.
3317 * - Once a "real" console is registered, any attempt to register a
3318 * bootconsoles will be rejected
3320 void register_console(struct console *newcon)
3322 struct console *con;
3323 bool bootcon_enabled = false;
3324 bool realcon_enabled = false;
3327 for_each_console(con) {
3328 if (WARN(con == newcon, "console '%s%d' already registered\n",
3329 con->name, con->index))
3333 for_each_console(con) {
3334 if (con->flags & CON_BOOT)
3335 bootcon_enabled = true;
3337 realcon_enabled = true;
3340 /* Do not register boot consoles when there already is a real one. */
3341 if (newcon->flags & CON_BOOT && realcon_enabled) {
3342 pr_info("Too late to register bootconsole %s%d\n",
3343 newcon->name, newcon->index);
3348 * See if we want to enable this console driver by default.
3350 * Nope when a console is preferred by the command line, device
3353 * The first real console with tty binding (driver) wins. More
3354 * consoles might get enabled before the right one is found.
3356 * Note that a console with tty binding will have CON_CONSDEV
3357 * flag set and will be first in the list.
3359 if (preferred_console < 0) {
3360 if (!console_drivers || !console_drivers->device ||
3361 console_drivers->flags & CON_BOOT) {
3362 try_enable_default_console(newcon);
3366 /* See if this console matches one we selected on the command line */
3367 err = try_enable_preferred_console(newcon, true);
3369 /* If not, try to match against the platform default(s) */
3371 err = try_enable_preferred_console(newcon, false);
3373 /* printk() messages are not printed to the Braille console. */
3374 if (err || newcon->flags & CON_BRL)
3378 * If we have a bootconsole, and are switching to a real console,
3379 * don't print everything out again, since when the boot console, and
3380 * the real console are the same physical device, it's annoying to
3381 * see the beginning boot messages twice
3383 if (bootcon_enabled &&
3384 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
3385 newcon->flags &= ~CON_PRINTBUFFER;
3389 * Put this console in the list - keep the
3390 * preferred driver at the head of the list.
3393 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
3394 newcon->next = console_drivers;
3395 console_drivers = newcon;
3397 newcon->next->flags &= ~CON_CONSDEV;
3398 /* Ensure this flag is always set for the head of the list */
3399 newcon->flags |= CON_CONSDEV;
3401 newcon->next = console_drivers->next;
3402 console_drivers->next = newcon;
3405 if (newcon->flags & CON_EXTENDED)
3406 nr_ext_console_drivers++;
3408 newcon->dropped = 0;
3409 newcon->thread = NULL;
3410 newcon->blocked = true;
3411 mutex_init(&newcon->lock);
3413 if (newcon->flags & CON_PRINTBUFFER) {
3414 /* Get a consistent copy of @syslog_seq. */
3415 mutex_lock(&syslog_lock);
3416 newcon->seq = syslog_seq;
3417 mutex_unlock(&syslog_lock);
3419 /* Begin with next message. */
3420 newcon->seq = prb_next_seq(prb);
3423 if (printk_kthreads_available)
3424 printk_start_kthread(newcon);
3427 console_sysfs_notify();
3430 * By unregistering the bootconsoles after we enable the real console
3431 * we get the "console xxx enabled" message on all the consoles -
3432 * boot consoles, real consoles, etc - this is to ensure that end
3433 * users know there might be something in the kernel's log buffer that
3434 * went to the bootconsole (that they do not see on the real console)
3436 con_printk(KERN_INFO, newcon, "enabled\n");
3437 if (bootcon_enabled &&
3438 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
3440 /* We need to iterate through all boot consoles, to make
3441 * sure we print everything out, before we unregister them.
3443 for_each_console(con)
3444 if (con->flags & CON_BOOT)
3445 unregister_console(con);
3448 EXPORT_SYMBOL(register_console);
3450 int unregister_console(struct console *console)
3452 struct task_struct *thd;
3453 struct console *con;
3456 con_printk(KERN_INFO, console, "disabled\n");
3458 res = _braille_unregister_console(console);
3466 if (console_drivers == console) {
3467 console_drivers=console->next;
3470 for_each_console(con) {
3471 if (con->next == console) {
3472 con->next = console->next;
3480 goto out_disable_unlock;
3482 if (console->flags & CON_EXTENDED)
3483 nr_ext_console_drivers--;
3486 * If this isn't the last console and it has CON_CONSDEV set, we
3487 * need to set it on the next preferred console.
3489 if (console_drivers != NULL && console->flags & CON_CONSDEV)
3490 console_drivers->flags |= CON_CONSDEV;
3492 console->flags &= ~CON_ENABLED;
3495 * console->thread can only be cleared under the console lock. But
3496 * stopping the thread must be done without the console lock. The
3497 * task that clears @thread is the task that stops the kthread.
3499 thd = console->thread;
3500 console->thread = NULL;
3507 console_sysfs_notify();
3510 res = console->exit(console);
3515 console->flags &= ~CON_ENABLED;
3520 EXPORT_SYMBOL(unregister_console);
3523 * Initialize the console device. This is called *early*, so
3524 * we can't necessarily depend on lots of kernel help here.
3525 * Just do some early initializations, and do the complex setup
3528 void __init console_init(void)
3532 initcall_entry_t *ce;
3534 /* Setup the default TTY line discipline. */
3538 * set up the console device so that later boot sequences can
3539 * inform about problems etc..
3541 ce = __con_initcall_start;
3542 trace_initcall_level("console");
3543 while (ce < __con_initcall_end) {
3544 call = initcall_from_entry(ce);
3545 trace_initcall_start(call);
3547 trace_initcall_finish(call, ret);
3553 * Some boot consoles access data that is in the init section and which will
3554 * be discarded after the initcalls have been run. To make sure that no code
3555 * will access this data, unregister the boot consoles in a late initcall.
3557 * If for some reason, such as deferred probe or the driver being a loadable
3558 * module, the real console hasn't registered yet at this point, there will
3559 * be a brief interval in which no messages are logged to the console, which
3560 * makes it difficult to diagnose problems that occur during this time.
3562 * To mitigate this problem somewhat, only unregister consoles whose memory
3563 * intersects with the init section. Note that all other boot consoles will
3564 * get unregistered when the real preferred console is registered.
3566 static int __init printk_late_init(void)
3568 struct console *con;
3571 for_each_console(con) {
3572 if (!(con->flags & CON_BOOT))
3575 /* Check addresses that might be used for enabled consoles. */
3576 if (init_section_intersects(con, sizeof(*con)) ||
3577 init_section_contains(con->write, 0) ||
3578 init_section_contains(con->read, 0) ||
3579 init_section_contains(con->device, 0) ||
3580 init_section_contains(con->unblank, 0) ||
3581 init_section_contains(con->data, 0)) {
3583 * Please, consider moving the reported consoles out
3584 * of the init section.
3586 pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3587 con->name, con->index);
3588 unregister_console(con);
3591 ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3592 console_cpu_notify);
3594 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3595 console_cpu_notify, NULL);
3597 printk_sysctl_init();
3600 late_initcall(printk_late_init);
3602 static int __init printk_activate_kthreads(void)
3604 struct console *con;
3607 printk_kthreads_available = true;
3608 for_each_console(con)
3609 printk_start_kthread(con);
3614 early_initcall(printk_activate_kthreads);
3616 #if defined CONFIG_PRINTK
3617 /* If @con is specified, only wait for that console. Otherwise wait for all. */
3618 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress)
3620 int remaining = timeout_ms;
3629 seq = prb_next_seq(prb);
3635 for_each_console(c) {
3636 if (con && con != c)
3638 if (!console_is_usable(c))
3640 printk_seq = c->seq;
3641 if (printk_seq < seq)
3642 diff += seq - printk_seq;
3646 if (diff != last_diff && reset_on_progress)
3647 remaining = timeout_ms;
3649 if (diff == 0 || remaining == 0)
3652 if (remaining < 0) {
3653 /* no timeout limit */
3655 } else if (remaining < 100) {
3670 * pr_flush() - Wait for printing threads to catch up.
3672 * @timeout_ms: The maximum time (in ms) to wait.
3673 * @reset_on_progress: Reset the timeout if forward progress is seen.
3675 * A value of 0 for @timeout_ms means no waiting will occur. A value of -1
3676 * represents infinite waiting.
3678 * If @reset_on_progress is true, the timeout will be reset whenever any
3679 * printer has been seen to make some forward progress.
3681 * Context: Process context. May sleep while acquiring console lock.
3682 * Return: true if all enabled printers are caught up.
3684 bool pr_flush(int timeout_ms, bool reset_on_progress)
3686 return __pr_flush(NULL, timeout_ms, reset_on_progress);
3688 EXPORT_SYMBOL(pr_flush);
3690 static void __printk_fallback_preferred_direct(void)
3692 printk_prefer_direct_enter();
3693 pr_err("falling back to preferred direct printing\n");
3694 printk_kthreads_available = false;
3698 * Enter preferred direct printing, but never exit. Mark console threads as
3699 * unavailable. The system is then forever in preferred direct printing and
3700 * any printing threads will exit.
3702 * Must *not* be called under console_lock. Use
3703 * __printk_fallback_preferred_direct() if already holding console_lock.
3705 static void printk_fallback_preferred_direct(void)
3708 __printk_fallback_preferred_direct();
3713 * Print a record for a given console, not allowing another printk() caller
3714 * to take over. This is appropriate for contexts that do not have the
3717 * See __console_emit_next_record() for argument and return details.
3719 static bool console_emit_next_record(struct console *con, char *text, char *ext_text,
3722 return __console_emit_next_record(con, text, ext_text, dropped_text, NULL);
3725 static bool printer_should_wake(struct console *con, u64 seq)
3729 if (kthread_should_stop() || !printk_kthreads_available)
3733 console_kthreads_atomically_blocked()) {
3738 * This is an unsafe read from con->flags, but a false positive is
3739 * not a problem. Worst case it would allow the printer to wake up
3740 * although it is disabled. But the printer will notice that when
3741 * attempting to print and instead go back to sleep.
3743 flags = data_race(READ_ONCE(con->flags));
3745 if (!__console_is_usable(flags))
3748 return prb_read_valid(prb, seq, NULL);
3751 static int printk_kthread_func(void *data)
3753 struct console *con = data;
3754 char *dropped_text = NULL;
3755 char *ext_text = NULL;
3760 text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
3762 con_printk(KERN_ERR, con, "failed to allocate text buffer\n");
3763 printk_fallback_preferred_direct();
3767 if (con->flags & CON_EXTENDED) {
3768 ext_text = kmalloc(CONSOLE_EXT_LOG_MAX, GFP_KERNEL);
3770 con_printk(KERN_ERR, con, "failed to allocate ext_text buffer\n");
3771 printk_fallback_preferred_direct();
3775 dropped_text = kmalloc(DROPPED_TEXT_MAX, GFP_KERNEL);
3776 if (!dropped_text) {
3777 con_printk(KERN_ERR, con, "failed to allocate dropped_text buffer\n");
3778 printk_fallback_preferred_direct();
3783 con_printk(KERN_INFO, con, "printing thread started\n");
3787 * Guarantee this task is visible on the waitqueue before
3788 * checking the wake condition.
3790 * The full memory barrier within set_current_state() of
3791 * prepare_to_wait_event() pairs with the full memory barrier
3792 * within wq_has_sleeper().
3794 * This pairs with __wake_up_klogd:A.
3796 error = wait_event_interruptible(log_wait,
3797 printer_should_wake(con, seq)); /* LMM(printk_kthread_func:A) */
3799 if (kthread_should_stop() || !printk_kthreads_available)
3805 error = mutex_lock_interruptible(&con->lock);
3810 !console_kthread_printing_tryenter()) {
3811 /* Another context has locked the console_lock. */
3812 mutex_unlock(&con->lock);
3817 * Although this context has not locked the console_lock, it
3818 * is known that the console_lock is not locked and it is not
3819 * possible for any other context to lock the console_lock.
3820 * Therefore it is safe to read con->flags.
3823 if (!__console_is_usable(con->flags)) {
3824 console_kthread_printing_exit();
3825 mutex_unlock(&con->lock);
3830 * Even though the printk kthread is always preemptible, it is
3831 * still not allowed to call cond_resched() from within
3832 * console drivers. The task may become non-preemptible in the
3833 * console driver call chain. For example, vt_console_print()
3834 * takes a spinlock and then can call into fbcon_redraw(),
3835 * which can conditionally invoke cond_resched().
3837 console_may_schedule = 0;
3838 console_emit_next_record(con, text, ext_text, dropped_text);
3842 console_kthread_printing_exit();
3844 mutex_unlock(&con->lock);
3847 con_printk(KERN_INFO, con, "printing thread stopped\n");
3849 kfree(dropped_text);
3855 * If this kthread is being stopped by another task, con->thread will
3856 * already be NULL. That is fine. The important thing is that it is
3857 * NULL after the kthread exits.
3865 /* Must be called under console_lock. */
3866 static void printk_start_kthread(struct console *con)
3869 * Do not start a kthread if there is no write() callback. The
3870 * kthreads assume the write() callback exists.
3875 con->thread = kthread_run(printk_kthread_func, con,
3876 "pr/%s%d", con->name, con->index);
3877 if (IS_ERR(con->thread)) {
3879 con_printk(KERN_ERR, con, "unable to start printing thread\n");
3880 __printk_fallback_preferred_direct();
3886 * Delayed printk version, for scheduler-internal messages:
3888 #define PRINTK_PENDING_WAKEUP 0x01
3889 #define PRINTK_PENDING_DIRECT_OUTPUT 0x02
3891 static DEFINE_PER_CPU(int, printk_pending);
3893 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3895 int pending = this_cpu_xchg(printk_pending, 0);
3897 if (pending & PRINTK_PENDING_DIRECT_OUTPUT) {
3898 printk_prefer_direct_enter();
3900 /* If trylock fails, someone else is doing the printing */
3901 if (console_trylock())
3904 printk_prefer_direct_exit();
3907 if (pending & PRINTK_PENDING_WAKEUP)
3908 wake_up_interruptible(&log_wait);
3911 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) =
3912 IRQ_WORK_INIT_LAZY(wake_up_klogd_work_func);
3914 static void __wake_up_klogd(int val)
3916 if (!printk_percpu_data_ready())
3921 * Guarantee any new records can be seen by tasks preparing to wait
3922 * before this context checks if the wait queue is empty.
3924 * The full memory barrier within wq_has_sleeper() pairs with the full
3925 * memory barrier within set_current_state() of
3926 * prepare_to_wait_event(), which is called after ___wait_event() adds
3927 * the waiter but before it has checked the wait condition.
3929 * This pairs with devkmsg_read:A, syslog_print:A, and
3930 * printk_kthread_func:A.
3932 if (wq_has_sleeper(&log_wait) || /* LMM(__wake_up_klogd:A) */
3933 (val & PRINTK_PENDING_DIRECT_OUTPUT)) {
3934 this_cpu_or(printk_pending, val);
3935 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3940 void wake_up_klogd(void)
3942 __wake_up_klogd(PRINTK_PENDING_WAKEUP);
3945 void defer_console_output(void)
3948 * New messages may have been added directly to the ringbuffer
3949 * using vprintk_store(), so wake any waiters as well.
3951 int val = PRINTK_PENDING_WAKEUP;
3954 * Make sure that some context will print the messages when direct
3955 * printing is allowed. This happens in situations when the kthreads
3956 * may not be as reliable or perhaps unusable.
3958 if (allow_direct_printing())
3959 val |= PRINTK_PENDING_DIRECT_OUTPUT;
3961 __wake_up_klogd(val);
3964 void printk_trigger_flush(void)
3966 defer_console_output();
3969 int vprintk_deferred(const char *fmt, va_list args)
3973 r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
3974 defer_console_output();
3979 int _printk_deferred(const char *fmt, ...)
3984 va_start(args, fmt);
3985 r = vprintk_deferred(fmt, args);
3992 * printk rate limiting, lifted from the networking subsystem.
3994 * This enforces a rate limit: not more than 10 kernel messages
3995 * every 5s to make a denial-of-service attack impossible.
3997 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3999 int __printk_ratelimit(const char *func)
4001 return ___ratelimit(&printk_ratelimit_state, func);
4003 EXPORT_SYMBOL(__printk_ratelimit);
4006 * printk_timed_ratelimit - caller-controlled printk ratelimiting
4007 * @caller_jiffies: pointer to caller's state
4008 * @interval_msecs: minimum interval between prints
4010 * printk_timed_ratelimit() returns true if more than @interval_msecs
4011 * milliseconds have elapsed since the last time printk_timed_ratelimit()
4014 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
4015 unsigned int interval_msecs)
4017 unsigned long elapsed = jiffies - *caller_jiffies;
4019 if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
4022 *caller_jiffies = jiffies;
4025 EXPORT_SYMBOL(printk_timed_ratelimit);
4027 static DEFINE_SPINLOCK(dump_list_lock);
4028 static LIST_HEAD(dump_list);
4031 * kmsg_dump_register - register a kernel log dumper.
4032 * @dumper: pointer to the kmsg_dumper structure
4034 * Adds a kernel log dumper to the system. The dump callback in the
4035 * structure will be called when the kernel oopses or panics and must be
4036 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
4038 int kmsg_dump_register(struct kmsg_dumper *dumper)
4040 unsigned long flags;
4043 /* The dump callback needs to be set */
4047 spin_lock_irqsave(&dump_list_lock, flags);
4048 /* Don't allow registering multiple times */
4049 if (!dumper->registered) {
4050 dumper->registered = 1;
4051 list_add_tail_rcu(&dumper->list, &dump_list);
4054 spin_unlock_irqrestore(&dump_list_lock, flags);
4058 EXPORT_SYMBOL_GPL(kmsg_dump_register);
4061 * kmsg_dump_unregister - unregister a kmsg dumper.
4062 * @dumper: pointer to the kmsg_dumper structure
4064 * Removes a dump device from the system. Returns zero on success and
4065 * %-EINVAL otherwise.
4067 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
4069 unsigned long flags;
4072 spin_lock_irqsave(&dump_list_lock, flags);
4073 if (dumper->registered) {
4074 dumper->registered = 0;
4075 list_del_rcu(&dumper->list);
4078 spin_unlock_irqrestore(&dump_list_lock, flags);
4083 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
4085 static bool always_kmsg_dump;
4086 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
4088 const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
4091 case KMSG_DUMP_PANIC:
4093 case KMSG_DUMP_OOPS:
4095 case KMSG_DUMP_EMERG:
4097 case KMSG_DUMP_SHUTDOWN:
4103 EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
4106 * kmsg_dump - dump kernel log to kernel message dumpers.
4107 * @reason: the reason (oops, panic etc) for dumping
4109 * Call each of the registered dumper's dump() callback, which can
4110 * retrieve the kmsg records with kmsg_dump_get_line() or
4111 * kmsg_dump_get_buffer().
4113 void kmsg_dump(enum kmsg_dump_reason reason)
4115 struct kmsg_dumper *dumper;
4118 list_for_each_entry_rcu(dumper, &dump_list, list) {
4119 enum kmsg_dump_reason max_reason = dumper->max_reason;
4122 * If client has not provided a specific max_reason, default
4123 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
4125 if (max_reason == KMSG_DUMP_UNDEF) {
4126 max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
4129 if (reason > max_reason)
4132 /* invoke dumper which will iterate over records */
4133 dumper->dump(dumper, reason);
4139 * kmsg_dump_get_line - retrieve one kmsg log line
4140 * @iter: kmsg dump iterator
4141 * @syslog: include the "<4>" prefixes
4142 * @line: buffer to copy the line to
4143 * @size: maximum size of the buffer
4144 * @len: length of line placed into buffer
4146 * Start at the beginning of the kmsg buffer, with the oldest kmsg
4147 * record, and copy one record into the provided buffer.
4149 * Consecutive calls will return the next available record moving
4150 * towards the end of the buffer with the youngest messages.
4152 * A return value of FALSE indicates that there are no more records to
4155 bool kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog,
4156 char *line, size_t size, size_t *len)
4158 u64 min_seq = latched_seq_read_nolock(&clear_seq);
4159 struct printk_info info;
4160 unsigned int line_count;
4161 struct printk_record r;
4165 if (iter->cur_seq < min_seq)
4166 iter->cur_seq = min_seq;
4168 prb_rec_init_rd(&r, &info, line, size);
4170 /* Read text or count text lines? */
4172 if (!prb_read_valid(prb, iter->cur_seq, &r))
4174 l = record_print_text(&r, syslog, printk_time);
4176 if (!prb_read_valid_info(prb, iter->cur_seq,
4177 &info, &line_count)) {
4180 l = get_record_print_text_size(&info, line_count, syslog,
4185 iter->cur_seq = r.info->seq + 1;
4192 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
4195 * kmsg_dump_get_buffer - copy kmsg log lines
4196 * @iter: kmsg dump iterator
4197 * @syslog: include the "<4>" prefixes
4198 * @buf: buffer to copy the line to
4199 * @size: maximum size of the buffer
4200 * @len_out: length of line placed into buffer
4202 * Start at the end of the kmsg buffer and fill the provided buffer
4203 * with as many of the *youngest* kmsg records that fit into it.
4204 * If the buffer is large enough, all available kmsg records will be
4205 * copied with a single call.
4207 * Consecutive calls will fill the buffer with the next block of
4208 * available older records, not including the earlier retrieved ones.
4210 * A return value of FALSE indicates that there are no more records to
4213 bool kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog,
4214 char *buf, size_t size, size_t *len_out)
4216 u64 min_seq = latched_seq_read_nolock(&clear_seq);
4217 struct printk_info info;
4218 struct printk_record r;
4223 bool time = printk_time;
4228 if (iter->cur_seq < min_seq)
4229 iter->cur_seq = min_seq;
4231 if (prb_read_valid_info(prb, iter->cur_seq, &info, NULL)) {
4232 if (info.seq != iter->cur_seq) {
4233 /* messages are gone, move to first available one */
4234 iter->cur_seq = info.seq;
4239 if (iter->cur_seq >= iter->next_seq)
4243 * Find first record that fits, including all following records,
4244 * into the user-provided buffer for this dump. Pass in size-1
4245 * because this function (by way of record_print_text()) will
4246 * not write more than size-1 bytes of text into @buf.
4248 seq = find_first_fitting_seq(iter->cur_seq, iter->next_seq,
4249 size - 1, syslog, time);
4252 * Next kmsg_dump_get_buffer() invocation will dump block of
4253 * older records stored right before this one.
4257 prb_rec_init_rd(&r, &info, buf, size);
4260 prb_for_each_record(seq, prb, seq, &r) {
4261 if (r.info->seq >= iter->next_seq)
4264 len += record_print_text(&r, syslog, time);
4266 /* Adjust record to store to remaining buffer space. */
4267 prb_rec_init_rd(&r, &info, buf + len, size - len);
4270 iter->next_seq = next_seq;
4277 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
4280 * kmsg_dump_rewind - reset the iterator
4281 * @iter: kmsg dump iterator
4283 * Reset the dumper's iterator so that kmsg_dump_get_line() and
4284 * kmsg_dump_get_buffer() can be called again and used multiple
4285 * times within the same dumper.dump() callback.
4287 void kmsg_dump_rewind(struct kmsg_dump_iter *iter)
4289 iter->cur_seq = latched_seq_read_nolock(&clear_seq);
4290 iter->next_seq = prb_next_seq(prb);
4292 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
4297 static atomic_t printk_cpu_sync_owner = ATOMIC_INIT(-1);
4298 static atomic_t printk_cpu_sync_nested = ATOMIC_INIT(0);
4301 * __printk_cpu_sync_wait() - Busy wait until the printk cpu-reentrant
4302 * spinning lock is not owned by any CPU.
4304 * Context: Any context.
4306 void __printk_cpu_sync_wait(void)
4310 } while (atomic_read(&printk_cpu_sync_owner) != -1);
4312 EXPORT_SYMBOL(__printk_cpu_sync_wait);
4315 * __printk_cpu_sync_try_get() - Try to acquire the printk cpu-reentrant
4318 * If no processor has the lock, the calling processor takes the lock and
4319 * becomes the owner. If the calling processor is already the owner of the
4320 * lock, this function succeeds immediately.
4322 * Context: Any context. Expects interrupts to be disabled.
4323 * Return: 1 on success, otherwise 0.
4325 int __printk_cpu_sync_try_get(void)
4330 cpu = smp_processor_id();
4333 * Guarantee loads and stores from this CPU when it is the lock owner
4334 * are _not_ visible to the previous lock owner. This pairs with
4335 * __printk_cpu_sync_put:B.
4337 * Memory barrier involvement:
4339 * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4340 * then __printk_cpu_sync_put:A can never read from
4341 * __printk_cpu_sync_try_get:B.
4345 * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
4346 * of the previous CPU
4348 * ACQUIRE from __printk_cpu_sync_try_get:A to
4349 * __printk_cpu_sync_try_get:B of this CPU
4351 old = atomic_cmpxchg_acquire(&printk_cpu_sync_owner, -1,
4352 cpu); /* LMM(__printk_cpu_sync_try_get:A) */
4355 * This CPU is now the owner and begins loading/storing
4356 * data: LMM(__printk_cpu_sync_try_get:B)
4360 } else if (old == cpu) {
4361 /* This CPU is already the owner. */
4362 atomic_inc(&printk_cpu_sync_nested);
4368 EXPORT_SYMBOL(__printk_cpu_sync_try_get);
4371 * __printk_cpu_sync_put() - Release the printk cpu-reentrant spinning lock.
4373 * The calling processor must be the owner of the lock.
4375 * Context: Any context. Expects interrupts to be disabled.
4377 void __printk_cpu_sync_put(void)
4379 if (atomic_read(&printk_cpu_sync_nested)) {
4380 atomic_dec(&printk_cpu_sync_nested);
4385 * This CPU is finished loading/storing data:
4386 * LMM(__printk_cpu_sync_put:A)
4390 * Guarantee loads and stores from this CPU when it was the
4391 * lock owner are visible to the next lock owner. This pairs
4392 * with __printk_cpu_sync_try_get:A.
4394 * Memory barrier involvement:
4396 * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4397 * then __printk_cpu_sync_try_get:B reads from __printk_cpu_sync_put:A.
4401 * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
4404 * ACQUIRE from __printk_cpu_sync_try_get:A to
4405 * __printk_cpu_sync_try_get:B of the next CPU
4407 atomic_set_release(&printk_cpu_sync_owner,
4408 -1); /* LMM(__printk_cpu_sync_put:B) */
4410 EXPORT_SYMBOL(__printk_cpu_sync_put);
4411 #endif /* CONFIG_SMP */