fs/seq_file.c:seq_lseek(): fix switch statement indenting
[linux/fpc-iii.git] / kernel / printk.c
blob0b31715f335a7a8ba1a846fe3b93fe71d97cd8d7
1 /*
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).
11 * Ted Ts'o, 2/11/93.
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>
20 #include <linux/mm.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/syscalls.h>
36 #include <linux/kexec.h>
37 #include <linux/kdb.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/notifier.h>
43 #include <linux/rculist.h>
44 #include <linux/poll.h>
45 #include <linux/irq_work.h>
47 #include <asm/uaccess.h>
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/printk.h>
53 * Architectures can override it:
55 void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
59 /* printk's without a loglevel use this.. */
60 #define DEFAULT_MESSAGE_LOGLEVEL CONFIG_DEFAULT_MESSAGE_LOGLEVEL
62 /* We show everything that is MORE important than this.. */
63 #define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
64 #define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
66 DECLARE_WAIT_QUEUE_HEAD(log_wait);
68 int console_printk[4] = {
69 DEFAULT_CONSOLE_LOGLEVEL, /* console_loglevel */
70 DEFAULT_MESSAGE_LOGLEVEL, /* default_message_loglevel */
71 MINIMUM_CONSOLE_LOGLEVEL, /* minimum_console_loglevel */
72 DEFAULT_CONSOLE_LOGLEVEL, /* default_console_loglevel */
76 * Low level drivers may need that to know if they can schedule in
77 * their unblank() callback or not. So let's export it.
79 int oops_in_progress;
80 EXPORT_SYMBOL(oops_in_progress);
83 * console_sem protects the console_drivers list, and also
84 * provides serialisation for access to the entire console
85 * driver system.
87 static DEFINE_SEMAPHORE(console_sem);
88 struct console *console_drivers;
89 EXPORT_SYMBOL_GPL(console_drivers);
91 #ifdef CONFIG_LOCKDEP
92 static struct lockdep_map console_lock_dep_map = {
93 .name = "console_lock"
95 #endif
98 * This is used for debugging the mess that is the VT code by
99 * keeping track if we have the console semaphore held. It's
100 * definitely not the perfect debug tool (we don't know if _WE_
101 * hold it are racing, but it helps tracking those weird code
102 * path in the console code where we end up in places I want
103 * locked without the console sempahore held
105 static int console_locked, console_suspended;
108 * If exclusive_console is non-NULL then only this console is to be printed to.
110 static struct console *exclusive_console;
113 * Array of consoles built from command line options (console=)
115 struct console_cmdline
117 char name[8]; /* Name of the driver */
118 int index; /* Minor dev. to use */
119 char *options; /* Options for the driver */
120 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
121 char *brl_options; /* Options for braille driver */
122 #endif
125 #define MAX_CMDLINECONSOLES 8
127 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
128 static int selected_console = -1;
129 static int preferred_console = -1;
130 int console_set_on_cmdline;
131 EXPORT_SYMBOL(console_set_on_cmdline);
133 /* Flag: console code may call schedule() */
134 static int console_may_schedule;
137 * The printk log buffer consists of a chain of concatenated variable
138 * length records. Every record starts with a record header, containing
139 * the overall length of the record.
141 * The heads to the first and last entry in the buffer, as well as the
142 * sequence numbers of these both entries are maintained when messages
143 * are stored..
145 * If the heads indicate available messages, the length in the header
146 * tells the start next message. A length == 0 for the next message
147 * indicates a wrap-around to the beginning of the buffer.
149 * Every record carries the monotonic timestamp in microseconds, as well as
150 * the standard userspace syslog level and syslog facility. The usual
151 * kernel messages use LOG_KERN; userspace-injected messages always carry
152 * a matching syslog facility, by default LOG_USER. The origin of every
153 * message can be reliably determined that way.
155 * The human readable log message directly follows the message header. The
156 * length of the message text is stored in the header, the stored message
157 * is not terminated.
159 * Optionally, a message can carry a dictionary of properties (key/value pairs),
160 * to provide userspace with a machine-readable message context.
162 * Examples for well-defined, commonly used property names are:
163 * DEVICE=b12:8 device identifier
164 * b12:8 block dev_t
165 * c127:3 char dev_t
166 * n8 netdev ifindex
167 * +sound:card0 subsystem:devname
168 * SUBSYSTEM=pci driver-core subsystem name
170 * Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
171 * follows directly after a '=' character. Every property is terminated by
172 * a '\0' character. The last property is not terminated.
174 * Example of a message structure:
175 * 0000 ff 8f 00 00 00 00 00 00 monotonic time in nsec
176 * 0008 34 00 record is 52 bytes long
177 * 000a 0b 00 text is 11 bytes long
178 * 000c 1f 00 dictionary is 23 bytes long
179 * 000e 03 00 LOG_KERN (facility) LOG_ERR (level)
180 * 0010 69 74 27 73 20 61 20 6c "it's a l"
181 * 69 6e 65 "ine"
182 * 001b 44 45 56 49 43 "DEVIC"
183 * 45 3d 62 38 3a 32 00 44 "E=b8:2\0D"
184 * 52 49 56 45 52 3d 62 75 "RIVER=bu"
185 * 67 "g"
186 * 0032 00 00 00 padding to next message header
188 * The 'struct log' buffer header must never be directly exported to
189 * userspace, it is a kernel-private implementation detail that might
190 * need to be changed in the future, when the requirements change.
192 * /dev/kmsg exports the structured data in the following line format:
193 * "level,sequnum,timestamp;<message text>\n"
195 * The optional key/value pairs are attached as continuation lines starting
196 * with a space character and terminated by a newline. All possible
197 * non-prinatable characters are escaped in the "\xff" notation.
199 * Users of the export format should ignore possible additional values
200 * separated by ',', and find the message after the ';' character.
203 enum log_flags {
204 LOG_NOCONS = 1, /* already flushed, do not print to console */
205 LOG_NEWLINE = 2, /* text ended with a newline */
206 LOG_PREFIX = 4, /* text started with a prefix */
207 LOG_CONT = 8, /* text is a fragment of a continuation line */
210 struct log {
211 u64 ts_nsec; /* timestamp in nanoseconds */
212 u16 len; /* length of entire record */
213 u16 text_len; /* length of text buffer */
214 u16 dict_len; /* length of dictionary buffer */
215 u8 facility; /* syslog facility */
216 u8 flags:5; /* internal record flags */
217 u8 level:3; /* syslog level */
221 * The logbuf_lock protects kmsg buffer, indices, counters. It is also
222 * used in interesting ways to provide interlocking in console_unlock();
224 static DEFINE_RAW_SPINLOCK(logbuf_lock);
226 #ifdef CONFIG_PRINTK
227 /* the next printk record to read by syslog(READ) or /proc/kmsg */
228 static u64 syslog_seq;
229 static u32 syslog_idx;
230 static enum log_flags syslog_prev;
231 static size_t syslog_partial;
233 /* index and sequence number of the first record stored in the buffer */
234 static u64 log_first_seq;
235 static u32 log_first_idx;
237 /* index and sequence number of the next record to store in the buffer */
238 static u64 log_next_seq;
239 static u32 log_next_idx;
241 /* the next printk record to write to the console */
242 static u64 console_seq;
243 static u32 console_idx;
244 static enum log_flags console_prev;
246 /* the next printk record to read after the last 'clear' command */
247 static u64 clear_seq;
248 static u32 clear_idx;
250 #define PREFIX_MAX 32
251 #define LOG_LINE_MAX 1024 - PREFIX_MAX
253 /* record buffer */
254 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
255 #define LOG_ALIGN 4
256 #else
257 #define LOG_ALIGN __alignof__(struct log)
258 #endif
259 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
260 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
261 static char *log_buf = __log_buf;
262 static u32 log_buf_len = __LOG_BUF_LEN;
264 /* cpu currently holding logbuf_lock */
265 static volatile unsigned int logbuf_cpu = UINT_MAX;
267 /* human readable text of the record */
268 static char *log_text(const struct log *msg)
270 return (char *)msg + sizeof(struct log);
273 /* optional key/value pair dictionary attached to the record */
274 static char *log_dict(const struct log *msg)
276 return (char *)msg + sizeof(struct log) + msg->text_len;
279 /* get record by index; idx must point to valid msg */
280 static struct log *log_from_idx(u32 idx)
282 struct log *msg = (struct log *)(log_buf + idx);
285 * A length == 0 record is the end of buffer marker. Wrap around and
286 * read the message at the start of the buffer.
288 if (!msg->len)
289 return (struct log *)log_buf;
290 return msg;
293 /* get next record; idx must point to valid msg */
294 static u32 log_next(u32 idx)
296 struct log *msg = (struct log *)(log_buf + idx);
298 /* length == 0 indicates the end of the buffer; wrap */
300 * A length == 0 record is the end of buffer marker. Wrap around and
301 * read the message at the start of the buffer as *this* one, and
302 * return the one after that.
304 if (!msg->len) {
305 msg = (struct log *)log_buf;
306 return msg->len;
308 return idx + msg->len;
311 /* insert record into the buffer, discard old ones, update heads */
312 static void log_store(int facility, int level,
313 enum log_flags flags, u64 ts_nsec,
314 const char *dict, u16 dict_len,
315 const char *text, u16 text_len)
317 struct log *msg;
318 u32 size, pad_len;
320 /* number of '\0' padding bytes to next message */
321 size = sizeof(struct log) + text_len + dict_len;
322 pad_len = (-size) & (LOG_ALIGN - 1);
323 size += pad_len;
325 while (log_first_seq < log_next_seq) {
326 u32 free;
328 if (log_next_idx > log_first_idx)
329 free = max(log_buf_len - log_next_idx, log_first_idx);
330 else
331 free = log_first_idx - log_next_idx;
333 if (free > size + sizeof(struct log))
334 break;
336 /* drop old messages until we have enough contiuous space */
337 log_first_idx = log_next(log_first_idx);
338 log_first_seq++;
341 if (log_next_idx + size + sizeof(struct log) >= log_buf_len) {
343 * This message + an additional empty header does not fit
344 * at the end of the buffer. Add an empty header with len == 0
345 * to signify a wrap around.
347 memset(log_buf + log_next_idx, 0, sizeof(struct log));
348 log_next_idx = 0;
351 /* fill message */
352 msg = (struct log *)(log_buf + log_next_idx);
353 memcpy(log_text(msg), text, text_len);
354 msg->text_len = text_len;
355 memcpy(log_dict(msg), dict, dict_len);
356 msg->dict_len = dict_len;
357 msg->facility = facility;
358 msg->level = level & 7;
359 msg->flags = flags & 0x1f;
360 if (ts_nsec > 0)
361 msg->ts_nsec = ts_nsec;
362 else
363 msg->ts_nsec = local_clock();
364 memset(log_dict(msg) + dict_len, 0, pad_len);
365 msg->len = sizeof(struct log) + text_len + dict_len + pad_len;
367 /* insert message */
368 log_next_idx += msg->len;
369 log_next_seq++;
372 /* /dev/kmsg - userspace message inject/listen interface */
373 struct devkmsg_user {
374 u64 seq;
375 u32 idx;
376 enum log_flags prev;
377 struct mutex lock;
378 char buf[8192];
381 static ssize_t devkmsg_writev(struct kiocb *iocb, const struct iovec *iv,
382 unsigned long count, loff_t pos)
384 char *buf, *line;
385 int i;
386 int level = default_message_loglevel;
387 int facility = 1; /* LOG_USER */
388 size_t len = iov_length(iv, count);
389 ssize_t ret = len;
391 if (len > LOG_LINE_MAX)
392 return -EINVAL;
393 buf = kmalloc(len+1, GFP_KERNEL);
394 if (buf == NULL)
395 return -ENOMEM;
397 line = buf;
398 for (i = 0; i < count; i++) {
399 if (copy_from_user(line, iv[i].iov_base, iv[i].iov_len)) {
400 ret = -EFAULT;
401 goto out;
403 line += iv[i].iov_len;
407 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
408 * the decimal value represents 32bit, the lower 3 bit are the log
409 * level, the rest are the log facility.
411 * If no prefix or no userspace facility is specified, we
412 * enforce LOG_USER, to be able to reliably distinguish
413 * kernel-generated messages from userspace-injected ones.
415 line = buf;
416 if (line[0] == '<') {
417 char *endp = NULL;
419 i = simple_strtoul(line+1, &endp, 10);
420 if (endp && endp[0] == '>') {
421 level = i & 7;
422 if (i >> 3)
423 facility = i >> 3;
424 endp++;
425 len -= endp - line;
426 line = endp;
429 line[len] = '\0';
431 printk_emit(facility, level, NULL, 0, "%s", line);
432 out:
433 kfree(buf);
434 return ret;
437 static ssize_t devkmsg_read(struct file *file, char __user *buf,
438 size_t count, loff_t *ppos)
440 struct devkmsg_user *user = file->private_data;
441 struct log *msg;
442 u64 ts_usec;
443 size_t i;
444 char cont = '-';
445 size_t len;
446 ssize_t ret;
448 if (!user)
449 return -EBADF;
451 ret = mutex_lock_interruptible(&user->lock);
452 if (ret)
453 return ret;
454 raw_spin_lock_irq(&logbuf_lock);
455 while (user->seq == log_next_seq) {
456 if (file->f_flags & O_NONBLOCK) {
457 ret = -EAGAIN;
458 raw_spin_unlock_irq(&logbuf_lock);
459 goto out;
462 raw_spin_unlock_irq(&logbuf_lock);
463 ret = wait_event_interruptible(log_wait,
464 user->seq != log_next_seq);
465 if (ret)
466 goto out;
467 raw_spin_lock_irq(&logbuf_lock);
470 if (user->seq < log_first_seq) {
471 /* our last seen message is gone, return error and reset */
472 user->idx = log_first_idx;
473 user->seq = log_first_seq;
474 ret = -EPIPE;
475 raw_spin_unlock_irq(&logbuf_lock);
476 goto out;
479 msg = log_from_idx(user->idx);
480 ts_usec = msg->ts_nsec;
481 do_div(ts_usec, 1000);
484 * If we couldn't merge continuation line fragments during the print,
485 * export the stored flags to allow an optional external merge of the
486 * records. Merging the records isn't always neccessarily correct, like
487 * when we hit a race during printing. In most cases though, it produces
488 * better readable output. 'c' in the record flags mark the first
489 * fragment of a line, '+' the following.
491 if (msg->flags & LOG_CONT && !(user->prev & LOG_CONT))
492 cont = 'c';
493 else if ((msg->flags & LOG_CONT) ||
494 ((user->prev & LOG_CONT) && !(msg->flags & LOG_PREFIX)))
495 cont = '+';
497 len = sprintf(user->buf, "%u,%llu,%llu,%c;",
498 (msg->facility << 3) | msg->level,
499 user->seq, ts_usec, cont);
500 user->prev = msg->flags;
502 /* escape non-printable characters */
503 for (i = 0; i < msg->text_len; i++) {
504 unsigned char c = log_text(msg)[i];
506 if (c < ' ' || c >= 127 || c == '\\')
507 len += sprintf(user->buf + len, "\\x%02x", c);
508 else
509 user->buf[len++] = c;
511 user->buf[len++] = '\n';
513 if (msg->dict_len) {
514 bool line = true;
516 for (i = 0; i < msg->dict_len; i++) {
517 unsigned char c = log_dict(msg)[i];
519 if (line) {
520 user->buf[len++] = ' ';
521 line = false;
524 if (c == '\0') {
525 user->buf[len++] = '\n';
526 line = true;
527 continue;
530 if (c < ' ' || c >= 127 || c == '\\') {
531 len += sprintf(user->buf + len, "\\x%02x", c);
532 continue;
535 user->buf[len++] = c;
537 user->buf[len++] = '\n';
540 user->idx = log_next(user->idx);
541 user->seq++;
542 raw_spin_unlock_irq(&logbuf_lock);
544 if (len > count) {
545 ret = -EINVAL;
546 goto out;
549 if (copy_to_user(buf, user->buf, len)) {
550 ret = -EFAULT;
551 goto out;
553 ret = len;
554 out:
555 mutex_unlock(&user->lock);
556 return ret;
559 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
561 struct devkmsg_user *user = file->private_data;
562 loff_t ret = 0;
564 if (!user)
565 return -EBADF;
566 if (offset)
567 return -ESPIPE;
569 raw_spin_lock_irq(&logbuf_lock);
570 switch (whence) {
571 case SEEK_SET:
572 /* the first record */
573 user->idx = log_first_idx;
574 user->seq = log_first_seq;
575 break;
576 case SEEK_DATA:
578 * The first record after the last SYSLOG_ACTION_CLEAR,
579 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
580 * changes no global state, and does not clear anything.
582 user->idx = clear_idx;
583 user->seq = clear_seq;
584 break;
585 case SEEK_END:
586 /* after the last record */
587 user->idx = log_next_idx;
588 user->seq = log_next_seq;
589 break;
590 default:
591 ret = -EINVAL;
593 raw_spin_unlock_irq(&logbuf_lock);
594 return ret;
597 static unsigned int devkmsg_poll(struct file *file, poll_table *wait)
599 struct devkmsg_user *user = file->private_data;
600 int ret = 0;
602 if (!user)
603 return POLLERR|POLLNVAL;
605 poll_wait(file, &log_wait, wait);
607 raw_spin_lock_irq(&logbuf_lock);
608 if (user->seq < log_next_seq) {
609 /* return error when data has vanished underneath us */
610 if (user->seq < log_first_seq)
611 ret = POLLIN|POLLRDNORM|POLLERR|POLLPRI;
612 ret = POLLIN|POLLRDNORM;
614 raw_spin_unlock_irq(&logbuf_lock);
616 return ret;
619 static int devkmsg_open(struct inode *inode, struct file *file)
621 struct devkmsg_user *user;
622 int err;
624 /* write-only does not need any file context */
625 if ((file->f_flags & O_ACCMODE) == O_WRONLY)
626 return 0;
628 err = security_syslog(SYSLOG_ACTION_READ_ALL);
629 if (err)
630 return err;
632 user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
633 if (!user)
634 return -ENOMEM;
636 mutex_init(&user->lock);
638 raw_spin_lock_irq(&logbuf_lock);
639 user->idx = log_first_idx;
640 user->seq = log_first_seq;
641 raw_spin_unlock_irq(&logbuf_lock);
643 file->private_data = user;
644 return 0;
647 static int devkmsg_release(struct inode *inode, struct file *file)
649 struct devkmsg_user *user = file->private_data;
651 if (!user)
652 return 0;
654 mutex_destroy(&user->lock);
655 kfree(user);
656 return 0;
659 const struct file_operations kmsg_fops = {
660 .open = devkmsg_open,
661 .read = devkmsg_read,
662 .aio_write = devkmsg_writev,
663 .llseek = devkmsg_llseek,
664 .poll = devkmsg_poll,
665 .release = devkmsg_release,
668 #ifdef CONFIG_KEXEC
670 * This appends the listed symbols to /proc/vmcoreinfo
672 * /proc/vmcoreinfo is used by various utiilties, like crash and makedumpfile to
673 * obtain access to symbols that are otherwise very difficult to locate. These
674 * symbols are specifically used so that utilities can access and extract the
675 * dmesg log from a vmcore file after a crash.
677 void log_buf_kexec_setup(void)
679 VMCOREINFO_SYMBOL(log_buf);
680 VMCOREINFO_SYMBOL(log_buf_len);
681 VMCOREINFO_SYMBOL(log_first_idx);
682 VMCOREINFO_SYMBOL(log_next_idx);
684 * Export struct log size and field offsets. User space tools can
685 * parse it and detect any changes to structure down the line.
687 VMCOREINFO_STRUCT_SIZE(log);
688 VMCOREINFO_OFFSET(log, ts_nsec);
689 VMCOREINFO_OFFSET(log, len);
690 VMCOREINFO_OFFSET(log, text_len);
691 VMCOREINFO_OFFSET(log, dict_len);
693 #endif
695 /* requested log_buf_len from kernel cmdline */
696 static unsigned long __initdata new_log_buf_len;
698 /* save requested log_buf_len since it's too early to process it */
699 static int __init log_buf_len_setup(char *str)
701 unsigned size = memparse(str, &str);
703 if (size)
704 size = roundup_pow_of_two(size);
705 if (size > log_buf_len)
706 new_log_buf_len = size;
708 return 0;
710 early_param("log_buf_len", log_buf_len_setup);
712 void __init setup_log_buf(int early)
714 unsigned long flags;
715 char *new_log_buf;
716 int free;
718 if (!new_log_buf_len)
719 return;
721 if (early) {
722 unsigned long mem;
724 mem = memblock_alloc(new_log_buf_len, PAGE_SIZE);
725 if (!mem)
726 return;
727 new_log_buf = __va(mem);
728 } else {
729 new_log_buf = alloc_bootmem_nopanic(new_log_buf_len);
732 if (unlikely(!new_log_buf)) {
733 pr_err("log_buf_len: %ld bytes not available\n",
734 new_log_buf_len);
735 return;
738 raw_spin_lock_irqsave(&logbuf_lock, flags);
739 log_buf_len = new_log_buf_len;
740 log_buf = new_log_buf;
741 new_log_buf_len = 0;
742 free = __LOG_BUF_LEN - log_next_idx;
743 memcpy(log_buf, __log_buf, __LOG_BUF_LEN);
744 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
746 pr_info("log_buf_len: %d\n", log_buf_len);
747 pr_info("early log buf free: %d(%d%%)\n",
748 free, (free * 100) / __LOG_BUF_LEN);
751 static bool __read_mostly ignore_loglevel;
753 static int __init ignore_loglevel_setup(char *str)
755 ignore_loglevel = 1;
756 printk(KERN_INFO "debug: ignoring loglevel setting.\n");
758 return 0;
761 early_param("ignore_loglevel", ignore_loglevel_setup);
762 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
763 MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
764 "print all kernel messages to the console.");
766 #ifdef CONFIG_BOOT_PRINTK_DELAY
768 static int boot_delay; /* msecs delay after each printk during bootup */
769 static unsigned long long loops_per_msec; /* based on boot_delay */
771 static int __init boot_delay_setup(char *str)
773 unsigned long lpj;
775 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
776 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
778 get_option(&str, &boot_delay);
779 if (boot_delay > 10 * 1000)
780 boot_delay = 0;
782 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
783 "HZ: %d, loops_per_msec: %llu\n",
784 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
785 return 1;
787 __setup("boot_delay=", boot_delay_setup);
789 static void boot_delay_msec(int level)
791 unsigned long long k;
792 unsigned long timeout;
794 if ((boot_delay == 0 || system_state != SYSTEM_BOOTING)
795 || (level >= console_loglevel && !ignore_loglevel)) {
796 return;
799 k = (unsigned long long)loops_per_msec * boot_delay;
801 timeout = jiffies + msecs_to_jiffies(boot_delay);
802 while (k) {
803 k--;
804 cpu_relax();
806 * use (volatile) jiffies to prevent
807 * compiler reduction; loop termination via jiffies
808 * is secondary and may or may not happen.
810 if (time_after(jiffies, timeout))
811 break;
812 touch_nmi_watchdog();
815 #else
816 static inline void boot_delay_msec(int level)
819 #endif
821 #ifdef CONFIG_SECURITY_DMESG_RESTRICT
822 int dmesg_restrict = 1;
823 #else
824 int dmesg_restrict;
825 #endif
827 static int syslog_action_restricted(int type)
829 if (dmesg_restrict)
830 return 1;
831 /* Unless restricted, we allow "read all" and "get buffer size" for everybody */
832 return type != SYSLOG_ACTION_READ_ALL && type != SYSLOG_ACTION_SIZE_BUFFER;
835 static int check_syslog_permissions(int type, bool from_file)
838 * If this is from /proc/kmsg and we've already opened it, then we've
839 * already done the capabilities checks at open time.
841 if (from_file && type != SYSLOG_ACTION_OPEN)
842 return 0;
844 if (syslog_action_restricted(type)) {
845 if (capable(CAP_SYSLOG))
846 return 0;
847 /* For historical reasons, accept CAP_SYS_ADMIN too, with a warning */
848 if (capable(CAP_SYS_ADMIN)) {
849 printk_once(KERN_WARNING "%s (%d): "
850 "Attempt to access syslog with CAP_SYS_ADMIN "
851 "but no CAP_SYSLOG (deprecated).\n",
852 current->comm, task_pid_nr(current));
853 return 0;
855 return -EPERM;
857 return 0;
860 #if defined(CONFIG_PRINTK_TIME)
861 static bool printk_time = 1;
862 #else
863 static bool printk_time;
864 #endif
865 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
867 static size_t print_time(u64 ts, char *buf)
869 unsigned long rem_nsec;
871 if (!printk_time)
872 return 0;
874 rem_nsec = do_div(ts, 1000000000);
876 if (!buf)
877 return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
879 return sprintf(buf, "[%5lu.%06lu] ",
880 (unsigned long)ts, rem_nsec / 1000);
883 static size_t print_prefix(const struct log *msg, bool syslog, char *buf)
885 size_t len = 0;
886 unsigned int prefix = (msg->facility << 3) | msg->level;
888 if (syslog) {
889 if (buf) {
890 len += sprintf(buf, "<%u>", prefix);
891 } else {
892 len += 3;
893 if (prefix > 999)
894 len += 3;
895 else if (prefix > 99)
896 len += 2;
897 else if (prefix > 9)
898 len++;
902 len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
903 return len;
906 static size_t msg_print_text(const struct log *msg, enum log_flags prev,
907 bool syslog, char *buf, size_t size)
909 const char *text = log_text(msg);
910 size_t text_size = msg->text_len;
911 bool prefix = true;
912 bool newline = true;
913 size_t len = 0;
915 if ((prev & LOG_CONT) && !(msg->flags & LOG_PREFIX))
916 prefix = false;
918 if (msg->flags & LOG_CONT) {
919 if ((prev & LOG_CONT) && !(prev & LOG_NEWLINE))
920 prefix = false;
922 if (!(msg->flags & LOG_NEWLINE))
923 newline = false;
926 do {
927 const char *next = memchr(text, '\n', text_size);
928 size_t text_len;
930 if (next) {
931 text_len = next - text;
932 next++;
933 text_size -= next - text;
934 } else {
935 text_len = text_size;
938 if (buf) {
939 if (print_prefix(msg, syslog, NULL) +
940 text_len + 1 >= size - len)
941 break;
943 if (prefix)
944 len += print_prefix(msg, syslog, buf + len);
945 memcpy(buf + len, text, text_len);
946 len += text_len;
947 if (next || newline)
948 buf[len++] = '\n';
949 } else {
950 /* SYSLOG_ACTION_* buffer size only calculation */
951 if (prefix)
952 len += print_prefix(msg, syslog, NULL);
953 len += text_len;
954 if (next || newline)
955 len++;
958 prefix = true;
959 text = next;
960 } while (text);
962 return len;
965 static int syslog_print(char __user *buf, int size)
967 char *text;
968 struct log *msg;
969 int len = 0;
971 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
972 if (!text)
973 return -ENOMEM;
975 while (size > 0) {
976 size_t n;
977 size_t skip;
979 raw_spin_lock_irq(&logbuf_lock);
980 if (syslog_seq < log_first_seq) {
981 /* messages are gone, move to first one */
982 syslog_seq = log_first_seq;
983 syslog_idx = log_first_idx;
984 syslog_prev = 0;
985 syslog_partial = 0;
987 if (syslog_seq == log_next_seq) {
988 raw_spin_unlock_irq(&logbuf_lock);
989 break;
992 skip = syslog_partial;
993 msg = log_from_idx(syslog_idx);
994 n = msg_print_text(msg, syslog_prev, true, text,
995 LOG_LINE_MAX + PREFIX_MAX);
996 if (n - syslog_partial <= size) {
997 /* message fits into buffer, move forward */
998 syslog_idx = log_next(syslog_idx);
999 syslog_seq++;
1000 syslog_prev = msg->flags;
1001 n -= syslog_partial;
1002 syslog_partial = 0;
1003 } else if (!len){
1004 /* partial read(), remember position */
1005 n = size;
1006 syslog_partial += n;
1007 } else
1008 n = 0;
1009 raw_spin_unlock_irq(&logbuf_lock);
1011 if (!n)
1012 break;
1014 if (copy_to_user(buf, text + skip, n)) {
1015 if (!len)
1016 len = -EFAULT;
1017 break;
1020 len += n;
1021 size -= n;
1022 buf += n;
1025 kfree(text);
1026 return len;
1029 static int syslog_print_all(char __user *buf, int size, bool clear)
1031 char *text;
1032 int len = 0;
1034 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1035 if (!text)
1036 return -ENOMEM;
1038 raw_spin_lock_irq(&logbuf_lock);
1039 if (buf) {
1040 u64 next_seq;
1041 u64 seq;
1042 u32 idx;
1043 enum log_flags prev;
1045 if (clear_seq < log_first_seq) {
1046 /* messages are gone, move to first available one */
1047 clear_seq = log_first_seq;
1048 clear_idx = log_first_idx;
1052 * Find first record that fits, including all following records,
1053 * into the user-provided buffer for this dump.
1055 seq = clear_seq;
1056 idx = clear_idx;
1057 prev = 0;
1058 while (seq < log_next_seq) {
1059 struct log *msg = log_from_idx(idx);
1061 len += msg_print_text(msg, prev, true, NULL, 0);
1062 prev = msg->flags;
1063 idx = log_next(idx);
1064 seq++;
1067 /* move first record forward until length fits into the buffer */
1068 seq = clear_seq;
1069 idx = clear_idx;
1070 prev = 0;
1071 while (len > size && seq < log_next_seq) {
1072 struct log *msg = log_from_idx(idx);
1074 len -= msg_print_text(msg, prev, true, NULL, 0);
1075 prev = msg->flags;
1076 idx = log_next(idx);
1077 seq++;
1080 /* last message fitting into this dump */
1081 next_seq = log_next_seq;
1083 len = 0;
1084 prev = 0;
1085 while (len >= 0 && seq < next_seq) {
1086 struct log *msg = log_from_idx(idx);
1087 int textlen;
1089 textlen = msg_print_text(msg, prev, true, text,
1090 LOG_LINE_MAX + PREFIX_MAX);
1091 if (textlen < 0) {
1092 len = textlen;
1093 break;
1095 idx = log_next(idx);
1096 seq++;
1097 prev = msg->flags;
1099 raw_spin_unlock_irq(&logbuf_lock);
1100 if (copy_to_user(buf + len, text, textlen))
1101 len = -EFAULT;
1102 else
1103 len += textlen;
1104 raw_spin_lock_irq(&logbuf_lock);
1106 if (seq < log_first_seq) {
1107 /* messages are gone, move to next one */
1108 seq = log_first_seq;
1109 idx = log_first_idx;
1110 prev = 0;
1115 if (clear) {
1116 clear_seq = log_next_seq;
1117 clear_idx = log_next_idx;
1119 raw_spin_unlock_irq(&logbuf_lock);
1121 kfree(text);
1122 return len;
1125 int do_syslog(int type, char __user *buf, int len, bool from_file)
1127 bool clear = false;
1128 static int saved_console_loglevel = -1;
1129 int error;
1131 error = check_syslog_permissions(type, from_file);
1132 if (error)
1133 goto out;
1135 error = security_syslog(type);
1136 if (error)
1137 return error;
1139 switch (type) {
1140 case SYSLOG_ACTION_CLOSE: /* Close log */
1141 break;
1142 case SYSLOG_ACTION_OPEN: /* Open log */
1143 break;
1144 case SYSLOG_ACTION_READ: /* Read from log */
1145 error = -EINVAL;
1146 if (!buf || len < 0)
1147 goto out;
1148 error = 0;
1149 if (!len)
1150 goto out;
1151 if (!access_ok(VERIFY_WRITE, buf, len)) {
1152 error = -EFAULT;
1153 goto out;
1155 error = wait_event_interruptible(log_wait,
1156 syslog_seq != log_next_seq);
1157 if (error)
1158 goto out;
1159 error = syslog_print(buf, len);
1160 break;
1161 /* Read/clear last kernel messages */
1162 case SYSLOG_ACTION_READ_CLEAR:
1163 clear = true;
1164 /* FALL THRU */
1165 /* Read last kernel messages */
1166 case SYSLOG_ACTION_READ_ALL:
1167 error = -EINVAL;
1168 if (!buf || len < 0)
1169 goto out;
1170 error = 0;
1171 if (!len)
1172 goto out;
1173 if (!access_ok(VERIFY_WRITE, buf, len)) {
1174 error = -EFAULT;
1175 goto out;
1177 error = syslog_print_all(buf, len, clear);
1178 break;
1179 /* Clear ring buffer */
1180 case SYSLOG_ACTION_CLEAR:
1181 syslog_print_all(NULL, 0, true);
1182 break;
1183 /* Disable logging to console */
1184 case SYSLOG_ACTION_CONSOLE_OFF:
1185 if (saved_console_loglevel == -1)
1186 saved_console_loglevel = console_loglevel;
1187 console_loglevel = minimum_console_loglevel;
1188 break;
1189 /* Enable logging to console */
1190 case SYSLOG_ACTION_CONSOLE_ON:
1191 if (saved_console_loglevel != -1) {
1192 console_loglevel = saved_console_loglevel;
1193 saved_console_loglevel = -1;
1195 break;
1196 /* Set level of messages printed to console */
1197 case SYSLOG_ACTION_CONSOLE_LEVEL:
1198 error = -EINVAL;
1199 if (len < 1 || len > 8)
1200 goto out;
1201 if (len < minimum_console_loglevel)
1202 len = minimum_console_loglevel;
1203 console_loglevel = len;
1204 /* Implicitly re-enable logging to console */
1205 saved_console_loglevel = -1;
1206 error = 0;
1207 break;
1208 /* Number of chars in the log buffer */
1209 case SYSLOG_ACTION_SIZE_UNREAD:
1210 raw_spin_lock_irq(&logbuf_lock);
1211 if (syslog_seq < log_first_seq) {
1212 /* messages are gone, move to first one */
1213 syslog_seq = log_first_seq;
1214 syslog_idx = log_first_idx;
1215 syslog_prev = 0;
1216 syslog_partial = 0;
1218 if (from_file) {
1220 * Short-cut for poll(/"proc/kmsg") which simply checks
1221 * for pending data, not the size; return the count of
1222 * records, not the length.
1224 error = log_next_idx - syslog_idx;
1225 } else {
1226 u64 seq = syslog_seq;
1227 u32 idx = syslog_idx;
1228 enum log_flags prev = syslog_prev;
1230 error = 0;
1231 while (seq < log_next_seq) {
1232 struct log *msg = log_from_idx(idx);
1234 error += msg_print_text(msg, prev, true, NULL, 0);
1235 idx = log_next(idx);
1236 seq++;
1237 prev = msg->flags;
1239 error -= syslog_partial;
1241 raw_spin_unlock_irq(&logbuf_lock);
1242 break;
1243 /* Size of the log buffer */
1244 case SYSLOG_ACTION_SIZE_BUFFER:
1245 error = log_buf_len;
1246 break;
1247 default:
1248 error = -EINVAL;
1249 break;
1251 out:
1252 return error;
1255 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1257 return do_syslog(type, buf, len, SYSLOG_FROM_CALL);
1261 * Call the console drivers, asking them to write out
1262 * log_buf[start] to log_buf[end - 1].
1263 * The console_lock must be held.
1265 static void call_console_drivers(int level, const char *text, size_t len)
1267 struct console *con;
1269 trace_console(text, 0, len, len);
1271 if (level >= console_loglevel && !ignore_loglevel)
1272 return;
1273 if (!console_drivers)
1274 return;
1276 for_each_console(con) {
1277 if (exclusive_console && con != exclusive_console)
1278 continue;
1279 if (!(con->flags & CON_ENABLED))
1280 continue;
1281 if (!con->write)
1282 continue;
1283 if (!cpu_online(smp_processor_id()) &&
1284 !(con->flags & CON_ANYTIME))
1285 continue;
1286 con->write(con, text, len);
1291 * Zap console related locks when oopsing. Only zap at most once
1292 * every 10 seconds, to leave time for slow consoles to print a
1293 * full oops.
1295 static void zap_locks(void)
1297 static unsigned long oops_timestamp;
1299 if (time_after_eq(jiffies, oops_timestamp) &&
1300 !time_after(jiffies, oops_timestamp + 30 * HZ))
1301 return;
1303 oops_timestamp = jiffies;
1305 debug_locks_off();
1306 /* If a crash is occurring, make sure we can't deadlock */
1307 raw_spin_lock_init(&logbuf_lock);
1308 /* And make sure that we print immediately */
1309 sema_init(&console_sem, 1);
1312 /* Check if we have any console registered that can be called early in boot. */
1313 static int have_callable_console(void)
1315 struct console *con;
1317 for_each_console(con)
1318 if (con->flags & CON_ANYTIME)
1319 return 1;
1321 return 0;
1325 * Can we actually use the console at this time on this cpu?
1327 * Console drivers may assume that per-cpu resources have
1328 * been allocated. So unless they're explicitly marked as
1329 * being able to cope (CON_ANYTIME) don't call them until
1330 * this CPU is officially up.
1332 static inline int can_use_console(unsigned int cpu)
1334 return cpu_online(cpu) || have_callable_console();
1338 * Try to get console ownership to actually show the kernel
1339 * messages from a 'printk'. Return true (and with the
1340 * console_lock held, and 'console_locked' set) if it
1341 * is successful, false otherwise.
1343 * This gets called with the 'logbuf_lock' spinlock held and
1344 * interrupts disabled. It should return with 'lockbuf_lock'
1345 * released but interrupts still disabled.
1347 static int console_trylock_for_printk(unsigned int cpu)
1348 __releases(&logbuf_lock)
1350 int retval = 0, wake = 0;
1352 if (console_trylock()) {
1353 retval = 1;
1356 * If we can't use the console, we need to release
1357 * the console semaphore by hand to avoid flushing
1358 * the buffer. We need to hold the console semaphore
1359 * in order to do this test safely.
1361 if (!can_use_console(cpu)) {
1362 console_locked = 0;
1363 wake = 1;
1364 retval = 0;
1367 logbuf_cpu = UINT_MAX;
1368 if (wake)
1369 up(&console_sem);
1370 raw_spin_unlock(&logbuf_lock);
1371 return retval;
1374 int printk_delay_msec __read_mostly;
1376 static inline void printk_delay(void)
1378 if (unlikely(printk_delay_msec)) {
1379 int m = printk_delay_msec;
1381 while (m--) {
1382 mdelay(1);
1383 touch_nmi_watchdog();
1389 * Continuation lines are buffered, and not committed to the record buffer
1390 * until the line is complete, or a race forces it. The line fragments
1391 * though, are printed immediately to the consoles to ensure everything has
1392 * reached the console in case of a kernel crash.
1394 static struct cont {
1395 char buf[LOG_LINE_MAX];
1396 size_t len; /* length == 0 means unused buffer */
1397 size_t cons; /* bytes written to console */
1398 struct task_struct *owner; /* task of first print*/
1399 u64 ts_nsec; /* time of first print */
1400 u8 level; /* log level of first message */
1401 u8 facility; /* log level of first message */
1402 enum log_flags flags; /* prefix, newline flags */
1403 bool flushed:1; /* buffer sealed and committed */
1404 } cont;
1406 static void cont_flush(enum log_flags flags)
1408 if (cont.flushed)
1409 return;
1410 if (cont.len == 0)
1411 return;
1413 if (cont.cons) {
1415 * If a fragment of this line was directly flushed to the
1416 * console; wait for the console to pick up the rest of the
1417 * line. LOG_NOCONS suppresses a duplicated output.
1419 log_store(cont.facility, cont.level, flags | LOG_NOCONS,
1420 cont.ts_nsec, NULL, 0, cont.buf, cont.len);
1421 cont.flags = flags;
1422 cont.flushed = true;
1423 } else {
1425 * If no fragment of this line ever reached the console,
1426 * just submit it to the store and free the buffer.
1428 log_store(cont.facility, cont.level, flags, 0,
1429 NULL, 0, cont.buf, cont.len);
1430 cont.len = 0;
1434 static bool cont_add(int facility, int level, const char *text, size_t len)
1436 if (cont.len && cont.flushed)
1437 return false;
1439 if (cont.len + len > sizeof(cont.buf)) {
1440 /* the line gets too long, split it up in separate records */
1441 cont_flush(LOG_CONT);
1442 return false;
1445 if (!cont.len) {
1446 cont.facility = facility;
1447 cont.level = level;
1448 cont.owner = current;
1449 cont.ts_nsec = local_clock();
1450 cont.flags = 0;
1451 cont.cons = 0;
1452 cont.flushed = false;
1455 memcpy(cont.buf + cont.len, text, len);
1456 cont.len += len;
1458 if (cont.len > (sizeof(cont.buf) * 80) / 100)
1459 cont_flush(LOG_CONT);
1461 return true;
1464 static size_t cont_print_text(char *text, size_t size)
1466 size_t textlen = 0;
1467 size_t len;
1469 if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
1470 textlen += print_time(cont.ts_nsec, text);
1471 size -= textlen;
1474 len = cont.len - cont.cons;
1475 if (len > 0) {
1476 if (len+1 > size)
1477 len = size-1;
1478 memcpy(text + textlen, cont.buf + cont.cons, len);
1479 textlen += len;
1480 cont.cons = cont.len;
1483 if (cont.flushed) {
1484 if (cont.flags & LOG_NEWLINE)
1485 text[textlen++] = '\n';
1486 /* got everything, release buffer */
1487 cont.len = 0;
1489 return textlen;
1492 asmlinkage int vprintk_emit(int facility, int level,
1493 const char *dict, size_t dictlen,
1494 const char *fmt, va_list args)
1496 static int recursion_bug;
1497 static char textbuf[LOG_LINE_MAX];
1498 char *text = textbuf;
1499 size_t text_len;
1500 enum log_flags lflags = 0;
1501 unsigned long flags;
1502 int this_cpu;
1503 int printed_len = 0;
1505 boot_delay_msec(level);
1506 printk_delay();
1508 /* This stops the holder of console_sem just where we want him */
1509 local_irq_save(flags);
1510 this_cpu = smp_processor_id();
1513 * Ouch, printk recursed into itself!
1515 if (unlikely(logbuf_cpu == this_cpu)) {
1517 * If a crash is occurring during printk() on this CPU,
1518 * then try to get the crash message out but make sure
1519 * we can't deadlock. Otherwise just return to avoid the
1520 * recursion and return - but flag the recursion so that
1521 * it can be printed at the next appropriate moment:
1523 if (!oops_in_progress && !lockdep_recursing(current)) {
1524 recursion_bug = 1;
1525 goto out_restore_irqs;
1527 zap_locks();
1530 lockdep_off();
1531 raw_spin_lock(&logbuf_lock);
1532 logbuf_cpu = this_cpu;
1534 if (recursion_bug) {
1535 static const char recursion_msg[] =
1536 "BUG: recent printk recursion!";
1538 recursion_bug = 0;
1539 printed_len += strlen(recursion_msg);
1540 /* emit KERN_CRIT message */
1541 log_store(0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
1542 NULL, 0, recursion_msg, printed_len);
1546 * The printf needs to come first; we need the syslog
1547 * prefix which might be passed-in as a parameter.
1549 text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
1551 /* mark and strip a trailing newline */
1552 if (text_len && text[text_len-1] == '\n') {
1553 text_len--;
1554 lflags |= LOG_NEWLINE;
1557 /* strip kernel syslog prefix and extract log level or control flags */
1558 if (facility == 0) {
1559 int kern_level = printk_get_level(text);
1561 if (kern_level) {
1562 const char *end_of_header = printk_skip_level(text);
1563 switch (kern_level) {
1564 case '0' ... '7':
1565 if (level == -1)
1566 level = kern_level - '0';
1567 case 'd': /* KERN_DEFAULT */
1568 lflags |= LOG_PREFIX;
1569 case 'c': /* KERN_CONT */
1570 break;
1572 text_len -= end_of_header - text;
1573 text = (char *)end_of_header;
1577 if (level == -1)
1578 level = default_message_loglevel;
1580 if (dict)
1581 lflags |= LOG_PREFIX|LOG_NEWLINE;
1583 if (!(lflags & LOG_NEWLINE)) {
1585 * Flush the conflicting buffer. An earlier newline was missing,
1586 * or another task also prints continuation lines.
1588 if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
1589 cont_flush(LOG_NEWLINE);
1591 /* buffer line if possible, otherwise store it right away */
1592 if (!cont_add(facility, level, text, text_len))
1593 log_store(facility, level, lflags | LOG_CONT, 0,
1594 dict, dictlen, text, text_len);
1595 } else {
1596 bool stored = false;
1599 * If an earlier newline was missing and it was the same task,
1600 * either merge it with the current buffer and flush, or if
1601 * there was a race with interrupts (prefix == true) then just
1602 * flush it out and store this line separately.
1604 if (cont.len && cont.owner == current) {
1605 if (!(lflags & LOG_PREFIX))
1606 stored = cont_add(facility, level, text, text_len);
1607 cont_flush(LOG_NEWLINE);
1610 if (!stored)
1611 log_store(facility, level, lflags, 0,
1612 dict, dictlen, text, text_len);
1614 printed_len += text_len;
1617 * Try to acquire and then immediately release the console semaphore.
1618 * The release will print out buffers and wake up /dev/kmsg and syslog()
1619 * users.
1621 * The console_trylock_for_printk() function will release 'logbuf_lock'
1622 * regardless of whether it actually gets the console semaphore or not.
1624 if (console_trylock_for_printk(this_cpu))
1625 console_unlock();
1627 lockdep_on();
1628 out_restore_irqs:
1629 local_irq_restore(flags);
1631 return printed_len;
1633 EXPORT_SYMBOL(vprintk_emit);
1635 asmlinkage int vprintk(const char *fmt, va_list args)
1637 return vprintk_emit(0, -1, NULL, 0, fmt, args);
1639 EXPORT_SYMBOL(vprintk);
1641 asmlinkage int printk_emit(int facility, int level,
1642 const char *dict, size_t dictlen,
1643 const char *fmt, ...)
1645 va_list args;
1646 int r;
1648 va_start(args, fmt);
1649 r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
1650 va_end(args);
1652 return r;
1654 EXPORT_SYMBOL(printk_emit);
1657 * printk - print a kernel message
1658 * @fmt: format string
1660 * This is printk(). It can be called from any context. We want it to work.
1662 * We try to grab the console_lock. If we succeed, it's easy - we log the
1663 * output and call the console drivers. If we fail to get the semaphore, we
1664 * place the output into the log buffer and return. The current holder of
1665 * the console_sem will notice the new output in console_unlock(); and will
1666 * send it to the consoles before releasing the lock.
1668 * One effect of this deferred printing is that code which calls printk() and
1669 * then changes console_loglevel may break. This is because console_loglevel
1670 * is inspected when the actual printing occurs.
1672 * See also:
1673 * printf(3)
1675 * See the vsnprintf() documentation for format string extensions over C99.
1677 asmlinkage int printk(const char *fmt, ...)
1679 va_list args;
1680 int r;
1682 #ifdef CONFIG_KGDB_KDB
1683 if (unlikely(kdb_trap_printk)) {
1684 va_start(args, fmt);
1685 r = vkdb_printf(fmt, args);
1686 va_end(args);
1687 return r;
1689 #endif
1690 va_start(args, fmt);
1691 r = vprintk_emit(0, -1, NULL, 0, fmt, args);
1692 va_end(args);
1694 return r;
1696 EXPORT_SYMBOL(printk);
1698 #else /* CONFIG_PRINTK */
1700 #define LOG_LINE_MAX 0
1701 #define PREFIX_MAX 0
1702 #define LOG_LINE_MAX 0
1703 static u64 syslog_seq;
1704 static u32 syslog_idx;
1705 static u64 console_seq;
1706 static u32 console_idx;
1707 static enum log_flags syslog_prev;
1708 static u64 log_first_seq;
1709 static u32 log_first_idx;
1710 static u64 log_next_seq;
1711 static enum log_flags console_prev;
1712 static struct cont {
1713 size_t len;
1714 size_t cons;
1715 u8 level;
1716 bool flushed:1;
1717 } cont;
1718 static struct log *log_from_idx(u32 idx) { return NULL; }
1719 static u32 log_next(u32 idx) { return 0; }
1720 static void call_console_drivers(int level, const char *text, size_t len) {}
1721 static size_t msg_print_text(const struct log *msg, enum log_flags prev,
1722 bool syslog, char *buf, size_t size) { return 0; }
1723 static size_t cont_print_text(char *text, size_t size) { return 0; }
1725 #endif /* CONFIG_PRINTK */
1727 static int __add_preferred_console(char *name, int idx, char *options,
1728 char *brl_options)
1730 struct console_cmdline *c;
1731 int i;
1734 * See if this tty is not yet registered, and
1735 * if we have a slot free.
1737 for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
1738 if (strcmp(console_cmdline[i].name, name) == 0 &&
1739 console_cmdline[i].index == idx) {
1740 if (!brl_options)
1741 selected_console = i;
1742 return 0;
1744 if (i == MAX_CMDLINECONSOLES)
1745 return -E2BIG;
1746 if (!brl_options)
1747 selected_console = i;
1748 c = &console_cmdline[i];
1749 strlcpy(c->name, name, sizeof(c->name));
1750 c->options = options;
1751 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1752 c->brl_options = brl_options;
1753 #endif
1754 c->index = idx;
1755 return 0;
1758 * Set up a list of consoles. Called from init/main.c
1760 static int __init console_setup(char *str)
1762 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
1763 char *s, *options, *brl_options = NULL;
1764 int idx;
1766 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1767 if (!memcmp(str, "brl,", 4)) {
1768 brl_options = "";
1769 str += 4;
1770 } else if (!memcmp(str, "brl=", 4)) {
1771 brl_options = str + 4;
1772 str = strchr(brl_options, ',');
1773 if (!str) {
1774 printk(KERN_ERR "need port name after brl=\n");
1775 return 1;
1777 *(str++) = 0;
1779 #endif
1782 * Decode str into name, index, options.
1784 if (str[0] >= '0' && str[0] <= '9') {
1785 strcpy(buf, "ttyS");
1786 strncpy(buf + 4, str, sizeof(buf) - 5);
1787 } else {
1788 strncpy(buf, str, sizeof(buf) - 1);
1790 buf[sizeof(buf) - 1] = 0;
1791 if ((options = strchr(str, ',')) != NULL)
1792 *(options++) = 0;
1793 #ifdef __sparc__
1794 if (!strcmp(str, "ttya"))
1795 strcpy(buf, "ttyS0");
1796 if (!strcmp(str, "ttyb"))
1797 strcpy(buf, "ttyS1");
1798 #endif
1799 for (s = buf; *s; s++)
1800 if ((*s >= '0' && *s <= '9') || *s == ',')
1801 break;
1802 idx = simple_strtoul(s, NULL, 10);
1803 *s = 0;
1805 __add_preferred_console(buf, idx, options, brl_options);
1806 console_set_on_cmdline = 1;
1807 return 1;
1809 __setup("console=", console_setup);
1812 * add_preferred_console - add a device to the list of preferred consoles.
1813 * @name: device name
1814 * @idx: device index
1815 * @options: options for this console
1817 * The last preferred console added will be used for kernel messages
1818 * and stdin/out/err for init. Normally this is used by console_setup
1819 * above to handle user-supplied console arguments; however it can also
1820 * be used by arch-specific code either to override the user or more
1821 * commonly to provide a default console (ie from PROM variables) when
1822 * the user has not supplied one.
1824 int add_preferred_console(char *name, int idx, char *options)
1826 return __add_preferred_console(name, idx, options, NULL);
1829 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
1831 struct console_cmdline *c;
1832 int i;
1834 for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
1835 if (strcmp(console_cmdline[i].name, name) == 0 &&
1836 console_cmdline[i].index == idx) {
1837 c = &console_cmdline[i];
1838 strlcpy(c->name, name_new, sizeof(c->name));
1839 c->name[sizeof(c->name) - 1] = 0;
1840 c->options = options;
1841 c->index = idx_new;
1842 return i;
1844 /* not found */
1845 return -1;
1848 bool console_suspend_enabled = 1;
1849 EXPORT_SYMBOL(console_suspend_enabled);
1851 static int __init console_suspend_disable(char *str)
1853 console_suspend_enabled = 0;
1854 return 1;
1856 __setup("no_console_suspend", console_suspend_disable);
1857 module_param_named(console_suspend, console_suspend_enabled,
1858 bool, S_IRUGO | S_IWUSR);
1859 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
1860 " and hibernate operations");
1863 * suspend_console - suspend the console subsystem
1865 * This disables printk() while we go into suspend states
1867 void suspend_console(void)
1869 if (!console_suspend_enabled)
1870 return;
1871 printk("Suspending console(s) (use no_console_suspend to debug)\n");
1872 console_lock();
1873 console_suspended = 1;
1874 up(&console_sem);
1877 void resume_console(void)
1879 if (!console_suspend_enabled)
1880 return;
1881 down(&console_sem);
1882 console_suspended = 0;
1883 console_unlock();
1887 * console_cpu_notify - print deferred console messages after CPU hotplug
1888 * @self: notifier struct
1889 * @action: CPU hotplug event
1890 * @hcpu: unused
1892 * If printk() is called from a CPU that is not online yet, the messages
1893 * will be spooled but will not show up on the console. This function is
1894 * called when a new CPU comes online (or fails to come up), and ensures
1895 * that any such output gets printed.
1897 static int __cpuinit console_cpu_notify(struct notifier_block *self,
1898 unsigned long action, void *hcpu)
1900 switch (action) {
1901 case CPU_ONLINE:
1902 case CPU_DEAD:
1903 case CPU_DOWN_FAILED:
1904 case CPU_UP_CANCELED:
1905 console_lock();
1906 console_unlock();
1908 return NOTIFY_OK;
1912 * console_lock - lock the console system for exclusive use.
1914 * Acquires a lock which guarantees that the caller has
1915 * exclusive access to the console system and the console_drivers list.
1917 * Can sleep, returns nothing.
1919 void console_lock(void)
1921 might_sleep();
1923 down(&console_sem);
1924 if (console_suspended)
1925 return;
1926 console_locked = 1;
1927 console_may_schedule = 1;
1928 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);
1930 EXPORT_SYMBOL(console_lock);
1933 * console_trylock - try to lock the console system for exclusive use.
1935 * Tried to acquire a lock which guarantees that the caller has
1936 * exclusive access to the console system and the console_drivers list.
1938 * returns 1 on success, and 0 on failure to acquire the lock.
1940 int console_trylock(void)
1942 if (down_trylock(&console_sem))
1943 return 0;
1944 if (console_suspended) {
1945 up(&console_sem);
1946 return 0;
1948 console_locked = 1;
1949 console_may_schedule = 0;
1950 mutex_acquire(&console_lock_dep_map, 0, 1, _RET_IP_);
1951 return 1;
1953 EXPORT_SYMBOL(console_trylock);
1955 int is_console_locked(void)
1957 return console_locked;
1961 * Delayed printk version, for scheduler-internal messages:
1963 #define PRINTK_BUF_SIZE 512
1965 #define PRINTK_PENDING_WAKEUP 0x01
1966 #define PRINTK_PENDING_SCHED 0x02
1968 static DEFINE_PER_CPU(int, printk_pending);
1969 static DEFINE_PER_CPU(char [PRINTK_BUF_SIZE], printk_sched_buf);
1971 static void wake_up_klogd_work_func(struct irq_work *irq_work)
1973 int pending = __this_cpu_xchg(printk_pending, 0);
1975 if (pending & PRINTK_PENDING_SCHED) {
1976 char *buf = __get_cpu_var(printk_sched_buf);
1977 printk(KERN_WARNING "[sched_delayed] %s", buf);
1980 if (pending & PRINTK_PENDING_WAKEUP)
1981 wake_up_interruptible(&log_wait);
1984 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
1985 .func = wake_up_klogd_work_func,
1986 .flags = IRQ_WORK_LAZY,
1989 void wake_up_klogd(void)
1991 preempt_disable();
1992 if (waitqueue_active(&log_wait)) {
1993 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
1994 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
1996 preempt_enable();
1999 static void console_cont_flush(char *text, size_t size)
2001 unsigned long flags;
2002 size_t len;
2004 raw_spin_lock_irqsave(&logbuf_lock, flags);
2006 if (!cont.len)
2007 goto out;
2010 * We still queue earlier records, likely because the console was
2011 * busy. The earlier ones need to be printed before this one, we
2012 * did not flush any fragment so far, so just let it queue up.
2014 if (console_seq < log_next_seq && !cont.cons)
2015 goto out;
2017 len = cont_print_text(text, size);
2018 raw_spin_unlock(&logbuf_lock);
2019 stop_critical_timings();
2020 call_console_drivers(cont.level, text, len);
2021 start_critical_timings();
2022 local_irq_restore(flags);
2023 return;
2024 out:
2025 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2029 * console_unlock - unlock the console system
2031 * Releases the console_lock which the caller holds on the console system
2032 * and the console driver list.
2034 * While the console_lock was held, console output may have been buffered
2035 * by printk(). If this is the case, console_unlock(); emits
2036 * the output prior to releasing the lock.
2038 * If there is output waiting, we wake /dev/kmsg and syslog() users.
2040 * console_unlock(); may be called from any context.
2042 void console_unlock(void)
2044 static char text[LOG_LINE_MAX + PREFIX_MAX];
2045 static u64 seen_seq;
2046 unsigned long flags;
2047 bool wake_klogd = false;
2048 bool retry;
2050 if (console_suspended) {
2051 up(&console_sem);
2052 return;
2055 console_may_schedule = 0;
2057 /* flush buffered message fragment immediately to console */
2058 console_cont_flush(text, sizeof(text));
2059 again:
2060 for (;;) {
2061 struct log *msg;
2062 size_t len;
2063 int level;
2065 raw_spin_lock_irqsave(&logbuf_lock, flags);
2066 if (seen_seq != log_next_seq) {
2067 wake_klogd = true;
2068 seen_seq = log_next_seq;
2071 if (console_seq < log_first_seq) {
2072 /* messages are gone, move to first one */
2073 console_seq = log_first_seq;
2074 console_idx = log_first_idx;
2075 console_prev = 0;
2077 skip:
2078 if (console_seq == log_next_seq)
2079 break;
2081 msg = log_from_idx(console_idx);
2082 if (msg->flags & LOG_NOCONS) {
2084 * Skip record we have buffered and already printed
2085 * directly to the console when we received it.
2087 console_idx = log_next(console_idx);
2088 console_seq++;
2090 * We will get here again when we register a new
2091 * CON_PRINTBUFFER console. Clear the flag so we
2092 * will properly dump everything later.
2094 msg->flags &= ~LOG_NOCONS;
2095 console_prev = msg->flags;
2096 goto skip;
2099 level = msg->level;
2100 len = msg_print_text(msg, console_prev, false,
2101 text, sizeof(text));
2102 console_idx = log_next(console_idx);
2103 console_seq++;
2104 console_prev = msg->flags;
2105 raw_spin_unlock(&logbuf_lock);
2107 stop_critical_timings(); /* don't trace print latency */
2108 call_console_drivers(level, text, len);
2109 start_critical_timings();
2110 local_irq_restore(flags);
2112 console_locked = 0;
2113 mutex_release(&console_lock_dep_map, 1, _RET_IP_);
2115 /* Release the exclusive_console once it is used */
2116 if (unlikely(exclusive_console))
2117 exclusive_console = NULL;
2119 raw_spin_unlock(&logbuf_lock);
2121 up(&console_sem);
2124 * Someone could have filled up the buffer again, so re-check if there's
2125 * something to flush. In case we cannot trylock the console_sem again,
2126 * there's a new owner and the console_unlock() from them will do the
2127 * flush, no worries.
2129 raw_spin_lock(&logbuf_lock);
2130 retry = console_seq != log_next_seq;
2131 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2133 if (retry && console_trylock())
2134 goto again;
2136 if (wake_klogd)
2137 wake_up_klogd();
2139 EXPORT_SYMBOL(console_unlock);
2142 * console_conditional_schedule - yield the CPU if required
2144 * If the console code is currently allowed to sleep, and
2145 * if this CPU should yield the CPU to another task, do
2146 * so here.
2148 * Must be called within console_lock();.
2150 void __sched console_conditional_schedule(void)
2152 if (console_may_schedule)
2153 cond_resched();
2155 EXPORT_SYMBOL(console_conditional_schedule);
2157 void console_unblank(void)
2159 struct console *c;
2162 * console_unblank can no longer be called in interrupt context unless
2163 * oops_in_progress is set to 1..
2165 if (oops_in_progress) {
2166 if (down_trylock(&console_sem) != 0)
2167 return;
2168 } else
2169 console_lock();
2171 console_locked = 1;
2172 console_may_schedule = 0;
2173 for_each_console(c)
2174 if ((c->flags & CON_ENABLED) && c->unblank)
2175 c->unblank();
2176 console_unlock();
2180 * Return the console tty driver structure and its associated index
2182 struct tty_driver *console_device(int *index)
2184 struct console *c;
2185 struct tty_driver *driver = NULL;
2187 console_lock();
2188 for_each_console(c) {
2189 if (!c->device)
2190 continue;
2191 driver = c->device(c, index);
2192 if (driver)
2193 break;
2195 console_unlock();
2196 return driver;
2200 * Prevent further output on the passed console device so that (for example)
2201 * serial drivers can disable console output before suspending a port, and can
2202 * re-enable output afterwards.
2204 void console_stop(struct console *console)
2206 console_lock();
2207 console->flags &= ~CON_ENABLED;
2208 console_unlock();
2210 EXPORT_SYMBOL(console_stop);
2212 void console_start(struct console *console)
2214 console_lock();
2215 console->flags |= CON_ENABLED;
2216 console_unlock();
2218 EXPORT_SYMBOL(console_start);
2220 static int __read_mostly keep_bootcon;
2222 static int __init keep_bootcon_setup(char *str)
2224 keep_bootcon = 1;
2225 printk(KERN_INFO "debug: skip boot console de-registration.\n");
2227 return 0;
2230 early_param("keep_bootcon", keep_bootcon_setup);
2233 * The console driver calls this routine during kernel initialization
2234 * to register the console printing procedure with printk() and to
2235 * print any messages that were printed by the kernel before the
2236 * console driver was initialized.
2238 * This can happen pretty early during the boot process (because of
2239 * early_printk) - sometimes before setup_arch() completes - be careful
2240 * of what kernel features are used - they may not be initialised yet.
2242 * There are two types of consoles - bootconsoles (early_printk) and
2243 * "real" consoles (everything which is not a bootconsole) which are
2244 * handled differently.
2245 * - Any number of bootconsoles can be registered at any time.
2246 * - As soon as a "real" console is registered, all bootconsoles
2247 * will be unregistered automatically.
2248 * - Once a "real" console is registered, any attempt to register a
2249 * bootconsoles will be rejected
2251 void register_console(struct console *newcon)
2253 int i;
2254 unsigned long flags;
2255 struct console *bcon = NULL;
2258 * before we register a new CON_BOOT console, make sure we don't
2259 * already have a valid console
2261 if (console_drivers && newcon->flags & CON_BOOT) {
2262 /* find the last or real console */
2263 for_each_console(bcon) {
2264 if (!(bcon->flags & CON_BOOT)) {
2265 printk(KERN_INFO "Too late to register bootconsole %s%d\n",
2266 newcon->name, newcon->index);
2267 return;
2272 if (console_drivers && console_drivers->flags & CON_BOOT)
2273 bcon = console_drivers;
2275 if (preferred_console < 0 || bcon || !console_drivers)
2276 preferred_console = selected_console;
2278 if (newcon->early_setup)
2279 newcon->early_setup();
2282 * See if we want to use this console driver. If we
2283 * didn't select a console we take the first one
2284 * that registers here.
2286 if (preferred_console < 0) {
2287 if (newcon->index < 0)
2288 newcon->index = 0;
2289 if (newcon->setup == NULL ||
2290 newcon->setup(newcon, NULL) == 0) {
2291 newcon->flags |= CON_ENABLED;
2292 if (newcon->device) {
2293 newcon->flags |= CON_CONSDEV;
2294 preferred_console = 0;
2300 * See if this console matches one we selected on
2301 * the command line.
2303 for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
2304 i++) {
2305 if (strcmp(console_cmdline[i].name, newcon->name) != 0)
2306 continue;
2307 if (newcon->index >= 0 &&
2308 newcon->index != console_cmdline[i].index)
2309 continue;
2310 if (newcon->index < 0)
2311 newcon->index = console_cmdline[i].index;
2312 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
2313 if (console_cmdline[i].brl_options) {
2314 newcon->flags |= CON_BRL;
2315 braille_register_console(newcon,
2316 console_cmdline[i].index,
2317 console_cmdline[i].options,
2318 console_cmdline[i].brl_options);
2319 return;
2321 #endif
2322 if (newcon->setup &&
2323 newcon->setup(newcon, console_cmdline[i].options) != 0)
2324 break;
2325 newcon->flags |= CON_ENABLED;
2326 newcon->index = console_cmdline[i].index;
2327 if (i == selected_console) {
2328 newcon->flags |= CON_CONSDEV;
2329 preferred_console = selected_console;
2331 break;
2334 if (!(newcon->flags & CON_ENABLED))
2335 return;
2338 * If we have a bootconsole, and are switching to a real console,
2339 * don't print everything out again, since when the boot console, and
2340 * the real console are the same physical device, it's annoying to
2341 * see the beginning boot messages twice
2343 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
2344 newcon->flags &= ~CON_PRINTBUFFER;
2347 * Put this console in the list - keep the
2348 * preferred driver at the head of the list.
2350 console_lock();
2351 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2352 newcon->next = console_drivers;
2353 console_drivers = newcon;
2354 if (newcon->next)
2355 newcon->next->flags &= ~CON_CONSDEV;
2356 } else {
2357 newcon->next = console_drivers->next;
2358 console_drivers->next = newcon;
2360 if (newcon->flags & CON_PRINTBUFFER) {
2362 * console_unlock(); will print out the buffered messages
2363 * for us.
2365 raw_spin_lock_irqsave(&logbuf_lock, flags);
2366 console_seq = syslog_seq;
2367 console_idx = syslog_idx;
2368 console_prev = syslog_prev;
2369 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2371 * We're about to replay the log buffer. Only do this to the
2372 * just-registered console to avoid excessive message spam to
2373 * the already-registered consoles.
2375 exclusive_console = newcon;
2377 console_unlock();
2378 console_sysfs_notify();
2381 * By unregistering the bootconsoles after we enable the real console
2382 * we get the "console xxx enabled" message on all the consoles -
2383 * boot consoles, real consoles, etc - this is to ensure that end
2384 * users know there might be something in the kernel's log buffer that
2385 * went to the bootconsole (that they do not see on the real console)
2387 if (bcon &&
2388 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2389 !keep_bootcon) {
2390 /* we need to iterate through twice, to make sure we print
2391 * everything out, before we unregister the console(s)
2393 printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
2394 newcon->name, newcon->index);
2395 for_each_console(bcon)
2396 if (bcon->flags & CON_BOOT)
2397 unregister_console(bcon);
2398 } else {
2399 printk(KERN_INFO "%sconsole [%s%d] enabled\n",
2400 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2401 newcon->name, newcon->index);
2404 EXPORT_SYMBOL(register_console);
2406 int unregister_console(struct console *console)
2408 struct console *a, *b;
2409 int res = 1;
2411 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
2412 if (console->flags & CON_BRL)
2413 return braille_unregister_console(console);
2414 #endif
2416 console_lock();
2417 if (console_drivers == console) {
2418 console_drivers=console->next;
2419 res = 0;
2420 } else if (console_drivers) {
2421 for (a=console_drivers->next, b=console_drivers ;
2422 a; b=a, a=b->next) {
2423 if (a == console) {
2424 b->next = a->next;
2425 res = 0;
2426 break;
2432 * If this isn't the last console and it has CON_CONSDEV set, we
2433 * need to set it on the next preferred console.
2435 if (console_drivers != NULL && console->flags & CON_CONSDEV)
2436 console_drivers->flags |= CON_CONSDEV;
2438 console_unlock();
2439 console_sysfs_notify();
2440 return res;
2442 EXPORT_SYMBOL(unregister_console);
2444 static int __init printk_late_init(void)
2446 struct console *con;
2448 for_each_console(con) {
2449 if (!keep_bootcon && con->flags & CON_BOOT) {
2450 printk(KERN_INFO "turn off boot console %s%d\n",
2451 con->name, con->index);
2452 unregister_console(con);
2455 hotcpu_notifier(console_cpu_notify, 0);
2456 return 0;
2458 late_initcall(printk_late_init);
2460 #if defined CONFIG_PRINTK
2462 int printk_sched(const char *fmt, ...)
2464 unsigned long flags;
2465 va_list args;
2466 char *buf;
2467 int r;
2469 local_irq_save(flags);
2470 buf = __get_cpu_var(printk_sched_buf);
2472 va_start(args, fmt);
2473 r = vsnprintf(buf, PRINTK_BUF_SIZE, fmt, args);
2474 va_end(args);
2476 __this_cpu_or(printk_pending, PRINTK_PENDING_SCHED);
2477 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
2478 local_irq_restore(flags);
2480 return r;
2484 * printk rate limiting, lifted from the networking subsystem.
2486 * This enforces a rate limit: not more than 10 kernel messages
2487 * every 5s to make a denial-of-service attack impossible.
2489 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
2491 int __printk_ratelimit(const char *func)
2493 return ___ratelimit(&printk_ratelimit_state, func);
2495 EXPORT_SYMBOL(__printk_ratelimit);
2498 * printk_timed_ratelimit - caller-controlled printk ratelimiting
2499 * @caller_jiffies: pointer to caller's state
2500 * @interval_msecs: minimum interval between prints
2502 * printk_timed_ratelimit() returns true if more than @interval_msecs
2503 * milliseconds have elapsed since the last time printk_timed_ratelimit()
2504 * returned true.
2506 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
2507 unsigned int interval_msecs)
2509 if (*caller_jiffies == 0
2510 || !time_in_range(jiffies, *caller_jiffies,
2511 *caller_jiffies
2512 + msecs_to_jiffies(interval_msecs))) {
2513 *caller_jiffies = jiffies;
2514 return true;
2516 return false;
2518 EXPORT_SYMBOL(printk_timed_ratelimit);
2520 static DEFINE_SPINLOCK(dump_list_lock);
2521 static LIST_HEAD(dump_list);
2524 * kmsg_dump_register - register a kernel log dumper.
2525 * @dumper: pointer to the kmsg_dumper structure
2527 * Adds a kernel log dumper to the system. The dump callback in the
2528 * structure will be called when the kernel oopses or panics and must be
2529 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
2531 int kmsg_dump_register(struct kmsg_dumper *dumper)
2533 unsigned long flags;
2534 int err = -EBUSY;
2536 /* The dump callback needs to be set */
2537 if (!dumper->dump)
2538 return -EINVAL;
2540 spin_lock_irqsave(&dump_list_lock, flags);
2541 /* Don't allow registering multiple times */
2542 if (!dumper->registered) {
2543 dumper->registered = 1;
2544 list_add_tail_rcu(&dumper->list, &dump_list);
2545 err = 0;
2547 spin_unlock_irqrestore(&dump_list_lock, flags);
2549 return err;
2551 EXPORT_SYMBOL_GPL(kmsg_dump_register);
2554 * kmsg_dump_unregister - unregister a kmsg dumper.
2555 * @dumper: pointer to the kmsg_dumper structure
2557 * Removes a dump device from the system. Returns zero on success and
2558 * %-EINVAL otherwise.
2560 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
2562 unsigned long flags;
2563 int err = -EINVAL;
2565 spin_lock_irqsave(&dump_list_lock, flags);
2566 if (dumper->registered) {
2567 dumper->registered = 0;
2568 list_del_rcu(&dumper->list);
2569 err = 0;
2571 spin_unlock_irqrestore(&dump_list_lock, flags);
2572 synchronize_rcu();
2574 return err;
2576 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
2578 static bool always_kmsg_dump;
2579 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
2582 * kmsg_dump - dump kernel log to kernel message dumpers.
2583 * @reason: the reason (oops, panic etc) for dumping
2585 * Call each of the registered dumper's dump() callback, which can
2586 * retrieve the kmsg records with kmsg_dump_get_line() or
2587 * kmsg_dump_get_buffer().
2589 void kmsg_dump(enum kmsg_dump_reason reason)
2591 struct kmsg_dumper *dumper;
2592 unsigned long flags;
2594 if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
2595 return;
2597 rcu_read_lock();
2598 list_for_each_entry_rcu(dumper, &dump_list, list) {
2599 if (dumper->max_reason && reason > dumper->max_reason)
2600 continue;
2602 /* initialize iterator with data about the stored records */
2603 dumper->active = true;
2605 raw_spin_lock_irqsave(&logbuf_lock, flags);
2606 dumper->cur_seq = clear_seq;
2607 dumper->cur_idx = clear_idx;
2608 dumper->next_seq = log_next_seq;
2609 dumper->next_idx = log_next_idx;
2610 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2612 /* invoke dumper which will iterate over records */
2613 dumper->dump(dumper, reason);
2615 /* reset iterator */
2616 dumper->active = false;
2618 rcu_read_unlock();
2622 * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
2623 * @dumper: registered kmsg dumper
2624 * @syslog: include the "<4>" prefixes
2625 * @line: buffer to copy the line to
2626 * @size: maximum size of the buffer
2627 * @len: length of line placed into buffer
2629 * Start at the beginning of the kmsg buffer, with the oldest kmsg
2630 * record, and copy one record into the provided buffer.
2632 * Consecutive calls will return the next available record moving
2633 * towards the end of the buffer with the youngest messages.
2635 * A return value of FALSE indicates that there are no more records to
2636 * read.
2638 * The function is similar to kmsg_dump_get_line(), but grabs no locks.
2640 bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
2641 char *line, size_t size, size_t *len)
2643 struct log *msg;
2644 size_t l = 0;
2645 bool ret = false;
2647 if (!dumper->active)
2648 goto out;
2650 if (dumper->cur_seq < log_first_seq) {
2651 /* messages are gone, move to first available one */
2652 dumper->cur_seq = log_first_seq;
2653 dumper->cur_idx = log_first_idx;
2656 /* last entry */
2657 if (dumper->cur_seq >= log_next_seq)
2658 goto out;
2660 msg = log_from_idx(dumper->cur_idx);
2661 l = msg_print_text(msg, 0, syslog, line, size);
2663 dumper->cur_idx = log_next(dumper->cur_idx);
2664 dumper->cur_seq++;
2665 ret = true;
2666 out:
2667 if (len)
2668 *len = l;
2669 return ret;
2673 * kmsg_dump_get_line - retrieve one kmsg log line
2674 * @dumper: registered kmsg dumper
2675 * @syslog: include the "<4>" prefixes
2676 * @line: buffer to copy the line to
2677 * @size: maximum size of the buffer
2678 * @len: length of line placed into buffer
2680 * Start at the beginning of the kmsg buffer, with the oldest kmsg
2681 * record, and copy one record into the provided buffer.
2683 * Consecutive calls will return the next available record moving
2684 * towards the end of the buffer with the youngest messages.
2686 * A return value of FALSE indicates that there are no more records to
2687 * read.
2689 bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
2690 char *line, size_t size, size_t *len)
2692 unsigned long flags;
2693 bool ret;
2695 raw_spin_lock_irqsave(&logbuf_lock, flags);
2696 ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
2697 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2699 return ret;
2701 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
2704 * kmsg_dump_get_buffer - copy kmsg log lines
2705 * @dumper: registered kmsg dumper
2706 * @syslog: include the "<4>" prefixes
2707 * @buf: buffer to copy the line to
2708 * @size: maximum size of the buffer
2709 * @len: length of line placed into buffer
2711 * Start at the end of the kmsg buffer and fill the provided buffer
2712 * with as many of the the *youngest* kmsg records that fit into it.
2713 * If the buffer is large enough, all available kmsg records will be
2714 * copied with a single call.
2716 * Consecutive calls will fill the buffer with the next block of
2717 * available older records, not including the earlier retrieved ones.
2719 * A return value of FALSE indicates that there are no more records to
2720 * read.
2722 bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
2723 char *buf, size_t size, size_t *len)
2725 unsigned long flags;
2726 u64 seq;
2727 u32 idx;
2728 u64 next_seq;
2729 u32 next_idx;
2730 enum log_flags prev;
2731 size_t l = 0;
2732 bool ret = false;
2734 if (!dumper->active)
2735 goto out;
2737 raw_spin_lock_irqsave(&logbuf_lock, flags);
2738 if (dumper->cur_seq < log_first_seq) {
2739 /* messages are gone, move to first available one */
2740 dumper->cur_seq = log_first_seq;
2741 dumper->cur_idx = log_first_idx;
2744 /* last entry */
2745 if (dumper->cur_seq >= dumper->next_seq) {
2746 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2747 goto out;
2750 /* calculate length of entire buffer */
2751 seq = dumper->cur_seq;
2752 idx = dumper->cur_idx;
2753 prev = 0;
2754 while (seq < dumper->next_seq) {
2755 struct log *msg = log_from_idx(idx);
2757 l += msg_print_text(msg, prev, true, NULL, 0);
2758 idx = log_next(idx);
2759 seq++;
2760 prev = msg->flags;
2763 /* move first record forward until length fits into the buffer */
2764 seq = dumper->cur_seq;
2765 idx = dumper->cur_idx;
2766 prev = 0;
2767 while (l > size && seq < dumper->next_seq) {
2768 struct log *msg = log_from_idx(idx);
2770 l -= msg_print_text(msg, prev, true, NULL, 0);
2771 idx = log_next(idx);
2772 seq++;
2773 prev = msg->flags;
2776 /* last message in next interation */
2777 next_seq = seq;
2778 next_idx = idx;
2780 l = 0;
2781 prev = 0;
2782 while (seq < dumper->next_seq) {
2783 struct log *msg = log_from_idx(idx);
2785 l += msg_print_text(msg, prev, syslog, buf + l, size - l);
2786 idx = log_next(idx);
2787 seq++;
2788 prev = msg->flags;
2791 dumper->next_seq = next_seq;
2792 dumper->next_idx = next_idx;
2793 ret = true;
2794 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2795 out:
2796 if (len)
2797 *len = l;
2798 return ret;
2800 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
2803 * kmsg_dump_rewind_nolock - reset the interator (unlocked version)
2804 * @dumper: registered kmsg dumper
2806 * Reset the dumper's iterator so that kmsg_dump_get_line() and
2807 * kmsg_dump_get_buffer() can be called again and used multiple
2808 * times within the same dumper.dump() callback.
2810 * The function is similar to kmsg_dump_rewind(), but grabs no locks.
2812 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
2814 dumper->cur_seq = clear_seq;
2815 dumper->cur_idx = clear_idx;
2816 dumper->next_seq = log_next_seq;
2817 dumper->next_idx = log_next_idx;
2821 * kmsg_dump_rewind - reset the interator
2822 * @dumper: registered kmsg dumper
2824 * Reset the dumper's iterator so that kmsg_dump_get_line() and
2825 * kmsg_dump_get_buffer() can be called again and used multiple
2826 * times within the same dumper.dump() callback.
2828 void kmsg_dump_rewind(struct kmsg_dumper *dumper)
2830 unsigned long flags;
2832 raw_spin_lock_irqsave(&logbuf_lock, flags);
2833 kmsg_dump_rewind_nolock(dumper);
2834 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2836 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
2837 #endif