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 static struct lockdep_map console_lock_dep_map = {
98 .name = "console_lock"
102 enum devkmsg_log_bits {
103 __DEVKMSG_LOG_BIT_ON = 0,
104 __DEVKMSG_LOG_BIT_OFF,
105 __DEVKMSG_LOG_BIT_LOCK,
108 enum devkmsg_log_masks {
109 DEVKMSG_LOG_MASK_ON = BIT(__DEVKMSG_LOG_BIT_ON),
110 DEVKMSG_LOG_MASK_OFF = BIT(__DEVKMSG_LOG_BIT_OFF),
111 DEVKMSG_LOG_MASK_LOCK = BIT(__DEVKMSG_LOG_BIT_LOCK),
114 /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
115 #define DEVKMSG_LOG_MASK_DEFAULT 0
117 static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
119 static int __control_devkmsg(char *str)
126 len = str_has_prefix(str, "on");
128 devkmsg_log = DEVKMSG_LOG_MASK_ON;
132 len = str_has_prefix(str, "off");
134 devkmsg_log = DEVKMSG_LOG_MASK_OFF;
138 len = str_has_prefix(str, "ratelimit");
140 devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
147 static int __init control_devkmsg(char *str)
149 if (__control_devkmsg(str) < 0) {
150 pr_warn("printk.devkmsg: bad option string '%s'\n", str);
155 * Set sysctl string accordingly:
157 if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
158 strcpy(devkmsg_log_str, "on");
159 else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
160 strcpy(devkmsg_log_str, "off");
161 /* else "ratelimit" which is set by default. */
164 * Sysctl cannot change it anymore. The kernel command line setting of
165 * this parameter is to force the setting to be permanent throughout the
166 * runtime of the system. This is a precation measure against userspace
167 * trying to be a smarta** and attempting to change it up on us.
169 devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
173 __setup("printk.devkmsg=", control_devkmsg);
175 char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
177 int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
178 void *buffer, size_t *lenp, loff_t *ppos)
180 char old_str[DEVKMSG_STR_MAX_SIZE];
185 if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
189 strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
192 err = proc_dostring(table, write, buffer, lenp, ppos);
197 err = __control_devkmsg(devkmsg_log_str);
200 * Do not accept an unknown string OR a known string with
203 if (err < 0 || (err + 1 != *lenp)) {
205 /* ... and restore old setting. */
207 strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
216 /* Number of registered extended console drivers. */
217 static int nr_ext_console_drivers;
220 * Helper macros to handle lockdep when locking/unlocking console_sem. We use
221 * macros instead of functions so that _RET_IP_ contains useful information.
223 #define down_console_sem() do { \
225 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
228 static int __down_trylock_console_sem(unsigned long ip)
234 * Here and in __up_console_sem() we need to be in safe mode,
235 * because spindump/WARN/etc from under console ->lock will
236 * deadlock in printk()->down_trylock_console_sem() otherwise.
238 printk_safe_enter_irqsave(flags);
239 lock_failed = down_trylock(&console_sem);
240 printk_safe_exit_irqrestore(flags);
244 mutex_acquire(&console_lock_dep_map, 0, 1, ip);
247 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
249 static void __up_console_sem(unsigned long ip)
253 mutex_release(&console_lock_dep_map, ip);
255 printk_safe_enter_irqsave(flags);
257 printk_safe_exit_irqrestore(flags);
259 #define up_console_sem() __up_console_sem(_RET_IP_)
262 * This is used for debugging the mess that is the VT code by
263 * keeping track if we have the console semaphore held. It's
264 * definitely not the perfect debug tool (we don't know if _WE_
265 * hold it and are racing, but it helps tracking those weird code
266 * paths in the console code where we end up in places I want
267 * locked without the console sempahore held).
269 static int console_locked, console_suspended;
272 * If exclusive_console is non-NULL then only this console is to be printed to.
274 static struct console *exclusive_console;
277 * Array of consoles built from command line options (console=)
280 #define MAX_CMDLINECONSOLES 8
282 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
284 static int preferred_console = -1;
285 static bool has_preferred_console;
286 int console_set_on_cmdline;
287 EXPORT_SYMBOL(console_set_on_cmdline);
289 /* Flag: console code may call schedule() */
290 static int console_may_schedule;
292 enum con_msg_format_flags {
293 MSG_FORMAT_DEFAULT = 0,
294 MSG_FORMAT_SYSLOG = (1 << 0),
297 static int console_msg_format = MSG_FORMAT_DEFAULT;
300 * The printk log buffer consists of a sequenced collection of records, each
301 * containing variable length message text. Every record also contains its
302 * own meta-data (@info).
304 * Every record meta-data carries the timestamp in microseconds, as well as
305 * the standard userspace syslog level and syslog facility. The usual kernel
306 * messages use LOG_KERN; userspace-injected messages always carry a matching
307 * syslog facility, by default LOG_USER. The origin of every message can be
308 * reliably determined that way.
310 * The human readable log message of a record is available in @text, the
311 * length of the message text in @text_len. The stored message is not
314 * Optionally, a record can carry a dictionary of properties (key/value
315 * pairs), to provide userspace with a machine-readable message context.
317 * Examples for well-defined, commonly used property names are:
318 * DEVICE=b12:8 device identifier
322 * +sound:card0 subsystem:devname
323 * SUBSYSTEM=pci driver-core subsystem name
325 * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
326 * and values are terminated by a '\0' character.
328 * Example of record values:
329 * record.text_buf = "it's a line" (unterminated)
330 * record.info.seq = 56
331 * record.info.ts_nsec = 36863
332 * record.info.text_len = 11
333 * record.info.facility = 0 (LOG_KERN)
334 * record.info.flags = 0
335 * record.info.level = 3 (LOG_ERR)
336 * record.info.caller_id = 299 (task 299)
337 * record.info.dev_info.subsystem = "pci" (terminated)
338 * record.info.dev_info.device = "+pci:0000:00:01.0" (terminated)
340 * The 'struct printk_info' buffer must never be directly exported to
341 * userspace, it is a kernel-private implementation detail that might
342 * need to be changed in the future, when the requirements change.
344 * /dev/kmsg exports the structured data in the following line format:
345 * "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
347 * Users of the export format should ignore possible additional values
348 * separated by ',', and find the message after the ';' character.
350 * The optional key/value pairs are attached as continuation lines starting
351 * with a space character and terminated by a newline. All possible
352 * non-prinatable characters are escaped in the "\xff" notation.
356 LOG_NEWLINE = 2, /* text ended with a newline */
357 LOG_CONT = 8, /* text is a fragment of a continuation line */
361 * The logbuf_lock protects kmsg buffer, indices, counters. This can be taken
362 * within the scheduler's rq lock. It must be released before calling
363 * console_unlock() or anything else that might wake up a process.
365 DEFINE_RAW_SPINLOCK(logbuf_lock);
368 * Helper macros to lock/unlock logbuf_lock and switch between
369 * printk-safe/unsafe modes.
371 #define logbuf_lock_irq() \
373 printk_safe_enter_irq(); \
374 raw_spin_lock(&logbuf_lock); \
377 #define logbuf_unlock_irq() \
379 raw_spin_unlock(&logbuf_lock); \
380 printk_safe_exit_irq(); \
383 #define logbuf_lock_irqsave(flags) \
385 printk_safe_enter_irqsave(flags); \
386 raw_spin_lock(&logbuf_lock); \
389 #define logbuf_unlock_irqrestore(flags) \
391 raw_spin_unlock(&logbuf_lock); \
392 printk_safe_exit_irqrestore(flags); \
396 DECLARE_WAIT_QUEUE_HEAD(log_wait);
397 /* the next printk record to read by syslog(READ) or /proc/kmsg */
398 static u64 syslog_seq;
399 static size_t syslog_partial;
400 static bool syslog_time;
402 /* the next printk record to write to the console */
403 static u64 console_seq;
404 static u64 exclusive_console_stop_seq;
405 static unsigned long console_dropped;
407 /* the next printk record to read after the last 'clear' command */
408 static u64 clear_seq;
410 #ifdef CONFIG_PRINTK_CALLER
411 #define PREFIX_MAX 48
413 #define PREFIX_MAX 32
415 #define LOG_LINE_MAX (1024 - PREFIX_MAX)
417 #define LOG_LEVEL(v) ((v) & 0x07)
418 #define LOG_FACILITY(v) ((v) >> 3 & 0xff)
421 #define LOG_ALIGN __alignof__(unsigned long)
422 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
423 #define LOG_BUF_LEN_MAX (u32)(1 << 31)
424 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
425 static char *log_buf = __log_buf;
426 static u32 log_buf_len = __LOG_BUF_LEN;
429 * Define the average message size. This only affects the number of
430 * descriptors that will be available. Underestimating is better than
431 * overestimating (too many available descriptors is better than not enough).
433 #define PRB_AVGBITS 5 /* 32 character average length */
435 #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
436 #error CONFIG_LOG_BUF_SHIFT value too small.
438 _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
439 PRB_AVGBITS, &__log_buf[0]);
441 static struct printk_ringbuffer printk_rb_dynamic;
443 static struct printk_ringbuffer *prb = &printk_rb_static;
446 * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
447 * per_cpu_areas are initialised. This variable is set to true when
448 * it's safe to access per-CPU data.
450 static bool __printk_percpu_data_ready __read_mostly;
452 bool printk_percpu_data_ready(void)
454 return __printk_percpu_data_ready;
457 /* Return log buffer address */
458 char *log_buf_addr_get(void)
463 /* Return log buffer size */
464 u32 log_buf_len_get(void)
470 * Define how much of the log buffer we could take at maximum. The value
471 * must be greater than two. Note that only half of the buffer is available
472 * when the index points to the middle.
474 #define MAX_LOG_TAKE_PART 4
475 static const char trunc_msg[] = "<truncated>";
477 static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
480 * The message should not take the whole buffer. Otherwise, it might
481 * get removed too soon.
483 u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
485 if (*text_len > max_text_len)
486 *text_len = max_text_len;
488 /* enable the warning message (if there is room) */
489 *trunc_msg_len = strlen(trunc_msg);
490 if (*text_len >= *trunc_msg_len)
491 *text_len -= *trunc_msg_len;
496 /* insert record into the buffer, discard old ones, update heads */
497 static int log_store(u32 caller_id, int facility, int level,
498 enum log_flags flags, u64 ts_nsec,
499 const struct dev_printk_info *dev_info,
500 const char *text, u16 text_len)
502 struct prb_reserved_entry e;
503 struct printk_record r;
504 u16 trunc_msg_len = 0;
506 prb_rec_init_wr(&r, text_len);
508 if (!prb_reserve(&e, prb, &r)) {
509 /* truncate the message if it is too long for empty buffer */
510 truncate_msg(&text_len, &trunc_msg_len);
511 prb_rec_init_wr(&r, text_len + trunc_msg_len);
512 /* survive when the log buffer is too small for trunc_msg */
513 if (!prb_reserve(&e, prb, &r))
518 memcpy(&r.text_buf[0], text, text_len);
520 memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
521 r.info->text_len = text_len + trunc_msg_len;
522 r.info->facility = facility;
523 r.info->level = level & 7;
524 r.info->flags = flags & 0x1f;
526 r.info->ts_nsec = ts_nsec;
528 r.info->ts_nsec = local_clock();
529 r.info->caller_id = caller_id;
531 memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
533 /* A message without a trailing newline can be continued. */
534 if (!(flags & LOG_NEWLINE))
537 prb_final_commit(&e);
539 return (text_len + trunc_msg_len);
542 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
544 static int syslog_action_restricted(int type)
549 * Unless restricted, we allow "read all" and "get buffer size"
552 return type != SYSLOG_ACTION_READ_ALL &&
553 type != SYSLOG_ACTION_SIZE_BUFFER;
556 static int check_syslog_permissions(int type, int source)
559 * If this is from /proc/kmsg and we've already opened it, then we've
560 * already done the capabilities checks at open time.
562 if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
565 if (syslog_action_restricted(type)) {
566 if (capable(CAP_SYSLOG))
569 * For historical reasons, accept CAP_SYS_ADMIN too, with
572 if (capable(CAP_SYS_ADMIN)) {
573 pr_warn_once("%s (%d): Attempt to access syslog with "
574 "CAP_SYS_ADMIN but no CAP_SYSLOG "
576 current->comm, task_pid_nr(current));
582 return security_syslog(type);
585 static void append_char(char **pp, char *e, char c)
591 static ssize_t info_print_ext_header(char *buf, size_t size,
592 struct printk_info *info)
594 u64 ts_usec = info->ts_nsec;
596 #ifdef CONFIG_PRINTK_CALLER
597 u32 id = info->caller_id;
599 snprintf(caller, sizeof(caller), ",caller=%c%u",
600 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
605 do_div(ts_usec, 1000);
607 return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
608 (info->facility << 3) | info->level, info->seq,
609 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
612 static ssize_t msg_add_ext_text(char *buf, size_t size,
613 const char *text, size_t text_len,
616 char *p = buf, *e = buf + size;
619 /* escape non-printable characters */
620 for (i = 0; i < text_len; i++) {
621 unsigned char c = text[i];
623 if (c < ' ' || c >= 127 || c == '\\')
624 p += scnprintf(p, e - p, "\\x%02x", c);
626 append_char(&p, e, c);
628 append_char(&p, e, endc);
633 static ssize_t msg_add_dict_text(char *buf, size_t size,
634 const char *key, const char *val)
636 size_t val_len = strlen(val);
642 len = msg_add_ext_text(buf, size, "", 0, ' '); /* dict prefix */
643 len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
644 len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
649 static ssize_t msg_print_ext_body(char *buf, size_t size,
650 char *text, size_t text_len,
651 struct dev_printk_info *dev_info)
655 len = msg_add_ext_text(buf, size, text, text_len, '\n');
660 len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
661 dev_info->subsystem);
662 len += msg_add_dict_text(buf + len, size - len, "DEVICE",
668 /* /dev/kmsg - userspace message inject/listen interface */
669 struct devkmsg_user {
671 struct ratelimit_state rs;
673 char buf[CONSOLE_EXT_LOG_MAX];
675 struct printk_info info;
676 char text_buf[CONSOLE_EXT_LOG_MAX];
677 struct printk_record record;
680 static __printf(3, 4) __cold
681 int devkmsg_emit(int facility, int level, const char *fmt, ...)
687 r = vprintk_emit(facility, level, NULL, fmt, args);
693 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
696 int level = default_message_loglevel;
697 int facility = 1; /* LOG_USER */
698 struct file *file = iocb->ki_filp;
699 struct devkmsg_user *user = file->private_data;
700 size_t len = iov_iter_count(from);
703 if (!user || len > LOG_LINE_MAX)
706 /* Ignore when user logging is disabled. */
707 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
710 /* Ratelimit when not explicitly enabled. */
711 if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
712 if (!___ratelimit(&user->rs, current->comm))
716 buf = kmalloc(len+1, GFP_KERNEL);
721 if (!copy_from_iter_full(buf, len, from)) {
727 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
728 * the decimal value represents 32bit, the lower 3 bit are the log
729 * level, the rest are the log facility.
731 * If no prefix or no userspace facility is specified, we
732 * enforce LOG_USER, to be able to reliably distinguish
733 * kernel-generated messages from userspace-injected ones.
736 if (line[0] == '<') {
740 u = simple_strtoul(line + 1, &endp, 10);
741 if (endp && endp[0] == '>') {
742 level = LOG_LEVEL(u);
743 if (LOG_FACILITY(u) != 0)
744 facility = LOG_FACILITY(u);
751 devkmsg_emit(facility, level, "%s", line);
756 static ssize_t devkmsg_read(struct file *file, char __user *buf,
757 size_t count, loff_t *ppos)
759 struct devkmsg_user *user = file->private_data;
760 struct printk_record *r = &user->record;
767 ret = mutex_lock_interruptible(&user->lock);
772 if (!prb_read_valid(prb, user->seq, r)) {
773 if (file->f_flags & O_NONBLOCK) {
780 ret = wait_event_interruptible(log_wait,
781 prb_read_valid(prb, user->seq, r));
787 if (r->info->seq != user->seq) {
788 /* our last seen message is gone, return error and reset */
789 user->seq = r->info->seq;
795 len = info_print_ext_header(user->buf, sizeof(user->buf), r->info);
796 len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
797 &r->text_buf[0], r->info->text_len,
800 user->seq = r->info->seq + 1;
808 if (copy_to_user(buf, user->buf, len)) {
814 mutex_unlock(&user->lock);
819 * Be careful when modifying this function!!!
821 * Only few operations are supported because the device works only with the
822 * entire variable length messages (records). Non-standard values are
823 * returned in the other cases and has been this way for quite some time.
824 * User space applications might depend on this behavior.
826 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
828 struct devkmsg_user *user = file->private_data;
839 /* the first record */
840 user->seq = prb_first_valid_seq(prb);
844 * The first record after the last SYSLOG_ACTION_CLEAR,
845 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
846 * changes no global state, and does not clear anything.
848 user->seq = clear_seq;
851 /* after the last record */
852 user->seq = prb_next_seq(prb);
861 static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
863 struct devkmsg_user *user = file->private_data;
864 struct printk_info info;
868 return EPOLLERR|EPOLLNVAL;
870 poll_wait(file, &log_wait, wait);
873 if (prb_read_valid_info(prb, user->seq, &info, NULL)) {
874 /* return error when data has vanished underneath us */
875 if (info.seq != user->seq)
876 ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
878 ret = EPOLLIN|EPOLLRDNORM;
885 static int devkmsg_open(struct inode *inode, struct file *file)
887 struct devkmsg_user *user;
890 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
893 /* write-only does not need any file context */
894 if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
895 err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
901 user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
905 ratelimit_default_init(&user->rs);
906 ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
908 mutex_init(&user->lock);
910 prb_rec_init_rd(&user->record, &user->info,
911 &user->text_buf[0], sizeof(user->text_buf));
914 user->seq = prb_first_valid_seq(prb);
917 file->private_data = user;
921 static int devkmsg_release(struct inode *inode, struct file *file)
923 struct devkmsg_user *user = file->private_data;
928 ratelimit_state_exit(&user->rs);
930 mutex_destroy(&user->lock);
935 const struct file_operations kmsg_fops = {
936 .open = devkmsg_open,
937 .read = devkmsg_read,
938 .write_iter = devkmsg_write,
939 .llseek = devkmsg_llseek,
940 .poll = devkmsg_poll,
941 .release = devkmsg_release,
944 #ifdef CONFIG_CRASH_CORE
946 * This appends the listed symbols to /proc/vmcore
948 * /proc/vmcore is used by various utilities, like crash and makedumpfile to
949 * obtain access to symbols that are otherwise very difficult to locate. These
950 * symbols are specifically used so that utilities can access and extract the
951 * dmesg log from a vmcore file after a crash.
953 void log_buf_vmcoreinfo_setup(void)
955 struct dev_printk_info *dev_info = NULL;
957 VMCOREINFO_SYMBOL(prb);
958 VMCOREINFO_SYMBOL(printk_rb_static);
959 VMCOREINFO_SYMBOL(clear_seq);
962 * Export struct size and field offsets. User space tools can
963 * parse it and detect any changes to structure down the line.
966 VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
967 VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
968 VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
969 VMCOREINFO_OFFSET(printk_ringbuffer, fail);
971 VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
972 VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
973 VMCOREINFO_OFFSET(prb_desc_ring, descs);
974 VMCOREINFO_OFFSET(prb_desc_ring, infos);
975 VMCOREINFO_OFFSET(prb_desc_ring, head_id);
976 VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
978 VMCOREINFO_STRUCT_SIZE(prb_desc);
979 VMCOREINFO_OFFSET(prb_desc, state_var);
980 VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
982 VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
983 VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
984 VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
986 VMCOREINFO_STRUCT_SIZE(printk_info);
987 VMCOREINFO_OFFSET(printk_info, seq);
988 VMCOREINFO_OFFSET(printk_info, ts_nsec);
989 VMCOREINFO_OFFSET(printk_info, text_len);
990 VMCOREINFO_OFFSET(printk_info, caller_id);
991 VMCOREINFO_OFFSET(printk_info, dev_info);
993 VMCOREINFO_STRUCT_SIZE(dev_printk_info);
994 VMCOREINFO_OFFSET(dev_printk_info, subsystem);
995 VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
996 VMCOREINFO_OFFSET(dev_printk_info, device);
997 VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
999 VMCOREINFO_STRUCT_SIZE(prb_data_ring);
1000 VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1001 VMCOREINFO_OFFSET(prb_data_ring, data);
1002 VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1003 VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1005 VMCOREINFO_SIZE(atomic_long_t);
1006 VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
1010 /* requested log_buf_len from kernel cmdline */
1011 static unsigned long __initdata new_log_buf_len;
1013 /* we practice scaling the ring buffer by powers of 2 */
1014 static void __init log_buf_len_update(u64 size)
1016 if (size > (u64)LOG_BUF_LEN_MAX) {
1017 size = (u64)LOG_BUF_LEN_MAX;
1018 pr_err("log_buf over 2G is not supported.\n");
1022 size = roundup_pow_of_two(size);
1023 if (size > log_buf_len)
1024 new_log_buf_len = (unsigned long)size;
1027 /* save requested log_buf_len since it's too early to process it */
1028 static int __init log_buf_len_setup(char *str)
1035 size = memparse(str, &str);
1037 log_buf_len_update(size);
1041 early_param("log_buf_len", log_buf_len_setup);
1044 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
1046 static void __init log_buf_add_cpu(void)
1048 unsigned int cpu_extra;
1051 * archs should set up cpu_possible_bits properly with
1052 * set_cpu_possible() after setup_arch() but just in
1053 * case lets ensure this is valid.
1055 if (num_possible_cpus() == 1)
1058 cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
1060 /* by default this will only continue through for large > 64 CPUs */
1061 if (cpu_extra <= __LOG_BUF_LEN / 2)
1064 pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
1065 __LOG_CPU_MAX_BUF_LEN);
1066 pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
1068 pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1070 log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1072 #else /* !CONFIG_SMP */
1073 static inline void log_buf_add_cpu(void) {}
1074 #endif /* CONFIG_SMP */
1076 static void __init set_percpu_data_ready(void)
1079 /* Make sure we set this flag only after printk_safe() init is done */
1081 __printk_percpu_data_ready = true;
1084 static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1085 struct printk_record *r)
1087 struct prb_reserved_entry e;
1088 struct printk_record dest_r;
1090 prb_rec_init_wr(&dest_r, r->info->text_len);
1092 if (!prb_reserve(&e, rb, &dest_r))
1095 memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1096 dest_r.info->text_len = r->info->text_len;
1097 dest_r.info->facility = r->info->facility;
1098 dest_r.info->level = r->info->level;
1099 dest_r.info->flags = r->info->flags;
1100 dest_r.info->ts_nsec = r->info->ts_nsec;
1101 dest_r.info->caller_id = r->info->caller_id;
1102 memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1104 prb_final_commit(&e);
1106 return prb_record_text_space(&e);
1109 static char setup_text_buf[LOG_LINE_MAX] __initdata;
1111 void __init setup_log_buf(int early)
1113 struct printk_info *new_infos;
1114 unsigned int new_descs_count;
1115 struct prb_desc *new_descs;
1116 struct printk_info info;
1117 struct printk_record r;
1118 size_t new_descs_size;
1119 size_t new_infos_size;
1120 unsigned long flags;
1126 * Some archs call setup_log_buf() multiple times - first is very
1127 * early, e.g. from setup_arch(), and second - when percpu_areas
1131 set_percpu_data_ready();
1133 if (log_buf != __log_buf)
1136 if (!early && !new_log_buf_len)
1139 if (!new_log_buf_len)
1142 new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1143 if (new_descs_count == 0) {
1144 pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1148 new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1149 if (unlikely(!new_log_buf)) {
1150 pr_err("log_buf_len: %lu text bytes not available\n",
1155 new_descs_size = new_descs_count * sizeof(struct prb_desc);
1156 new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1157 if (unlikely(!new_descs)) {
1158 pr_err("log_buf_len: %zu desc bytes not available\n",
1160 goto err_free_log_buf;
1163 new_infos_size = new_descs_count * sizeof(struct printk_info);
1164 new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1165 if (unlikely(!new_infos)) {
1166 pr_err("log_buf_len: %zu info bytes not available\n",
1168 goto err_free_descs;
1171 prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1173 prb_init(&printk_rb_dynamic,
1174 new_log_buf, ilog2(new_log_buf_len),
1175 new_descs, ilog2(new_descs_count),
1178 logbuf_lock_irqsave(flags);
1180 log_buf_len = new_log_buf_len;
1181 log_buf = new_log_buf;
1182 new_log_buf_len = 0;
1184 free = __LOG_BUF_LEN;
1185 prb_for_each_record(0, &printk_rb_static, seq, &r)
1186 free -= add_to_rb(&printk_rb_dynamic, &r);
1189 * This is early enough that everything is still running on the
1190 * boot CPU and interrupts are disabled. So no new messages will
1191 * appear during the transition to the dynamic buffer.
1193 prb = &printk_rb_dynamic;
1195 logbuf_unlock_irqrestore(flags);
1197 if (seq != prb_next_seq(&printk_rb_static)) {
1198 pr_err("dropped %llu messages\n",
1199 prb_next_seq(&printk_rb_static) - seq);
1202 pr_info("log_buf_len: %u bytes\n", log_buf_len);
1203 pr_info("early log buf free: %u(%u%%)\n",
1204 free, (free * 100) / __LOG_BUF_LEN);
1208 memblock_free(__pa(new_descs), new_descs_size);
1210 memblock_free(__pa(new_log_buf), new_log_buf_len);
1213 static bool __read_mostly ignore_loglevel;
1215 static int __init ignore_loglevel_setup(char *str)
1217 ignore_loglevel = true;
1218 pr_info("debug: ignoring loglevel setting.\n");
1223 early_param("ignore_loglevel", ignore_loglevel_setup);
1224 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1225 MODULE_PARM_DESC(ignore_loglevel,
1226 "ignore loglevel setting (prints all kernel messages to the console)");
1228 static bool suppress_message_printing(int level)
1230 return (level >= console_loglevel && !ignore_loglevel);
1233 #ifdef CONFIG_BOOT_PRINTK_DELAY
1235 static int boot_delay; /* msecs delay after each printk during bootup */
1236 static unsigned long long loops_per_msec; /* based on boot_delay */
1238 static int __init boot_delay_setup(char *str)
1242 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
1243 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1245 get_option(&str, &boot_delay);
1246 if (boot_delay > 10 * 1000)
1249 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1250 "HZ: %d, loops_per_msec: %llu\n",
1251 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1254 early_param("boot_delay", boot_delay_setup);
1256 static void boot_delay_msec(int level)
1258 unsigned long long k;
1259 unsigned long timeout;
1261 if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1262 || suppress_message_printing(level)) {
1266 k = (unsigned long long)loops_per_msec * boot_delay;
1268 timeout = jiffies + msecs_to_jiffies(boot_delay);
1273 * use (volatile) jiffies to prevent
1274 * compiler reduction; loop termination via jiffies
1275 * is secondary and may or may not happen.
1277 if (time_after(jiffies, timeout))
1279 touch_nmi_watchdog();
1283 static inline void boot_delay_msec(int level)
1288 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1289 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1291 static size_t print_syslog(unsigned int level, char *buf)
1293 return sprintf(buf, "<%u>", level);
1296 static size_t print_time(u64 ts, char *buf)
1298 unsigned long rem_nsec = do_div(ts, 1000000000);
1300 return sprintf(buf, "[%5lu.%06lu]",
1301 (unsigned long)ts, rem_nsec / 1000);
1304 #ifdef CONFIG_PRINTK_CALLER
1305 static size_t print_caller(u32 id, char *buf)
1309 snprintf(caller, sizeof(caller), "%c%u",
1310 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1311 return sprintf(buf, "[%6s]", caller);
1314 #define print_caller(id, buf) 0
1317 static size_t info_print_prefix(const struct printk_info *info, bool syslog,
1318 bool time, char *buf)
1323 len = print_syslog((info->facility << 3) | info->level, buf);
1326 len += print_time(info->ts_nsec, buf + len);
1328 len += print_caller(info->caller_id, buf + len);
1330 if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1339 * Prepare the record for printing. The text is shifted within the given
1340 * buffer to avoid a need for another one. The following operations are
1343 * - Add prefix for each line.
1344 * - Drop truncated lines that no longer fit into the buffer.
1345 * - Add the trailing newline that has been removed in vprintk_store().
1346 * - Add a string terminator.
1348 * Since the produced string is always terminated, the maximum possible
1349 * return value is @r->text_buf_size - 1;
1351 * Return: The length of the updated/prepared text, including the added
1352 * prefixes and the newline. The terminator is not counted. The dropped
1353 * line(s) are not counted.
1355 static size_t record_print_text(struct printk_record *r, bool syslog,
1358 size_t text_len = r->info->text_len;
1359 size_t buf_size = r->text_buf_size;
1360 char *text = r->text_buf;
1361 char prefix[PREFIX_MAX];
1362 bool truncated = false;
1369 * If the message was truncated because the buffer was not large
1370 * enough, treat the available text as if it were the full text.
1372 if (text_len > buf_size)
1373 text_len = buf_size;
1375 prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1378 * @text_len: bytes of unprocessed text
1379 * @line_len: bytes of current line _without_ newline
1380 * @text: pointer to beginning of current line
1381 * @len: number of bytes prepared in r->text_buf
1384 next = memchr(text, '\n', text_len);
1386 line_len = next - text;
1388 /* Drop truncated line(s). */
1391 line_len = text_len;
1395 * Truncate the text if there is not enough space to add the
1396 * prefix and a trailing newline and a terminator.
1398 if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1399 /* Drop even the current line if no space. */
1400 if (len + prefix_len + line_len + 1 + 1 > buf_size)
1403 text_len = buf_size - len - prefix_len - 1 - 1;
1407 memmove(text + prefix_len, text, text_len);
1408 memcpy(text, prefix, prefix_len);
1411 * Increment the prepared length to include the text and
1412 * prefix that were just moved+copied. Also increment for the
1413 * newline at the end of this line. If this is the last line,
1414 * there is no newline, but it will be added immediately below.
1416 len += prefix_len + line_len + 1;
1417 if (text_len == line_len) {
1419 * This is the last line. Add the trailing newline
1420 * removed in vprintk_store().
1422 text[prefix_len + line_len] = '\n';
1427 * Advance beyond the added prefix and the related line with
1430 text += prefix_len + line_len + 1;
1433 * The remaining text has only decreased by the line with its
1436 * Note that @text_len can become zero. It happens when @text
1437 * ended with a newline (either due to truncation or the
1438 * original string ending with "\n\n"). The loop is correctly
1439 * repeated and (if not truncated) an empty line with a prefix
1442 text_len -= line_len + 1;
1446 * If a buffer was provided, it will be terminated. Space for the
1447 * string terminator is guaranteed to be available. The terminator is
1448 * not counted in the return value.
1451 r->text_buf[len] = 0;
1456 static size_t get_record_print_text_size(struct printk_info *info,
1457 unsigned int line_count,
1458 bool syslog, bool time)
1460 char prefix[PREFIX_MAX];
1463 prefix_len = info_print_prefix(info, syslog, time, prefix);
1466 * Each line will be preceded with a prefix. The intermediate
1467 * newlines are already within the text, but a final trailing
1468 * newline will be added.
1470 return ((prefix_len * line_count) + info->text_len + 1);
1473 static int syslog_print(char __user *buf, int size)
1475 struct printk_info info;
1476 struct printk_record r;
1480 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1484 prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
1491 if (!prb_read_valid(prb, syslog_seq, &r)) {
1492 logbuf_unlock_irq();
1495 if (r.info->seq != syslog_seq) {
1496 /* message is gone, move to next valid one */
1497 syslog_seq = r.info->seq;
1502 * To keep reading/counting partial line consistent,
1503 * use printk_time value as of the beginning of a line.
1505 if (!syslog_partial)
1506 syslog_time = printk_time;
1508 skip = syslog_partial;
1509 n = record_print_text(&r, true, syslog_time);
1510 if (n - syslog_partial <= size) {
1511 /* message fits into buffer, move forward */
1512 syslog_seq = r.info->seq + 1;
1513 n -= syslog_partial;
1516 /* partial read(), remember position */
1518 syslog_partial += n;
1521 logbuf_unlock_irq();
1526 if (copy_to_user(buf, text + skip, n)) {
1541 static int syslog_print_all(char __user *buf, int size, bool clear)
1543 struct printk_info info;
1544 unsigned int line_count;
1545 struct printk_record r;
1551 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1558 * Find first record that fits, including all following records,
1559 * into the user-provided buffer for this dump.
1561 prb_for_each_info(clear_seq, prb, seq, &info, &line_count)
1562 len += get_record_print_text_size(&info, line_count, true, time);
1564 /* move first record forward until length fits into the buffer */
1565 prb_for_each_info(clear_seq, prb, seq, &info, &line_count) {
1568 len -= get_record_print_text_size(&info, line_count, true, time);
1571 prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
1574 prb_for_each_record(seq, prb, seq, &r) {
1577 textlen = record_print_text(&r, true, time);
1579 if (len + textlen > size) {
1584 logbuf_unlock_irq();
1585 if (copy_to_user(buf + len, text, textlen))
1597 logbuf_unlock_irq();
1603 static void syslog_clear(void)
1606 clear_seq = prb_next_seq(prb);
1607 logbuf_unlock_irq();
1610 int do_syslog(int type, char __user *buf, int len, int source)
1612 struct printk_info info;
1614 static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1617 error = check_syslog_permissions(type, source);
1622 case SYSLOG_ACTION_CLOSE: /* Close log */
1624 case SYSLOG_ACTION_OPEN: /* Open log */
1626 case SYSLOG_ACTION_READ: /* Read from log */
1627 if (!buf || len < 0)
1631 if (!access_ok(buf, len))
1633 error = wait_event_interruptible(log_wait,
1634 prb_read_valid(prb, syslog_seq, NULL));
1637 error = syslog_print(buf, len);
1639 /* Read/clear last kernel messages */
1640 case SYSLOG_ACTION_READ_CLEAR:
1643 /* Read last kernel messages */
1644 case SYSLOG_ACTION_READ_ALL:
1645 if (!buf || len < 0)
1649 if (!access_ok(buf, len))
1651 error = syslog_print_all(buf, len, clear);
1653 /* Clear ring buffer */
1654 case SYSLOG_ACTION_CLEAR:
1657 /* Disable logging to console */
1658 case SYSLOG_ACTION_CONSOLE_OFF:
1659 if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1660 saved_console_loglevel = console_loglevel;
1661 console_loglevel = minimum_console_loglevel;
1663 /* Enable logging to console */
1664 case SYSLOG_ACTION_CONSOLE_ON:
1665 if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1666 console_loglevel = saved_console_loglevel;
1667 saved_console_loglevel = LOGLEVEL_DEFAULT;
1670 /* Set level of messages printed to console */
1671 case SYSLOG_ACTION_CONSOLE_LEVEL:
1672 if (len < 1 || len > 8)
1674 if (len < minimum_console_loglevel)
1675 len = minimum_console_loglevel;
1676 console_loglevel = len;
1677 /* Implicitly re-enable logging to console */
1678 saved_console_loglevel = LOGLEVEL_DEFAULT;
1680 /* Number of chars in the log buffer */
1681 case SYSLOG_ACTION_SIZE_UNREAD:
1683 if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1684 /* No unread messages. */
1685 logbuf_unlock_irq();
1688 if (info.seq != syslog_seq) {
1689 /* messages are gone, move to first one */
1690 syslog_seq = info.seq;
1693 if (source == SYSLOG_FROM_PROC) {
1695 * Short-cut for poll(/"proc/kmsg") which simply checks
1696 * for pending data, not the size; return the count of
1697 * records, not the length.
1699 error = prb_next_seq(prb) - syslog_seq;
1701 bool time = syslog_partial ? syslog_time : printk_time;
1702 unsigned int line_count;
1705 prb_for_each_info(syslog_seq, prb, seq, &info,
1707 error += get_record_print_text_size(&info, line_count,
1711 error -= syslog_partial;
1713 logbuf_unlock_irq();
1715 /* Size of the log buffer */
1716 case SYSLOG_ACTION_SIZE_BUFFER:
1717 error = log_buf_len;
1727 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1729 return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1733 * Special console_lock variants that help to reduce the risk of soft-lockups.
1734 * They allow to pass console_lock to another printk() call using a busy wait.
1737 #ifdef CONFIG_LOCKDEP
1738 static struct lockdep_map console_owner_dep_map = {
1739 .name = "console_owner"
1743 static DEFINE_RAW_SPINLOCK(console_owner_lock);
1744 static struct task_struct *console_owner;
1745 static bool console_waiter;
1748 * console_lock_spinning_enable - mark beginning of code where another
1749 * thread might safely busy wait
1751 * This basically converts console_lock into a spinlock. This marks
1752 * the section where the console_lock owner can not sleep, because
1753 * there may be a waiter spinning (like a spinlock). Also it must be
1754 * ready to hand over the lock at the end of the section.
1756 static void console_lock_spinning_enable(void)
1758 raw_spin_lock(&console_owner_lock);
1759 console_owner = current;
1760 raw_spin_unlock(&console_owner_lock);
1762 /* The waiter may spin on us after setting console_owner */
1763 spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1767 * console_lock_spinning_disable_and_check - mark end of code where another
1768 * thread was able to busy wait and check if there is a waiter
1770 * This is called at the end of the section where spinning is allowed.
1771 * It has two functions. First, it is a signal that it is no longer
1772 * safe to start busy waiting for the lock. Second, it checks if
1773 * there is a busy waiter and passes the lock rights to her.
1775 * Important: Callers lose the lock if there was a busy waiter.
1776 * They must not touch items synchronized by console_lock
1779 * Return: 1 if the lock rights were passed, 0 otherwise.
1781 static int console_lock_spinning_disable_and_check(void)
1785 raw_spin_lock(&console_owner_lock);
1786 waiter = READ_ONCE(console_waiter);
1787 console_owner = NULL;
1788 raw_spin_unlock(&console_owner_lock);
1791 spin_release(&console_owner_dep_map, _THIS_IP_);
1795 /* The waiter is now free to continue */
1796 WRITE_ONCE(console_waiter, false);
1798 spin_release(&console_owner_dep_map, _THIS_IP_);
1801 * Hand off console_lock to waiter. The waiter will perform
1802 * the up(). After this, the waiter is the console_lock owner.
1804 mutex_release(&console_lock_dep_map, _THIS_IP_);
1809 * console_trylock_spinning - try to get console_lock by busy waiting
1811 * This allows to busy wait for the console_lock when the current
1812 * owner is running in specially marked sections. It means that
1813 * the current owner is running and cannot reschedule until it
1814 * is ready to lose the lock.
1816 * Return: 1 if we got the lock, 0 othrewise
1818 static int console_trylock_spinning(void)
1820 struct task_struct *owner = NULL;
1823 unsigned long flags;
1825 if (console_trylock())
1828 printk_safe_enter_irqsave(flags);
1830 raw_spin_lock(&console_owner_lock);
1831 owner = READ_ONCE(console_owner);
1832 waiter = READ_ONCE(console_waiter);
1833 if (!waiter && owner && owner != current) {
1834 WRITE_ONCE(console_waiter, true);
1837 raw_spin_unlock(&console_owner_lock);
1840 * If there is an active printk() writing to the
1841 * consoles, instead of having it write our data too,
1842 * see if we can offload that load from the active
1843 * printer, and do some printing ourselves.
1844 * Go into a spin only if there isn't already a waiter
1845 * spinning, and there is an active printer, and
1846 * that active printer isn't us (recursive printk?).
1849 printk_safe_exit_irqrestore(flags);
1853 /* We spin waiting for the owner to release us */
1854 spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1855 /* Owner will clear console_waiter on hand off */
1856 while (READ_ONCE(console_waiter))
1858 spin_release(&console_owner_dep_map, _THIS_IP_);
1860 printk_safe_exit_irqrestore(flags);
1862 * The owner passed the console lock to us.
1863 * Since we did not spin on console lock, annotate
1864 * this as a trylock. Otherwise lockdep will
1867 mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
1870 * Update @console_may_schedule for trylock because the previous
1871 * owner may have been schedulable.
1873 console_may_schedule = 0;
1879 * Call the console drivers, asking them to write out
1880 * log_buf[start] to log_buf[end - 1].
1881 * The console_lock must be held.
1883 static void call_console_drivers(const char *ext_text, size_t ext_len,
1884 const char *text, size_t len)
1886 static char dropped_text[64];
1887 size_t dropped_len = 0;
1888 struct console *con;
1890 trace_console_rcuidle(text, len);
1892 if (!console_drivers)
1895 if (console_dropped) {
1896 dropped_len = snprintf(dropped_text, sizeof(dropped_text),
1897 "** %lu printk messages dropped **\n",
1899 console_dropped = 0;
1902 for_each_console(con) {
1903 if (exclusive_console && con != exclusive_console)
1905 if (!(con->flags & CON_ENABLED))
1909 if (!cpu_online(smp_processor_id()) &&
1910 !(con->flags & CON_ANYTIME))
1912 if (con->flags & CON_EXTENDED)
1913 con->write(con, ext_text, ext_len);
1916 con->write(con, dropped_text, dropped_len);
1917 con->write(con, text, len);
1922 int printk_delay_msec __read_mostly;
1924 static inline void printk_delay(void)
1926 if (unlikely(printk_delay_msec)) {
1927 int m = printk_delay_msec;
1931 touch_nmi_watchdog();
1936 static inline u32 printk_caller_id(void)
1938 return in_task() ? task_pid_nr(current) :
1939 0x80000000 + raw_smp_processor_id();
1942 static size_t log_output(int facility, int level, enum log_flags lflags,
1943 const struct dev_printk_info *dev_info,
1944 char *text, size_t text_len)
1946 const u32 caller_id = printk_caller_id();
1948 if (lflags & LOG_CONT) {
1949 struct prb_reserved_entry e;
1950 struct printk_record r;
1952 prb_rec_init_wr(&r, text_len);
1953 if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
1954 memcpy(&r.text_buf[r.info->text_len], text, text_len);
1955 r.info->text_len += text_len;
1956 if (lflags & LOG_NEWLINE) {
1957 r.info->flags |= LOG_NEWLINE;
1958 prb_final_commit(&e);
1966 /* Store it in the record log */
1967 return log_store(caller_id, facility, level, lflags, 0,
1968 dev_info, text, text_len);
1971 /* Must be called under logbuf_lock. */
1972 int vprintk_store(int facility, int level,
1973 const struct dev_printk_info *dev_info,
1974 const char *fmt, va_list args)
1976 static char textbuf[LOG_LINE_MAX];
1977 char *text = textbuf;
1979 enum log_flags lflags = 0;
1982 * The printf needs to come first; we need the syslog
1983 * prefix which might be passed-in as a parameter.
1985 text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
1987 /* mark and strip a trailing newline */
1988 if (text_len && text[text_len-1] == '\n') {
1990 lflags |= LOG_NEWLINE;
1993 /* strip kernel syslog prefix and extract log level or control flags */
1994 if (facility == 0) {
1997 while ((kern_level = printk_get_level(text)) != 0) {
1998 switch (kern_level) {
2000 if (level == LOGLEVEL_DEFAULT)
2001 level = kern_level - '0';
2003 case 'c': /* KERN_CONT */
2012 if (level == LOGLEVEL_DEFAULT)
2013 level = default_message_loglevel;
2016 lflags |= LOG_NEWLINE;
2018 return log_output(facility, level, lflags, dev_info, text, text_len);
2021 asmlinkage int vprintk_emit(int facility, int level,
2022 const struct dev_printk_info *dev_info,
2023 const char *fmt, va_list args)
2026 bool in_sched = false;
2027 unsigned long flags;
2029 /* Suppress unimportant messages after panic happens */
2030 if (unlikely(suppress_printk))
2033 if (level == LOGLEVEL_SCHED) {
2034 level = LOGLEVEL_DEFAULT;
2038 boot_delay_msec(level);
2041 /* This stops the holder of console_sem just where we want him */
2042 logbuf_lock_irqsave(flags);
2043 printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2044 logbuf_unlock_irqrestore(flags);
2046 /* If called from the scheduler, we can not call up(). */
2049 * Disable preemption to avoid being preempted while holding
2050 * console_sem which would prevent anyone from printing to
2055 * Try to acquire and then immediately release the console
2056 * semaphore. The release will print out buffers and wake up
2057 * /dev/kmsg and syslog() users.
2059 if (console_trylock_spinning())
2067 EXPORT_SYMBOL(vprintk_emit);
2069 asmlinkage int vprintk(const char *fmt, va_list args)
2071 return vprintk_func(fmt, args);
2073 EXPORT_SYMBOL(vprintk);
2075 int vprintk_default(const char *fmt, va_list args)
2077 return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2079 EXPORT_SYMBOL_GPL(vprintk_default);
2082 * printk - print a kernel message
2083 * @fmt: format string
2085 * This is printk(). It can be called from any context. We want it to work.
2087 * We try to grab the console_lock. If we succeed, it's easy - we log the
2088 * output and call the console drivers. If we fail to get the semaphore, we
2089 * place the output into the log buffer and return. The current holder of
2090 * the console_sem will notice the new output in console_unlock(); and will
2091 * send it to the consoles before releasing the lock.
2093 * One effect of this deferred printing is that code which calls printk() and
2094 * then changes console_loglevel may break. This is because console_loglevel
2095 * is inspected when the actual printing occurs.
2100 * See the vsnprintf() documentation for format string extensions over C99.
2102 asmlinkage __visible int printk(const char *fmt, ...)
2107 va_start(args, fmt);
2108 r = vprintk_func(fmt, args);
2113 EXPORT_SYMBOL(printk);
2115 #else /* CONFIG_PRINTK */
2117 #define LOG_LINE_MAX 0
2118 #define PREFIX_MAX 0
2119 #define printk_time false
2121 #define prb_read_valid(rb, seq, r) false
2122 #define prb_first_valid_seq(rb) 0
2124 static u64 syslog_seq;
2125 static u64 console_seq;
2126 static u64 exclusive_console_stop_seq;
2127 static unsigned long console_dropped;
2129 static size_t record_print_text(const struct printk_record *r,
2130 bool syslog, bool time)
2134 static ssize_t info_print_ext_header(char *buf, size_t size,
2135 struct printk_info *info)
2139 static ssize_t msg_print_ext_body(char *buf, size_t size,
2140 char *text, size_t text_len,
2141 struct dev_printk_info *dev_info) { return 0; }
2142 static void console_lock_spinning_enable(void) { }
2143 static int console_lock_spinning_disable_and_check(void) { return 0; }
2144 static void call_console_drivers(const char *ext_text, size_t ext_len,
2145 const char *text, size_t len) {}
2146 static bool suppress_message_printing(int level) { return false; }
2148 #endif /* CONFIG_PRINTK */
2150 #ifdef CONFIG_EARLY_PRINTK
2151 struct console *early_console;
2153 asmlinkage __visible void early_printk(const char *fmt, ...)
2163 n = vscnprintf(buf, sizeof(buf), fmt, ap);
2166 early_console->write(early_console, buf, n);
2170 static int __add_preferred_console(char *name, int idx, char *options,
2171 char *brl_options, bool user_specified)
2173 struct console_cmdline *c;
2177 * See if this tty is not yet registered, and
2178 * if we have a slot free.
2180 for (i = 0, c = console_cmdline;
2181 i < MAX_CMDLINECONSOLES && c->name[0];
2183 if (strcmp(c->name, name) == 0 && c->index == idx) {
2185 preferred_console = i;
2187 c->user_specified = true;
2191 if (i == MAX_CMDLINECONSOLES)
2194 preferred_console = i;
2195 strlcpy(c->name, name, sizeof(c->name));
2196 c->options = options;
2197 c->user_specified = user_specified;
2198 braille_set_options(c, brl_options);
2204 static int __init console_msg_format_setup(char *str)
2206 if (!strcmp(str, "syslog"))
2207 console_msg_format = MSG_FORMAT_SYSLOG;
2208 if (!strcmp(str, "default"))
2209 console_msg_format = MSG_FORMAT_DEFAULT;
2212 __setup("console_msg_format=", console_msg_format_setup);
2215 * Set up a console. Called via do_early_param() in init/main.c
2216 * for each "console=" parameter in the boot command line.
2218 static int __init console_setup(char *str)
2220 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2221 char *s, *options, *brl_options = NULL;
2225 * console="" or console=null have been suggested as a way to
2226 * disable console output. Use ttynull that has been created
2227 * for exacly this purpose.
2229 if (str[0] == 0 || strcmp(str, "null") == 0) {
2230 __add_preferred_console("ttynull", 0, NULL, NULL, true);
2234 if (_braille_console_setup(&str, &brl_options))
2238 * Decode str into name, index, options.
2240 if (str[0] >= '0' && str[0] <= '9') {
2241 strcpy(buf, "ttyS");
2242 strncpy(buf + 4, str, sizeof(buf) - 5);
2244 strncpy(buf, str, sizeof(buf) - 1);
2246 buf[sizeof(buf) - 1] = 0;
2247 options = strchr(str, ',');
2251 if (!strcmp(str, "ttya"))
2252 strcpy(buf, "ttyS0");
2253 if (!strcmp(str, "ttyb"))
2254 strcpy(buf, "ttyS1");
2256 for (s = buf; *s; s++)
2257 if (isdigit(*s) || *s == ',')
2259 idx = simple_strtoul(s, NULL, 10);
2262 __add_preferred_console(buf, idx, options, brl_options, true);
2263 console_set_on_cmdline = 1;
2266 __setup("console=", console_setup);
2269 * add_preferred_console - add a device to the list of preferred consoles.
2270 * @name: device name
2271 * @idx: device index
2272 * @options: options for this console
2274 * The last preferred console added will be used for kernel messages
2275 * and stdin/out/err for init. Normally this is used by console_setup
2276 * above to handle user-supplied console arguments; however it can also
2277 * be used by arch-specific code either to override the user or more
2278 * commonly to provide a default console (ie from PROM variables) when
2279 * the user has not supplied one.
2281 int add_preferred_console(char *name, int idx, char *options)
2283 return __add_preferred_console(name, idx, options, NULL, false);
2286 bool console_suspend_enabled = true;
2287 EXPORT_SYMBOL(console_suspend_enabled);
2289 static int __init console_suspend_disable(char *str)
2291 console_suspend_enabled = false;
2294 __setup("no_console_suspend", console_suspend_disable);
2295 module_param_named(console_suspend, console_suspend_enabled,
2296 bool, S_IRUGO | S_IWUSR);
2297 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2298 " and hibernate operations");
2301 * suspend_console - suspend the console subsystem
2303 * This disables printk() while we go into suspend states
2305 void suspend_console(void)
2307 if (!console_suspend_enabled)
2309 pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2311 console_suspended = 1;
2315 void resume_console(void)
2317 if (!console_suspend_enabled)
2320 console_suspended = 0;
2325 * console_cpu_notify - print deferred console messages after CPU hotplug
2328 * If printk() is called from a CPU that is not online yet, the messages
2329 * will be printed on the console only if there are CON_ANYTIME consoles.
2330 * This function is called when a new CPU comes online (or fails to come
2331 * up) or goes offline.
2333 static int console_cpu_notify(unsigned int cpu)
2335 if (!cpuhp_tasks_frozen) {
2336 /* If trylock fails, someone else is doing the printing */
2337 if (console_trylock())
2344 * console_lock - lock the console system for exclusive use.
2346 * Acquires a lock which guarantees that the caller has
2347 * exclusive access to the console system and the console_drivers list.
2349 * Can sleep, returns nothing.
2351 void console_lock(void)
2356 if (console_suspended)
2359 console_may_schedule = 1;
2361 EXPORT_SYMBOL(console_lock);
2364 * console_trylock - try to lock the console system for exclusive use.
2366 * Try to acquire a lock which guarantees that the caller has exclusive
2367 * access to the console system and the console_drivers list.
2369 * returns 1 on success, and 0 on failure to acquire the lock.
2371 int console_trylock(void)
2373 if (down_trylock_console_sem())
2375 if (console_suspended) {
2380 console_may_schedule = 0;
2383 EXPORT_SYMBOL(console_trylock);
2385 int is_console_locked(void)
2387 return console_locked;
2389 EXPORT_SYMBOL(is_console_locked);
2392 * Check if we have any console that is capable of printing while cpu is
2393 * booting or shutting down. Requires console_sem.
2395 static int have_callable_console(void)
2397 struct console *con;
2399 for_each_console(con)
2400 if ((con->flags & CON_ENABLED) &&
2401 (con->flags & CON_ANYTIME))
2408 * Can we actually use the console at this time on this cpu?
2410 * Console drivers may assume that per-cpu resources have been allocated. So
2411 * unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
2412 * call them until this CPU is officially up.
2414 static inline int can_use_console(void)
2416 return cpu_online(raw_smp_processor_id()) || have_callable_console();
2420 * console_unlock - unlock the console system
2422 * Releases the console_lock which the caller holds on the console system
2423 * and the console driver list.
2425 * While the console_lock was held, console output may have been buffered
2426 * by printk(). If this is the case, console_unlock(); emits
2427 * the output prior to releasing the lock.
2429 * If there is output waiting, we wake /dev/kmsg and syslog() users.
2431 * console_unlock(); may be called from any context.
2433 void console_unlock(void)
2435 static char ext_text[CONSOLE_EXT_LOG_MAX];
2436 static char text[LOG_LINE_MAX + PREFIX_MAX];
2437 unsigned long flags;
2438 bool do_cond_resched, retry;
2439 struct printk_info info;
2440 struct printk_record r;
2442 if (console_suspended) {
2447 prb_rec_init_rd(&r, &info, text, sizeof(text));
2450 * Console drivers are called with interrupts disabled, so
2451 * @console_may_schedule should be cleared before; however, we may
2452 * end up dumping a lot of lines, for example, if called from
2453 * console registration path, and should invoke cond_resched()
2454 * between lines if allowable. Not doing so can cause a very long
2455 * scheduling stall on a slow console leading to RCU stall and
2456 * softlockup warnings which exacerbate the issue with more
2457 * messages practically incapacitating the system.
2459 * console_trylock() is not able to detect the preemptive
2460 * context reliably. Therefore the value must be stored before
2461 * and cleared after the "again" goto label.
2463 do_cond_resched = console_may_schedule;
2465 console_may_schedule = 0;
2468 * We released the console_sem lock, so we need to recheck if
2469 * cpu is online and (if not) is there at least one CON_ANYTIME
2472 if (!can_use_console()) {
2482 printk_safe_enter_irqsave(flags);
2483 raw_spin_lock(&logbuf_lock);
2485 if (!prb_read_valid(prb, console_seq, &r))
2488 if (console_seq != r.info->seq) {
2489 console_dropped += r.info->seq - console_seq;
2490 console_seq = r.info->seq;
2493 if (suppress_message_printing(r.info->level)) {
2495 * Skip record we have buffered and already printed
2496 * directly to the console when we received it, and
2497 * record that has level above the console loglevel.
2503 /* Output to all consoles once old messages replayed. */
2504 if (unlikely(exclusive_console &&
2505 console_seq >= exclusive_console_stop_seq)) {
2506 exclusive_console = NULL;
2510 * Handle extended console text first because later
2511 * record_print_text() will modify the record buffer in-place.
2513 if (nr_ext_console_drivers) {
2514 ext_len = info_print_ext_header(ext_text,
2517 ext_len += msg_print_ext_body(ext_text + ext_len,
2518 sizeof(ext_text) - ext_len,
2523 len = record_print_text(&r,
2524 console_msg_format & MSG_FORMAT_SYSLOG,
2527 raw_spin_unlock(&logbuf_lock);
2530 * While actively printing out messages, if another printk()
2531 * were to occur on another CPU, it may wait for this one to
2532 * finish. This task can not be preempted if there is a
2533 * waiter waiting to take over.
2535 console_lock_spinning_enable();
2537 stop_critical_timings(); /* don't trace print latency */
2538 call_console_drivers(ext_text, ext_len, text, len);
2539 start_critical_timings();
2541 if (console_lock_spinning_disable_and_check()) {
2542 printk_safe_exit_irqrestore(flags);
2546 printk_safe_exit_irqrestore(flags);
2548 if (do_cond_resched)
2554 raw_spin_unlock(&logbuf_lock);
2559 * Someone could have filled up the buffer again, so re-check if there's
2560 * something to flush. In case we cannot trylock the console_sem again,
2561 * there's a new owner and the console_unlock() from them will do the
2562 * flush, no worries.
2564 raw_spin_lock(&logbuf_lock);
2565 retry = prb_read_valid(prb, console_seq, NULL);
2566 raw_spin_unlock(&logbuf_lock);
2567 printk_safe_exit_irqrestore(flags);
2569 if (retry && console_trylock())
2572 EXPORT_SYMBOL(console_unlock);
2575 * console_conditional_schedule - yield the CPU if required
2577 * If the console code is currently allowed to sleep, and
2578 * if this CPU should yield the CPU to another task, do
2581 * Must be called within console_lock();.
2583 void __sched console_conditional_schedule(void)
2585 if (console_may_schedule)
2588 EXPORT_SYMBOL(console_conditional_schedule);
2590 void console_unblank(void)
2595 * console_unblank can no longer be called in interrupt context unless
2596 * oops_in_progress is set to 1..
2598 if (oops_in_progress) {
2599 if (down_trylock_console_sem() != 0)
2605 console_may_schedule = 0;
2607 if ((c->flags & CON_ENABLED) && c->unblank)
2613 * console_flush_on_panic - flush console content on panic
2614 * @mode: flush all messages in buffer or just the pending ones
2616 * Immediately output all pending messages no matter what.
2618 void console_flush_on_panic(enum con_flush_mode mode)
2621 * If someone else is holding the console lock, trylock will fail
2622 * and may_schedule may be set. Ignore and proceed to unlock so
2623 * that messages are flushed out. As this can be called from any
2624 * context and we don't want to get preempted while flushing,
2625 * ensure may_schedule is cleared.
2628 console_may_schedule = 0;
2630 if (mode == CONSOLE_REPLAY_ALL) {
2631 unsigned long flags;
2633 logbuf_lock_irqsave(flags);
2634 console_seq = prb_first_valid_seq(prb);
2635 logbuf_unlock_irqrestore(flags);
2641 * Return the console tty driver structure and its associated index
2643 struct tty_driver *console_device(int *index)
2646 struct tty_driver *driver = NULL;
2649 for_each_console(c) {
2652 driver = c->device(c, index);
2661 * Prevent further output on the passed console device so that (for example)
2662 * serial drivers can disable console output before suspending a port, and can
2663 * re-enable output afterwards.
2665 void console_stop(struct console *console)
2668 console->flags &= ~CON_ENABLED;
2671 EXPORT_SYMBOL(console_stop);
2673 void console_start(struct console *console)
2676 console->flags |= CON_ENABLED;
2679 EXPORT_SYMBOL(console_start);
2681 static int __read_mostly keep_bootcon;
2683 static int __init keep_bootcon_setup(char *str)
2686 pr_info("debug: skip boot console de-registration.\n");
2691 early_param("keep_bootcon", keep_bootcon_setup);
2693 static int console_call_setup(struct console *newcon, char *options)
2700 /* Synchronize with possible boot console. */
2702 err = newcon->setup(newcon, options);
2709 * This is called by register_console() to try to match
2710 * the newly registered console with any of the ones selected
2711 * by either the command line or add_preferred_console() and
2714 * Care need to be taken with consoles that are statically
2715 * enabled such as netconsole
2717 static int try_enable_preferred_console(struct console *newcon,
2718 bool user_specified)
2720 struct console_cmdline *c;
2723 for (i = 0, c = console_cmdline;
2724 i < MAX_CMDLINECONSOLES && c->name[0];
2726 if (c->user_specified != user_specified)
2728 if (!newcon->match ||
2729 newcon->match(newcon, c->name, c->index, c->options) != 0) {
2730 /* default matching */
2731 BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
2732 if (strcmp(c->name, newcon->name) != 0)
2734 if (newcon->index >= 0 &&
2735 newcon->index != c->index)
2737 if (newcon->index < 0)
2738 newcon->index = c->index;
2740 if (_braille_register_console(newcon, c))
2743 err = console_call_setup(newcon, c->options);
2747 newcon->flags |= CON_ENABLED;
2748 if (i == preferred_console) {
2749 newcon->flags |= CON_CONSDEV;
2750 has_preferred_console = true;
2756 * Some consoles, such as pstore and netconsole, can be enabled even
2757 * without matching. Accept the pre-enabled consoles only when match()
2758 * and setup() had a chance to be called.
2760 if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
2766 /* Try to enable the console unconditionally */
2767 static void try_enable_default_console(struct console *newcon)
2769 if (newcon->index < 0)
2772 if (console_call_setup(newcon, NULL) != 0)
2775 newcon->flags |= CON_ENABLED;
2777 if (newcon->device) {
2778 newcon->flags |= CON_CONSDEV;
2779 has_preferred_console = true;
2784 * The console driver calls this routine during kernel initialization
2785 * to register the console printing procedure with printk() and to
2786 * print any messages that were printed by the kernel before the
2787 * console driver was initialized.
2789 * This can happen pretty early during the boot process (because of
2790 * early_printk) - sometimes before setup_arch() completes - be careful
2791 * of what kernel features are used - they may not be initialised yet.
2793 * There are two types of consoles - bootconsoles (early_printk) and
2794 * "real" consoles (everything which is not a bootconsole) which are
2795 * handled differently.
2796 * - Any number of bootconsoles can be registered at any time.
2797 * - As soon as a "real" console is registered, all bootconsoles
2798 * will be unregistered automatically.
2799 * - Once a "real" console is registered, any attempt to register a
2800 * bootconsoles will be rejected
2802 void register_console(struct console *newcon)
2804 unsigned long flags;
2805 struct console *bcon = NULL;
2808 for_each_console(bcon) {
2809 if (WARN(bcon == newcon, "console '%s%d' already registered\n",
2810 bcon->name, bcon->index))
2815 * before we register a new CON_BOOT console, make sure we don't
2816 * already have a valid console
2818 if (newcon->flags & CON_BOOT) {
2819 for_each_console(bcon) {
2820 if (!(bcon->flags & CON_BOOT)) {
2821 pr_info("Too late to register bootconsole %s%d\n",
2822 newcon->name, newcon->index);
2828 if (console_drivers && console_drivers->flags & CON_BOOT)
2829 bcon = console_drivers;
2831 if (!has_preferred_console || bcon || !console_drivers)
2832 has_preferred_console = preferred_console >= 0;
2835 * See if we want to use this console driver. If we
2836 * didn't select a console we take the first one
2837 * that registers here.
2839 if (!has_preferred_console)
2840 try_enable_default_console(newcon);
2842 /* See if this console matches one we selected on the command line */
2843 err = try_enable_preferred_console(newcon, true);
2845 /* If not, try to match against the platform default(s) */
2847 err = try_enable_preferred_console(newcon, false);
2849 /* printk() messages are not printed to the Braille console. */
2850 if (err || newcon->flags & CON_BRL)
2854 * If we have a bootconsole, and are switching to a real console,
2855 * don't print everything out again, since when the boot console, and
2856 * the real console are the same physical device, it's annoying to
2857 * see the beginning boot messages twice
2859 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
2860 newcon->flags &= ~CON_PRINTBUFFER;
2863 * Put this console in the list - keep the
2864 * preferred driver at the head of the list.
2867 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2868 newcon->next = console_drivers;
2869 console_drivers = newcon;
2871 newcon->next->flags &= ~CON_CONSDEV;
2872 /* Ensure this flag is always set for the head of the list */
2873 newcon->flags |= CON_CONSDEV;
2875 newcon->next = console_drivers->next;
2876 console_drivers->next = newcon;
2879 if (newcon->flags & CON_EXTENDED)
2880 nr_ext_console_drivers++;
2882 if (newcon->flags & CON_PRINTBUFFER) {
2884 * console_unlock(); will print out the buffered messages
2887 logbuf_lock_irqsave(flags);
2889 * We're about to replay the log buffer. Only do this to the
2890 * just-registered console to avoid excessive message spam to
2891 * the already-registered consoles.
2893 * Set exclusive_console with disabled interrupts to reduce
2894 * race window with eventual console_flush_on_panic() that
2895 * ignores console_lock.
2897 exclusive_console = newcon;
2898 exclusive_console_stop_seq = console_seq;
2899 console_seq = syslog_seq;
2900 logbuf_unlock_irqrestore(flags);
2903 console_sysfs_notify();
2906 * By unregistering the bootconsoles after we enable the real console
2907 * we get the "console xxx enabled" message on all the consoles -
2908 * boot consoles, real consoles, etc - this is to ensure that end
2909 * users know there might be something in the kernel's log buffer that
2910 * went to the bootconsole (that they do not see on the real console)
2912 pr_info("%sconsole [%s%d] enabled\n",
2913 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2914 newcon->name, newcon->index);
2916 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2918 /* We need to iterate through all boot consoles, to make
2919 * sure we print everything out, before we unregister them.
2921 for_each_console(bcon)
2922 if (bcon->flags & CON_BOOT)
2923 unregister_console(bcon);
2926 EXPORT_SYMBOL(register_console);
2928 int unregister_console(struct console *console)
2930 struct console *con;
2933 pr_info("%sconsole [%s%d] disabled\n",
2934 (console->flags & CON_BOOT) ? "boot" : "" ,
2935 console->name, console->index);
2937 res = _braille_unregister_console(console);
2945 if (console_drivers == console) {
2946 console_drivers=console->next;
2949 for_each_console(con) {
2950 if (con->next == console) {
2951 con->next = console->next;
2959 goto out_disable_unlock;
2961 if (console->flags & CON_EXTENDED)
2962 nr_ext_console_drivers--;
2965 * If this isn't the last console and it has CON_CONSDEV set, we
2966 * need to set it on the next preferred console.
2968 if (console_drivers != NULL && console->flags & CON_CONSDEV)
2969 console_drivers->flags |= CON_CONSDEV;
2971 console->flags &= ~CON_ENABLED;
2973 console_sysfs_notify();
2976 res = console->exit(console);
2981 console->flags &= ~CON_ENABLED;
2986 EXPORT_SYMBOL(unregister_console);
2989 * Initialize the console device. This is called *early*, so
2990 * we can't necessarily depend on lots of kernel help here.
2991 * Just do some early initializations, and do the complex setup
2994 void __init console_init(void)
2998 initcall_entry_t *ce;
3000 /* Setup the default TTY line discipline. */
3004 * set up the console device so that later boot sequences can
3005 * inform about problems etc..
3007 ce = __con_initcall_start;
3008 trace_initcall_level("console");
3009 while (ce < __con_initcall_end) {
3010 call = initcall_from_entry(ce);
3011 trace_initcall_start(call);
3013 trace_initcall_finish(call, ret);
3019 * Some boot consoles access data that is in the init section and which will
3020 * be discarded after the initcalls have been run. To make sure that no code
3021 * will access this data, unregister the boot consoles in a late initcall.
3023 * If for some reason, such as deferred probe or the driver being a loadable
3024 * module, the real console hasn't registered yet at this point, there will
3025 * be a brief interval in which no messages are logged to the console, which
3026 * makes it difficult to diagnose problems that occur during this time.
3028 * To mitigate this problem somewhat, only unregister consoles whose memory
3029 * intersects with the init section. Note that all other boot consoles will
3030 * get unregistred when the real preferred console is registered.
3032 static int __init printk_late_init(void)
3034 struct console *con;
3037 for_each_console(con) {
3038 if (!(con->flags & CON_BOOT))
3041 /* Check addresses that might be used for enabled consoles. */
3042 if (init_section_intersects(con, sizeof(*con)) ||
3043 init_section_contains(con->write, 0) ||
3044 init_section_contains(con->read, 0) ||
3045 init_section_contains(con->device, 0) ||
3046 init_section_contains(con->unblank, 0) ||
3047 init_section_contains(con->data, 0)) {
3049 * Please, consider moving the reported consoles out
3050 * of the init section.
3052 pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3053 con->name, con->index);
3054 unregister_console(con);
3057 ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3058 console_cpu_notify);
3060 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3061 console_cpu_notify, NULL);
3065 late_initcall(printk_late_init);
3067 #if defined CONFIG_PRINTK
3069 * Delayed printk version, for scheduler-internal messages:
3071 #define PRINTK_PENDING_WAKEUP 0x01
3072 #define PRINTK_PENDING_OUTPUT 0x02
3074 static DEFINE_PER_CPU(int, printk_pending);
3076 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3078 int pending = __this_cpu_xchg(printk_pending, 0);
3080 if (pending & PRINTK_PENDING_OUTPUT) {
3081 /* If trylock fails, someone else is doing the printing */
3082 if (console_trylock())
3086 if (pending & PRINTK_PENDING_WAKEUP)
3087 wake_up_interruptible(&log_wait);
3090 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
3091 .func = wake_up_klogd_work_func,
3092 .flags = ATOMIC_INIT(IRQ_WORK_LAZY),
3095 void wake_up_klogd(void)
3097 if (!printk_percpu_data_ready())
3101 if (waitqueue_active(&log_wait)) {
3102 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
3103 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3108 void defer_console_output(void)
3110 if (!printk_percpu_data_ready())
3114 __this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
3115 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3119 int vprintk_deferred(const char *fmt, va_list args)
3123 r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
3124 defer_console_output();
3129 int printk_deferred(const char *fmt, ...)
3134 va_start(args, fmt);
3135 r = vprintk_deferred(fmt, args);
3142 * printk rate limiting, lifted from the networking subsystem.
3144 * This enforces a rate limit: not more than 10 kernel messages
3145 * every 5s to make a denial-of-service attack impossible.
3147 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3149 int __printk_ratelimit(const char *func)
3151 return ___ratelimit(&printk_ratelimit_state, func);
3153 EXPORT_SYMBOL(__printk_ratelimit);
3156 * printk_timed_ratelimit - caller-controlled printk ratelimiting
3157 * @caller_jiffies: pointer to caller's state
3158 * @interval_msecs: minimum interval between prints
3160 * printk_timed_ratelimit() returns true if more than @interval_msecs
3161 * milliseconds have elapsed since the last time printk_timed_ratelimit()
3164 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
3165 unsigned int interval_msecs)
3167 unsigned long elapsed = jiffies - *caller_jiffies;
3169 if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
3172 *caller_jiffies = jiffies;
3175 EXPORT_SYMBOL(printk_timed_ratelimit);
3177 static DEFINE_SPINLOCK(dump_list_lock);
3178 static LIST_HEAD(dump_list);
3181 * kmsg_dump_register - register a kernel log dumper.
3182 * @dumper: pointer to the kmsg_dumper structure
3184 * Adds a kernel log dumper to the system. The dump callback in the
3185 * structure will be called when the kernel oopses or panics and must be
3186 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
3188 int kmsg_dump_register(struct kmsg_dumper *dumper)
3190 unsigned long flags;
3193 /* The dump callback needs to be set */
3197 spin_lock_irqsave(&dump_list_lock, flags);
3198 /* Don't allow registering multiple times */
3199 if (!dumper->registered) {
3200 dumper->registered = 1;
3201 list_add_tail_rcu(&dumper->list, &dump_list);
3204 spin_unlock_irqrestore(&dump_list_lock, flags);
3208 EXPORT_SYMBOL_GPL(kmsg_dump_register);
3211 * kmsg_dump_unregister - unregister a kmsg dumper.
3212 * @dumper: pointer to the kmsg_dumper structure
3214 * Removes a dump device from the system. Returns zero on success and
3215 * %-EINVAL otherwise.
3217 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
3219 unsigned long flags;
3222 spin_lock_irqsave(&dump_list_lock, flags);
3223 if (dumper->registered) {
3224 dumper->registered = 0;
3225 list_del_rcu(&dumper->list);
3228 spin_unlock_irqrestore(&dump_list_lock, flags);
3233 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
3235 static bool always_kmsg_dump;
3236 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
3238 const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
3241 case KMSG_DUMP_PANIC:
3243 case KMSG_DUMP_OOPS:
3245 case KMSG_DUMP_EMERG:
3247 case KMSG_DUMP_SHUTDOWN:
3253 EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
3256 * kmsg_dump - dump kernel log to kernel message dumpers.
3257 * @reason: the reason (oops, panic etc) for dumping
3259 * Call each of the registered dumper's dump() callback, which can
3260 * retrieve the kmsg records with kmsg_dump_get_line() or
3261 * kmsg_dump_get_buffer().
3263 void kmsg_dump(enum kmsg_dump_reason reason)
3265 struct kmsg_dumper *dumper;
3266 unsigned long flags;
3269 list_for_each_entry_rcu(dumper, &dump_list, list) {
3270 enum kmsg_dump_reason max_reason = dumper->max_reason;
3273 * If client has not provided a specific max_reason, default
3274 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
3276 if (max_reason == KMSG_DUMP_UNDEF) {
3277 max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
3280 if (reason > max_reason)
3283 /* initialize iterator with data about the stored records */
3284 dumper->active = true;
3286 logbuf_lock_irqsave(flags);
3287 dumper->cur_seq = clear_seq;
3288 dumper->next_seq = prb_next_seq(prb);
3289 logbuf_unlock_irqrestore(flags);
3291 /* invoke dumper which will iterate over records */
3292 dumper->dump(dumper, reason);
3294 /* reset iterator */
3295 dumper->active = false;
3301 * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
3302 * @dumper: registered kmsg dumper
3303 * @syslog: include the "<4>" prefixes
3304 * @line: buffer to copy the line to
3305 * @size: maximum size of the buffer
3306 * @len: length of line placed into buffer
3308 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3309 * record, and copy one record into the provided buffer.
3311 * Consecutive calls will return the next available record moving
3312 * towards the end of the buffer with the youngest messages.
3314 * A return value of FALSE indicates that there are no more records to
3317 * The function is similar to kmsg_dump_get_line(), but grabs no locks.
3319 bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
3320 char *line, size_t size, size_t *len)
3322 struct printk_info info;
3323 unsigned int line_count;
3324 struct printk_record r;
3328 prb_rec_init_rd(&r, &info, line, size);
3330 if (!dumper->active)
3333 /* Read text or count text lines? */
3335 if (!prb_read_valid(prb, dumper->cur_seq, &r))
3337 l = record_print_text(&r, syslog, printk_time);
3339 if (!prb_read_valid_info(prb, dumper->cur_seq,
3340 &info, &line_count)) {
3343 l = get_record_print_text_size(&info, line_count, syslog,
3348 dumper->cur_seq = r.info->seq + 1;
3357 * kmsg_dump_get_line - retrieve one kmsg log line
3358 * @dumper: registered kmsg dumper
3359 * @syslog: include the "<4>" prefixes
3360 * @line: buffer to copy the line to
3361 * @size: maximum size of the buffer
3362 * @len: length of line placed into buffer
3364 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3365 * record, and copy one record into the provided buffer.
3367 * Consecutive calls will return the next available record moving
3368 * towards the end of the buffer with the youngest messages.
3370 * A return value of FALSE indicates that there are no more records to
3373 bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
3374 char *line, size_t size, size_t *len)
3376 unsigned long flags;
3379 logbuf_lock_irqsave(flags);
3380 ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
3381 logbuf_unlock_irqrestore(flags);
3385 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
3388 * kmsg_dump_get_buffer - copy kmsg log lines
3389 * @dumper: registered kmsg dumper
3390 * @syslog: include the "<4>" prefixes
3391 * @buf: buffer to copy the line to
3392 * @size: maximum size of the buffer
3393 * @len: length of line placed into buffer
3395 * Start at the end of the kmsg buffer and fill the provided buffer
3396 * with as many of the *youngest* kmsg records that fit into it.
3397 * If the buffer is large enough, all available kmsg records will be
3398 * copied with a single call.
3400 * Consecutive calls will fill the buffer with the next block of
3401 * available older records, not including the earlier retrieved ones.
3403 * A return value of FALSE indicates that there are no more records to
3406 bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
3407 char *buf, size_t size, size_t *len)
3409 struct printk_info info;
3410 unsigned int line_count;
3411 struct printk_record r;
3412 unsigned long flags;
3417 bool time = printk_time;
3419 prb_rec_init_rd(&r, &info, buf, size);
3421 if (!dumper->active || !buf || !size)
3424 logbuf_lock_irqsave(flags);
3425 if (prb_read_valid_info(prb, dumper->cur_seq, &info, NULL)) {
3426 if (info.seq != dumper->cur_seq) {
3427 /* messages are gone, move to first available one */
3428 dumper->cur_seq = info.seq;
3433 if (dumper->cur_seq >= dumper->next_seq) {
3434 logbuf_unlock_irqrestore(flags);
3438 /* calculate length of entire buffer */
3439 seq = dumper->cur_seq;
3440 while (prb_read_valid_info(prb, seq, &info, &line_count)) {
3441 if (r.info->seq >= dumper->next_seq)
3443 l += get_record_print_text_size(&info, line_count, syslog, time);
3444 seq = r.info->seq + 1;
3447 /* move first record forward until length fits into the buffer */
3448 seq = dumper->cur_seq;
3449 while (l >= size && prb_read_valid_info(prb, seq,
3450 &info, &line_count)) {
3451 if (r.info->seq >= dumper->next_seq)
3453 l -= get_record_print_text_size(&info, line_count, syslog, time);
3454 seq = r.info->seq + 1;
3457 /* last message in next interation */
3460 /* actually read text into the buffer now */
3462 while (prb_read_valid(prb, seq, &r)) {
3463 if (r.info->seq >= dumper->next_seq)
3466 l += record_print_text(&r, syslog, time);
3468 /* adjust record to store to remaining buffer space */
3469 prb_rec_init_rd(&r, &info, buf + l, size - l);
3471 seq = r.info->seq + 1;
3474 dumper->next_seq = next_seq;
3476 logbuf_unlock_irqrestore(flags);
3482 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
3485 * kmsg_dump_rewind_nolock - reset the iterator (unlocked version)
3486 * @dumper: registered kmsg dumper
3488 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3489 * kmsg_dump_get_buffer() can be called again and used multiple
3490 * times within the same dumper.dump() callback.
3492 * The function is similar to kmsg_dump_rewind(), but grabs no locks.
3494 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
3496 dumper->cur_seq = clear_seq;
3497 dumper->next_seq = prb_next_seq(prb);
3501 * kmsg_dump_rewind - reset the iterator
3502 * @dumper: registered kmsg dumper
3504 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3505 * kmsg_dump_get_buffer() can be called again and used multiple
3506 * times within the same dumper.dump() callback.
3508 void kmsg_dump_rewind(struct kmsg_dumper *dumper)
3510 unsigned long flags;
3512 logbuf_lock_irqsave(flags);
3513 kmsg_dump_rewind_nolock(dumper);
3514 logbuf_unlock_irqrestore(flags);
3516 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);