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/kthread.h>
48 #include <linux/kdb.h>
49 #include <linux/clocksource.h>
50 #include <linux/sched/clock.h>
51 #include <linux/sched/debug.h>
52 #include <linux/sched/task_stack.h>
54 #include <linux/uaccess.h>
55 #include <asm/sections.h>
57 #include <trace/events/initcall.h>
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/printk.h>
61 #include "printk_ringbuffer.h"
62 #include "console_cmdline.h"
65 int console_printk[4] = {
66 CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
67 MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
68 CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
69 CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
71 EXPORT_SYMBOL_GPL(console_printk);
73 atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
74 EXPORT_SYMBOL(ignore_console_lock_warning);
77 * Low level drivers may need that to know if they can schedule in
78 * their unblank() callback or not. So let's export it.
81 EXPORT_SYMBOL(oops_in_progress);
84 * console_sem protects the console_drivers list, and also
85 * provides serialisation for access to the entire console
88 static DEFINE_SEMAPHORE(console_sem);
89 struct console *console_drivers;
90 EXPORT_SYMBOL_GPL(console_drivers);
93 * System may need to suppress printk message under certain
94 * circumstances, like after kernel panic happens.
96 int __read_mostly suppress_printk;
99 static struct lockdep_map console_lock_dep_map = {
100 .name = "console_lock"
104 enum devkmsg_log_bits {
105 __DEVKMSG_LOG_BIT_ON = 0,
106 __DEVKMSG_LOG_BIT_OFF,
107 __DEVKMSG_LOG_BIT_LOCK,
110 enum devkmsg_log_masks {
111 DEVKMSG_LOG_MASK_ON = BIT(__DEVKMSG_LOG_BIT_ON),
112 DEVKMSG_LOG_MASK_OFF = BIT(__DEVKMSG_LOG_BIT_OFF),
113 DEVKMSG_LOG_MASK_LOCK = BIT(__DEVKMSG_LOG_BIT_LOCK),
116 /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
117 #define DEVKMSG_LOG_MASK_DEFAULT 0
119 static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
121 static int __control_devkmsg(char *str)
128 len = str_has_prefix(str, "on");
130 devkmsg_log = DEVKMSG_LOG_MASK_ON;
134 len = str_has_prefix(str, "off");
136 devkmsg_log = DEVKMSG_LOG_MASK_OFF;
140 len = str_has_prefix(str, "ratelimit");
142 devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
149 static int __init control_devkmsg(char *str)
151 if (__control_devkmsg(str) < 0)
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)
230 if (down_trylock(&console_sem))
232 mutex_acquire(&console_lock_dep_map, 0, 1, ip);
235 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
237 static void __up_console_sem(unsigned long ip)
239 mutex_release(&console_lock_dep_map, ip);
243 #define up_console_sem() __up_console_sem(_RET_IP_)
246 * This is used for debugging the mess that is the VT code by
247 * keeping track if we have the console semaphore held. It's
248 * definitely not the perfect debug tool (we don't know if _WE_
249 * hold it and are racing, but it helps tracking those weird code
250 * paths in the console code where we end up in places I want
251 * locked without the console sempahore held).
253 static int console_locked, console_suspended;
256 * Array of consoles built from command line options (console=)
259 #define MAX_CMDLINECONSOLES 8
261 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
263 static int preferred_console = -1;
264 static bool has_preferred_console;
265 int console_set_on_cmdline;
266 EXPORT_SYMBOL(console_set_on_cmdline);
268 /* Flag: console code may call schedule() */
269 static int console_may_schedule;
271 enum con_msg_format_flags {
272 MSG_FORMAT_DEFAULT = 0,
273 MSG_FORMAT_SYSLOG = (1 << 0),
276 static int console_msg_format = MSG_FORMAT_DEFAULT;
279 * The printk log buffer consists of a sequenced collection of records, each
280 * containing variable length message text. Every record also contains its
281 * own meta-data (@info).
283 * Every record meta-data carries the timestamp in microseconds, as well as
284 * the standard userspace syslog level and syslog facility. The usual kernel
285 * messages use LOG_KERN; userspace-injected messages always carry a matching
286 * syslog facility, by default LOG_USER. The origin of every message can be
287 * reliably determined that way.
289 * The human readable log message of a record is available in @text, the
290 * length of the message text in @text_len. The stored message is not
293 * Optionally, a record can carry a dictionary of properties (key/value
294 * pairs), to provide userspace with a machine-readable message context.
296 * Examples for well-defined, commonly used property names are:
297 * DEVICE=b12:8 device identifier
301 * +sound:card0 subsystem:devname
302 * SUBSYSTEM=pci driver-core subsystem name
304 * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
305 * and values are terminated by a '\0' character.
307 * Example of record values:
308 * record.text_buf = "it's a line" (unterminated)
309 * record.info.seq = 56
310 * record.info.ts_nsec = 36863
311 * record.info.text_len = 11
312 * record.info.facility = 0 (LOG_KERN)
313 * record.info.flags = 0
314 * record.info.level = 3 (LOG_ERR)
315 * record.info.caller_id = 299 (task 299)
316 * record.info.dev_info.subsystem = "pci" (terminated)
317 * record.info.dev_info.device = "+pci:0000:00:01.0" (terminated)
319 * The 'struct printk_info' buffer must never be directly exported to
320 * userspace, it is a kernel-private implementation detail that might
321 * need to be changed in the future, when the requirements change.
323 * /dev/kmsg exports the structured data in the following line format:
324 * "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
326 * Users of the export format should ignore possible additional values
327 * separated by ',', and find the message after the ';' character.
329 * The optional key/value pairs are attached as continuation lines starting
330 * with a space character and terminated by a newline. All possible
331 * non-prinatable characters are escaped in the "\xff" notation.
335 LOG_NEWLINE = 2, /* text ended with a newline */
336 LOG_CONT = 8, /* text is a fragment of a continuation line */
340 /* syslog_lock protects syslog_* variables and write access to clear_seq. */
341 static DEFINE_SPINLOCK(syslog_lock);
343 /* Set to enable sync mode. Once set, it is never cleared. */
344 static bool sync_mode;
346 DECLARE_WAIT_QUEUE_HEAD(log_wait);
347 /* All 3 protected by @syslog_lock. */
348 /* the next printk record to read by syslog(READ) or /proc/kmsg */
349 static u64 syslog_seq;
350 static size_t syslog_partial;
351 static bool syslog_time;
354 seqcount_latch_t latch;
359 * The next printk record to read after the last 'clear' command. There are
360 * two copies (updated with seqcount_latch) so that reads can locklessly
361 * access a valid value. Writers are synchronized by @syslog_lock.
363 static struct latched_seq clear_seq = {
364 .latch = SEQCNT_LATCH_ZERO(clear_seq.latch),
369 #ifdef CONFIG_PRINTK_CALLER
370 #define PREFIX_MAX 48
372 #define PREFIX_MAX 32
375 /* the maximum size allowed to be reserved for a record */
376 #define LOG_LINE_MAX (1024 - PREFIX_MAX)
378 #define LOG_LEVEL(v) ((v) & 0x07)
379 #define LOG_FACILITY(v) ((v) >> 3 & 0xff)
382 #define LOG_ALIGN __alignof__(unsigned long)
383 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
384 #define LOG_BUF_LEN_MAX (u32)(1 << 31)
385 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
386 static char *log_buf = __log_buf;
387 static u32 log_buf_len = __LOG_BUF_LEN;
390 * Define the average message size. This only affects the number of
391 * descriptors that will be available. Underestimating is better than
392 * overestimating (too many available descriptors is better than not enough).
394 #define PRB_AVGBITS 5 /* 32 character average length */
396 #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
397 #error CONFIG_LOG_BUF_SHIFT value too small.
399 _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
400 PRB_AVGBITS, &__log_buf[0]);
402 static struct printk_ringbuffer printk_rb_dynamic;
404 static struct printk_ringbuffer *prb = &printk_rb_static;
407 * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
408 * per_cpu_areas are initialised. This variable is set to true when
409 * it's safe to access per-CPU data.
411 static bool __printk_percpu_data_ready __read_mostly;
413 static bool printk_percpu_data_ready(void)
415 return __printk_percpu_data_ready;
418 /* Must be called under syslog_lock. */
419 static void latched_seq_write(struct latched_seq *ls, u64 val)
421 raw_write_seqcount_latch(&ls->latch);
423 raw_write_seqcount_latch(&ls->latch);
427 /* Can be called from any context. */
428 static u64 latched_seq_read_nolock(struct latched_seq *ls)
435 seq = raw_read_seqcount_latch(&ls->latch);
438 } while (read_seqcount_latch_retry(&ls->latch, seq));
443 /* Return log buffer address */
444 char *log_buf_addr_get(void)
449 /* Return log buffer size */
450 u32 log_buf_len_get(void)
456 * Define how much of the log buffer we could take at maximum. The value
457 * must be greater than two. Note that only half of the buffer is available
458 * when the index points to the middle.
460 #define MAX_LOG_TAKE_PART 4
461 static const char trunc_msg[] = "<truncated>";
463 static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
466 * The message should not take the whole buffer. Otherwise, it might
467 * get removed too soon.
469 u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
471 if (*text_len > max_text_len)
472 *text_len = max_text_len;
474 /* enable the warning message (if there is room) */
475 *trunc_msg_len = strlen(trunc_msg);
476 if (*text_len >= *trunc_msg_len)
477 *text_len -= *trunc_msg_len;
482 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
484 static int syslog_action_restricted(int type)
489 * Unless restricted, we allow "read all" and "get buffer size"
492 return type != SYSLOG_ACTION_READ_ALL &&
493 type != SYSLOG_ACTION_SIZE_BUFFER;
496 static int check_syslog_permissions(int type, int source)
499 * If this is from /proc/kmsg and we've already opened it, then we've
500 * already done the capabilities checks at open time.
502 if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
505 if (syslog_action_restricted(type)) {
506 if (capable(CAP_SYSLOG))
509 * For historical reasons, accept CAP_SYS_ADMIN too, with
512 if (capable(CAP_SYS_ADMIN)) {
513 pr_warn_once("%s (%d): Attempt to access syslog with "
514 "CAP_SYS_ADMIN but no CAP_SYSLOG "
516 current->comm, task_pid_nr(current));
522 return security_syslog(type);
525 static void append_char(char **pp, char *e, char c)
531 static ssize_t info_print_ext_header(char *buf, size_t size,
532 struct printk_info *info)
534 u64 ts_usec = info->ts_nsec;
536 #ifdef CONFIG_PRINTK_CALLER
537 u32 id = info->caller_id;
539 snprintf(caller, sizeof(caller), ",caller=%c%u",
540 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
545 do_div(ts_usec, 1000);
547 return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
548 (info->facility << 3) | info->level, info->seq,
549 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
552 static ssize_t msg_add_ext_text(char *buf, size_t size,
553 const char *text, size_t text_len,
556 char *p = buf, *e = buf + size;
559 /* escape non-printable characters */
560 for (i = 0; i < text_len; i++) {
561 unsigned char c = text[i];
563 if (c < ' ' || c >= 127 || c == '\\')
564 p += scnprintf(p, e - p, "\\x%02x", c);
566 append_char(&p, e, c);
568 append_char(&p, e, endc);
573 static ssize_t msg_add_dict_text(char *buf, size_t size,
574 const char *key, const char *val)
576 size_t val_len = strlen(val);
582 len = msg_add_ext_text(buf, size, "", 0, ' '); /* dict prefix */
583 len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
584 len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
589 static ssize_t msg_print_ext_body(char *buf, size_t size,
590 char *text, size_t text_len,
591 struct dev_printk_info *dev_info)
595 len = msg_add_ext_text(buf, size, text, text_len, '\n');
600 len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
601 dev_info->subsystem);
602 len += msg_add_dict_text(buf + len, size - len, "DEVICE",
608 /* /dev/kmsg - userspace message inject/listen interface */
609 struct devkmsg_user {
611 struct ratelimit_state rs;
613 char buf[CONSOLE_EXT_LOG_MAX];
615 struct printk_info info;
616 char text_buf[CONSOLE_EXT_LOG_MAX];
617 struct printk_record record;
620 static __printf(3, 4) __cold
621 int devkmsg_emit(int facility, int level, const char *fmt, ...)
627 r = vprintk_emit(facility, level, NULL, fmt, args);
633 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
636 int level = default_message_loglevel;
637 int facility = 1; /* LOG_USER */
638 struct file *file = iocb->ki_filp;
639 struct devkmsg_user *user = file->private_data;
640 size_t len = iov_iter_count(from);
643 if (!user || len > LOG_LINE_MAX)
646 /* Ignore when user logging is disabled. */
647 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
650 /* Ratelimit when not explicitly enabled. */
651 if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
652 if (!___ratelimit(&user->rs, current->comm))
656 buf = kmalloc(len+1, GFP_KERNEL);
661 if (!copy_from_iter_full(buf, len, from)) {
667 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
668 * the decimal value represents 32bit, the lower 3 bit are the log
669 * level, the rest are the log facility.
671 * If no prefix or no userspace facility is specified, we
672 * enforce LOG_USER, to be able to reliably distinguish
673 * kernel-generated messages from userspace-injected ones.
676 if (line[0] == '<') {
680 u = simple_strtoul(line + 1, &endp, 10);
681 if (endp && endp[0] == '>') {
682 level = LOG_LEVEL(u);
683 if (LOG_FACILITY(u) != 0)
684 facility = LOG_FACILITY(u);
691 devkmsg_emit(facility, level, "%s", line);
696 static ssize_t devkmsg_read(struct file *file, char __user *buf,
697 size_t count, loff_t *ppos)
699 struct devkmsg_user *user = file->private_data;
700 struct printk_record *r = &user->record;
707 ret = mutex_lock_interruptible(&user->lock);
711 if (!prb_read_valid(prb, atomic64_read(&user->seq), r)) {
712 if (file->f_flags & O_NONBLOCK) {
717 ret = wait_event_interruptible(log_wait,
718 prb_read_valid(prb, atomic64_read(&user->seq), r));
723 if (r->info->seq != atomic64_read(&user->seq)) {
724 /* our last seen message is gone, return error and reset */
725 atomic64_set(&user->seq, r->info->seq);
730 len = info_print_ext_header(user->buf, sizeof(user->buf), r->info);
731 len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
732 &r->text_buf[0], r->info->text_len,
735 atomic64_set(&user->seq, r->info->seq + 1);
742 if (copy_to_user(buf, user->buf, len)) {
748 mutex_unlock(&user->lock);
753 * Be careful when modifying this function!!!
755 * Only few operations are supported because the device works only with the
756 * entire variable length messages (records). Non-standard values are
757 * returned in the other cases and has been this way for quite some time.
758 * User space applications might depend on this behavior.
760 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
762 struct devkmsg_user *user = file->private_data;
772 /* the first record */
773 atomic64_set(&user->seq, prb_first_valid_seq(prb));
777 * The first record after the last SYSLOG_ACTION_CLEAR,
778 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
779 * changes no global state, and does not clear anything.
781 atomic64_set(&user->seq, latched_seq_read_nolock(&clear_seq));
784 /* after the last record */
785 atomic64_set(&user->seq, prb_next_seq(prb));
793 static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
795 struct devkmsg_user *user = file->private_data;
796 struct printk_info info;
800 return EPOLLERR|EPOLLNVAL;
802 poll_wait(file, &log_wait, wait);
804 if (prb_read_valid_info(prb, atomic64_read(&user->seq), &info, NULL)) {
805 /* return error when data has vanished underneath us */
806 if (info.seq != atomic64_read(&user->seq))
807 ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
809 ret = EPOLLIN|EPOLLRDNORM;
815 static int devkmsg_open(struct inode *inode, struct file *file)
817 struct devkmsg_user *user;
820 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
823 /* write-only does not need any file context */
824 if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
825 err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
831 user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
835 ratelimit_default_init(&user->rs);
836 ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
838 mutex_init(&user->lock);
840 prb_rec_init_rd(&user->record, &user->info,
841 &user->text_buf[0], sizeof(user->text_buf));
843 atomic64_set(&user->seq, prb_first_valid_seq(prb));
845 file->private_data = user;
849 static int devkmsg_release(struct inode *inode, struct file *file)
851 struct devkmsg_user *user = file->private_data;
856 ratelimit_state_exit(&user->rs);
858 mutex_destroy(&user->lock);
863 const struct file_operations kmsg_fops = {
864 .open = devkmsg_open,
865 .read = devkmsg_read,
866 .write_iter = devkmsg_write,
867 .llseek = devkmsg_llseek,
868 .poll = devkmsg_poll,
869 .release = devkmsg_release,
872 #ifdef CONFIG_CRASH_CORE
874 * This appends the listed symbols to /proc/vmcore
876 * /proc/vmcore is used by various utilities, like crash and makedumpfile to
877 * obtain access to symbols that are otherwise very difficult to locate. These
878 * symbols are specifically used so that utilities can access and extract the
879 * dmesg log from a vmcore file after a crash.
881 void log_buf_vmcoreinfo_setup(void)
883 struct dev_printk_info *dev_info = NULL;
885 VMCOREINFO_SYMBOL(prb);
886 VMCOREINFO_SYMBOL(printk_rb_static);
887 VMCOREINFO_SYMBOL(clear_seq);
890 * Export struct size and field offsets. User space tools can
891 * parse it and detect any changes to structure down the line.
894 VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
895 VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
896 VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
897 VMCOREINFO_OFFSET(printk_ringbuffer, fail);
899 VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
900 VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
901 VMCOREINFO_OFFSET(prb_desc_ring, descs);
902 VMCOREINFO_OFFSET(prb_desc_ring, infos);
903 VMCOREINFO_OFFSET(prb_desc_ring, head_id);
904 VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
906 VMCOREINFO_STRUCT_SIZE(prb_desc);
907 VMCOREINFO_OFFSET(prb_desc, state_var);
908 VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
910 VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
911 VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
912 VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
914 VMCOREINFO_STRUCT_SIZE(printk_info);
915 VMCOREINFO_OFFSET(printk_info, seq);
916 VMCOREINFO_OFFSET(printk_info, ts_nsec);
917 VMCOREINFO_OFFSET(printk_info, text_len);
918 VMCOREINFO_OFFSET(printk_info, caller_id);
919 VMCOREINFO_OFFSET(printk_info, dev_info);
921 VMCOREINFO_STRUCT_SIZE(dev_printk_info);
922 VMCOREINFO_OFFSET(dev_printk_info, subsystem);
923 VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
924 VMCOREINFO_OFFSET(dev_printk_info, device);
925 VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
927 VMCOREINFO_STRUCT_SIZE(prb_data_ring);
928 VMCOREINFO_OFFSET(prb_data_ring, size_bits);
929 VMCOREINFO_OFFSET(prb_data_ring, data);
930 VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
931 VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
933 VMCOREINFO_SIZE(atomic_long_t);
934 VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
936 VMCOREINFO_STRUCT_SIZE(latched_seq);
937 VMCOREINFO_OFFSET(latched_seq, val);
941 /* requested log_buf_len from kernel cmdline */
942 static unsigned long __initdata new_log_buf_len;
944 /* we practice scaling the ring buffer by powers of 2 */
945 static void __init log_buf_len_update(u64 size)
947 if (size > (u64)LOG_BUF_LEN_MAX) {
948 size = (u64)LOG_BUF_LEN_MAX;
949 pr_err("log_buf over 2G is not supported.\n");
953 size = roundup_pow_of_two(size);
954 if (size > log_buf_len)
955 new_log_buf_len = (unsigned long)size;
958 /* save requested log_buf_len since it's too early to process it */
959 static int __init log_buf_len_setup(char *str)
966 size = memparse(str, &str);
968 log_buf_len_update(size);
972 early_param("log_buf_len", log_buf_len_setup);
975 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
977 static void __init log_buf_add_cpu(void)
979 unsigned int cpu_extra;
982 * archs should set up cpu_possible_bits properly with
983 * set_cpu_possible() after setup_arch() but just in
984 * case lets ensure this is valid.
986 if (num_possible_cpus() == 1)
989 cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
991 /* by default this will only continue through for large > 64 CPUs */
992 if (cpu_extra <= __LOG_BUF_LEN / 2)
995 pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
996 __LOG_CPU_MAX_BUF_LEN);
997 pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
999 pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1001 log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1003 #else /* !CONFIG_SMP */
1004 static inline void log_buf_add_cpu(void) {}
1005 #endif /* CONFIG_SMP */
1007 static void __init set_percpu_data_ready(void)
1009 __printk_percpu_data_ready = true;
1012 static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1013 struct printk_record *r)
1015 struct prb_reserved_entry e;
1016 struct printk_record dest_r;
1018 prb_rec_init_wr(&dest_r, r->info->text_len);
1020 if (!prb_reserve(&e, rb, &dest_r))
1023 memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1024 dest_r.info->text_len = r->info->text_len;
1025 dest_r.info->facility = r->info->facility;
1026 dest_r.info->level = r->info->level;
1027 dest_r.info->flags = r->info->flags;
1028 dest_r.info->ts_nsec = r->info->ts_nsec;
1029 dest_r.info->caller_id = r->info->caller_id;
1030 memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1032 prb_final_commit(&e);
1034 return prb_record_text_space(&e);
1037 static char setup_text_buf[LOG_LINE_MAX] __initdata;
1039 void __init setup_log_buf(int early)
1041 struct printk_info *new_infos;
1042 unsigned int new_descs_count;
1043 struct prb_desc *new_descs;
1044 struct printk_info info;
1045 struct printk_record r;
1046 size_t new_descs_size;
1047 size_t new_infos_size;
1053 * Some archs call setup_log_buf() multiple times - first is very
1054 * early, e.g. from setup_arch(), and second - when percpu_areas
1058 set_percpu_data_ready();
1060 if (log_buf != __log_buf)
1063 if (!early && !new_log_buf_len)
1066 if (!new_log_buf_len)
1069 new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1070 if (new_descs_count == 0) {
1071 pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1075 new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1076 if (unlikely(!new_log_buf)) {
1077 pr_err("log_buf_len: %lu text bytes not available\n",
1082 new_descs_size = new_descs_count * sizeof(struct prb_desc);
1083 new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1084 if (unlikely(!new_descs)) {
1085 pr_err("log_buf_len: %zu desc bytes not available\n",
1087 goto err_free_log_buf;
1090 new_infos_size = new_descs_count * sizeof(struct printk_info);
1091 new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1092 if (unlikely(!new_infos)) {
1093 pr_err("log_buf_len: %zu info bytes not available\n",
1095 goto err_free_descs;
1098 prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1100 prb_init(&printk_rb_dynamic,
1101 new_log_buf, ilog2(new_log_buf_len),
1102 new_descs, ilog2(new_descs_count),
1105 log_buf_len = new_log_buf_len;
1106 log_buf = new_log_buf;
1107 new_log_buf_len = 0;
1109 free = __LOG_BUF_LEN;
1110 prb_for_each_record(0, &printk_rb_static, seq, &r)
1111 free -= add_to_rb(&printk_rb_dynamic, &r);
1114 * This is early enough that everything is still running on the
1115 * boot CPU and interrupts are disabled. So no new messages will
1116 * appear during the transition to the dynamic buffer.
1118 prb = &printk_rb_dynamic;
1120 if (seq != prb_next_seq(&printk_rb_static)) {
1121 pr_err("dropped %llu messages\n",
1122 prb_next_seq(&printk_rb_static) - seq);
1125 pr_info("log_buf_len: %u bytes\n", log_buf_len);
1126 pr_info("early log buf free: %u(%u%%)\n",
1127 free, (free * 100) / __LOG_BUF_LEN);
1131 memblock_free(__pa(new_descs), new_descs_size);
1133 memblock_free(__pa(new_log_buf), new_log_buf_len);
1136 static bool __read_mostly ignore_loglevel;
1138 static int __init ignore_loglevel_setup(char *str)
1140 ignore_loglevel = true;
1141 pr_info("debug: ignoring loglevel setting.\n");
1146 early_param("ignore_loglevel", ignore_loglevel_setup);
1147 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1148 MODULE_PARM_DESC(ignore_loglevel,
1149 "ignore loglevel setting (prints all kernel messages to the console)");
1151 static bool suppress_message_printing(int level)
1153 return (level >= console_loglevel && !ignore_loglevel);
1156 #ifdef CONFIG_BOOT_PRINTK_DELAY
1158 static int boot_delay; /* msecs delay after each printk during bootup */
1159 static unsigned long long loops_per_msec; /* based on boot_delay */
1161 static int __init boot_delay_setup(char *str)
1165 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
1166 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1168 get_option(&str, &boot_delay);
1169 if (boot_delay > 10 * 1000)
1172 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1173 "HZ: %d, loops_per_msec: %llu\n",
1174 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1177 early_param("boot_delay", boot_delay_setup);
1179 static void boot_delay_msec(int level)
1181 unsigned long long k;
1182 unsigned long timeout;
1184 if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1185 || suppress_message_printing(level)) {
1189 k = (unsigned long long)loops_per_msec * boot_delay;
1191 timeout = jiffies + msecs_to_jiffies(boot_delay);
1196 * use (volatile) jiffies to prevent
1197 * compiler reduction; loop termination via jiffies
1198 * is secondary and may or may not happen.
1200 if (time_after(jiffies, timeout))
1202 touch_nmi_watchdog();
1206 static inline void boot_delay_msec(int level)
1211 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1212 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1214 static size_t print_syslog(unsigned int level, char *buf)
1216 return sprintf(buf, "<%u>", level);
1219 static size_t print_time(u64 ts, char *buf)
1221 unsigned long rem_nsec = do_div(ts, 1000000000);
1223 return sprintf(buf, "[%5lu.%06lu]",
1224 (unsigned long)ts, rem_nsec / 1000);
1227 #ifdef CONFIG_PRINTK_CALLER
1228 static size_t print_caller(u32 id, char *buf)
1232 snprintf(caller, sizeof(caller), "%c%u",
1233 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1234 return sprintf(buf, "[%6s]", caller);
1237 #define print_caller(id, buf) 0
1240 static size_t info_print_prefix(const struct printk_info *info, bool syslog,
1241 bool time, char *buf)
1246 len = print_syslog((info->facility << 3) | info->level, buf);
1249 len += print_time(info->ts_nsec, buf + len);
1251 len += print_caller(info->caller_id, buf + len);
1253 if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1262 * Prepare the record for printing. The text is shifted within the given
1263 * buffer to avoid a need for another one. The following operations are
1266 * - Add prefix for each line.
1267 * - Drop truncated lines that no longer fit into the buffer.
1268 * - Add the trailing newline that has been removed in vprintk_store().
1269 * - Add a string terminator.
1271 * Since the produced string is always terminated, the maximum possible
1272 * return value is @r->text_buf_size - 1;
1274 * Return: The length of the updated/prepared text, including the added
1275 * prefixes and the newline. The terminator is not counted. The dropped
1276 * line(s) are not counted.
1278 static size_t record_print_text(struct printk_record *r, bool syslog,
1281 size_t text_len = r->info->text_len;
1282 size_t buf_size = r->text_buf_size;
1283 char *text = r->text_buf;
1284 char prefix[PREFIX_MAX];
1285 bool truncated = false;
1292 * If the message was truncated because the buffer was not large
1293 * enough, treat the available text as if it were the full text.
1295 if (text_len > buf_size)
1296 text_len = buf_size;
1298 prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1301 * @text_len: bytes of unprocessed text
1302 * @line_len: bytes of current line _without_ newline
1303 * @text: pointer to beginning of current line
1304 * @len: number of bytes prepared in r->text_buf
1307 next = memchr(text, '\n', text_len);
1309 line_len = next - text;
1311 /* Drop truncated line(s). */
1314 line_len = text_len;
1318 * Truncate the text if there is not enough space to add the
1319 * prefix and a trailing newline and a terminator.
1321 if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1322 /* Drop even the current line if no space. */
1323 if (len + prefix_len + line_len + 1 + 1 > buf_size)
1326 text_len = buf_size - len - prefix_len - 1 - 1;
1330 memmove(text + prefix_len, text, text_len);
1331 memcpy(text, prefix, prefix_len);
1334 * Increment the prepared length to include the text and
1335 * prefix that were just moved+copied. Also increment for the
1336 * newline at the end of this line. If this is the last line,
1337 * there is no newline, but it will be added immediately below.
1339 len += prefix_len + line_len + 1;
1340 if (text_len == line_len) {
1342 * This is the last line. Add the trailing newline
1343 * removed in vprintk_store().
1345 text[prefix_len + line_len] = '\n';
1350 * Advance beyond the added prefix and the related line with
1353 text += prefix_len + line_len + 1;
1356 * The remaining text has only decreased by the line with its
1359 * Note that @text_len can become zero. It happens when @text
1360 * ended with a newline (either due to truncation or the
1361 * original string ending with "\n\n"). The loop is correctly
1362 * repeated and (if not truncated) an empty line with a prefix
1365 text_len -= line_len + 1;
1369 * If a buffer was provided, it will be terminated. Space for the
1370 * string terminator is guaranteed to be available. The terminator is
1371 * not counted in the return value.
1374 r->text_buf[len] = 0;
1379 static size_t get_record_print_text_size(struct printk_info *info,
1380 unsigned int line_count,
1381 bool syslog, bool time)
1383 char prefix[PREFIX_MAX];
1386 prefix_len = info_print_prefix(info, syslog, time, prefix);
1389 * Each line will be preceded with a prefix. The intermediate
1390 * newlines are already within the text, but a final trailing
1391 * newline will be added.
1393 return ((prefix_len * line_count) + info->text_len + 1);
1397 * Beginning with @start_seq, find the first record where it and all following
1398 * records up to (but not including) @max_seq fit into @size.
1400 * @max_seq is simply an upper bound and does not need to exist. If the caller
1401 * does not require an upper bound, -1 can be used for @max_seq.
1403 static u64 find_first_fitting_seq(u64 start_seq, u64 max_seq, size_t size,
1404 bool syslog, bool time)
1406 struct printk_info info;
1407 unsigned int line_count;
1411 /* Determine the size of the records up to @max_seq. */
1412 prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1413 if (info.seq >= max_seq)
1415 len += get_record_print_text_size(&info, line_count, syslog, time);
1419 * Adjust the upper bound for the next loop to avoid subtracting
1420 * lengths that were never added.
1426 * Move first record forward until length fits into the buffer. Ignore
1427 * newest messages that were not counted in the above cycle. Messages
1428 * might appear and get lost in the meantime. This is a best effort
1429 * that prevents an infinite loop that could occur with a retry.
1431 prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1432 if (len <= size || info.seq >= max_seq)
1434 len -= get_record_print_text_size(&info, line_count, syslog, time);
1440 static int syslog_print(char __user *buf, int size)
1442 struct printk_info info;
1443 struct printk_record r;
1447 text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
1451 prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
1457 spin_lock_irq(&syslog_lock);
1458 if (!prb_read_valid(prb, syslog_seq, &r)) {
1459 spin_unlock_irq(&syslog_lock);
1462 if (r.info->seq != syslog_seq) {
1463 /* message is gone, move to next valid one */
1464 syslog_seq = r.info->seq;
1469 * To keep reading/counting partial line consistent,
1470 * use printk_time value as of the beginning of a line.
1472 if (!syslog_partial)
1473 syslog_time = printk_time;
1475 skip = syslog_partial;
1476 n = record_print_text(&r, true, syslog_time);
1477 if (n - syslog_partial <= size) {
1478 /* message fits into buffer, move forward */
1479 syslog_seq = r.info->seq + 1;
1480 n -= syslog_partial;
1483 /* partial read(), remember position */
1485 syslog_partial += n;
1488 spin_unlock_irq(&syslog_lock);
1493 if (copy_to_user(buf, text + skip, n)) {
1508 static int syslog_print_all(char __user *buf, int size, bool clear)
1510 struct printk_info info;
1511 struct printk_record r;
1517 text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
1523 * Find first record that fits, including all following records,
1524 * into the user-provided buffer for this dump.
1526 seq = find_first_fitting_seq(latched_seq_read_nolock(&clear_seq), -1,
1529 prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
1532 prb_for_each_record(seq, prb, seq, &r) {
1535 textlen = record_print_text(&r, true, time);
1537 if (len + textlen > size) {
1542 if (copy_to_user(buf + len, text, textlen))
1552 spin_lock_irq(&syslog_lock);
1553 latched_seq_write(&clear_seq, seq);
1554 spin_unlock_irq(&syslog_lock);
1561 static void syslog_clear(void)
1563 spin_lock_irq(&syslog_lock);
1564 latched_seq_write(&clear_seq, prb_next_seq(prb));
1565 spin_unlock_irq(&syslog_lock);
1568 /* Return a consistent copy of @syslog_seq. */
1569 static u64 read_syslog_seq_irq(void)
1573 spin_lock_irq(&syslog_lock);
1575 spin_unlock_irq(&syslog_lock);
1580 int do_syslog(int type, char __user *buf, int len, int source)
1582 struct printk_info info;
1584 static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1587 error = check_syslog_permissions(type, source);
1592 case SYSLOG_ACTION_CLOSE: /* Close log */
1594 case SYSLOG_ACTION_OPEN: /* Open log */
1596 case SYSLOG_ACTION_READ: /* Read from log */
1597 if (!buf || len < 0)
1601 if (!access_ok(buf, len))
1604 error = wait_event_interruptible(log_wait,
1605 prb_read_valid(prb, read_syslog_seq_irq(), NULL));
1608 error = syslog_print(buf, len);
1610 /* Read/clear last kernel messages */
1611 case SYSLOG_ACTION_READ_CLEAR:
1614 /* Read last kernel messages */
1615 case SYSLOG_ACTION_READ_ALL:
1616 if (!buf || len < 0)
1620 if (!access_ok(buf, len))
1622 error = syslog_print_all(buf, len, clear);
1624 /* Clear ring buffer */
1625 case SYSLOG_ACTION_CLEAR:
1628 /* Disable logging to console */
1629 case SYSLOG_ACTION_CONSOLE_OFF:
1630 if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1631 saved_console_loglevel = console_loglevel;
1632 console_loglevel = minimum_console_loglevel;
1634 /* Enable logging to console */
1635 case SYSLOG_ACTION_CONSOLE_ON:
1636 if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1637 console_loglevel = saved_console_loglevel;
1638 saved_console_loglevel = LOGLEVEL_DEFAULT;
1641 /* Set level of messages printed to console */
1642 case SYSLOG_ACTION_CONSOLE_LEVEL:
1643 if (len < 1 || len > 8)
1645 if (len < minimum_console_loglevel)
1646 len = minimum_console_loglevel;
1647 console_loglevel = len;
1648 /* Implicitly re-enable logging to console */
1649 saved_console_loglevel = LOGLEVEL_DEFAULT;
1651 /* Number of chars in the log buffer */
1652 case SYSLOG_ACTION_SIZE_UNREAD:
1653 spin_lock_irq(&syslog_lock);
1654 if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1655 /* No unread messages. */
1656 spin_unlock_irq(&syslog_lock);
1659 if (info.seq != syslog_seq) {
1660 /* messages are gone, move to first one */
1661 syslog_seq = info.seq;
1664 if (source == SYSLOG_FROM_PROC) {
1666 * Short-cut for poll(/"proc/kmsg") which simply checks
1667 * for pending data, not the size; return the count of
1668 * records, not the length.
1670 error = prb_next_seq(prb) - syslog_seq;
1672 bool time = syslog_partial ? syslog_time : printk_time;
1673 unsigned int line_count;
1676 prb_for_each_info(syslog_seq, prb, seq, &info,
1678 error += get_record_print_text_size(&info, line_count,
1682 error -= syslog_partial;
1684 spin_unlock_irq(&syslog_lock);
1686 /* Size of the log buffer */
1687 case SYSLOG_ACTION_SIZE_BUFFER:
1688 error = log_buf_len;
1698 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1700 return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1703 int printk_delay_msec __read_mostly;
1705 static inline void printk_delay(int level)
1707 boot_delay_msec(level);
1709 if (unlikely(printk_delay_msec)) {
1710 int m = printk_delay_msec;
1714 touch_nmi_watchdog();
1719 static bool kernel_sync_mode(void)
1721 return (oops_in_progress || sync_mode);
1724 static bool console_can_sync(struct console *con)
1726 if (!(con->flags & CON_ENABLED))
1728 if (con->write_atomic && kernel_sync_mode())
1730 if (con->write_atomic && (con->flags & CON_HANDOVER) && !con->thread)
1732 if (con->write && (con->flags & CON_BOOT) && !con->thread)
1737 static bool call_sync_console_driver(struct console *con, const char *text, size_t text_len)
1739 if (!(con->flags & CON_ENABLED))
1741 if (con->write_atomic && kernel_sync_mode())
1742 con->write_atomic(con, text, text_len);
1743 else if (con->write_atomic && (con->flags & CON_HANDOVER) && !con->thread)
1744 con->write_atomic(con, text, text_len);
1745 else if (con->write && (con->flags & CON_BOOT) && !con->thread)
1746 con->write(con, text, text_len);
1753 static bool have_atomic_console(void)
1755 struct console *con;
1757 for_each_console(con) {
1758 if (!(con->flags & CON_ENABLED))
1760 if (con->write_atomic)
1766 static bool print_sync(struct console *con, u64 *seq)
1768 struct printk_info info;
1769 struct printk_record r;
1772 prb_rec_init_rd(&r, &info, &con->sync_buf[0], sizeof(con->sync_buf));
1774 if (!prb_read_valid(prb, *seq, &r))
1777 text_len = record_print_text(&r, console_msg_format & MSG_FORMAT_SYSLOG, printk_time);
1779 if (!call_sync_console_driver(con, &con->sync_buf[0], text_len))
1784 touch_softlockup_watchdog_sync();
1785 clocksource_touch_watchdog();
1786 rcu_cpu_stall_reset();
1787 touch_nmi_watchdog();
1790 printk_delay(r.info->level);
1795 static void print_sync_until(struct console *con, u64 seq)
1800 console_atomic_lock(&flags);
1802 printk_seq = atomic64_read(&con->printk_seq);
1803 if (printk_seq >= seq)
1805 if (!print_sync(con, &printk_seq))
1807 atomic64_set(&con->printk_seq, printk_seq + 1);
1809 console_atomic_unlock(flags);
1812 #ifdef CONFIG_PRINTK_NMI
1813 #define NUM_RECURSION_CTX 2
1815 #define NUM_RECURSION_CTX 1
1818 struct printk_recursion {
1819 char count[NUM_RECURSION_CTX];
1822 static DEFINE_PER_CPU(struct printk_recursion, percpu_printk_recursion);
1823 static char printk_recursion_count[NUM_RECURSION_CTX];
1825 static char *printk_recursion_counter(void)
1827 struct printk_recursion *rec;
1830 if (!printk_percpu_data_ready()) {
1831 count = &printk_recursion_count[0];
1833 rec = this_cpu_ptr(&percpu_printk_recursion);
1835 count = &rec->count[0];
1838 #ifdef CONFIG_PRINTK_NMI
1846 static bool printk_enter_irqsave(unsigned long *flags)
1850 local_irq_save(*flags);
1851 count = printk_recursion_counter();
1852 /* Only 1 level of recursion allowed. */
1854 local_irq_restore(*flags);
1862 static void printk_exit_irqrestore(unsigned long flags)
1866 count = printk_recursion_counter();
1868 local_irq_restore(flags);
1871 static inline u32 printk_caller_id(void)
1873 return in_task() ? task_pid_nr(current) :
1874 0x80000000 + raw_smp_processor_id();
1878 * parse_prefix - Parse level and control flags.
1880 * @text: The terminated text message.
1881 * @level: A pointer to the current level value, will be updated.
1882 * @lflags: A pointer to the current log flags, will be updated.
1884 * @level may be NULL if the caller is not interested in the parsed value.
1885 * Otherwise the variable pointed to by @level must be set to
1886 * LOGLEVEL_DEFAULT in order to be updated with the parsed value.
1888 * @lflags may be NULL if the caller is not interested in the parsed value.
1889 * Otherwise the variable pointed to by @lflags will be OR'd with the parsed
1892 * Return: The length of the parsed level and control flags.
1894 static u16 parse_prefix(char *text, int *level, enum log_flags *lflags)
1900 kern_level = printk_get_level(text);
1904 switch (kern_level) {
1906 if (level && *level == LOGLEVEL_DEFAULT)
1907 *level = kern_level - '0';
1909 case 'c': /* KERN_CONT */
1911 *lflags |= LOG_CONT;
1921 static u16 printk_sprint(char *text, u16 size, int facility, enum log_flags *lflags,
1922 const char *fmt, va_list args)
1926 text_len = vscnprintf(text, size, fmt, args);
1928 /* Mark and strip a trailing newline. */
1929 if (text_len && text[text_len - 1] == '\n') {
1931 *lflags |= LOG_NEWLINE;
1934 /* Strip log level and control flags. */
1935 if (facility == 0) {
1938 prefix_len = parse_prefix(text, NULL, NULL);
1940 text_len -= prefix_len;
1941 memmove(text, text + prefix_len, text_len);
1949 static int vprintk_store(int facility, int level,
1950 const struct dev_printk_info *dev_info,
1951 const char *fmt, va_list args)
1953 const u32 caller_id = printk_caller_id();
1954 struct prb_reserved_entry e;
1955 enum log_flags lflags = 0;
1956 bool final_commit = false;
1957 struct printk_record r;
1958 unsigned long irqflags;
1959 u16 trunc_msg_len = 0;
1969 * Since the duration of printk() can vary depending on the message
1970 * and state of the ringbuffer, grab the timestamp now so that it is
1971 * close to the call of printk(). This provides a more deterministic
1972 * timestamp with respect to the caller.
1974 ts_nsec = local_clock();
1976 if (!printk_enter_irqsave(&irqflags))
1980 * The sprintf needs to come first since the syslog prefix might be
1981 * passed in as a parameter. An extra byte must be reserved so that
1982 * later the vscnprintf() into the reserved buffer has room for the
1983 * terminating '\0', which is not counted by vsnprintf().
1985 va_copy(args2, args);
1986 reserve_size = vsnprintf(&prefix_buf[0], sizeof(prefix_buf), fmt, args2) + 1;
1989 if (reserve_size > LOG_LINE_MAX)
1990 reserve_size = LOG_LINE_MAX;
1992 /* Extract log level or control flags. */
1994 parse_prefix(&prefix_buf[0], &level, &lflags);
1996 if (level == LOGLEVEL_DEFAULT)
1997 level = default_message_loglevel;
2000 lflags |= LOG_NEWLINE;
2002 if (lflags & LOG_CONT) {
2003 prb_rec_init_wr(&r, reserve_size);
2004 if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
2006 text_len = printk_sprint(&r.text_buf[r.info->text_len], reserve_size,
2007 facility, &lflags, fmt, args);
2008 r.info->text_len += text_len;
2010 if (lflags & LOG_NEWLINE) {
2011 r.info->flags |= LOG_NEWLINE;
2012 prb_final_commit(&e);
2013 final_commit = true;
2024 * Explicitly initialize the record before every prb_reserve() call.
2025 * prb_reserve_in_last() and prb_reserve() purposely invalidate the
2026 * structure when they fail.
2028 prb_rec_init_wr(&r, reserve_size);
2029 if (!prb_reserve(&e, prb, &r)) {
2030 /* truncate the message if it is too long for empty buffer */
2031 truncate_msg(&reserve_size, &trunc_msg_len);
2033 prb_rec_init_wr(&r, reserve_size + trunc_msg_len);
2034 if (!prb_reserve(&e, prb, &r))
2041 text_len = printk_sprint(&r.text_buf[0], reserve_size, facility, &lflags, fmt, args);
2043 memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
2044 r.info->text_len = text_len + trunc_msg_len;
2045 r.info->facility = facility;
2046 r.info->level = level & 7;
2047 r.info->flags = lflags & 0x1f;
2048 r.info->ts_nsec = ts_nsec;
2049 r.info->caller_id = caller_id;
2051 memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
2053 /* A message without a trailing newline can be continued. */
2054 if (!(lflags & LOG_NEWLINE)) {
2057 prb_final_commit(&e);
2058 final_commit = true;
2061 ret = text_len + trunc_msg_len;
2063 /* only the kernel may perform synchronous printing */
2064 if (facility == 0 && final_commit) {
2065 struct console *con;
2067 for_each_console(con) {
2068 if (console_can_sync(con))
2069 print_sync_until(con, seq + 1);
2073 printk_exit_irqrestore(irqflags);
2077 asmlinkage int vprintk_emit(int facility, int level,
2078 const struct dev_printk_info *dev_info,
2079 const char *fmt, va_list args)
2083 /* Suppress unimportant messages after panic happens */
2084 if (unlikely(suppress_printk))
2087 if (level == LOGLEVEL_SCHED)
2088 level = LOGLEVEL_DEFAULT;
2090 printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2095 EXPORT_SYMBOL(vprintk_emit);
2098 static int vprintk_default(const char *fmt, va_list args)
2100 return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2104 static int vprintk_func(const char *fmt, va_list args)
2106 #ifdef CONFIG_KGDB_KDB
2107 /* Allow to pass printk() to kdb but avoid a recursion. */
2108 if (unlikely(kdb_trap_printk && kdb_printf_cpu < 0))
2109 return vkdb_printf(KDB_MSGSRC_PRINTK, fmt, args);
2111 return vprintk_default(fmt, args);
2114 asmlinkage int vprintk(const char *fmt, va_list args)
2116 return vprintk_func(fmt, args);
2118 EXPORT_SYMBOL(vprintk);
2121 * printk - print a kernel message
2122 * @fmt: format string
2124 * This is printk(). It can be called from any context. We want it to work.
2126 * We try to grab the console_lock. If we succeed, it's easy - we log the
2127 * output and call the console drivers. If we fail to get the semaphore, we
2128 * place the output into the log buffer and return. The current holder of
2129 * the console_sem will notice the new output in console_unlock(); and will
2130 * send it to the consoles before releasing the lock.
2132 * One effect of this deferred printing is that code which calls printk() and
2133 * then changes console_loglevel may break. This is because console_loglevel
2134 * is inspected when the actual printing occurs.
2139 * See the vsnprintf() documentation for format string extensions over C99.
2141 asmlinkage __visible int printk(const char *fmt, ...)
2146 va_start(args, fmt);
2147 r = vprintk_func(fmt, args);
2152 EXPORT_SYMBOL(printk);
2154 static int printk_kthread_func(void *data)
2156 struct console *con = data;
2157 unsigned long dropped = 0;
2158 char *dropped_text = NULL;
2159 struct printk_info info;
2160 struct printk_record r;
2161 char *ext_text = NULL;
2171 if (con->flags & CON_EXTENDED) {
2172 ext_text = kmalloc(CONSOLE_EXT_LOG_MAX, GFP_KERNEL);
2176 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
2177 dropped_text = kmalloc(64, GFP_KERNEL);
2178 if (!text || !dropped_text)
2181 if (con->flags & CON_EXTENDED)
2182 write_text = ext_text;
2186 seq = atomic64_read(&con->printk_seq);
2188 prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
2191 error = wait_event_interruptible(log_wait,
2192 prb_read_valid(prb, seq, &r) || kthread_should_stop());
2194 if (kthread_should_stop())
2200 if (seq != r.info->seq) {
2201 dropped += r.info->seq - seq;
2207 if (!(con->flags & CON_ENABLED))
2210 if (suppress_message_printing(r.info->level))
2213 if (con->flags & CON_EXTENDED) {
2214 len = info_print_ext_header(ext_text,
2215 CONSOLE_EXT_LOG_MAX,
2217 len += msg_print_ext_body(ext_text + len,
2218 CONSOLE_EXT_LOG_MAX - len,
2219 &r.text_buf[0], r.info->text_len,
2222 len = record_print_text(&r,
2223 console_msg_format & MSG_FORMAT_SYSLOG,
2227 printk_seq = atomic64_read(&con->printk_seq);
2230 console_may_schedule = 0;
2232 if (kernel_sync_mode() && con->write_atomic) {
2237 if (!(con->flags & CON_EXTENDED) && dropped) {
2238 dropped_len = snprintf(dropped_text, 64,
2239 "** %lu printk messages dropped **\n",
2243 con->write(con, dropped_text, dropped_len);
2244 printk_delay(r.info->level);
2247 con->write(con, write_text, len);
2249 printk_delay(r.info->level);
2251 atomic64_cmpxchg_relaxed(&con->printk_seq, printk_seq, seq);
2256 kfree(dropped_text);
2259 pr_info("%sconsole [%s%d]: printing thread stopped\n",
2260 (con->flags & CON_BOOT) ? "boot" : "",
2261 con->name, con->index);
2265 /* Must be called within console_lock(). */
2266 static void start_printk_kthread(struct console *con)
2268 con->thread = kthread_run(printk_kthread_func, con,
2269 "pr/%s%d", con->name, con->index);
2270 if (IS_ERR(con->thread)) {
2271 pr_err("%sconsole [%s%d]: unable to start printing thread\n",
2272 (con->flags & CON_BOOT) ? "boot" : "",
2273 con->name, con->index);
2276 pr_info("%sconsole [%s%d]: printing thread started\n",
2277 (con->flags & CON_BOOT) ? "boot" : "",
2278 con->name, con->index);
2281 /* protected by console_lock */
2282 static bool kthreads_started;
2284 /* Must be called within console_lock(). */
2285 static void console_try_thread(struct console *con)
2287 if (kthreads_started) {
2288 start_printk_kthread(con);
2293 * The printing threads have not been started yet. If this console
2294 * can print synchronously, print all unprinted messages.
2296 if (console_can_sync(con))
2297 print_sync_until(con, prb_next_seq(prb));
2300 #else /* CONFIG_PRINTK */
2302 #define prb_first_valid_seq(rb) 0
2303 #define prb_next_seq(rb) 0
2305 #define console_try_thread(con)
2307 #endif /* CONFIG_PRINTK */
2309 #ifdef CONFIG_EARLY_PRINTK
2310 struct console *early_console;
2312 asmlinkage __visible void early_printk(const char *fmt, ...)
2322 n = vscnprintf(buf, sizeof(buf), fmt, ap);
2325 early_console->write(early_console, buf, n);
2329 static int __add_preferred_console(char *name, int idx, char *options,
2330 char *brl_options, bool user_specified)
2332 struct console_cmdline *c;
2336 * See if this tty is not yet registered, and
2337 * if we have a slot free.
2339 for (i = 0, c = console_cmdline;
2340 i < MAX_CMDLINECONSOLES && c->name[0];
2342 if (strcmp(c->name, name) == 0 && c->index == idx) {
2344 preferred_console = i;
2346 c->user_specified = true;
2350 if (i == MAX_CMDLINECONSOLES)
2353 preferred_console = i;
2354 strlcpy(c->name, name, sizeof(c->name));
2355 c->options = options;
2356 c->user_specified = user_specified;
2357 braille_set_options(c, brl_options);
2363 static int __init console_msg_format_setup(char *str)
2365 if (!strcmp(str, "syslog"))
2366 console_msg_format = MSG_FORMAT_SYSLOG;
2367 if (!strcmp(str, "default"))
2368 console_msg_format = MSG_FORMAT_DEFAULT;
2371 __setup("console_msg_format=", console_msg_format_setup);
2374 * Set up a console. Called via do_early_param() in init/main.c
2375 * for each "console=" parameter in the boot command line.
2377 static int __init console_setup(char *str)
2379 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2380 char *s, *options, *brl_options = NULL;
2384 * console="" or console=null have been suggested as a way to
2385 * disable console output. Use ttynull that has been created
2386 * for exacly this purpose.
2388 if (str[0] == 0 || strcmp(str, "null") == 0) {
2389 __add_preferred_console("ttynull", 0, NULL, NULL, true);
2393 if (_braille_console_setup(&str, &brl_options))
2397 * Decode str into name, index, options.
2399 if (str[0] >= '0' && str[0] <= '9') {
2400 strcpy(buf, "ttyS");
2401 strncpy(buf + 4, str, sizeof(buf) - 5);
2403 strncpy(buf, str, sizeof(buf) - 1);
2405 buf[sizeof(buf) - 1] = 0;
2406 options = strchr(str, ',');
2410 if (!strcmp(str, "ttya"))
2411 strcpy(buf, "ttyS0");
2412 if (!strcmp(str, "ttyb"))
2413 strcpy(buf, "ttyS1");
2415 for (s = buf; *s; s++)
2416 if (isdigit(*s) || *s == ',')
2418 idx = simple_strtoul(s, NULL, 10);
2421 __add_preferred_console(buf, idx, options, brl_options, true);
2422 console_set_on_cmdline = 1;
2425 __setup("console=", console_setup);
2428 * add_preferred_console - add a device to the list of preferred consoles.
2429 * @name: device name
2430 * @idx: device index
2431 * @options: options for this console
2433 * The last preferred console added will be used for kernel messages
2434 * and stdin/out/err for init. Normally this is used by console_setup
2435 * above to handle user-supplied console arguments; however it can also
2436 * be used by arch-specific code either to override the user or more
2437 * commonly to provide a default console (ie from PROM variables) when
2438 * the user has not supplied one.
2440 int add_preferred_console(char *name, int idx, char *options)
2442 return __add_preferred_console(name, idx, options, NULL, false);
2445 bool console_suspend_enabled = true;
2446 EXPORT_SYMBOL(console_suspend_enabled);
2448 static int __init console_suspend_disable(char *str)
2450 console_suspend_enabled = false;
2453 __setup("no_console_suspend", console_suspend_disable);
2454 module_param_named(console_suspend, console_suspend_enabled,
2455 bool, S_IRUGO | S_IWUSR);
2456 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2457 " and hibernate operations");
2460 * suspend_console - suspend the console subsystem
2462 * This disables printk() while we go into suspend states
2464 void suspend_console(void)
2466 if (!console_suspend_enabled)
2468 pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2470 console_suspended = 1;
2474 void resume_console(void)
2476 if (!console_suspend_enabled)
2479 console_suspended = 0;
2484 * console_cpu_notify - print deferred console messages after CPU hotplug
2487 * If printk() is called from a CPU that is not online yet, the messages
2488 * will be printed on the console only if there are CON_ANYTIME consoles.
2489 * This function is called when a new CPU comes online (or fails to come
2490 * up) or goes offline.
2492 static int console_cpu_notify(unsigned int cpu)
2494 if (!cpuhp_tasks_frozen) {
2495 /* If trylock fails, someone else is doing the printing */
2496 if (console_trylock())
2503 * console_lock - lock the console system for exclusive use.
2505 * Acquires a lock which guarantees that the caller has
2506 * exclusive access to the console system and the console_drivers list.
2508 * Can sleep, returns nothing.
2510 void console_lock(void)
2515 if (console_suspended)
2518 console_may_schedule = 1;
2520 EXPORT_SYMBOL(console_lock);
2523 * console_trylock - try to lock the console system for exclusive use.
2525 * Try to acquire a lock which guarantees that the caller has exclusive
2526 * access to the console system and the console_drivers list.
2528 * returns 1 on success, and 0 on failure to acquire the lock.
2530 int console_trylock(void)
2532 if (down_trylock_console_sem())
2534 if (console_suspended) {
2539 console_may_schedule = 0;
2542 EXPORT_SYMBOL(console_trylock);
2544 int is_console_locked(void)
2546 return console_locked;
2548 EXPORT_SYMBOL(is_console_locked);
2551 * console_unlock - unlock the console system
2553 * Releases the console_lock which the caller holds on the console system
2554 * and the console driver list.
2556 * While the console_lock was held, console output may have been buffered
2557 * by printk(). If this is the case, console_unlock(); emits
2558 * the output prior to releasing the lock.
2560 * If there is output waiting, we wake /dev/kmsg and syslog() users.
2562 * console_unlock(); may be called from any context.
2564 void console_unlock(void)
2566 if (console_suspended) {
2575 EXPORT_SYMBOL(console_unlock);
2578 * console_conditional_schedule - yield the CPU if required
2580 * If the console code is currently allowed to sleep, and
2581 * if this CPU should yield the CPU to another task, do
2584 * Must be called within console_lock();.
2586 void __sched console_conditional_schedule(void)
2588 if (console_may_schedule)
2591 EXPORT_SYMBOL(console_conditional_schedule);
2593 void console_unblank(void)
2598 * console_unblank can no longer be called in interrupt context unless
2599 * oops_in_progress is set to 1..
2601 if (oops_in_progress) {
2602 if (down_trylock_console_sem() != 0)
2608 console_may_schedule = 0;
2610 if ((c->flags & CON_ENABLED) && c->unblank)
2616 * console_flush_on_panic - flush console content on panic
2617 * @mode: flush all messages in buffer or just the pending ones
2619 * Immediately output all pending messages no matter what.
2621 void console_flush_on_panic(enum con_flush_mode mode)
2626 if (!console_trylock())
2629 console_may_schedule = 0;
2631 if (mode == CONSOLE_REPLAY_ALL) {
2632 seq = prb_first_valid_seq(prb);
2634 atomic64_set(&c->printk_seq, seq);
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);
2694 * This is called by register_console() to try to match
2695 * the newly registered console with any of the ones selected
2696 * by either the command line or add_preferred_console() and
2699 * Care need to be taken with consoles that are statically
2700 * enabled such as netconsole
2702 static int try_enable_new_console(struct console *newcon, bool user_specified)
2704 struct console_cmdline *c;
2707 for (i = 0, c = console_cmdline;
2708 i < MAX_CMDLINECONSOLES && c->name[0];
2710 if (c->user_specified != user_specified)
2712 if (!newcon->match ||
2713 newcon->match(newcon, c->name, c->index, c->options) != 0) {
2714 /* default matching */
2715 BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
2716 if (strcmp(c->name, newcon->name) != 0)
2718 if (newcon->index >= 0 &&
2719 newcon->index != c->index)
2721 if (newcon->index < 0)
2722 newcon->index = c->index;
2724 if (_braille_register_console(newcon, c))
2727 if (newcon->setup &&
2728 (err = newcon->setup(newcon, c->options)) != 0)
2731 newcon->flags |= CON_ENABLED;
2732 if (i == preferred_console) {
2733 newcon->flags |= CON_CONSDEV;
2734 has_preferred_console = true;
2740 * Some consoles, such as pstore and netconsole, can be enabled even
2741 * without matching. Accept the pre-enabled consoles only when match()
2742 * and setup() had a chance to be called.
2744 if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
2751 * The console driver calls this routine during kernel initialization
2752 * to register the console printing procedure with printk() and to
2753 * print any messages that were printed by the kernel before the
2754 * console driver was initialized.
2756 * This can happen pretty early during the boot process (because of
2757 * early_printk) - sometimes before setup_arch() completes - be careful
2758 * of what kernel features are used - they may not be initialised yet.
2760 * There are two types of consoles - bootconsoles (early_printk) and
2761 * "real" consoles (everything which is not a bootconsole) which are
2762 * handled differently.
2763 * - Any number of bootconsoles can be registered at any time.
2764 * - As soon as a "real" console is registered, all bootconsoles
2765 * will be unregistered automatically.
2766 * - Once a "real" console is registered, any attempt to register a
2767 * bootconsoles will be rejected
2769 void register_console(struct console *newcon)
2771 struct console *bcon = NULL;
2774 for_each_console(bcon) {
2775 if (WARN(bcon == newcon, "console '%s%d' already registered\n",
2776 bcon->name, bcon->index))
2781 * before we register a new CON_BOOT console, make sure we don't
2782 * already have a valid console
2784 if (newcon->flags & CON_BOOT) {
2785 for_each_console(bcon) {
2786 if (!(bcon->flags & CON_BOOT)) {
2787 pr_info("Too late to register bootconsole %s%d\n",
2788 newcon->name, newcon->index);
2794 newcon->thread = NULL;
2796 if (console_drivers && console_drivers->flags & CON_BOOT)
2797 bcon = console_drivers;
2799 if (!has_preferred_console || bcon || !console_drivers)
2800 has_preferred_console = preferred_console >= 0;
2803 * See if we want to use this console driver. If we
2804 * didn't select a console we take the first one
2805 * that registers here.
2807 if (!has_preferred_console) {
2808 if (newcon->index < 0)
2810 if (newcon->setup == NULL ||
2811 newcon->setup(newcon, NULL) == 0) {
2812 newcon->flags |= CON_ENABLED;
2813 if (newcon->device) {
2814 newcon->flags |= CON_CONSDEV;
2815 has_preferred_console = true;
2820 /* See if this console matches one we selected on the command line */
2821 err = try_enable_new_console(newcon, true);
2823 /* If not, try to match against the platform default(s) */
2825 err = try_enable_new_console(newcon, false);
2827 /* printk() messages are not printed to the Braille console. */
2828 if (err || newcon->flags & CON_BRL)
2832 * If we have a bootconsole, and are switching to a real console,
2833 * don't print everything out again, since when the boot console, and
2834 * the real console are the same physical device, it's annoying to
2835 * see the beginning boot messages twice
2837 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
2838 newcon->flags &= ~CON_PRINTBUFFER;
2839 newcon->flags |= CON_HANDOVER;
2843 * Put this console in the list - keep the
2844 * preferred driver at the head of the list.
2847 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2848 newcon->next = console_drivers;
2849 console_drivers = newcon;
2851 newcon->next->flags &= ~CON_CONSDEV;
2852 /* Ensure this flag is always set for the head of the list */
2853 newcon->flags |= CON_CONSDEV;
2855 newcon->next = console_drivers->next;
2856 console_drivers->next = newcon;
2859 if (newcon->flags & CON_EXTENDED)
2860 nr_ext_console_drivers++;
2862 if (newcon->flags & CON_PRINTBUFFER)
2863 atomic64_set(&newcon->printk_seq, 0);
2865 atomic64_set(&newcon->printk_seq, prb_next_seq(prb));
2867 console_try_thread(newcon);
2869 console_sysfs_notify();
2872 * By unregistering the bootconsoles after we enable the real console
2873 * we get the "console xxx enabled" message on all the consoles -
2874 * boot consoles, real consoles, etc - this is to ensure that end
2875 * users know there might be something in the kernel's log buffer that
2876 * went to the bootconsole (that they do not see on the real console)
2878 pr_info("%sconsole [%s%d] enabled\n",
2879 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2880 newcon->name, newcon->index);
2882 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2884 /* We need to iterate through all boot consoles, to make
2885 * sure we print everything out, before we unregister them.
2887 for_each_console(bcon)
2888 if (bcon->flags & CON_BOOT)
2889 unregister_console(bcon);
2892 EXPORT_SYMBOL(register_console);
2894 int unregister_console(struct console *console)
2896 struct console *con;
2899 pr_info("%sconsole [%s%d] disabled\n",
2900 (console->flags & CON_BOOT) ? "boot" : "" ,
2901 console->name, console->index);
2903 res = _braille_unregister_console(console);
2911 if (console_drivers == console) {
2912 console_drivers=console->next;
2915 for_each_console(con) {
2916 if (con->next == console) {
2917 con->next = console->next;
2925 goto out_disable_unlock;
2927 if (console->flags & CON_EXTENDED)
2928 nr_ext_console_drivers--;
2931 * If this isn't the last console and it has CON_CONSDEV set, we
2932 * need to set it on the next preferred console.
2934 if (console_drivers != NULL && console->flags & CON_CONSDEV)
2935 console_drivers->flags |= CON_CONSDEV;
2937 console->flags &= ~CON_ENABLED;
2939 console_sysfs_notify();
2941 if (console->thread && !IS_ERR(console->thread))
2942 kthread_stop(console->thread);
2945 res = console->exit(console);
2950 console->flags &= ~CON_ENABLED;
2955 EXPORT_SYMBOL(unregister_console);
2958 * Initialize the console device. This is called *early*, so
2959 * we can't necessarily depend on lots of kernel help here.
2960 * Just do some early initializations, and do the complex setup
2963 void __init console_init(void)
2967 initcall_entry_t *ce;
2969 /* Setup the default TTY line discipline. */
2973 * set up the console device so that later boot sequences can
2974 * inform about problems etc..
2976 ce = __con_initcall_start;
2977 trace_initcall_level("console");
2978 while (ce < __con_initcall_end) {
2979 call = initcall_from_entry(ce);
2980 trace_initcall_start(call);
2982 trace_initcall_finish(call, ret);
2988 * Some boot consoles access data that is in the init section and which will
2989 * be discarded after the initcalls have been run. To make sure that no code
2990 * will access this data, unregister the boot consoles in a late initcall.
2992 * If for some reason, such as deferred probe or the driver being a loadable
2993 * module, the real console hasn't registered yet at this point, there will
2994 * be a brief interval in which no messages are logged to the console, which
2995 * makes it difficult to diagnose problems that occur during this time.
2997 * To mitigate this problem somewhat, only unregister consoles whose memory
2998 * intersects with the init section. Note that all other boot consoles will
2999 * get unregistred when the real preferred console is registered.
3001 static int __init printk_late_init(void)
3003 struct console *con;
3006 for_each_console(con) {
3007 if (!(con->flags & CON_BOOT))
3010 /* Check addresses that might be used for enabled consoles. */
3011 if (init_section_intersects(con, sizeof(*con)) ||
3012 init_section_contains(con->write, 0) ||
3013 init_section_contains(con->read, 0) ||
3014 init_section_contains(con->device, 0) ||
3015 init_section_contains(con->unblank, 0) ||
3016 init_section_contains(con->data, 0)) {
3018 * Please, consider moving the reported consoles out
3019 * of the init section.
3021 pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3022 con->name, con->index);
3023 unregister_console(con);
3027 #ifdef CONFIG_PRINTK
3029 for_each_console(con)
3030 start_printk_kthread(con);
3031 kthreads_started = true;
3035 ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3036 console_cpu_notify);
3038 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3039 console_cpu_notify, NULL);
3043 late_initcall(printk_late_init);
3045 #if defined CONFIG_PRINTK
3047 * Delayed printk version, for scheduler-internal messages:
3049 #define PRINTK_PENDING_WAKEUP 0x01
3051 static DEFINE_PER_CPU(int, printk_pending);
3053 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3055 int pending = __this_cpu_xchg(printk_pending, 0);
3057 if (pending & PRINTK_PENDING_WAKEUP)
3058 wake_up_interruptible_all(&log_wait);
3061 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
3062 .func = wake_up_klogd_work_func,
3063 .flags = ATOMIC_INIT(IRQ_WORK_LAZY),
3066 void wake_up_klogd(void)
3068 if (!printk_percpu_data_ready())
3072 if (waitqueue_active(&log_wait)) {
3073 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
3074 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3080 static int vprintk_deferred(const char *fmt, va_list args)
3082 return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
3085 int printk_deferred(const char *fmt, ...)
3090 va_start(args, fmt);
3091 r = vprintk_deferred(fmt, args);
3098 * printk rate limiting, lifted from the networking subsystem.
3100 * This enforces a rate limit: not more than 10 kernel messages
3101 * every 5s to make a denial-of-service attack impossible.
3103 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3105 int __printk_ratelimit(const char *func)
3107 return ___ratelimit(&printk_ratelimit_state, func);
3109 EXPORT_SYMBOL(__printk_ratelimit);
3112 * printk_timed_ratelimit - caller-controlled printk ratelimiting
3113 * @caller_jiffies: pointer to caller's state
3114 * @interval_msecs: minimum interval between prints
3116 * printk_timed_ratelimit() returns true if more than @interval_msecs
3117 * milliseconds have elapsed since the last time printk_timed_ratelimit()
3120 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
3121 unsigned int interval_msecs)
3123 unsigned long elapsed = jiffies - *caller_jiffies;
3125 if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
3128 *caller_jiffies = jiffies;
3131 EXPORT_SYMBOL(printk_timed_ratelimit);
3133 static DEFINE_SPINLOCK(dump_list_lock);
3134 static LIST_HEAD(dump_list);
3137 * kmsg_dump_register - register a kernel log dumper.
3138 * @dumper: pointer to the kmsg_dumper structure
3140 * Adds a kernel log dumper to the system. The dump callback in the
3141 * structure will be called when the kernel oopses or panics and must be
3142 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
3144 int kmsg_dump_register(struct kmsg_dumper *dumper)
3146 unsigned long flags;
3149 /* The dump callback needs to be set */
3153 spin_lock_irqsave(&dump_list_lock, flags);
3154 /* Don't allow registering multiple times */
3155 if (!dumper->registered) {
3156 dumper->registered = 1;
3157 list_add_tail_rcu(&dumper->list, &dump_list);
3160 spin_unlock_irqrestore(&dump_list_lock, flags);
3164 EXPORT_SYMBOL_GPL(kmsg_dump_register);
3167 * kmsg_dump_unregister - unregister a kmsg dumper.
3168 * @dumper: pointer to the kmsg_dumper structure
3170 * Removes a dump device from the system. Returns zero on success and
3171 * %-EINVAL otherwise.
3173 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
3175 unsigned long flags;
3178 spin_lock_irqsave(&dump_list_lock, flags);
3179 if (dumper->registered) {
3180 dumper->registered = 0;
3181 list_del_rcu(&dumper->list);
3184 spin_unlock_irqrestore(&dump_list_lock, flags);
3189 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
3191 static bool always_kmsg_dump;
3192 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
3194 const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
3197 case KMSG_DUMP_PANIC:
3199 case KMSG_DUMP_OOPS:
3201 case KMSG_DUMP_EMERG:
3203 case KMSG_DUMP_SHUTDOWN:
3209 EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
3212 * kmsg_dump - dump kernel log to kernel message dumpers.
3213 * @reason: the reason (oops, panic etc) for dumping
3215 * Call each of the registered dumper's dump() callback, which can
3216 * retrieve the kmsg records with kmsg_dump_get_line() or
3217 * kmsg_dump_get_buffer().
3219 void kmsg_dump(enum kmsg_dump_reason reason)
3221 struct kmsg_dumper_iter iter;
3222 struct kmsg_dumper *dumper;
3224 if (!oops_in_progress) {
3226 * If atomic consoles are available, activate kernel sync mode
3227 * to make sure any final messages are visible. The trailing
3228 * printk message is important to flush any pending messages.
3230 if (have_atomic_console()) {
3232 pr_info("enabled sync mode\n");
3236 * Give the printing threads time to flush, allowing up to
3237 * 1s of no printing forward progress before giving up.
3239 pr_flush(1000, true);
3243 list_for_each_entry_rcu(dumper, &dump_list, list) {
3244 enum kmsg_dump_reason max_reason = dumper->max_reason;
3247 * If client has not provided a specific max_reason, default
3248 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
3250 if (max_reason == KMSG_DUMP_UNDEF) {
3251 max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
3254 if (reason > max_reason)
3257 /* initialize iterator with data about the stored records */
3259 kmsg_dump_rewind(&iter);
3261 /* invoke dumper which will iterate over records */
3262 dumper->dump(dumper, reason, &iter);
3268 * kmsg_dump_get_line - retrieve one kmsg log line
3269 * @iter: kmsg dumper iterator
3270 * @syslog: include the "<4>" prefixes
3271 * @line: buffer to copy the line to
3272 * @size: maximum size of the buffer
3273 * @len: length of line placed into buffer
3275 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3276 * record, and copy one record into the provided buffer.
3278 * Consecutive calls will return the next available record moving
3279 * towards the end of the buffer with the youngest messages.
3281 * A return value of FALSE indicates that there are no more records to
3284 bool kmsg_dump_get_line(struct kmsg_dumper_iter *iter, bool syslog,
3285 char *line, size_t size, size_t *len)
3287 struct printk_info info;
3288 unsigned int line_count;
3289 struct printk_record r;
3293 prb_rec_init_rd(&r, &info, line, size);
3298 /* Read text or count text lines? */
3300 if (!prb_read_valid(prb, iter->cur_seq, &r))
3302 l = record_print_text(&r, syslog, printk_time);
3304 if (!prb_read_valid_info(prb, iter->cur_seq,
3305 &info, &line_count)) {
3308 l = get_record_print_text_size(&info, line_count, syslog,
3313 iter->cur_seq = r.info->seq + 1;
3320 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
3323 * kmsg_dump_get_buffer - copy kmsg log lines
3324 * @iter: kmsg dumper iterator
3325 * @syslog: include the "<4>" prefixes
3326 * @buf: buffer to copy the line to
3327 * @size: maximum size of the buffer
3328 * @len: length of line placed into buffer
3330 * Start at the end of the kmsg buffer and fill the provided buffer
3331 * with as many of the *youngest* kmsg records that fit into it.
3332 * If the buffer is large enough, all available kmsg records will be
3333 * copied with a single call.
3335 * Consecutive calls will fill the buffer with the next block of
3336 * available older records, not including the earlier retrieved ones.
3338 * A return value of FALSE indicates that there are no more records to
3341 bool kmsg_dump_get_buffer(struct kmsg_dumper_iter *iter, bool syslog,
3342 char *buf, size_t size, size_t *len_out)
3344 struct printk_info info;
3345 struct printk_record r;
3350 bool time = printk_time;
3352 if (!iter->active || !buf || !size)
3355 if (prb_read_valid_info(prb, iter->cur_seq, &info, NULL)) {
3356 if (info.seq != iter->cur_seq) {
3357 /* messages are gone, move to first available one */
3358 iter->cur_seq = info.seq;
3363 if (iter->cur_seq >= iter->next_seq)
3367 * Find first record that fits, including all following records,
3368 * into the user-provided buffer for this dump. Pass in size-1
3369 * because this function (by way of record_print_text()) will
3370 * not write more than size-1 bytes of text into @buf.
3372 seq = find_first_fitting_seq(iter->cur_seq, iter->next_seq,
3373 size - 1, syslog, time);
3376 * Next kmsg_dump_get_buffer() invocation will dump block of
3377 * older records stored right before this one.
3381 prb_rec_init_rd(&r, &info, buf, size);
3384 prb_for_each_record(seq, prb, seq, &r) {
3385 if (r.info->seq >= iter->next_seq)
3388 len += record_print_text(&r, syslog, time);
3390 /* Adjust record to store to remaining buffer space. */
3391 prb_rec_init_rd(&r, &info, buf + len, size - len);
3394 iter->next_seq = next_seq;
3401 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
3404 * kmsg_dump_rewind - reset the iterator
3405 * @iter: kmsg dumper iterator
3407 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3408 * kmsg_dump_get_buffer() can be called again and used multiple
3409 * times within the same dumper.dump() callback.
3411 void kmsg_dump_rewind(struct kmsg_dumper_iter *iter)
3413 iter->cur_seq = latched_seq_read_nolock(&clear_seq);
3414 iter->next_seq = prb_next_seq(prb);
3416 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
3420 struct prb_cpulock {
3422 unsigned long __percpu *irqflags;
3425 #define DECLARE_STATIC_PRINTKRB_CPULOCK(name) \
3426 static DEFINE_PER_CPU(unsigned long, _##name##_percpu_irqflags); \
3427 static struct prb_cpulock name = { \
3428 .owner = ATOMIC_INIT(-1), \
3429 .irqflags = &_##name##_percpu_irqflags, \
3432 static bool __prb_trylock(struct prb_cpulock *cpu_lock,
3433 unsigned int *cpu_store)
3435 unsigned long *flags;
3440 *cpu_store = atomic_read(&cpu_lock->owner);
3441 /* memory barrier to ensure the current lock owner is visible */
3443 if (*cpu_store == -1) {
3444 flags = per_cpu_ptr(cpu_lock->irqflags, cpu);
3445 local_irq_save(*flags);
3446 if (atomic_try_cmpxchg_acquire(&cpu_lock->owner,
3450 local_irq_restore(*flags);
3451 } else if (*cpu_store == cpu) {
3460 * prb_lock: Perform a processor-reentrant spin lock.
3461 * @cpu_lock: A pointer to the lock object.
3462 * @cpu_store: A "flags" pointer to store lock status information.
3464 * If no processor has the lock, the calling processor takes the lock and
3465 * becomes the owner. If the calling processor is already the owner of the
3466 * lock, this function succeeds immediately. If lock is locked by another
3467 * processor, this function spins until the calling processor becomes the
3470 * It is safe to call this function from any context and state.
3472 static void prb_lock(struct prb_cpulock *cpu_lock, unsigned int *cpu_store)
3475 if (__prb_trylock(cpu_lock, cpu_store))
3482 * prb_unlock: Perform a processor-reentrant spin unlock.
3483 * @cpu_lock: A pointer to the lock object.
3484 * @cpu_store: A "flags" object storing lock status information.
3486 * Release the lock. The calling processor must be the owner of the lock.
3488 * It is safe to call this function from any context and state.
3490 static void prb_unlock(struct prb_cpulock *cpu_lock, unsigned int cpu_store)
3492 unsigned long *flags;
3495 cpu = atomic_read(&cpu_lock->owner);
3496 atomic_set_release(&cpu_lock->owner, cpu_store);
3498 if (cpu_store == -1) {
3499 flags = per_cpu_ptr(cpu_lock->irqflags, cpu);
3500 local_irq_restore(*flags);
3506 DECLARE_STATIC_PRINTKRB_CPULOCK(printk_cpulock);
3508 void console_atomic_lock(unsigned int *flags)
3510 prb_lock(&printk_cpulock, flags);
3512 EXPORT_SYMBOL(console_atomic_lock);
3514 void console_atomic_unlock(unsigned int flags)
3516 prb_unlock(&printk_cpulock, flags);
3518 EXPORT_SYMBOL(console_atomic_unlock);
3520 static void pr_msleep(bool may_sleep, int ms)
3531 * pr_flush() - Wait for printing threads to catch up.
3533 * @timeout_ms: The maximum time (in ms) to wait.
3534 * @reset_on_progress: Reset the timeout if forward progress is seen.
3536 * A value of 0 for @timeout_ms means no waiting will occur. A value of -1
3537 * represents infinite waiting.
3539 * If @reset_on_progress is true, the timeout will be reset whenever any
3540 * printer has been seen to make some forward progress.
3542 * Context: Any context.
3543 * Return: true if all enabled printers are caught up.
3545 bool pr_flush(int timeout_ms, bool reset_on_progress)
3547 int remaining = timeout_ms;
3548 struct console *con;
3555 may_sleep = (preemptible() &&
3557 system_state >= SYSTEM_RUNNING);
3559 seq = prb_next_seq(prb);
3564 for_each_console(con) {
3565 if (!(con->flags & CON_ENABLED))
3567 printk_seq = atomic64_read(&con->printk_seq);
3568 if (printk_seq < seq)
3569 diff += seq - printk_seq;
3572 if (diff != last_diff && reset_on_progress)
3573 remaining = timeout_ms;
3575 if (!diff || remaining == 0)
3578 if (remaining < 0) {
3579 pr_msleep(may_sleep, 100);
3580 } else if (remaining < 100) {
3581 pr_msleep(may_sleep, remaining);
3584 pr_msleep(may_sleep, 100);
3593 EXPORT_SYMBOL(pr_flush);