2 * linux/kernel/printk.c
4 * Copyright (C) 1991, 1992 Linus Torvalds
6 * Modified to make sys_syslog() more flexible: added commands to
7 * return the last 4k of kernel messages, regardless of whether
8 * they've been read or not. Added option to suppress kernel printk's
9 * to the console. Added hook for sending the console messages
10 * elsewhere, in preparation for a serial line console (someday).
12 * Modified for sysctl support, 1/8/97, Chris Horn.
13 * Fixed SMP synchronization, 08/08/99, Manfred Spraul
14 * manfred@colorfullife.com
15 * Rewrote bits to get rid of console_lock
16 * 01Mar01 Andrew Morton
19 #include <linux/kernel.h>
21 #include <linux/tty.h>
22 #include <linux/tty_driver.h>
23 #include <linux/console.h>
24 #include <linux/init.h>
25 #include <linux/jiffies.h>
26 #include <linux/nmi.h>
27 #include <linux/module.h>
28 #include <linux/moduleparam.h>
29 #include <linux/interrupt.h> /* For in_interrupt() */
30 #include <linux/delay.h>
31 #include <linux/smp.h>
32 #include <linux/security.h>
33 #include <linux/bootmem.h>
34 #include <linux/memblock.h>
35 #include <linux/aio.h>
36 #include <linux/syscalls.h>
37 #include <linux/kexec.h>
38 #include <linux/kdb.h>
39 #include <linux/ratelimit.h>
40 #include <linux/kmsg_dump.h>
41 #include <linux/syslog.h>
42 #include <linux/cpu.h>
43 #include <linux/notifier.h>
44 #include <linux/rculist.h>
45 #include <linux/poll.h>
46 #include <linux/irq_work.h>
47 #include <linux/utsname.h>
48 #include <linux/device.h>
49 #include <linux/slab.h>
50 #include <linux/kref.h>
51 #include <linux/kdev_t.h>
53 #include <asm/uaccess.h>
55 #if defined(CONFIG_SEC_DEBUG)
56 #include <soc/sprd/sec_debug.h>
57 #include <linux/vmalloc.h>
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/printk.h>
63 #include <uapi/linux/kmsg_ioctl.h>
66 #ifdef CONFIG_DEBUG_LL
67 extern void printascii(char *);
70 /* printk's without a loglevel use this.. */
71 #define DEFAULT_MESSAGE_LOGLEVEL CONFIG_DEFAULT_MESSAGE_LOGLEVEL
73 /* We show everything that is MORE important than this.. */
74 #define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
75 #define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
77 int console_printk[4] = {
78 DEFAULT_CONSOLE_LOGLEVEL, /* console_loglevel */
79 DEFAULT_MESSAGE_LOGLEVEL, /* default_message_loglevel */
80 MINIMUM_CONSOLE_LOGLEVEL, /* minimum_console_loglevel */
81 DEFAULT_CONSOLE_LOGLEVEL, /* default_console_loglevel */
85 * Low level drivers may need that to know if they can schedule in
86 * their unblank() callback or not. So let's export it.
89 EXPORT_SYMBOL(oops_in_progress);
92 * console_sem protects the console_drivers list, and also
93 * provides serialisation for access to the entire console
96 static DEFINE_SEMAPHORE(console_sem);
97 struct console *console_drivers;
98 EXPORT_SYMBOL_GPL(console_drivers);
100 #ifdef CONFIG_LOCKDEP
101 static struct lockdep_map console_lock_dep_map = {
102 .name = "console_lock"
107 * This is used for debugging the mess that is the VT code by
108 * keeping track if we have the console semaphore held. It's
109 * definitely not the perfect debug tool (we don't know if _WE_
110 * hold it are racing, but it helps tracking those weird code
111 * path in the console code where we end up in places I want
112 * locked without the console sempahore held
114 static int console_locked, console_suspended;
117 * If exclusive_console is non-NULL then only this console is to be printed to.
119 static struct console *exclusive_console;
122 * Array of consoles built from command line options (console=)
124 struct console_cmdline
126 char name[8]; /* Name of the driver */
127 int index; /* Minor dev. to use */
128 char *options; /* Options for the driver */
129 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
130 char *brl_options; /* Options for braille driver */
134 #define MAX_CMDLINECONSOLES 8
136 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
137 static int selected_console = -1;
138 static int preferred_console = -1;
139 int console_set_on_cmdline;
140 EXPORT_SYMBOL(console_set_on_cmdline);
142 /* Flag: console code may call schedule() */
143 static int console_may_schedule;
146 * The printk log buffer consists of a chain of concatenated variable
147 * length records. Every record starts with a record header, containing
148 * the overall length of the record.
150 * The heads to the first and last entry in the buffer, as well as the
151 * sequence numbers of these both entries are maintained when messages
154 * If the heads indicate available messages, the length in the header
155 * tells the start next message. A length == 0 for the next message
156 * indicates a wrap-around to the beginning of the buffer.
158 * Every record carries the monotonic timestamp in microseconds, as well as
159 * the standard userspace syslog level and syslog facility. The usual
160 * kernel messages use LOG_KERN; userspace-injected messages always carry
161 * a matching syslog facility, by default LOG_USER. The origin of every
162 * message can be reliably determined that way.
164 * The human readable log message directly follows the message header. The
165 * length of the message text is stored in the header, the stored message
168 * Optionally, a message can carry a dictionary of properties (key/value pairs),
169 * to provide userspace with a machine-readable message context.
171 * Examples for well-defined, commonly used property names are:
172 * DEVICE=b12:8 device identifier
176 * +sound:card0 subsystem:devname
177 * SUBSYSTEM=pci driver-core subsystem name
179 * Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
180 * follows directly after a '=' character. Every property is terminated by
181 * a '\0' character. The last property is not terminated.
183 * Example of a message structure:
184 * 0000 ff 8f 00 00 00 00 00 00 monotonic time in nsec
185 * 0008 34 00 record is 52 bytes long
186 * 000a 0b 00 text is 11 bytes long
187 * 000c 1f 00 dictionary is 23 bytes long
188 * 000e 03 00 LOG_KERN (facility) LOG_ERR (level)
189 * 0010 69 74 27 73 20 61 20 6c "it's a l"
191 * 001b 44 45 56 49 43 "DEVIC"
192 * 45 3d 62 38 3a 32 00 44 "E=b8:2\0D"
193 * 52 49 56 45 52 3d 62 75 "RIVER=bu"
195 * 0032 00 00 00 padding to next message header
197 * The 'struct log' buffer header must never be directly exported to
198 * userspace, it is a kernel-private implementation detail that might
199 * need to be changed in the future, when the requirements change.
201 * /dev/kmsg exports the structured data in the following line format:
202 * "level,sequnum,timestamp;<message text>\n"
204 * The optional key/value pairs are attached as continuation lines starting
205 * with a space character and terminated by a newline. All possible
206 * non-prinatable characters are escaped in the "\xff" notation.
208 * Users of the export format should ignore possible additional values
209 * separated by ',', and find the message after the ';' character.
213 LOG_NOCONS = 1, /* already flushed, do not print to console */
214 LOG_NEWLINE = 2, /* text ended with a newline */
215 LOG_PREFIX = 4, /* text started with a prefix */
216 LOG_CONT = 8, /* text is a fragment of a continuation line */
220 u64 ts_nsec; /* timestamp in nanoseconds */
221 u16 len; /* length of entire record */
222 u16 text_len; /* length of text buffer */
223 u16 dict_len; /* length of dictionary buffer */
224 u8 facility; /* syslog facility */
225 u8 flags:5; /* internal record flags */
226 u8 level:3; /* syslog level */
227 #ifdef CONFIG_PRINTK_PROCESS
228 char process[16]; /* process Name CONFIG_PRINTK_PROCESS */
229 u16 pid; /* process id CONFIG_PRINTK_PROCESS */
230 u16 cpu; /* cpu core number CONFIG_PRINTK_PROCESS */
231 u8 in_interrupt; /* in interrupt CONFIG_PRINTK_PROCESS */
233 int cpu; /* the print cpu */
239 struct list_head list; /* kmsg as head of the list */
240 char *buf; /* cyclic log buffer */
241 u32 len; /* buffer length */
242 wait_queue_head_t wait; /* wait queue for kmsg buffer */
243 struct kref refcount; /* refcount for kmsg_sys buffers */
246 * The lock protects kmsg buffer, indices, counters. This can be taken within
247 * the scheduler's rq lock. It must be released before calling console_unlock()
248 * or anything else that might wake up a process.
251 u64 first_seq; /* sequence number of the first record stored */
252 u32 first_idx; /* index of the first record stored */
253 /* sequence number of the next record to store */
256 u32 next_idx; /* index of the next record to store */
257 /* sequence number of the next record to read after last 'clear' command */
259 /* index of the next record to read after last 'clear' command */
261 int mode; /* mode of device */
262 int minor; /* minor representing buffer device */
267 /* the next printk record to read by syslog(READ) or /proc/kmsg */
268 static u64 syslog_seq;
269 static u32 syslog_idx;
270 static enum log_flags syslog_prev;
271 static size_t syslog_partial;
273 /* the next printk record to write to the console */
274 static u64 console_seq;
275 static u32 console_idx;
276 static enum log_flags console_prev;
278 #ifdef CONFIG_PRINTK_PROCESS
279 #define PREFIX_MAX 48
281 #define PREFIX_MAX 32
283 #define LOG_LINE_MAX 1024 - PREFIX_MAX
284 #define KMSG_NUM_MAX 255
287 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
290 #define LOG_ALIGN __alignof__(struct log)
292 #define __LOG_BUF_K_LEN (1 << CONFIG_LOG_BUF_SHIFT)
293 static char __log_buf_k[__LOG_BUF_K_LEN] __aligned(LOG_ALIGN);
295 static struct log_buffer log_buf = {
296 .list = LIST_HEAD_INIT(log_buf.list),
298 .len = __LOG_BUF_K_LEN,
299 .lock = __RAW_SPIN_LOCK_UNLOCKED(log_buf.lock),
300 .wait = __WAIT_QUEUE_HEAD_INITIALIZER(log_buf.wait),
301 .refcount = { .refcount = { .counter = 0 } },
312 wait_queue_head_t *log_wait = &log_buf.wait;
314 /* Return log buffer address */
315 char *log_buf_addr_get(void)
320 /* Return log buffer size */
321 u32 log_buf_len_get(void)
326 /* cpu currently holding log_buf.lock */
327 static volatile unsigned int logbuf_cpu = UINT_MAX;
329 /* human readable text of the record */
330 static char *log_text(const struct log *msg)
332 return (char *)msg + sizeof(struct log);
335 /* optional key/value pair dictionary attached to the record */
336 static char *log_dict(const struct log *msg)
338 return (char *)msg + sizeof(struct log) + msg->text_len;
341 /* get record by index; idx must point to valid msg */
342 static struct log *log_from_idx(struct log_buffer *log_b, u32 idx)
344 struct log *msg = (struct log *)(log_b->buf + idx);
347 * A length == 0 record is the end of buffer marker. Wrap around and
348 * read the message at the start of the buffer.
351 return (struct log *)log_b->buf;
355 /* get next record; idx must point to valid msg */
356 static u32 log_next(struct log_buffer *log_b, u32 idx)
358 struct log *msg = (struct log *)(log_b->buf + idx);
360 /* length == 0 indicates the end of the buffer; wrap */
362 * A length == 0 record is the end of buffer marker. Wrap around and
363 * read the message at the start of the buffer as *this* one, and
364 * return the one after that.
367 msg = (struct log *)log_b->buf;
370 return idx + msg->len;
374 * Check whether there is enough free space for the given message.
376 * The same values of first_idx and next_idx mean that the buffer
377 * is either empty or full.
379 * If the buffer is empty, we must respect the position of the indexes.
380 * They cannot be reset to the beginning of the buffer.
382 static int logbuf_has_space(struct log_buffer *log_b, u32 msg_size, bool empty)
386 if (log_b->next_idx > log_b->first_idx || empty)
387 free = max(log_b->len - log_b->next_idx, log_b->first_idx);
389 free = log_b->first_idx - log_b->next_idx;
392 * We need space also for an empty header that signalizes wrapping
395 return free >= msg_size + sizeof(struct log);
398 static int log_make_free_space(struct log_buffer *log_b, u32 msg_size)
400 while (log_b->first_seq < log_b->next_seq) {
401 if (logbuf_has_space(log_b, msg_size, false))
403 /* drop old messages until we have enough contiguous space */
404 log_b->first_idx = log_next(log_b, log_b->first_idx);
408 /* sequence numbers are equal, so the log buffer is empty */
409 if (logbuf_has_space(log_b, msg_size, true))
415 /* compute the message size including the padding bytes */
416 static u32 msg_used_size(u16 text_len, u16 dict_len, u32 *pad_len)
420 size = sizeof(struct log) + text_len + dict_len;
421 *pad_len = (-size) & (LOG_ALIGN - 1);
428 * Define how much of the log buffer we could take at maximum. The value
429 * must be greater than two. Note that only half of the buffer is available
430 * when the index points to the middle.
432 #define MAX_LOG_TAKE_PART 4
433 static const char trunc_msg[] = "<truncated>";
436 static u32 truncate_msg(struct log_buffer *log_b,
438 u16 *dict_len, u32 *pad_len)
441 * The message should not take the whole buffer. Otherwise, it might
442 * get removed too soon.
444 u32 max_text_len = log_b->len / MAX_LOG_TAKE_PART;
445 if (*text_len > max_text_len)
446 *text_len = max_text_len;
447 /* disable the "dict" completely */
449 /* compute the size again, count also the warning message */
450 return msg_used_size(*text_len + strlen(trunc_msg), 0, pad_len);
453 #ifdef CONFIG_SEC_LOG
454 static char initial_log_buf[__LOG_BUF_K_LEN];
455 static unsigned int initial_log_idx = 0;
456 static void (*log_text_hook)(char *text, size_t size);
457 static char *seclog_buf;
458 static unsigned *seclog_ptr;
459 static size_t seclog_size;
460 static char sec_text[1024]; /* buffer size: LOG_LINE_MAX + PREFIX_MAX */
461 void register_log_text_hook(void (*f)(char *text, size_t size), char * buf,
462 unsigned *position, size_t bufsize)
465 raw_spin_lock_irqsave(&log_buf.lock, flags);
466 if (buf && bufsize) {
468 seclog_ptr = position;
469 seclog_size = bufsize;
472 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
474 EXPORT_SYMBOL(register_log_text_hook);
475 static size_t msg_print_text(const struct log *msg, enum log_flags prev,
476 bool syslog, char *buf, size_t size);
479 /* insert record into the buffer, discard old ones, update heads */
480 static int log_store(struct log_buffer *log_b,
481 int facility, int level,
482 enum log_flags flags, u64 ts_nsec,
483 const char *dict, u16 dict_len,
484 const char *text, u16 text_len, int cpu)
489 /* number of '\0' padding bytes to next message */
490 size = msg_used_size(text_len, dict_len, &pad_len);
492 if (log_make_free_space(log_b, size)) {
493 /* truncate the message if it is too long for empty buffer */
494 size = truncate_msg(log_b, &text_len, &dict_len, &pad_len);
495 /* survive when the log buffer is too small for trunc_msg */
496 if (log_make_free_space(log_b, size))
500 if (log_b->next_idx + size + sizeof(struct log) > log_b->len) {
502 * This message + an additional empty header does not fit
503 * at the end of the buffer. Add an empty header with len == 0
504 * to signify a wrap around.
506 memset(log_b->buf + log_b->next_idx, 0,
512 msg = (struct log *)(log_b->buf + log_b->next_idx);
513 memcpy(log_text(msg), text, text_len);
514 msg->text_len = text_len;
515 memcpy(log_dict(msg), dict, dict_len);
516 msg->dict_len = dict_len;
517 msg->facility = facility;
518 msg->level = level & 7;
519 msg->flags = flags & 0x1f;
522 msg->ts_nsec = ts_nsec;
524 msg->ts_nsec = local_clock();
525 memset(log_dict(msg) + dict_len, 0, pad_len);
526 msg->len = sizeof(struct log) + text_len + dict_len + pad_len;
528 #ifdef CONFIG_PRINTK_PROCESS
529 strncpy(msg->process, current->comm, sizeof(msg->process));
530 msg->pid = task_pid_nr(current);
531 msg->cpu = smp_processor_id();
532 msg->in_interrupt = in_interrupt()? 1 : 0;
535 #ifdef CONFIG_SEC_LOG
537 if(initial_log_idx) {
538 /* Copying of stored initial kernel boot log to
541 log_text_hook(initial_log_buf, initial_log_idx);
545 size = msg_print_text(msg, msg->flags, true,
548 log_text_hook(sec_text, size);
549 } else if (initial_log_idx < (__LOG_BUF_K_LEN)) {
550 /* Storing of kernel boot logs prior to log_text_hook()
553 size = msg_print_text(msg, msg->flags, true,
555 memcpy(initial_log_buf + initial_log_idx, sec_text, size);
556 initial_log_idx += size;
560 log_b->next_idx += msg->len;
563 return msg->text_len;
566 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
567 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
569 static size_t print_time(u64 ts, char *buf)
571 unsigned long rem_nsec;
576 rem_nsec = do_div(ts, 1000000000);
579 return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
581 return sprintf(buf, "[%5lu.%06lu] ",
582 (unsigned long)ts, rem_nsec / 1000);
586 * Continuation lines are buffered, and not committed to the record buffer
587 * until the line is complete, or a race forces it. The line fragments
588 * though, are printed immediately to the consoles to ensure everything has
589 * reached the console in case of a kernel crash.
592 char buf[LOG_LINE_MAX];
593 size_t len; /* length == 0 means unused buffer */
594 size_t cons; /* bytes written to console */
595 struct task_struct *owner; /* task of first print*/
596 u64 ts_nsec; /* time of first print */
597 u8 level; /* log level of first message */
598 u8 facility; /* log facility of first message */
599 enum log_flags flags; /* prefix, newline flags */
600 bool flushed:1; /* buffer sealed and committed */
604 static void cont_flush(enum log_flags flags)
613 * If a fragment of this line was directly flushed to the
614 * console; wait for the console to pick up the rest of the
615 * line. LOG_NOCONS suppresses a duplicated output.
617 log_store(&log_buf, cont.facility, cont.level,
618 flags | LOG_NOCONS, cont.ts_nsec, NULL, 0,
619 cont.buf, cont.len, cont.cpu);
624 * If no fragment of this line ever reached the console,
625 * just submit it to the store and free the buffer.
627 log_store(&log_buf, cont.facility, cont.level, flags, 0,
628 NULL, 0, cont.buf, cont.len, cont.cpu);
633 static bool cont_add(int facility, int level, const char *text, size_t len)
635 if (cont.len && cont.flushed)
638 if (cont.len + len > sizeof(cont.buf)) {
639 /* the line gets too long, split it up in separate records */
640 cont_flush(LOG_CONT);
645 cont.facility = facility;
647 cont.owner = current;
648 cont.ts_nsec = local_clock();
651 cont.flushed = false;
654 memcpy(cont.buf + cont.len, text, len);
657 if (cont.len > (sizeof(cont.buf) * 80) / 100)
658 cont_flush(LOG_CONT);
663 static size_t cont_print_text(char *text, size_t size)
668 if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
669 textlen += print_time(cont.ts_nsec, text);
673 len = cont.len - cont.cons;
677 memcpy(text + textlen, cont.buf + cont.cons, len);
679 cont.cons = cont.len;
683 if (cont.flags & LOG_NEWLINE)
684 text[textlen++] = '\n';
685 /* got everything, release buffer */
691 static int log_format_and_store(struct log_buffer *log_b,
692 int facility, int level,
693 const char *dict, size_t dictlen,
694 const char *fmt, int cpu, va_list args)
696 static char textbuf[LOG_LINE_MAX];
697 char *text = textbuf;
699 enum log_flags lflags = 0;
703 * The printf needs to come first; we need the syslog
704 * prefix which might be passed-in as a parameter.
706 text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
708 /* mark and strip a trailing newline */
709 if (text_len && text[text_len-1] == '\n') {
711 lflags |= LOG_NEWLINE;
714 /* strip kernel syslog prefix and extract log level or control flags */
716 int kern_level = printk_get_level(text);
719 const char *end_of_header = printk_skip_level(text);
721 switch (kern_level) {
723 if (level == DEFAULT_MESSAGE_LOGLEVEL)
724 level = kern_level - '0';
726 case 'd': /* KERN_DEFAULT */
727 lflags |= LOG_PREFIX;
730 * No need to check length here because vscnprintf
731 * put '\0' at the end of the string. Only valid and
732 * newly printed level is detected.
734 text_len -= end_of_header - text;
735 text = (char *)end_of_header;
739 if (level == DEFAULT_MESSAGE_LOGLEVEL)
740 level = default_message_loglevel;
743 lflags |= LOG_PREFIX|LOG_NEWLINE;
745 if (log_b != &log_buf)
746 return log_store(log_b, facility, level, lflags, 0,
747 dict, dictlen, text, text_len, cpu);
749 if (!(lflags & LOG_NEWLINE)) {
751 * Flush the conflicting buffer. An earlier newline was missing,
752 * or another task also prints continuation lines.
754 if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
755 cont_flush(LOG_NEWLINE);
757 /* buffer line if possible, otherwise store it right away */
758 if (cont_add(facility, level, text, text_len))
759 printed_len += text_len;
761 printed_len += log_store(log_b, facility, level,
762 lflags | LOG_CONT, 0,
769 * If an earlier newline was missing and it was the same task,
770 * either merge it with the current buffer and flush, or if
771 * there was a race with interrupts (prefix == true) then just
772 * flush it out and store this line separately.
773 * If the preceding printk was from a different task and missed
774 * a newline, flush and append the newline.
777 if (cont.owner == current && !(lflags & LOG_PREFIX))
778 stored = cont_add(facility, level, text,
780 cont_flush(LOG_NEWLINE);
784 printed_len += text_len;
786 printed_len += log_store(log_b, facility, level,
787 lflags, 0, dict, dictlen,
788 text, text_len, cpu);
793 #ifdef CONFIG_SECURITY_DMESG_RESTRICT
794 int dmesg_restrict = 1;
799 static int syslog_action_restricted(int type)
804 * Unless restricted, we allow "read all" and "get buffer size"
807 return type != SYSLOG_ACTION_READ_ALL &&
808 type != SYSLOG_ACTION_SIZE_BUFFER;
811 static int check_syslog_permissions(int type, bool from_file)
814 * If this is from /proc/kmsg and we've already opened it, then we've
815 * already done the capabilities checks at open time.
817 if (from_file && type != SYSLOG_ACTION_OPEN)
820 if (syslog_action_restricted(type)) {
821 if (capable(CAP_SYSLOG))
824 * For historical reasons, accept CAP_SYS_ADMIN too, with
827 if (capable(CAP_SYS_ADMIN)) {
828 pr_warn_once("%s (%d): Attempt to access syslog with "
829 "CAP_SYS_ADMIN but no CAP_SYSLOG "
831 current->comm, task_pid_nr(current));
836 return security_syslog(type);
839 static void append_char(char **pp, char *e, char c)
845 /* /dev/kmsg - userspace message inject/listen interface */
846 struct devkmsg_user {
851 char buf[CONSOLE_EXT_LOG_MAX];
854 void log_buf_release(struct kref *ref)
856 struct log_buffer *log_b = container_of(ref, struct log_buffer,
863 #define MAX_PID_LEN 20
864 #define MAX_TID_LEN 20
866 * Fromat below describes dict appended to message written from userspace:
867 * "_PID=<pid>\0_TID=<tid>\0_COMM=<comm>"
868 * KMSG_DICT_MAX_LEN definition represents maximal length of this dict.
870 #define KMSG_DICT_MAX_LEN (5 + MAX_PID_LEN + 1 + \
871 5 + MAX_TID_LEN + 1 + \
874 static size_t set_kmsg_dict(char *buf)
878 len = sprintf(buf, "_PID=%d", task_tgid_nr(current)) + 1;
879 len += sprintf(buf + len, "_TID=%d", task_pid_nr(current)) + 1;
880 memcpy(buf + len, "_COMM=", 6);
882 get_task_comm(buf + len, current);
883 while (buf[len] != '\0')
888 static int kmsg_sys_write(int minor, int level,
889 const char *dict, size_t dictlen,
890 const char *fmt, ...)
894 struct log_buffer *log_b;
897 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
898 if (log_b->minor != minor)
901 raw_spin_lock(&log_b->lock);
904 log_format_and_store(log_b, 1 /* LOG_USER */, level,
905 dict, dictlen, fmt, smp_processor_id(), args);
907 wake_up_interruptible(&log_b->wait);
909 raw_spin_unlock(&log_b->lock);
918 static ssize_t devkmsg_writev(struct kiocb *iocb, const struct iovec *iv,
919 unsigned long count, loff_t pos)
923 int level = default_message_loglevel;
924 int facility = 1; /* LOG_USER */
925 size_t len = iov_length(iv, count);
926 char dict[KMSG_DICT_MAX_LEN];
929 int minor = iminor(iocb->ki_filp->f_inode);
931 if (len > LOG_LINE_MAX)
933 buf = kmalloc(len+1, GFP_KERNEL);
938 for (i = 0; i < count; i++) {
939 if (copy_from_user(line, iv[i].iov_base, iv[i].iov_len)) {
943 line += iv[i].iov_len;
947 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
948 * the decimal value represents 32bit, the lower 3 bit are the log
949 * level, the rest are the log facility.
951 * If no prefix or no userspace facility is specified, we
952 * enforce LOG_USER, to be able to reliably distinguish
953 * kernel-generated messages from userspace-injected ones.
956 if (line[0] == '<') {
959 i = simple_strtoul(line+1, &endp, 10);
960 if (endp && endp[0] == '>') {
971 dictlen = set_kmsg_dict(dict);
973 if (minor == log_buf.minor) {
974 printk_emit(facility, level, dict, dictlen, "%s", line);
976 int error = kmsg_sys_write(minor, level, dict, dictlen, "%s", line);
987 static ssize_t kmsg_read(struct log_buffer *log_b, struct file *file,
988 char __user *buf, size_t count, loff_t *ppos)
990 struct devkmsg_user *user = file->private_data;
1000 e = user->buf + sizeof(user->buf);
1002 ret = mutex_lock_interruptible(&user->lock);
1005 raw_spin_lock_irq(&log_b->lock);
1006 while (user->seq == log_b->next_seq) {
1007 if (file->f_flags & O_NONBLOCK) {
1009 raw_spin_unlock_irq(&log_b->lock);
1013 raw_spin_unlock_irq(&log_b->lock);
1015 if (log_b == &log_buf) {
1016 ret = wait_event_interruptible(log_b->wait,
1017 user->seq != log_b->next_seq);
1019 kref_get(&log_b->refcount);
1020 ret = wait_event_interruptible(log_b->wait,
1021 user->seq != log_b->next_seq);
1022 if (log_b->minor == -1)
1024 if (kref_put(&log_b->refcount, log_buf_release))
1029 raw_spin_lock_irq(&log_b->lock);
1032 if (user->seq < log_b->first_seq) {
1033 /* our last seen message is gone, return error and reset */
1034 user->idx = log_b->first_idx;
1035 user->seq = log_b->first_seq;
1037 raw_spin_unlock_irq(&log_b->lock);
1041 msg = log_from_idx(log_b, user->idx);
1042 ts_usec = msg->ts_nsec;
1043 do_div(ts_usec, 1000);
1046 * If we couldn't merge continuation line fragments during the print,
1047 * export the stored flags to allow an optional external merge of the
1048 * records. Merging the records isn't always neccessarily correct, like
1049 * when we hit a race during printing. In most cases though, it produces
1050 * better readable output. 'c' in the record flags mark the first
1051 * fragment of a line, '+' the following.
1053 if (msg->flags & LOG_CONT && !(user->prev & LOG_CONT))
1055 else if ((msg->flags & LOG_CONT) ||
1056 ((user->prev & LOG_CONT) && !(msg->flags & LOG_PREFIX)))
1059 p += scnprintf(p, e - p, "%u,%llu,%llu,%c;",
1060 (msg->facility << 3) | msg->level,
1061 user->seq, ts_usec, cont);
1062 user->prev = msg->flags;
1064 for (i = 0; i < msg->text_len; i++) {
1065 unsigned char c = log_text(msg)[i];
1067 append_char(&p, e, c);
1071 * The \0 is delimits the text part, while the newline is for formatting
1072 * when catting the device directly. We cannot use \n for delimiting due
1073 * to security: else one could forge dictionary tags through the message
1074 * such as "text\n _PID=123"
1076 append_char(&p, e, '\0');
1077 append_char(&p, e, '\n');
1079 if (msg->dict_len) {
1082 for (i = 0; i < msg->dict_len; i++) {
1083 unsigned char c = log_dict(msg)[i];
1086 append_char(&p, e, ' ');
1091 append_char(&p, e, '\n');
1096 append_char(&p, e, c);
1098 append_char(&p, e, '\n');
1101 user->idx = log_next(log_b, user->idx);
1103 raw_spin_unlock_irq(&log_b->lock);
1105 len = p - user->buf;
1111 if (copy_to_user(buf, user->buf, len)) {
1117 mutex_unlock(&user->lock);
1122 static ssize_t devkmsg_read(struct file *file, char __user *buf,
1123 size_t count, loff_t *ppos)
1125 struct devkmsg_user *user = file->private_data;
1126 ssize_t ret = -ENXIO;
1127 int minor = iminor(file->f_inode);
1128 struct log_buffer *log_b;
1134 if (minor == log_buf.minor)
1135 return kmsg_read(&log_buf, file, buf, count, ppos);
1138 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
1139 if (log_b->minor == minor) {
1141 kref_get(&log_b->refcount);
1148 ret = kmsg_read(log_b, file, buf, count, ppos);
1149 kref_put(&log_b->refcount, log_buf_release);
1154 static loff_t kmsg_llseek(struct log_buffer *log_b, struct file *file,
1157 struct devkmsg_user *user = file->private_data;
1160 raw_spin_lock_irq(&log_b->lock);
1163 /* the first record */
1164 user->idx = log_b->first_idx;
1165 user->seq = log_b->first_seq;
1169 * The first record after the last SYSLOG_ACTION_CLEAR,
1170 * like issued by 'dmesg -c' or KMSG_CMD_CLEAR ioctl
1171 * command. Reading /dev/kmsg itself changes no global
1172 * state, and does not clear anything.
1174 user->idx = log_b->clear_idx;
1175 user->seq = log_b->clear_seq;
1178 /* after the last record */
1179 user->idx = log_b->next_idx;
1180 user->seq = log_b->next_seq;
1185 raw_spin_unlock_irq(&log_b->lock);
1189 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
1191 struct devkmsg_user *user = file->private_data;
1192 loff_t ret = -ENXIO;
1193 int minor = iminor(file->f_inode);
1194 struct log_buffer *log_b;
1201 if (minor == log_buf.minor)
1202 return kmsg_llseek(&log_buf, file, whence);
1205 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
1206 if (log_b->minor == minor) {
1207 ret = kmsg_llseek(log_b, file, whence);
1215 static unsigned int kmsg_poll(struct log_buffer *log_b,
1216 struct file *file, poll_table *wait)
1218 struct devkmsg_user *user = file->private_data;
1221 poll_wait(file, &log_b->wait, wait);
1223 raw_spin_lock_irq(&log_b->lock);
1224 if (user->seq < log_b->next_seq) {
1225 /* return error when data has vanished underneath us */
1226 if (user->seq < log_b->first_seq)
1227 ret = POLLIN|POLLRDNORM|POLLERR|POLLPRI;
1229 ret = POLLIN|POLLRDNORM;
1231 raw_spin_unlock_irq(&log_b->lock);
1236 static unsigned int devkmsg_poll(struct file *file, poll_table *wait)
1238 struct devkmsg_user *user = file->private_data;
1239 int ret = POLLERR|POLLNVAL;
1240 int minor = iminor(file->f_inode);
1241 struct log_buffer *log_b;
1244 return POLLERR|POLLNVAL;
1246 if (minor == log_buf.minor)
1247 return kmsg_poll(&log_buf, file, wait);
1250 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
1251 if (log_b->minor == minor) {
1252 kref_get(&log_b->refcount);
1255 ret = kmsg_poll(log_b, file, wait);
1257 if (kref_put(&log_b->refcount, log_buf_release))
1258 return POLLERR|POLLNVAL;
1266 static int kmsg_open(struct log_buffer *log_b, struct file *file)
1268 struct devkmsg_user *user;
1270 user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
1274 mutex_init(&user->lock);
1276 raw_spin_lock_irq(&log_b->lock);
1277 user->idx = log_b->first_idx;
1278 user->seq = log_b->first_seq;
1279 raw_spin_unlock_irq(&log_b->lock);
1281 file->private_data = user;
1285 static int devkmsg_open(struct inode *inode, struct file *file)
1288 int minor = iminor(file->f_inode);
1289 struct log_buffer *log_b;
1292 /* write-only does not need any file context */
1293 if ((file->f_flags & O_ACCMODE) == O_WRONLY)
1296 if (minor == log_buf.minor) {
1297 ret = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
1298 SYSLOG_FROM_READER);
1302 return kmsg_open(&log_buf, file);
1306 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
1307 if (log_b->minor == minor) {
1309 kref_get(&log_b->refcount);
1316 ret = kmsg_open(log_b, file);
1317 kref_put(&log_b->refcount, log_buf_release);
1322 static long kmsg_ioctl(struct log_buffer *log_b, unsigned int cmd,
1325 void __user *argp = (void __user *)arg;
1326 static const u32 read_size_max = CONSOLE_EXT_LOG_MAX;
1329 case KMSG_CMD_GET_BUF_SIZE:
1330 if (copy_to_user(argp, &log_b->len, sizeof(u32)))
1333 case KMSG_CMD_GET_READ_SIZE_MAX:
1334 if (copy_to_user(argp, &read_size_max, sizeof(u32)))
1337 case KMSG_CMD_CLEAR:
1338 if (!capable(CAP_SYSLOG))
1340 raw_spin_lock_irq(&log_b->lock);
1341 log_b->clear_seq = log_b->next_seq;
1342 log_b->clear_idx = log_b->next_idx;
1343 raw_spin_unlock_irq(&log_b->lock);
1351 static long devkmsg_ioctl(struct file *file, unsigned int cmd,
1355 int minor = iminor(file->f_inode);
1356 struct log_buffer *log_b;
1358 if (minor == log_buf.minor)
1359 return kmsg_ioctl(&log_buf, cmd, arg);
1362 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
1363 if (log_b->minor == minor) {
1364 ret = kmsg_ioctl(log_b, cmd, arg);
1372 static int devkmsg_release(struct inode *inode, struct file *file)
1374 struct devkmsg_user *user = file->private_data;
1379 mutex_destroy(&user->lock);
1384 const struct file_operations kmsg_fops = {
1385 .open = devkmsg_open,
1386 .read = devkmsg_read,
1387 .aio_write = devkmsg_writev,
1388 .llseek = devkmsg_llseek,
1389 .poll = devkmsg_poll,
1390 .unlocked_ioctl = devkmsg_ioctl,
1391 .compat_ioctl = devkmsg_ioctl,
1392 .release = devkmsg_release,
1395 #define MAX_MINOR_LEN 20
1397 static int kmsg_open_ext(struct inode *inode, struct file *file)
1399 return kmsg_fops.open(inode, file);
1402 static ssize_t kmsg_writev_ext(struct kiocb *iocb, const struct iovec *iov, unsigned long count, loff_t pos)
1404 return kmsg_fops.aio_write(iocb, iov, count, pos);
1407 static ssize_t kmsg_read_ext(struct file *file, char __user *buf,
1408 size_t count, loff_t *ppos)
1410 return kmsg_fops.read(file, buf, count, ppos);
1413 static loff_t kmsg_llseek_ext(struct file *file, loff_t offset, int whence)
1415 return kmsg_fops.llseek(file, offset, whence);
1418 static unsigned int kmsg_poll_ext(struct file *file,
1419 struct poll_table_struct *wait)
1421 return kmsg_fops.poll(file, wait);
1424 static long kmsg_ioctl_buffers(struct file *file, unsigned int cmd,
1427 void __user *argp = (void __user *)arg;
1430 char name[4 + MAX_MINOR_LEN + 1];
1434 if (iminor(file->f_inode) != log_buf.minor)
1438 case KMSG_CMD_BUFFER_ADD:
1439 if (copy_from_user(&size, argp, sizeof(size)))
1441 argp += sizeof(size);
1442 if (copy_from_user(&mode, argp, sizeof(mode)))
1444 argp += sizeof(mode);
1445 minor = kmsg_sys_buffer_add(size, mode);
1448 sprintf(name, "kmsg%d", minor);
1449 dev = device_create(mem_class, NULL, MKDEV(MEM_MAJOR, minor),
1452 kmsg_sys_buffer_del(minor);
1453 return PTR_ERR(dev);
1455 if (copy_to_user(argp, &minor, sizeof(minor))) {
1456 device_destroy(mem_class, MKDEV(MEM_MAJOR, minor));
1457 kmsg_sys_buffer_del(minor);
1461 case KMSG_CMD_BUFFER_DEL:
1462 if (copy_from_user(&minor, argp, sizeof(minor)))
1464 if (minor <= log_buf.minor)
1466 device_destroy(mem_class, MKDEV(MEM_MAJOR, minor));
1467 kmsg_sys_buffer_del(minor);
1473 static long kmsg_unlocked_ioctl_ext(struct file *file, unsigned int cmd,
1476 long ret = kmsg_ioctl_buffers(file, cmd, arg);
1479 return kmsg_fops.unlocked_ioctl(file, cmd, arg);
1483 static long kmsg_compat_ioctl_ext(struct file *file, unsigned int cmd,
1486 long ret = kmsg_ioctl_buffers(file, cmd, arg);
1489 return kmsg_fops.compat_ioctl(file, cmd, arg);
1493 static int kmsg_release_ext(struct inode *inode, struct file *file)
1495 return kmsg_fops.release(inode, file);
1498 const struct file_operations kmsg_fops_ext = {
1499 .open = kmsg_open_ext,
1500 .read = kmsg_read_ext,
1501 .aio_write = kmsg_writev_ext,
1502 .llseek = kmsg_llseek_ext,
1503 .poll = kmsg_poll_ext,
1504 .unlocked_ioctl = kmsg_unlocked_ioctl_ext,
1505 .compat_ioctl = kmsg_compat_ioctl_ext,
1506 .release = kmsg_release_ext,
1509 /* Should be used for device registration */
1510 struct device *init_kmsg(int minor, umode_t mode)
1512 log_buf.minor = minor;
1513 log_buf.mode = mode;
1514 return device_create(mem_class, NULL, MKDEV(MEM_MAJOR, minor),
1518 int kmsg_memory_open(struct inode *inode, struct file *filp)
1520 filp->f_op = &kmsg_fops;
1522 return kmsg_fops.open(inode, filp);
1525 int kmsg_memory_open_ext(struct inode *inode, struct file *filp)
1527 filp->f_op = &kmsg_fops_ext;
1529 return kmsg_fops_ext.open(inode, filp);
1532 int kmsg_mode(int minor, umode_t *mode)
1535 struct log_buffer *log_b;
1537 if (minor == log_buf.minor) {
1538 *mode = log_buf.mode;
1543 list_for_each_entry_rcu(log_b, &log_buf.list, list) {
1544 if (log_b->minor == minor) {
1545 *mode = log_b->mode;
1555 static DEFINE_SPINLOCK(kmsg_sys_list_lock);
1557 int kmsg_sys_buffer_add(size_t size, umode_t mode)
1559 unsigned long flags;
1560 int minor = log_buf.minor;
1561 struct log_buffer *log_b;
1562 struct log_buffer *log_b_new;
1564 if (size < LOG_LINE_MAX + PREFIX_MAX)
1567 log_b_new = kzalloc(sizeof(struct log_buffer), GFP_KERNEL);
1571 log_b_new->buf = kmalloc(size, GFP_KERNEL);
1572 if (!log_b_new->buf) {
1577 log_b_new->len = size;
1578 log_b_new->lock = __RAW_SPIN_LOCK_UNLOCKED(log_b_new->lock);
1579 init_waitqueue_head(&log_b_new->wait);
1580 kref_init(&log_b_new->refcount);
1581 log_b_new->mode = mode;
1583 kref_get(&log_b_new->refcount);
1585 spin_lock_irqsave(&kmsg_sys_list_lock, flags);
1587 list_for_each_entry(log_b, &log_buf.list, list) {
1588 if (log_b->minor - minor > 1)
1591 minor = log_b->minor;
1594 if (!(minor & MINORMASK) || (minor & MINORMASK) >= KMSG_NUM_MAX) {
1595 kref_put(&log_b->refcount, log_buf_release);
1596 spin_unlock_irqrestore(&kmsg_sys_list_lock, flags);
1601 log_b_new->minor = minor;
1603 list_add_tail_rcu(&log_b_new->list, &log_b->list);
1605 spin_unlock_irqrestore(&kmsg_sys_list_lock, flags);
1610 void kmsg_sys_buffer_del(int minor)
1612 unsigned long flags;
1613 struct log_buffer *log_b;
1615 spin_lock_irqsave(&kmsg_sys_list_lock, flags);
1617 list_for_each_entry(log_b, &log_buf.list, list) {
1618 if (log_b->minor == minor)
1622 if (log_b == &log_buf) {
1623 spin_unlock_irqrestore(&kmsg_sys_list_lock, flags);
1627 list_del_rcu(&log_b->list);
1629 spin_unlock_irqrestore(&kmsg_sys_list_lock, flags);
1632 wake_up_interruptible(&log_b->wait);
1634 kref_put(&log_b->refcount, log_buf_release);
1639 * This appends the listed symbols to /proc/vmcoreinfo
1641 * /proc/vmcoreinfo is used by various utiilties, like crash and makedumpfile to
1642 * obtain access to symbols that are otherwise very difficult to locate. These
1643 * symbols are specifically used so that utilities can access and extract the
1644 * dmesg log from a vmcore file after a crash.
1646 void log_buf_kexec_setup(void)
1648 VMCOREINFO_SYMBOL(log_buf);
1649 VMCOREINFO_STRUCT_SIZE(log_buffer);
1650 VMCOREINFO_OFFSET(log_buffer, buf);
1651 VMCOREINFO_OFFSET(log_buffer, len);
1652 VMCOREINFO_OFFSET(log_buffer, first_idx);
1653 VMCOREINFO_OFFSET(log_buffer, next_idx);
1655 * Export struct log size and field offsets. User space tools can
1656 * parse it and detect any changes to structure down the line.
1658 VMCOREINFO_STRUCT_SIZE(log);
1659 VMCOREINFO_OFFSET(log, ts_nsec);
1660 VMCOREINFO_OFFSET(log, len);
1661 VMCOREINFO_OFFSET(log, text_len);
1662 VMCOREINFO_OFFSET(log, dict_len);
1666 /* requested log_buf.len from kernel cmdline */
1667 static unsigned long __initdata new_log_buf_len;
1669 /* save requested log_buf_len since it's too early to process it */
1670 static int __init log_buf_len_setup(char *str)
1672 unsigned size = memparse(str, &str);
1675 size = roundup_pow_of_two(size);
1676 if (size > log_buf.len)
1677 new_log_buf_len = size;
1681 early_param("log_buf_len", log_buf_len_setup);
1683 void __init setup_log_buf(int early)
1685 unsigned long flags;
1689 if (!new_log_buf_len)
1695 mem = memblock_alloc(new_log_buf_len, PAGE_SIZE);
1698 new_log_buf = __va(mem);
1700 new_log_buf = alloc_bootmem_nopanic(new_log_buf_len);
1703 if (unlikely(!new_log_buf)) {
1704 pr_err("log_buf.len: %ld bytes not available\n",
1709 raw_spin_lock_irqsave(&log_buf.lock, flags);
1710 log_buf.len = new_log_buf_len;
1711 log_buf.buf = new_log_buf;
1712 new_log_buf_len = 0;
1713 free = __LOG_BUF_K_LEN - log_buf.next_idx;
1714 memcpy(log_buf.buf, __log_buf_k, __LOG_BUF_K_LEN);
1715 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
1717 pr_info("log_buf.len: %d\n", log_buf.len);
1718 pr_info("early log buf free: %d(%d%%)\n",
1719 free, (free * 100) / __LOG_BUF_K_LEN);
1722 static bool __read_mostly ignore_loglevel;
1724 static int __init ignore_loglevel_setup(char *str)
1726 ignore_loglevel = 1;
1727 printk(KERN_INFO "debug: ignoring loglevel setting.\n");
1732 early_param("ignore_loglevel", ignore_loglevel_setup);
1733 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1734 MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
1735 "print all kernel messages to the console.");
1737 #ifdef CONFIG_BOOT_PRINTK_DELAY
1739 static int boot_delay; /* msecs delay after each printk during bootup */
1740 static unsigned long long loops_per_msec; /* based on boot_delay */
1742 static int __init boot_delay_setup(char *str)
1746 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
1747 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1749 get_option(&str, &boot_delay);
1750 if (boot_delay > 10 * 1000)
1753 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1754 "HZ: %d, loops_per_msec: %llu\n",
1755 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1758 __setup("boot_delay=", boot_delay_setup);
1760 static void boot_delay_msec(int level)
1762 unsigned long long k;
1763 unsigned long timeout;
1765 if ((boot_delay == 0 || system_state != SYSTEM_BOOTING)
1766 || (level >= console_loglevel && !ignore_loglevel)) {
1770 k = (unsigned long long)loops_per_msec * boot_delay;
1772 timeout = jiffies + msecs_to_jiffies(boot_delay);
1777 * use (volatile) jiffies to prevent
1778 * compiler reduction; loop termination via jiffies
1779 * is secondary and may or may not happen.
1781 if (time_after(jiffies, timeout))
1783 touch_nmi_watchdog();
1787 static inline void boot_delay_msec(int level)
1792 #ifdef CONFIG_PRINTK_PROCESS
1793 static size_t print_process(const struct log *msg, char *buf)
1796 return snprintf(NULL, 0, "%c[%1d:%15s:%5d] ", ' ', 0, " ", 0);
1798 return sprintf(buf, "%c[%1d:%15s:%5d] ",
1799 msg->in_interrupt ? 'I' : ' ',
1806 static size_t print_prefix(const struct log *msg, bool syslog, char *buf)
1809 unsigned int prefix = (msg->facility << 3) | msg->level;
1813 len += sprintf(buf, "<%u>", prefix);
1818 else if (prefix > 99)
1820 else if (prefix > 9)
1825 len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
1826 #ifdef CONFIG_PRINTK_PROCESS
1827 len += print_process(msg, buf ? buf + len : NULL);
1832 static size_t msg_print_text(const struct log *msg, enum log_flags prev,
1833 bool syslog, char *buf, size_t size)
1835 const char *text = log_text(msg);
1836 size_t text_size = msg->text_len;
1838 bool newline = true;
1841 if ((prev & LOG_CONT) && !(msg->flags & LOG_PREFIX))
1844 if (msg->flags & LOG_CONT) {
1845 if ((prev & LOG_CONT) && !(prev & LOG_NEWLINE))
1848 if (!(msg->flags & LOG_NEWLINE))
1853 const char *next = memchr(text, '\n', text_size);
1857 text_len = next - text;
1859 text_size -= next - text;
1861 text_len = text_size;
1865 if (print_prefix(msg, syslog, NULL) +
1866 text_len + 1 >= size - len)
1870 len += print_prefix(msg, syslog, buf + len);
1871 memcpy(buf + len, text, text_len);
1873 if (next || newline)
1876 /* SYSLOG_ACTION_* buffer size only calculation */
1878 len += print_prefix(msg, syslog, NULL);
1880 if (next || newline)
1891 static int syslog_print(char __user *buf, int size)
1897 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1905 raw_spin_lock_irq(&log_buf.lock);
1906 if (syslog_seq < log_buf.first_seq) {
1907 /* messages are gone, move to first one */
1908 syslog_seq = log_buf.first_seq;
1909 syslog_idx = log_buf.first_idx;
1913 if (syslog_seq == log_buf.next_seq) {
1914 raw_spin_unlock_irq(&log_buf.lock);
1918 skip = syslog_partial;
1919 msg = log_from_idx(&log_buf, syslog_idx);
1920 n = msg_print_text(msg, syslog_prev, true, text,
1921 LOG_LINE_MAX + PREFIX_MAX);
1922 if (n - syslog_partial <= size) {
1923 /* message fits into buffer, move forward */
1924 syslog_idx = log_next(&log_buf, syslog_idx);
1926 syslog_prev = msg->flags;
1927 n -= syslog_partial;
1930 /* partial read(), remember position */
1932 syslog_partial += n;
1935 raw_spin_unlock_irq(&log_buf.lock);
1940 if (copy_to_user(buf, text + skip, n)) {
1955 static int syslog_print_all(char __user *buf, int size, bool clear)
1960 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1964 raw_spin_lock_irq(&log_buf.lock);
1969 enum log_flags prev;
1971 if (log_buf.clear_seq < log_buf.first_seq) {
1972 /* messages are gone, move to first available one */
1973 log_buf.clear_seq = log_buf.first_seq;
1974 log_buf.clear_idx = log_buf.first_idx;
1978 * Find first record that fits, including all following records,
1979 * into the user-provided buffer for this dump.
1981 seq = log_buf.clear_seq;
1982 idx = log_buf.clear_idx;
1984 while (seq < log_buf.next_seq) {
1985 struct log *msg = log_from_idx(&log_buf, idx);
1987 len += msg_print_text(msg, prev, true, NULL, 0);
1989 idx = log_next(&log_buf, idx);
1993 /* move first record forward until length fits into the buffer */
1994 seq = log_buf.clear_seq;
1995 idx = log_buf.clear_idx;
1997 while (len > size && seq < log_buf.next_seq) {
1998 struct log *msg = log_from_idx(&log_buf, idx);
2000 len -= msg_print_text(msg, prev, true, NULL, 0);
2002 idx = log_next(&log_buf, idx);
2006 /* last message fitting into this dump */
2007 next_seq = log_buf.next_seq;
2011 while (len >= 0 && seq < next_seq) {
2012 struct log *msg = log_from_idx(&log_buf, idx);
2015 textlen = msg_print_text(msg, prev, true, text,
2016 LOG_LINE_MAX + PREFIX_MAX);
2021 idx = log_next(&log_buf, idx);
2025 raw_spin_unlock_irq(&log_buf.lock);
2026 if (copy_to_user(buf + len, text, textlen))
2030 raw_spin_lock_irq(&log_buf.lock);
2032 if (seq < log_buf.first_seq) {
2033 /* messages are gone, move to next one */
2034 seq = log_buf.first_seq;
2035 idx = log_buf.first_idx;
2042 log_buf.clear_seq = log_buf.next_seq;
2043 log_buf.clear_idx = log_buf.next_idx;
2045 raw_spin_unlock_irq(&log_buf.lock);
2051 int do_syslog(int type, char __user *buf, int len, bool from_file)
2054 static int saved_console_loglevel = -1;
2057 error = check_syslog_permissions(type, from_file);
2061 error = security_syslog(type);
2066 case SYSLOG_ACTION_CLOSE: /* Close log */
2068 case SYSLOG_ACTION_OPEN: /* Open log */
2070 case SYSLOG_ACTION_READ: /* Read from log */
2072 if (!buf || len < 0)
2077 if (!access_ok(VERIFY_WRITE, buf, len)) {
2081 error = wait_event_interruptible(log_buf.wait,
2082 syslog_seq != log_buf.next_seq);
2085 error = syslog_print(buf, len);
2087 /* Read/clear last kernel messages */
2088 case SYSLOG_ACTION_READ_CLEAR:
2091 /* Read last kernel messages */
2092 case SYSLOG_ACTION_READ_ALL:
2094 if (!buf || len < 0)
2099 if (!access_ok(VERIFY_WRITE, buf, len)) {
2103 error = syslog_print_all(buf, len, clear);
2105 /* Clear ring buffer */
2106 case SYSLOG_ACTION_CLEAR:
2107 syslog_print_all(NULL, 0, true);
2109 /* Disable logging to console */
2110 case SYSLOG_ACTION_CONSOLE_OFF:
2111 if (saved_console_loglevel == -1)
2112 saved_console_loglevel = console_loglevel;
2113 console_loglevel = minimum_console_loglevel;
2115 /* Enable logging to console */
2116 case SYSLOG_ACTION_CONSOLE_ON:
2117 if (saved_console_loglevel != -1) {
2118 console_loglevel = saved_console_loglevel;
2119 saved_console_loglevel = -1;
2122 /* Set level of messages printed to console */
2123 case SYSLOG_ACTION_CONSOLE_LEVEL:
2125 if (len < 1 || len > 8)
2127 if (len < minimum_console_loglevel)
2128 len = minimum_console_loglevel;
2129 console_loglevel = len;
2130 /* Implicitly re-enable logging to console */
2131 saved_console_loglevel = -1;
2134 /* Number of chars in the log buffer */
2135 case SYSLOG_ACTION_SIZE_UNREAD:
2136 raw_spin_lock_irq(&log_buf.lock);
2137 if (syslog_seq < log_buf.first_seq) {
2138 /* messages are gone, move to first one */
2139 syslog_seq = log_buf.first_seq;
2140 syslog_idx = log_buf.first_idx;
2146 * Short-cut for poll(/"proc/kmsg") which simply checks
2147 * for pending data, not the size; return the count of
2148 * records, not the length.
2150 error = log_buf.next_idx - syslog_idx;
2152 u64 seq = syslog_seq;
2153 u32 idx = syslog_idx;
2154 enum log_flags prev = syslog_prev;
2157 while (seq < log_buf.next_seq) {
2158 struct log *msg = log_from_idx(&log_buf, idx);
2160 error += msg_print_text(msg, prev, true, NULL, 0);
2161 idx = log_next(&log_buf, idx);
2165 error -= syslog_partial;
2167 raw_spin_unlock_irq(&log_buf.lock);
2169 /* Size of the log buffer */
2170 case SYSLOG_ACTION_SIZE_BUFFER:
2171 error = log_buf.len;
2181 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
2183 return do_syslog(type, buf, len, SYSLOG_FROM_READER);
2187 * Call the console drivers, asking them to write out
2188 * log_buf[start] to log_buf[end - 1].
2189 * The console_lock must be held.
2191 static void call_console_drivers(int level, const char *text, size_t len)
2193 struct console *con;
2195 trace_console(text, len);
2197 if (level >= console_loglevel && !ignore_loglevel)
2199 if (!console_drivers)
2202 for_each_console(con) {
2203 if (exclusive_console && con != exclusive_console)
2205 if (!(con->flags & CON_ENABLED))
2209 if (!cpu_online(smp_processor_id()) &&
2210 !(con->flags & CON_ANYTIME))
2212 con->write(con, text, len);
2217 * Zap console related locks when oopsing. Only zap at most once
2218 * every 10 seconds, to leave time for slow consoles to print a
2221 static void zap_locks(void)
2223 static unsigned long oops_timestamp;
2225 if (time_after_eq(jiffies, oops_timestamp) &&
2226 !time_after(jiffies, oops_timestamp + 30 * HZ))
2229 oops_timestamp = jiffies;
2232 /* If a crash is occurring, make sure we can't deadlock */
2233 raw_spin_lock_init(&log_buf.lock);
2234 /* And make sure that we print immediately */
2235 sema_init(&console_sem, 1);
2238 /* Check if we have any console registered that can be called early in boot. */
2239 static int have_callable_console(void)
2241 struct console *con;
2243 for_each_console(con)
2244 if (con->flags & CON_ANYTIME)
2251 * Can we actually use the console at this time on this cpu?
2253 * Console drivers may assume that per-cpu resources have
2254 * been allocated. So unless they're explicitly marked as
2255 * being able to cope (CON_ANYTIME) don't call them until
2256 * this CPU is officially up.
2258 static inline int can_use_console(unsigned int cpu)
2260 return cpu_online(cpu) || have_callable_console();
2264 * Try to get console ownership to actually show the kernel
2265 * messages from a 'printk'. Return true (and with the
2266 * console_lock held, and 'console_locked' set) if it
2267 * is successful, false otherwise.
2269 * This gets called with the 'log_buf.lock' spinlock held and
2270 * interrupts disabled. It should return with 'lockbuf_lock'
2271 * released but interrupts still disabled.
2273 static int console_trylock_for_printk(unsigned int cpu)
2274 __releases(&log_buf.lock)
2276 int retval = 0, wake = 0;
2278 if (console_trylock()) {
2282 * If we can't use the console, we need to release
2283 * the console semaphore by hand to avoid flushing
2284 * the buffer. We need to hold the console semaphore
2285 * in order to do this test safely.
2287 if (!can_use_console(cpu)) {
2293 logbuf_cpu = UINT_MAX;
2294 raw_spin_unlock(&log_buf.lock);
2300 int printk_delay_msec __read_mostly;
2302 static inline void printk_delay(void)
2304 if (unlikely(printk_delay_msec)) {
2305 int m = printk_delay_msec;
2309 touch_nmi_watchdog();
2314 asmlinkage int vprintk_emit(int facility, int level,
2315 const char *dict, size_t dictlen,
2316 const char *fmt, va_list args)
2318 static int recursion_bug;
2319 unsigned long flags;
2321 int printed_len = 0;
2323 boot_delay_msec(level);
2326 /* This stops the holder of console_sem just where we want him */
2327 local_irq_save(flags);
2328 this_cpu = smp_processor_id();
2331 * Ouch, printk recursed into itself!
2333 if (unlikely(logbuf_cpu == this_cpu)) {
2335 * If a crash is occurring during printk() on this CPU,
2336 * then try to get the crash message out but make sure
2337 * we can't deadlock. Otherwise just return to avoid the
2338 * recursion and return - but flag the recursion so that
2339 * it can be printed at the next appropriate moment:
2341 if (!oops_in_progress && !lockdep_recursing(current)) {
2343 goto out_restore_irqs;
2349 raw_spin_lock(&log_buf.lock);
2350 logbuf_cpu = this_cpu;
2352 if (recursion_bug) {
2353 static const char recursion_msg[] =
2354 "BUG: recent printk recursion!";
2357 /* emit KERN_CRIT message */
2358 printed_len += log_store(&log_buf, 0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
2359 NULL, 0, recursion_msg, strlen(recursion_msg), this_cpu);
2363 printed_len += log_format_and_store(&log_buf, facility, level, dict, dictlen,
2364 fmt, this_cpu, args);
2367 * Try to acquire and then immediately release the console semaphore.
2368 * The release will print out buffers and wake up /dev/kmsg and syslog()
2371 * The console_trylock_for_printk() function will release 'log_buf.lock'
2372 * regardless of whether it actually gets the console semaphore or not.
2374 if (console_trylock_for_printk(this_cpu))
2379 local_irq_restore(flags);
2383 EXPORT_SYMBOL(vprintk_emit);
2385 asmlinkage int vprintk(const char *fmt, va_list args)
2387 return vprintk_emit(0, -1, NULL, 0, fmt, args);
2389 EXPORT_SYMBOL(vprintk);
2391 asmlinkage int printk_emit(int facility, int level,
2392 const char *dict, size_t dictlen,
2393 const char *fmt, ...)
2398 va_start(args, fmt);
2399 r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
2404 EXPORT_SYMBOL(printk_emit);
2407 * printk - print a kernel message
2408 * @fmt: format string
2410 * This is printk(). It can be called from any context. We want it to work.
2412 * We try to grab the console_lock. If we succeed, it's easy - we log the
2413 * output and call the console drivers. If we fail to get the semaphore, we
2414 * place the output into the log buffer and return. The current holder of
2415 * the console_sem will notice the new output in console_unlock(); and will
2416 * send it to the consoles before releasing the lock.
2418 * One effect of this deferred printing is that code which calls printk() and
2419 * then changes console_loglevel may break. This is because console_loglevel
2420 * is inspected when the actual printing occurs.
2425 * See the vsnprintf() documentation for format string extensions over C99.
2427 asmlinkage int printk(const char *fmt, ...)
2432 #ifdef CONFIG_KGDB_KDB
2433 if (unlikely(kdb_trap_printk)) {
2434 va_start(args, fmt);
2435 r = vkdb_printf(fmt, args);
2440 va_start(args, fmt);
2441 r = vprintk_emit(0, -1, NULL, 0, fmt, args);
2446 EXPORT_SYMBOL(printk);
2448 #else /* CONFIG_PRINTK */
2450 #define LOG_LINE_MAX 0
2451 #define PREFIX_MAX 0
2453 static struct log_buffer log_buf = {
2454 .lock = __RAW_SPIN_LOCK_UNLOCKED(log_buf.lock),
2460 static u64 syslog_seq;
2461 static u32 syslog_idx;
2462 static u64 console_seq;
2463 static u32 console_idx;
2464 static enum log_flags syslog_prev;
2465 static enum log_flags console_prev;
2466 static struct cont {
2472 static struct log *log_from_idx(struct log_buffer *log_b, u32 idx) { return NULL; }
2473 static u32 log_next(struct log_buffer *log_b, u32 idx) { return 0; }
2474 static void call_console_drivers(int level, const char *text, size_t len) {}
2475 static size_t msg_print_text(const struct log *msg, enum log_flags prev,
2476 bool syslog, char *buf, size_t size) { return 0; }
2477 static size_t cont_print_text(char *text, size_t size) { return 0; }
2479 #endif /* CONFIG_PRINTK */
2481 #ifdef CONFIG_EARLY_PRINTK
2482 struct console *early_console;
2484 void early_vprintk(const char *fmt, va_list ap)
2486 if (early_console) {
2488 int n = vscnprintf(buf, sizeof(buf), fmt, ap);
2490 early_console->write(early_console, buf, n);
2494 asmlinkage void early_printk(const char *fmt, ...)
2499 early_vprintk(fmt, ap);
2504 static int __add_preferred_console(char *name, int idx, char *options,
2507 struct console_cmdline *c;
2511 * See if this tty is not yet registered, and
2512 * if we have a slot free.
2514 for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
2515 if (strcmp(console_cmdline[i].name, name) == 0 &&
2516 console_cmdline[i].index == idx) {
2518 selected_console = i;
2521 if (i == MAX_CMDLINECONSOLES)
2524 selected_console = i;
2525 c = &console_cmdline[i];
2526 strlcpy(c->name, name, sizeof(c->name));
2527 c->options = options;
2528 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
2529 c->brl_options = brl_options;
2535 * Set up a list of consoles. Called from init/main.c
2537 static int __init console_setup(char *str)
2539 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
2540 char *s, *options, *brl_options = NULL;
2543 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
2544 if (!memcmp(str, "brl,", 4)) {
2547 } else if (!memcmp(str, "brl=", 4)) {
2548 brl_options = str + 4;
2549 str = strchr(brl_options, ',');
2551 printk(KERN_ERR "need port name after brl=\n");
2559 * Decode str into name, index, options.
2561 if (str[0] >= '0' && str[0] <= '9') {
2562 strcpy(buf, "ttyS");
2563 strncpy(buf + 4, str, sizeof(buf) - 5);
2565 strncpy(buf, str, sizeof(buf) - 1);
2567 buf[sizeof(buf) - 1] = 0;
2568 if ((options = strchr(str, ',')) != NULL)
2571 if (!strcmp(str, "ttya"))
2572 strcpy(buf, "ttyS0");
2573 if (!strcmp(str, "ttyb"))
2574 strcpy(buf, "ttyS1");
2576 for (s = buf; *s; s++)
2577 if ((*s >= '0' && *s <= '9') || *s == ',')
2579 idx = simple_strtoul(s, NULL, 10);
2582 __add_preferred_console(buf, idx, options, brl_options);
2583 console_set_on_cmdline = 1;
2586 __setup("console=", console_setup);
2589 * add_preferred_console - add a device to the list of preferred consoles.
2590 * @name: device name
2591 * @idx: device index
2592 * @options: options for this console
2594 * The last preferred console added will be used for kernel messages
2595 * and stdin/out/err for init. Normally this is used by console_setup
2596 * above to handle user-supplied console arguments; however it can also
2597 * be used by arch-specific code either to override the user or more
2598 * commonly to provide a default console (ie from PROM variables) when
2599 * the user has not supplied one.
2601 int add_preferred_console(char *name, int idx, char *options)
2603 return __add_preferred_console(name, idx, options, NULL);
2606 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
2608 struct console_cmdline *c;
2611 for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
2612 if (strcmp(console_cmdline[i].name, name) == 0 &&
2613 console_cmdline[i].index == idx) {
2614 c = &console_cmdline[i];
2615 strlcpy(c->name, name_new, sizeof(c->name));
2616 c->name[sizeof(c->name) - 1] = 0;
2617 c->options = options;
2625 bool console_suspend_enabled = 1;
2626 EXPORT_SYMBOL(console_suspend_enabled);
2628 static int __init console_suspend_disable(char *str)
2630 console_suspend_enabled = 0;
2633 __setup("no_console_suspend", console_suspend_disable);
2634 module_param_named(console_suspend, console_suspend_enabled,
2635 bool, S_IRUGO | S_IWUSR);
2636 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2637 " and hibernate operations");
2640 * suspend_console - suspend the console subsystem
2642 * This disables printk() while we go into suspend states
2644 void suspend_console(void)
2646 if (!console_suspend_enabled)
2648 printk("Suspending console(s) (use no_console_suspend to debug)\n");
2650 console_suspended = 1;
2654 void resume_console(void)
2656 if (!console_suspend_enabled)
2659 console_suspended = 0;
2664 * console_cpu_notify - print deferred console messages after CPU hotplug
2665 * @self: notifier struct
2666 * @action: CPU hotplug event
2669 * If printk() is called from a CPU that is not online yet, the messages
2670 * will be spooled but will not show up on the console. This function is
2671 * called when a new CPU comes online (or fails to come up), and ensures
2672 * that any such output gets printed.
2674 static int __cpuinit console_cpu_notify(struct notifier_block *self,
2675 unsigned long action, void *hcpu)
2680 case CPU_DOWN_FAILED:
2681 case CPU_UP_CANCELED:
2689 * console_lock - lock the console system for exclusive use.
2691 * Acquires a lock which guarantees that the caller has
2692 * exclusive access to the console system and the console_drivers list.
2694 * Can sleep, returns nothing.
2696 void console_lock(void)
2701 if (console_suspended)
2704 console_may_schedule = 1;
2705 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);
2707 EXPORT_SYMBOL(console_lock);
2710 * console_trylock - try to lock the console system for exclusive use.
2712 * Tried to acquire a lock which guarantees that the caller has
2713 * exclusive access to the console system and the console_drivers list.
2715 * returns 1 on success, and 0 on failure to acquire the lock.
2717 int console_trylock(void)
2719 if (down_trylock(&console_sem))
2721 if (console_suspended) {
2726 console_may_schedule = 0;
2727 mutex_acquire(&console_lock_dep_map, 0, 1, _RET_IP_);
2730 EXPORT_SYMBOL(console_trylock);
2732 int is_console_locked(void)
2734 return console_locked;
2737 static void console_cont_flush(char *text, size_t size)
2739 unsigned long flags;
2742 raw_spin_lock_irqsave(&log_buf.lock, flags);
2748 * We still queue earlier records, likely because the console was
2749 * busy. The earlier ones need to be printed before this one, we
2750 * did not flush any fragment so far, so just let it queue up.
2752 if (console_seq < log_buf.next_seq && !cont.cons)
2755 len = cont_print_text(text, size);
2756 raw_spin_unlock(&log_buf.lock);
2757 stop_critical_timings();
2758 call_console_drivers(cont.level, text, len);
2759 start_critical_timings();
2760 local_irq_restore(flags);
2763 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
2767 * console_unlock - unlock the console system
2769 * Releases the console_lock which the caller holds on the console system
2770 * and the console driver list.
2772 * While the console_lock was held, console output may have been buffered
2773 * by printk(). If this is the case, console_unlock(); emits
2774 * the output prior to releasing the lock.
2776 * If there is output waiting, we wake /dev/kmsg and syslog() users.
2778 * console_unlock(); may be called from any context.
2780 void console_unlock(void)
2782 static char text[LOG_LINE_MAX + PREFIX_MAX];
2783 static u64 seen_seq;
2784 unsigned long flags;
2785 bool wake_klogd = false;
2788 if (console_suspended) {
2793 console_may_schedule = 0;
2795 /* flush buffered message fragment immediately to console */
2796 console_cont_flush(text, sizeof(text));
2803 raw_spin_lock_irqsave(&log_buf.lock, flags);
2804 if (seen_seq != log_buf.next_seq) {
2806 seen_seq = log_buf.next_seq;
2809 if (console_seq < log_buf.first_seq) {
2810 /* messages are gone, move to first one */
2811 console_seq = log_buf.first_seq;
2812 console_idx = log_buf.first_idx;
2816 if (console_seq == log_buf.next_seq)
2819 msg = log_from_idx(&log_buf, console_idx);
2820 if (msg->flags & LOG_NOCONS) {
2822 * Skip record we have buffered and already printed
2823 * directly to the console when we received it.
2825 console_idx = log_next(&log_buf, console_idx);
2828 * We will get here again when we register a new
2829 * CON_PRINTBUFFER console. Clear the flag so we
2830 * will properly dump everything later.
2832 msg->flags &= ~LOG_NOCONS;
2833 console_prev = msg->flags;
2838 len = msg_print_text(msg, console_prev, false,
2839 text, sizeof(text));
2840 console_idx = log_next(&log_buf, console_idx);
2842 console_prev = msg->flags;
2843 raw_spin_unlock(&log_buf.lock);
2845 stop_critical_timings(); /* don't trace print latency */
2846 call_console_drivers(level, text, len);
2847 start_critical_timings();
2848 local_irq_restore(flags);
2851 mutex_release(&console_lock_dep_map, 1, _RET_IP_);
2853 /* Release the exclusive_console once it is used */
2854 if (unlikely(exclusive_console))
2855 exclusive_console = NULL;
2857 raw_spin_unlock(&log_buf.lock);
2862 * Someone could have filled up the buffer again, so re-check if there's
2863 * something to flush. In case we cannot trylock the console_sem again,
2864 * there's a new owner and the console_unlock() from them will do the
2865 * flush, no worries.
2867 raw_spin_lock(&log_buf.lock);
2868 retry = console_seq != log_buf.next_seq;
2869 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
2871 if (retry && console_trylock())
2877 EXPORT_SYMBOL(console_unlock);
2880 * console_conditional_schedule - yield the CPU if required
2882 * If the console code is currently allowed to sleep, and
2883 * if this CPU should yield the CPU to another task, do
2886 * Must be called within console_lock();.
2888 void __sched console_conditional_schedule(void)
2890 if (console_may_schedule)
2893 EXPORT_SYMBOL(console_conditional_schedule);
2895 void console_unblank(void)
2900 * console_unblank can no longer be called in interrupt context unless
2901 * oops_in_progress is set to 1..
2903 if (oops_in_progress) {
2904 if (down_trylock(&console_sem) != 0)
2910 console_may_schedule = 0;
2912 if ((c->flags & CON_ENABLED) && c->unblank)
2918 * Return the console tty driver structure and its associated index
2920 struct tty_driver *console_device(int *index)
2923 struct tty_driver *driver = NULL;
2926 for_each_console(c) {
2929 driver = c->device(c, index);
2938 * Prevent further output on the passed console device so that (for example)
2939 * serial drivers can disable console output before suspending a port, and can
2940 * re-enable output afterwards.
2942 void console_stop(struct console *console)
2945 console->flags &= ~CON_ENABLED;
2948 EXPORT_SYMBOL(console_stop);
2950 void console_start(struct console *console)
2953 console->flags |= CON_ENABLED;
2956 EXPORT_SYMBOL(console_start);
2958 static int __read_mostly keep_bootcon;
2960 static int __init keep_bootcon_setup(char *str)
2963 printk(KERN_INFO "debug: skip boot console de-registration.\n");
2968 early_param("keep_bootcon", keep_bootcon_setup);
2971 * The console driver calls this routine during kernel initialization
2972 * to register the console printing procedure with printk() and to
2973 * print any messages that were printed by the kernel before the
2974 * console driver was initialized.
2976 * This can happen pretty early during the boot process (because of
2977 * early_printk) - sometimes before setup_arch() completes - be careful
2978 * of what kernel features are used - they may not be initialised yet.
2980 * There are two types of consoles - bootconsoles (early_printk) and
2981 * "real" consoles (everything which is not a bootconsole) which are
2982 * handled differently.
2983 * - Any number of bootconsoles can be registered at any time.
2984 * - As soon as a "real" console is registered, all bootconsoles
2985 * will be unregistered automatically.
2986 * - Once a "real" console is registered, any attempt to register a
2987 * bootconsoles will be rejected
2989 void register_console(struct console *newcon)
2992 unsigned long flags;
2993 struct console *bcon = NULL;
2996 * before we register a new CON_BOOT console, make sure we don't
2997 * already have a valid console
2999 if (console_drivers && newcon->flags & CON_BOOT) {
3000 /* find the last or real console */
3001 for_each_console(bcon) {
3002 if (!(bcon->flags & CON_BOOT)) {
3003 printk(KERN_INFO "Too late to register bootconsole %s%d\n",
3004 newcon->name, newcon->index);
3010 if (console_drivers && console_drivers->flags & CON_BOOT)
3011 bcon = console_drivers;
3013 if (preferred_console < 0 || bcon || !console_drivers)
3014 preferred_console = selected_console;
3016 if (newcon->early_setup)
3017 newcon->early_setup();
3020 * See if we want to use this console driver. If we
3021 * didn't select a console we take the first one
3022 * that registers here.
3024 if (preferred_console < 0) {
3025 if (newcon->index < 0)
3027 if (newcon->setup == NULL ||
3028 newcon->setup(newcon, NULL) == 0) {
3029 newcon->flags |= CON_ENABLED;
3030 if (newcon->device) {
3031 newcon->flags |= CON_CONSDEV;
3032 preferred_console = 0;
3038 * See if this console matches one we selected on
3041 for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
3043 if (strcmp(console_cmdline[i].name, newcon->name) != 0)
3045 if (newcon->index >= 0 &&
3046 newcon->index != console_cmdline[i].index)
3048 if (newcon->index < 0)
3049 newcon->index = console_cmdline[i].index;
3050 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
3051 if (console_cmdline[i].brl_options) {
3052 newcon->flags |= CON_BRL;
3053 braille_register_console(newcon,
3054 console_cmdline[i].index,
3055 console_cmdline[i].options,
3056 console_cmdline[i].brl_options);
3060 if (newcon->setup &&
3061 newcon->setup(newcon, console_cmdline[i].options) != 0)
3063 newcon->flags |= CON_ENABLED;
3064 newcon->index = console_cmdline[i].index;
3065 if (i == selected_console) {
3066 newcon->flags |= CON_CONSDEV;
3067 preferred_console = selected_console;
3072 if (!(newcon->flags & CON_ENABLED))
3076 * If we have a bootconsole, and are switching to a real console,
3077 * don't print everything out again, since when the boot console, and
3078 * the real console are the same physical device, it's annoying to
3079 * see the beginning boot messages twice
3081 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
3082 newcon->flags &= ~CON_PRINTBUFFER;
3085 * Put this console in the list - keep the
3086 * preferred driver at the head of the list.
3089 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
3090 newcon->next = console_drivers;
3091 console_drivers = newcon;
3093 newcon->next->flags &= ~CON_CONSDEV;
3095 newcon->next = console_drivers->next;
3096 console_drivers->next = newcon;
3098 if (newcon->flags & CON_PRINTBUFFER) {
3100 * console_unlock(); will print out the buffered messages
3103 raw_spin_lock_irqsave(&log_buf.lock, flags);
3104 console_seq = syslog_seq;
3105 console_idx = syslog_idx;
3106 console_prev = syslog_prev;
3107 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
3109 * We're about to replay the log buffer. Only do this to the
3110 * just-registered console to avoid excessive message spam to
3111 * the already-registered consoles.
3113 exclusive_console = newcon;
3116 console_sysfs_notify();
3119 * By unregistering the bootconsoles after we enable the real console
3120 * we get the "console xxx enabled" message on all the consoles -
3121 * boot consoles, real consoles, etc - this is to ensure that end
3122 * users know there might be something in the kernel's log buffer that
3123 * went to the bootconsole (that they do not see on the real console)
3126 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
3128 /* we need to iterate through twice, to make sure we print
3129 * everything out, before we unregister the console(s)
3131 printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
3132 newcon->name, newcon->index);
3133 for_each_console(bcon)
3134 if (bcon->flags & CON_BOOT)
3135 unregister_console(bcon);
3137 printk(KERN_INFO "%sconsole [%s%d] enabled\n",
3138 (newcon->flags & CON_BOOT) ? "boot" : "" ,
3139 newcon->name, newcon->index);
3142 EXPORT_SYMBOL(register_console);
3144 int unregister_console(struct console *console)
3146 struct console *a, *b;
3149 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
3150 if (console->flags & CON_BRL)
3151 return braille_unregister_console(console);
3155 if (console_drivers == console) {
3156 console_drivers=console->next;
3158 } else if (console_drivers) {
3159 for (a=console_drivers->next, b=console_drivers ;
3160 a; b=a, a=b->next) {
3170 * If this isn't the last console and it has CON_CONSDEV set, we
3171 * need to set it on the next preferred console.
3173 if (console_drivers != NULL && console->flags & CON_CONSDEV)
3174 console_drivers->flags |= CON_CONSDEV;
3177 console_sysfs_notify();
3180 EXPORT_SYMBOL(unregister_console);
3182 static int __init printk_late_init(void)
3184 struct console *con;
3186 for_each_console(con) {
3187 if (!keep_bootcon && con->flags & CON_BOOT) {
3188 printk(KERN_INFO "turn off boot console %s%d\n",
3189 con->name, con->index);
3190 unregister_console(con);
3193 hotcpu_notifier(console_cpu_notify, 0);
3196 late_initcall(printk_late_init);
3198 #if defined CONFIG_PRINTK
3200 * Delayed printk version, for scheduler-internal messages:
3202 #define PRINTK_BUF_SIZE 512
3204 #define PRINTK_PENDING_WAKEUP 0x01
3205 #define PRINTK_PENDING_SCHED 0x02
3207 static DEFINE_PER_CPU(int, printk_pending);
3208 static DEFINE_PER_CPU(char [PRINTK_BUF_SIZE], printk_sched_buf);
3210 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3212 int pending = __this_cpu_xchg(printk_pending, 0);
3214 if (pending & PRINTK_PENDING_SCHED) {
3215 char *buf = __get_cpu_var(printk_sched_buf);
3216 printk(KERN_WARNING "[sched_delayed] %s", buf);
3219 if (pending & PRINTK_PENDING_WAKEUP)
3220 wake_up_interruptible(&log_buf.wait);
3223 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
3224 .func = wake_up_klogd_work_func,
3225 .flags = IRQ_WORK_LAZY,
3228 void wake_up_klogd(void)
3231 if (waitqueue_active(&log_buf.wait)) {
3232 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
3233 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
3238 int printk_deferred(const char *fmt, ...)
3240 unsigned long flags;
3245 local_irq_save(flags);
3246 buf = __get_cpu_var(printk_sched_buf);
3248 va_start(args, fmt);
3249 r = vsnprintf(buf, PRINTK_BUF_SIZE, fmt, args);
3252 __this_cpu_or(printk_pending, PRINTK_PENDING_SCHED);
3253 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
3254 local_irq_restore(flags);
3260 * printk rate limiting, lifted from the networking subsystem.
3262 * This enforces a rate limit: not more than 10 kernel messages
3263 * every 5s to make a denial-of-service attack impossible.
3265 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3267 int __printk_ratelimit(const char *func)
3269 return ___ratelimit(&printk_ratelimit_state, func);
3271 EXPORT_SYMBOL(__printk_ratelimit);
3274 * printk_timed_ratelimit - caller-controlled printk ratelimiting
3275 * @caller_jiffies: pointer to caller's state
3276 * @interval_msecs: minimum interval between prints
3278 * printk_timed_ratelimit() returns true if more than @interval_msecs
3279 * milliseconds have elapsed since the last time printk_timed_ratelimit()
3282 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
3283 unsigned int interval_msecs)
3285 if (*caller_jiffies == 0
3286 || !time_in_range(jiffies, *caller_jiffies,
3288 + msecs_to_jiffies(interval_msecs))) {
3289 *caller_jiffies = jiffies;
3294 EXPORT_SYMBOL(printk_timed_ratelimit);
3296 static DEFINE_SPINLOCK(dump_list_lock);
3297 static LIST_HEAD(dump_list);
3300 * kmsg_dump_register - register a kernel log dumper.
3301 * @dumper: pointer to the kmsg_dumper structure
3303 * Adds a kernel log dumper to the system. The dump callback in the
3304 * structure will be called when the kernel oopses or panics and must be
3305 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
3307 int kmsg_dump_register(struct kmsg_dumper *dumper)
3309 unsigned long flags;
3312 /* The dump callback needs to be set */
3316 spin_lock_irqsave(&dump_list_lock, flags);
3317 /* Don't allow registering multiple times */
3318 if (!dumper->registered) {
3319 dumper->registered = 1;
3320 list_add_tail_rcu(&dumper->list, &dump_list);
3323 spin_unlock_irqrestore(&dump_list_lock, flags);
3327 EXPORT_SYMBOL_GPL(kmsg_dump_register);
3330 * kmsg_dump_unregister - unregister a kmsg dumper.
3331 * @dumper: pointer to the kmsg_dumper structure
3333 * Removes a dump device from the system. Returns zero on success and
3334 * %-EINVAL otherwise.
3336 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
3338 unsigned long flags;
3341 spin_lock_irqsave(&dump_list_lock, flags);
3342 if (dumper->registered) {
3343 dumper->registered = 0;
3344 list_del_rcu(&dumper->list);
3347 spin_unlock_irqrestore(&dump_list_lock, flags);
3352 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
3354 static bool always_kmsg_dump;
3355 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
3358 * kmsg_dump - dump kernel log to kernel message dumpers.
3359 * @reason: the reason (oops, panic etc) for dumping
3361 * Call each of the registered dumper's dump() callback, which can
3362 * retrieve the kmsg records with kmsg_dump_get_line() or
3363 * kmsg_dump_get_buffer().
3365 void kmsg_dump(enum kmsg_dump_reason reason)
3367 struct kmsg_dumper *dumper;
3368 unsigned long flags;
3370 if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
3374 list_for_each_entry_rcu(dumper, &dump_list, list) {
3375 if (dumper->max_reason && reason > dumper->max_reason)
3378 /* initialize iterator with data about the stored records */
3379 dumper->active = true;
3381 raw_spin_lock_irqsave(&log_buf.lock, flags);
3382 dumper->cur_seq = log_buf.clear_seq;
3383 dumper->cur_idx = log_buf.clear_idx;
3384 dumper->next_seq = log_buf.next_seq;
3385 dumper->next_idx = log_buf.next_idx;
3386 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
3388 /* invoke dumper which will iterate over records */
3389 dumper->dump(dumper, reason);
3391 /* reset iterator */
3392 dumper->active = false;
3398 * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
3399 * @dumper: registered kmsg dumper
3400 * @syslog: include the "<4>" prefixes
3401 * @line: buffer to copy the line to
3402 * @size: maximum size of the buffer
3403 * @len: length of line placed into buffer
3405 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3406 * record, and copy one record into the provided buffer.
3408 * Consecutive calls will return the next available record moving
3409 * towards the end of the buffer with the youngest messages.
3411 * A return value of FALSE indicates that there are no more records to
3414 * The function is similar to kmsg_dump_get_line(), but grabs no locks.
3416 bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
3417 char *line, size_t size, size_t *len)
3423 if (!dumper->active)
3426 if (dumper->cur_seq < log_buf.first_seq) {
3427 /* messages are gone, move to first available one */
3428 dumper->cur_seq = log_buf.first_seq;
3429 dumper->cur_idx = log_buf.first_idx;
3433 if (dumper->cur_seq >= log_buf.next_seq)
3436 msg = log_from_idx(&log_buf, dumper->cur_idx);
3437 l = msg_print_text(msg, 0, syslog, line, size);
3439 dumper->cur_idx = log_next(&log_buf, dumper->cur_idx);
3449 * kmsg_dump_get_line - retrieve one kmsg log line
3450 * @dumper: registered kmsg dumper
3451 * @syslog: include the "<4>" prefixes
3452 * @line: buffer to copy the line to
3453 * @size: maximum size of the buffer
3454 * @len: length of line placed into buffer
3456 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3457 * record, and copy one record into the provided buffer.
3459 * Consecutive calls will return the next available record moving
3460 * towards the end of the buffer with the youngest messages.
3462 * A return value of FALSE indicates that there are no more records to
3465 bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
3466 char *line, size_t size, size_t *len)
3468 unsigned long flags;
3471 raw_spin_lock_irqsave(&log_buf.lock, flags);
3472 ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
3473 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
3477 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
3480 * kmsg_dump_get_buffer - copy kmsg log lines
3481 * @dumper: registered kmsg dumper
3482 * @syslog: include the "<4>" prefixes
3483 * @buf: buffer to copy the line to
3484 * @size: maximum size of the buffer
3485 * @len: length of line placed into buffer
3487 * Start at the end of the kmsg buffer and fill the provided buffer
3488 * with as many of the the *youngest* kmsg records that fit into it.
3489 * If the buffer is large enough, all available kmsg records will be
3490 * copied with a single call.
3492 * Consecutive calls will fill the buffer with the next block of
3493 * available older records, not including the earlier retrieved ones.
3495 * A return value of FALSE indicates that there are no more records to
3498 bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
3499 char *buf, size_t size, size_t *len)
3501 unsigned long flags;
3506 enum log_flags prev;
3510 if (!dumper->active)
3513 raw_spin_lock_irqsave(&log_buf.lock, flags);
3514 if (dumper->cur_seq < log_buf.first_seq) {
3515 /* messages are gone, move to first available one */
3516 dumper->cur_seq = log_buf.first_seq;
3517 dumper->cur_idx = log_buf.first_idx;
3521 if (dumper->cur_seq >= dumper->next_seq) {
3522 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
3526 /* calculate length of entire buffer */
3527 seq = dumper->cur_seq;
3528 idx = dumper->cur_idx;
3530 while (seq < dumper->next_seq) {
3531 struct log *msg = log_from_idx(&log_buf, idx);
3533 l += msg_print_text(msg, prev, true, NULL, 0);
3534 idx = log_next(&log_buf, idx);
3539 /* move first record forward until length fits into the buffer */
3540 seq = dumper->cur_seq;
3541 idx = dumper->cur_idx;
3543 while (l > size && seq < dumper->next_seq) {
3544 struct log *msg = log_from_idx(&log_buf, idx);
3546 l -= msg_print_text(msg, prev, true, NULL, 0);
3547 idx = log_next(&log_buf, idx);
3552 /* last message in next interation */
3558 while (seq < dumper->next_seq) {
3559 struct log *msg = log_from_idx(&log_buf, idx);
3561 l += msg_print_text(msg, prev, syslog, buf + l, size - l);
3562 idx = log_next(&log_buf, idx);
3567 dumper->next_seq = next_seq;
3568 dumper->next_idx = next_idx;
3570 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
3576 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
3579 * kmsg_dump_rewind_nolock - reset the interator (unlocked version)
3580 * @dumper: registered kmsg dumper
3582 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3583 * kmsg_dump_get_buffer() can be called again and used multiple
3584 * times within the same dumper.dump() callback.
3586 * The function is similar to kmsg_dump_rewind(), but grabs no locks.
3588 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
3590 dumper->cur_seq = log_buf.clear_seq;
3591 dumper->cur_idx = log_buf.clear_idx;
3592 dumper->next_seq = log_buf.next_seq;
3593 dumper->next_idx = log_buf.next_idx;
3597 * kmsg_dump_rewind - reset the interator
3598 * @dumper: registered kmsg dumper
3600 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3601 * kmsg_dump_get_buffer() can be called again and used multiple
3602 * times within the same dumper.dump() callback.
3604 void kmsg_dump_rewind(struct kmsg_dumper *dumper)
3606 unsigned long flags;
3608 raw_spin_lock_irqsave(&log_buf.lock, flags);
3609 kmsg_dump_rewind_nolock(dumper);
3610 raw_spin_unlock_irqrestore(&log_buf.lock, flags);
3612 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
3614 static char dump_stack_arch_desc_str[128];
3617 * dump_stack_set_arch_desc - set arch-specific str to show with task dumps
3618 * @fmt: printf-style format string
3619 * @...: arguments for the format string
3621 * The configured string will be printed right after utsname during task
3622 * dumps. Usually used to add arch-specific system identifiers. If an
3623 * arch wants to make use of such an ID string, it should initialize this
3624 * as soon as possible during boot.
3626 void __init dump_stack_set_arch_desc(const char *fmt, ...)
3630 va_start(args, fmt);
3631 vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
3637 * dump_stack_print_info - print generic debug info for dump_stack()
3638 * @log_lvl: log level
3640 * Arch-specific dump_stack() implementations can use this function to
3641 * print out the same debug information as the generic dump_stack().
3643 void dump_stack_print_info(const char *log_lvl)
3645 printk("%sCPU: %d PID: %d Comm: %.20s %s %s %.*s\n",
3646 log_lvl, raw_smp_processor_id(), current->pid, current->comm,
3647 print_tainted(), init_utsname()->release,
3648 (int)strcspn(init_utsname()->version, " "),
3649 init_utsname()->version);
3651 if (dump_stack_arch_desc_str[0] != '\0')
3652 printk("%sHardware name: %s\n",
3653 log_lvl, dump_stack_arch_desc_str);
3655 print_worker_info(log_lvl, current);
3659 * show_regs_print_info - print generic debug info for show_regs()
3660 * @log_lvl: log level
3662 * show_regs() implementations can use this function to print out generic
3663 * debug information.
3665 void show_regs_print_info(const char *log_lvl)
3667 dump_stack_print_info(log_lvl);
3669 printk("%stask: %p ti: %p task.ti: %p\n",
3670 log_lvl, current, current_thread_info(),
3671 task_thread_info(current));