printk: split code for making free space in the log buffer
[linux-2.6-block.git] / kernel / printk / printk.c
CommitLineData
1da177e4
LT
1/*
2 * linux/kernel/printk.c
3 *
4 * Copyright (C) 1991, 1992 Linus Torvalds
5 *
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.
40dc5651 13 * Fixed SMP synchronization, 08/08/99, Manfred Spraul
624dffcb 14 * manfred@colorfullife.com
1da177e4 15 * Rewrote bits to get rid of console_lock
e1f8e874 16 * 01Mar01 Andrew Morton
1da177e4
LT
17 */
18
19#include <linux/kernel.h>
20#include <linux/mm.h>
21#include <linux/tty.h>
22#include <linux/tty_driver.h>
1da177e4
LT
23#include <linux/console.h>
24#include <linux/init.h>
bfe8df3d
RD
25#include <linux/jiffies.h>
26#include <linux/nmi.h>
1da177e4 27#include <linux/module.h>
3b9c0410 28#include <linux/moduleparam.h>
1da177e4 29#include <linux/interrupt.h> /* For in_interrupt() */
1da177e4
LT
30#include <linux/delay.h>
31#include <linux/smp.h>
32#include <linux/security.h>
33#include <linux/bootmem.h>
162a7e75 34#include <linux/memblock.h>
a27bb332 35#include <linux/aio.h>
1da177e4 36#include <linux/syscalls.h>
04d491ab 37#include <linux/kexec.h>
d37d39ae 38#include <linux/kdb.h>
3fff4c42 39#include <linux/ratelimit.h>
456b565c 40#include <linux/kmsg_dump.h>
00234592 41#include <linux/syslog.h>
034260d6
KC
42#include <linux/cpu.h>
43#include <linux/notifier.h>
fb842b00 44#include <linux/rculist.h>
e11fea92 45#include <linux/poll.h>
74876a98 46#include <linux/irq_work.h>
196779b9 47#include <linux/utsname.h>
1da177e4
LT
48
49#include <asm/uaccess.h>
50
95100358
JB
51#define CREATE_TRACE_POINTS
52#include <trace/events/printk.h>
53
d197c43d 54#include "console_cmdline.h"
bbeddf52 55#include "braille.h"
d197c43d 56
1da177e4 57/* printk's without a loglevel use this.. */
5af5bcb8 58#define DEFAULT_MESSAGE_LOGLEVEL CONFIG_DEFAULT_MESSAGE_LOGLEVEL
1da177e4
LT
59
60/* We show everything that is MORE important than this.. */
61#define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
62#define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
63
1da177e4
LT
64int console_printk[4] = {
65 DEFAULT_CONSOLE_LOGLEVEL, /* console_loglevel */
66 DEFAULT_MESSAGE_LOGLEVEL, /* default_message_loglevel */
67 MINIMUM_CONSOLE_LOGLEVEL, /* minimum_console_loglevel */
68 DEFAULT_CONSOLE_LOGLEVEL, /* default_console_loglevel */
69};
70
1da177e4 71/*
0bbfb7c2 72 * Low level drivers may need that to know if they can schedule in
1da177e4
LT
73 * their unblank() callback or not. So let's export it.
74 */
75int oops_in_progress;
76EXPORT_SYMBOL(oops_in_progress);
77
78/*
79 * console_sem protects the console_drivers list, and also
80 * provides serialisation for access to the entire console
81 * driver system.
82 */
5b8c4f23 83static DEFINE_SEMAPHORE(console_sem);
1da177e4 84struct console *console_drivers;
a29d1cfe
IM
85EXPORT_SYMBOL_GPL(console_drivers);
86
daee7797
DV
87#ifdef CONFIG_LOCKDEP
88static struct lockdep_map console_lock_dep_map = {
89 .name = "console_lock"
90};
91#endif
92
1da177e4
LT
93/*
94 * This is used for debugging the mess that is the VT code by
95 * keeping track if we have the console semaphore held. It's
96 * definitely not the perfect debug tool (we don't know if _WE_
97 * hold it are racing, but it helps tracking those weird code
98 * path in the console code where we end up in places I want
99 * locked without the console sempahore held
100 */
557240b4 101static int console_locked, console_suspended;
1da177e4 102
fe3d8ad3
FT
103/*
104 * If exclusive_console is non-NULL then only this console is to be printed to.
105 */
106static struct console *exclusive_console;
107
1da177e4
LT
108/*
109 * Array of consoles built from command line options (console=)
110 */
1da177e4
LT
111
112#define MAX_CMDLINECONSOLES 8
113
114static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
d197c43d 115
1da177e4
LT
116static int selected_console = -1;
117static int preferred_console = -1;
9e124fe1
MA
118int console_set_on_cmdline;
119EXPORT_SYMBOL(console_set_on_cmdline);
1da177e4
LT
120
121/* Flag: console code may call schedule() */
122static int console_may_schedule;
123
7ff9554b
KS
124/*
125 * The printk log buffer consists of a chain of concatenated variable
126 * length records. Every record starts with a record header, containing
127 * the overall length of the record.
128 *
129 * The heads to the first and last entry in the buffer, as well as the
130 * sequence numbers of these both entries are maintained when messages
131 * are stored..
132 *
133 * If the heads indicate available messages, the length in the header
134 * tells the start next message. A length == 0 for the next message
135 * indicates a wrap-around to the beginning of the buffer.
136 *
137 * Every record carries the monotonic timestamp in microseconds, as well as
138 * the standard userspace syslog level and syslog facility. The usual
139 * kernel messages use LOG_KERN; userspace-injected messages always carry
140 * a matching syslog facility, by default LOG_USER. The origin of every
141 * message can be reliably determined that way.
142 *
143 * The human readable log message directly follows the message header. The
144 * length of the message text is stored in the header, the stored message
145 * is not terminated.
146 *
e11fea92
KS
147 * Optionally, a message can carry a dictionary of properties (key/value pairs),
148 * to provide userspace with a machine-readable message context.
149 *
150 * Examples for well-defined, commonly used property names are:
151 * DEVICE=b12:8 device identifier
152 * b12:8 block dev_t
153 * c127:3 char dev_t
154 * n8 netdev ifindex
155 * +sound:card0 subsystem:devname
156 * SUBSYSTEM=pci driver-core subsystem name
157 *
158 * Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
159 * follows directly after a '=' character. Every property is terminated by
160 * a '\0' character. The last property is not terminated.
161 *
162 * Example of a message structure:
163 * 0000 ff 8f 00 00 00 00 00 00 monotonic time in nsec
164 * 0008 34 00 record is 52 bytes long
165 * 000a 0b 00 text is 11 bytes long
166 * 000c 1f 00 dictionary is 23 bytes long
167 * 000e 03 00 LOG_KERN (facility) LOG_ERR (level)
168 * 0010 69 74 27 73 20 61 20 6c "it's a l"
169 * 69 6e 65 "ine"
170 * 001b 44 45 56 49 43 "DEVIC"
171 * 45 3d 62 38 3a 32 00 44 "E=b8:2\0D"
172 * 52 49 56 45 52 3d 62 75 "RIVER=bu"
173 * 67 "g"
174 * 0032 00 00 00 padding to next message header
175 *
62e32ac3 176 * The 'struct printk_log' buffer header must never be directly exported to
e11fea92
KS
177 * userspace, it is a kernel-private implementation detail that might
178 * need to be changed in the future, when the requirements change.
179 *
180 * /dev/kmsg exports the structured data in the following line format:
181 * "level,sequnum,timestamp;<message text>\n"
182 *
183 * The optional key/value pairs are attached as continuation lines starting
184 * with a space character and terminated by a newline. All possible
185 * non-prinatable characters are escaped in the "\xff" notation.
186 *
187 * Users of the export format should ignore possible additional values
188 * separated by ',', and find the message after the ';' character.
7ff9554b
KS
189 */
190
084681d1 191enum log_flags {
5becfb1d
KS
192 LOG_NOCONS = 1, /* already flushed, do not print to console */
193 LOG_NEWLINE = 2, /* text ended with a newline */
194 LOG_PREFIX = 4, /* text started with a prefix */
195 LOG_CONT = 8, /* text is a fragment of a continuation line */
084681d1
KS
196};
197
62e32ac3 198struct printk_log {
7ff9554b
KS
199 u64 ts_nsec; /* timestamp in nanoseconds */
200 u16 len; /* length of entire record */
201 u16 text_len; /* length of text buffer */
202 u16 dict_len; /* length of dictionary buffer */
084681d1
KS
203 u8 facility; /* syslog facility */
204 u8 flags:5; /* internal record flags */
205 u8 level:3; /* syslog level */
7ff9554b
KS
206};
207
208/*
209 * The logbuf_lock protects kmsg buffer, indices, counters. It is also
210 * used in interesting ways to provide interlocking in console_unlock();
211 */
212static DEFINE_RAW_SPINLOCK(logbuf_lock);
d59745ce 213
96efedf1 214#ifdef CONFIG_PRINTK
dc72c32e 215DECLARE_WAIT_QUEUE_HEAD(log_wait);
7f3a781d
KS
216/* the next printk record to read by syslog(READ) or /proc/kmsg */
217static u64 syslog_seq;
218static u32 syslog_idx;
5becfb1d 219static enum log_flags syslog_prev;
eb02dac9 220static size_t syslog_partial;
7ff9554b
KS
221
222/* index and sequence number of the first record stored in the buffer */
223static u64 log_first_seq;
224static u32 log_first_idx;
225
226/* index and sequence number of the next record to store in the buffer */
227static u64 log_next_seq;
228static u32 log_next_idx;
229
eab07260
KS
230/* the next printk record to write to the console */
231static u64 console_seq;
232static u32 console_idx;
233static enum log_flags console_prev;
234
7ff9554b
KS
235/* the next printk record to read after the last 'clear' command */
236static u64 clear_seq;
237static u32 clear_idx;
238
70498253
KS
239#define PREFIX_MAX 32
240#define LOG_LINE_MAX 1024 - PREFIX_MAX
7f3a781d
KS
241
242/* record buffer */
6ebb017d 243#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
f8450fca
SW
244#define LOG_ALIGN 4
245#else
62e32ac3 246#define LOG_ALIGN __alignof__(struct printk_log)
f8450fca 247#endif
7f3a781d 248#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
f8450fca 249static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
7f3a781d
KS
250static char *log_buf = __log_buf;
251static u32 log_buf_len = __LOG_BUF_LEN;
252
253/* cpu currently holding logbuf_lock */
254static volatile unsigned int logbuf_cpu = UINT_MAX;
7ff9554b
KS
255
256/* human readable text of the record */
62e32ac3 257static char *log_text(const struct printk_log *msg)
7ff9554b 258{
62e32ac3 259 return (char *)msg + sizeof(struct printk_log);
7ff9554b
KS
260}
261
262/* optional key/value pair dictionary attached to the record */
62e32ac3 263static char *log_dict(const struct printk_log *msg)
7ff9554b 264{
62e32ac3 265 return (char *)msg + sizeof(struct printk_log) + msg->text_len;
7ff9554b
KS
266}
267
268/* get record by index; idx must point to valid msg */
62e32ac3 269static struct printk_log *log_from_idx(u32 idx)
7ff9554b 270{
62e32ac3 271 struct printk_log *msg = (struct printk_log *)(log_buf + idx);
7ff9554b
KS
272
273 /*
274 * A length == 0 record is the end of buffer marker. Wrap around and
275 * read the message at the start of the buffer.
276 */
277 if (!msg->len)
62e32ac3 278 return (struct printk_log *)log_buf;
7ff9554b
KS
279 return msg;
280}
281
282/* get next record; idx must point to valid msg */
283static u32 log_next(u32 idx)
284{
62e32ac3 285 struct printk_log *msg = (struct printk_log *)(log_buf + idx);
7ff9554b
KS
286
287 /* length == 0 indicates the end of the buffer; wrap */
288 /*
289 * A length == 0 record is the end of buffer marker. Wrap around and
290 * read the message at the start of the buffer as *this* one, and
291 * return the one after that.
292 */
293 if (!msg->len) {
62e32ac3 294 msg = (struct printk_log *)log_buf;
7ff9554b
KS
295 return msg->len;
296 }
297 return idx + msg->len;
298}
299
0a581694
PM
300/* check whether there is enough free space for the given message */
301static int logbuf_has_space(u32 msg_size)
302{
303 u32 free;
304
305 if (log_next_idx > log_first_idx)
306 free = max(log_buf_len - log_next_idx, log_first_idx);
307 else
308 free = log_first_idx - log_next_idx;
309
310 /*
311 * We need space also for an empty header that signalizes wrapping
312 * of the buffer.
313 */
314 return free >= msg_size + sizeof(struct printk_log);
315}
316
317static void log_make_free_space(u32 msg_size)
318{
319 while (log_first_seq < log_next_seq) {
320 if (logbuf_has_space(msg_size))
321 return;
322 /* drop old messages until we have enough continuous space */
323 log_first_idx = log_next(log_first_idx);
324 log_first_seq++;
325 }
326}
327
7ff9554b
KS
328/* insert record into the buffer, discard old ones, update heads */
329static void log_store(int facility, int level,
084681d1 330 enum log_flags flags, u64 ts_nsec,
7ff9554b
KS
331 const char *dict, u16 dict_len,
332 const char *text, u16 text_len)
333{
62e32ac3 334 struct printk_log *msg;
7ff9554b
KS
335 u32 size, pad_len;
336
337 /* number of '\0' padding bytes to next message */
62e32ac3 338 size = sizeof(struct printk_log) + text_len + dict_len;
7ff9554b
KS
339 pad_len = (-size) & (LOG_ALIGN - 1);
340 size += pad_len;
341
0a581694 342 log_make_free_space(size);
7ff9554b 343
39b25109 344 if (log_next_idx + size + sizeof(struct printk_log) > log_buf_len) {
7ff9554b
KS
345 /*
346 * This message + an additional empty header does not fit
347 * at the end of the buffer. Add an empty header with len == 0
348 * to signify a wrap around.
349 */
62e32ac3 350 memset(log_buf + log_next_idx, 0, sizeof(struct printk_log));
7ff9554b
KS
351 log_next_idx = 0;
352 }
353
354 /* fill message */
62e32ac3 355 msg = (struct printk_log *)(log_buf + log_next_idx);
7ff9554b
KS
356 memcpy(log_text(msg), text, text_len);
357 msg->text_len = text_len;
358 memcpy(log_dict(msg), dict, dict_len);
359 msg->dict_len = dict_len;
084681d1
KS
360 msg->facility = facility;
361 msg->level = level & 7;
362 msg->flags = flags & 0x1f;
363 if (ts_nsec > 0)
364 msg->ts_nsec = ts_nsec;
365 else
366 msg->ts_nsec = local_clock();
7ff9554b 367 memset(log_dict(msg) + dict_len, 0, pad_len);
fce6e033 368 msg->len = size;
7ff9554b
KS
369
370 /* insert message */
371 log_next_idx += msg->len;
372 log_next_seq++;
373}
d59745ce 374
637241a9
KC
375#ifdef CONFIG_SECURITY_DMESG_RESTRICT
376int dmesg_restrict = 1;
377#else
378int dmesg_restrict;
379#endif
380
381static int syslog_action_restricted(int type)
382{
383 if (dmesg_restrict)
384 return 1;
385 /*
386 * Unless restricted, we allow "read all" and "get buffer size"
387 * for everybody.
388 */
389 return type != SYSLOG_ACTION_READ_ALL &&
390 type != SYSLOG_ACTION_SIZE_BUFFER;
391}
392
393static int check_syslog_permissions(int type, bool from_file)
394{
395 /*
396 * If this is from /proc/kmsg and we've already opened it, then we've
397 * already done the capabilities checks at open time.
398 */
399 if (from_file && type != SYSLOG_ACTION_OPEN)
400 return 0;
401
402 if (syslog_action_restricted(type)) {
403 if (capable(CAP_SYSLOG))
404 return 0;
405 /*
406 * For historical reasons, accept CAP_SYS_ADMIN too, with
407 * a warning.
408 */
409 if (capable(CAP_SYS_ADMIN)) {
410 pr_warn_once("%s (%d): Attempt to access syslog with "
411 "CAP_SYS_ADMIN but no CAP_SYSLOG "
412 "(deprecated).\n",
413 current->comm, task_pid_nr(current));
414 return 0;
415 }
416 return -EPERM;
417 }
418 return security_syslog(type);
419}
420
421
e11fea92
KS
422/* /dev/kmsg - userspace message inject/listen interface */
423struct devkmsg_user {
424 u64 seq;
425 u32 idx;
d39f3d77 426 enum log_flags prev;
e11fea92
KS
427 struct mutex lock;
428 char buf[8192];
429};
430
431static ssize_t devkmsg_writev(struct kiocb *iocb, const struct iovec *iv,
432 unsigned long count, loff_t pos)
433{
434 char *buf, *line;
435 int i;
436 int level = default_message_loglevel;
437 int facility = 1; /* LOG_USER */
438 size_t len = iov_length(iv, count);
439 ssize_t ret = len;
440
441 if (len > LOG_LINE_MAX)
442 return -EINVAL;
443 buf = kmalloc(len+1, GFP_KERNEL);
444 if (buf == NULL)
445 return -ENOMEM;
446
447 line = buf;
448 for (i = 0; i < count; i++) {
cdf53441
KS
449 if (copy_from_user(line, iv[i].iov_base, iv[i].iov_len)) {
450 ret = -EFAULT;
e11fea92 451 goto out;
cdf53441 452 }
e11fea92
KS
453 line += iv[i].iov_len;
454 }
455
456 /*
457 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
458 * the decimal value represents 32bit, the lower 3 bit are the log
459 * level, the rest are the log facility.
460 *
461 * If no prefix or no userspace facility is specified, we
462 * enforce LOG_USER, to be able to reliably distinguish
463 * kernel-generated messages from userspace-injected ones.
464 */
465 line = buf;
466 if (line[0] == '<') {
467 char *endp = NULL;
468
469 i = simple_strtoul(line+1, &endp, 10);
470 if (endp && endp[0] == '>') {
471 level = i & 7;
472 if (i >> 3)
473 facility = i >> 3;
474 endp++;
475 len -= endp - line;
476 line = endp;
477 }
478 }
479 line[len] = '\0';
480
481 printk_emit(facility, level, NULL, 0, "%s", line);
482out:
483 kfree(buf);
484 return ret;
485}
486
487static ssize_t devkmsg_read(struct file *file, char __user *buf,
488 size_t count, loff_t *ppos)
489{
490 struct devkmsg_user *user = file->private_data;
62e32ac3 491 struct printk_log *msg;
5fc32490 492 u64 ts_usec;
e11fea92 493 size_t i;
d39f3d77 494 char cont = '-';
e11fea92
KS
495 size_t len;
496 ssize_t ret;
497
498 if (!user)
499 return -EBADF;
500
4a77a5a0
YL
501 ret = mutex_lock_interruptible(&user->lock);
502 if (ret)
503 return ret;
5c53d819 504 raw_spin_lock_irq(&logbuf_lock);
e11fea92
KS
505 while (user->seq == log_next_seq) {
506 if (file->f_flags & O_NONBLOCK) {
507 ret = -EAGAIN;
5c53d819 508 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
509 goto out;
510 }
511
5c53d819 512 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
513 ret = wait_event_interruptible(log_wait,
514 user->seq != log_next_seq);
515 if (ret)
516 goto out;
5c53d819 517 raw_spin_lock_irq(&logbuf_lock);
e11fea92
KS
518 }
519
520 if (user->seq < log_first_seq) {
521 /* our last seen message is gone, return error and reset */
522 user->idx = log_first_idx;
523 user->seq = log_first_seq;
524 ret = -EPIPE;
5c53d819 525 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
526 goto out;
527 }
528
529 msg = log_from_idx(user->idx);
5fc32490
KS
530 ts_usec = msg->ts_nsec;
531 do_div(ts_usec, 1000);
d39f3d77
KS
532
533 /*
534 * If we couldn't merge continuation line fragments during the print,
535 * export the stored flags to allow an optional external merge of the
536 * records. Merging the records isn't always neccessarily correct, like
537 * when we hit a race during printing. In most cases though, it produces
538 * better readable output. 'c' in the record flags mark the first
539 * fragment of a line, '+' the following.
540 */
541 if (msg->flags & LOG_CONT && !(user->prev & LOG_CONT))
542 cont = 'c';
543 else if ((msg->flags & LOG_CONT) ||
544 ((user->prev & LOG_CONT) && !(msg->flags & LOG_PREFIX)))
545 cont = '+';
546
547 len = sprintf(user->buf, "%u,%llu,%llu,%c;",
548 (msg->facility << 3) | msg->level,
549 user->seq, ts_usec, cont);
550 user->prev = msg->flags;
e11fea92
KS
551
552 /* escape non-printable characters */
553 for (i = 0; i < msg->text_len; i++) {
3ce9a7c0 554 unsigned char c = log_text(msg)[i];
e11fea92 555
e3f5a5f2 556 if (c < ' ' || c >= 127 || c == '\\')
e11fea92
KS
557 len += sprintf(user->buf + len, "\\x%02x", c);
558 else
559 user->buf[len++] = c;
560 }
561 user->buf[len++] = '\n';
562
563 if (msg->dict_len) {
564 bool line = true;
565
566 for (i = 0; i < msg->dict_len; i++) {
3ce9a7c0 567 unsigned char c = log_dict(msg)[i];
e11fea92
KS
568
569 if (line) {
570 user->buf[len++] = ' ';
571 line = false;
572 }
573
574 if (c == '\0') {
575 user->buf[len++] = '\n';
576 line = true;
577 continue;
578 }
579
e3f5a5f2 580 if (c < ' ' || c >= 127 || c == '\\') {
e11fea92
KS
581 len += sprintf(user->buf + len, "\\x%02x", c);
582 continue;
583 }
584
585 user->buf[len++] = c;
586 }
587 user->buf[len++] = '\n';
588 }
589
590 user->idx = log_next(user->idx);
591 user->seq++;
5c53d819 592 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
593
594 if (len > count) {
595 ret = -EINVAL;
596 goto out;
597 }
598
599 if (copy_to_user(buf, user->buf, len)) {
600 ret = -EFAULT;
601 goto out;
602 }
603 ret = len;
604out:
605 mutex_unlock(&user->lock);
606 return ret;
607}
608
609static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
610{
611 struct devkmsg_user *user = file->private_data;
612 loff_t ret = 0;
613
614 if (!user)
615 return -EBADF;
616 if (offset)
617 return -ESPIPE;
618
5c53d819 619 raw_spin_lock_irq(&logbuf_lock);
e11fea92
KS
620 switch (whence) {
621 case SEEK_SET:
622 /* the first record */
623 user->idx = log_first_idx;
624 user->seq = log_first_seq;
625 break;
626 case SEEK_DATA:
627 /*
628 * The first record after the last SYSLOG_ACTION_CLEAR,
629 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
630 * changes no global state, and does not clear anything.
631 */
632 user->idx = clear_idx;
633 user->seq = clear_seq;
634 break;
635 case SEEK_END:
636 /* after the last record */
637 user->idx = log_next_idx;
638 user->seq = log_next_seq;
639 break;
640 default:
641 ret = -EINVAL;
642 }
5c53d819 643 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
644 return ret;
645}
646
647static unsigned int devkmsg_poll(struct file *file, poll_table *wait)
648{
649 struct devkmsg_user *user = file->private_data;
650 int ret = 0;
651
652 if (!user)
653 return POLLERR|POLLNVAL;
654
655 poll_wait(file, &log_wait, wait);
656
5c53d819 657 raw_spin_lock_irq(&logbuf_lock);
e11fea92
KS
658 if (user->seq < log_next_seq) {
659 /* return error when data has vanished underneath us */
660 if (user->seq < log_first_seq)
661 ret = POLLIN|POLLRDNORM|POLLERR|POLLPRI;
0a285317
NK
662 else
663 ret = POLLIN|POLLRDNORM;
e11fea92 664 }
5c53d819 665 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
666
667 return ret;
668}
669
670static int devkmsg_open(struct inode *inode, struct file *file)
671{
672 struct devkmsg_user *user;
673 int err;
674
675 /* write-only does not need any file context */
676 if ((file->f_flags & O_ACCMODE) == O_WRONLY)
677 return 0;
678
637241a9
KC
679 err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
680 SYSLOG_FROM_READER);
e11fea92
KS
681 if (err)
682 return err;
683
684 user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
685 if (!user)
686 return -ENOMEM;
687
688 mutex_init(&user->lock);
689
5c53d819 690 raw_spin_lock_irq(&logbuf_lock);
e11fea92
KS
691 user->idx = log_first_idx;
692 user->seq = log_first_seq;
5c53d819 693 raw_spin_unlock_irq(&logbuf_lock);
e11fea92
KS
694
695 file->private_data = user;
696 return 0;
697}
698
699static int devkmsg_release(struct inode *inode, struct file *file)
700{
701 struct devkmsg_user *user = file->private_data;
702
703 if (!user)
704 return 0;
705
706 mutex_destroy(&user->lock);
707 kfree(user);
708 return 0;
709}
710
711const struct file_operations kmsg_fops = {
712 .open = devkmsg_open,
713 .read = devkmsg_read,
714 .aio_write = devkmsg_writev,
715 .llseek = devkmsg_llseek,
716 .poll = devkmsg_poll,
717 .release = devkmsg_release,
718};
719
04d491ab
NH
720#ifdef CONFIG_KEXEC
721/*
4c1ace64 722 * This appends the listed symbols to /proc/vmcore
04d491ab 723 *
4c1ace64 724 * /proc/vmcore is used by various utilities, like crash and makedumpfile to
04d491ab
NH
725 * obtain access to symbols that are otherwise very difficult to locate. These
726 * symbols are specifically used so that utilities can access and extract the
727 * dmesg log from a vmcore file after a crash.
728 */
729void log_buf_kexec_setup(void)
730{
731 VMCOREINFO_SYMBOL(log_buf);
04d491ab 732 VMCOREINFO_SYMBOL(log_buf_len);
7ff9554b
KS
733 VMCOREINFO_SYMBOL(log_first_idx);
734 VMCOREINFO_SYMBOL(log_next_idx);
6791457a 735 /*
62e32ac3 736 * Export struct printk_log size and field offsets. User space tools can
6791457a
VG
737 * parse it and detect any changes to structure down the line.
738 */
62e32ac3
JP
739 VMCOREINFO_STRUCT_SIZE(printk_log);
740 VMCOREINFO_OFFSET(printk_log, ts_nsec);
741 VMCOREINFO_OFFSET(printk_log, len);
742 VMCOREINFO_OFFSET(printk_log, text_len);
743 VMCOREINFO_OFFSET(printk_log, dict_len);
04d491ab
NH
744}
745#endif
746
162a7e75
MT
747/* requested log_buf_len from kernel cmdline */
748static unsigned long __initdata new_log_buf_len;
749
750/* save requested log_buf_len since it's too early to process it */
1da177e4
LT
751static int __init log_buf_len_setup(char *str)
752{
eed4a2ab 753 unsigned size = memparse(str, &str);
1da177e4
LT
754
755 if (size)
756 size = roundup_pow_of_two(size);
162a7e75
MT
757 if (size > log_buf_len)
758 new_log_buf_len = size;
759
760 return 0;
1da177e4 761}
162a7e75
MT
762early_param("log_buf_len", log_buf_len_setup);
763
764void __init setup_log_buf(int early)
765{
766 unsigned long flags;
162a7e75
MT
767 char *new_log_buf;
768 int free;
769
770 if (!new_log_buf_len)
771 return;
1da177e4 772
162a7e75 773 if (early) {
9da791df
SS
774 new_log_buf =
775 memblock_virt_alloc(new_log_buf_len, PAGE_SIZE);
162a7e75 776 } else {
9da791df 777 new_log_buf = memblock_virt_alloc_nopanic(new_log_buf_len, 0);
162a7e75
MT
778 }
779
780 if (unlikely(!new_log_buf)) {
781 pr_err("log_buf_len: %ld bytes not available\n",
782 new_log_buf_len);
783 return;
784 }
785
07354eb1 786 raw_spin_lock_irqsave(&logbuf_lock, flags);
162a7e75
MT
787 log_buf_len = new_log_buf_len;
788 log_buf = new_log_buf;
789 new_log_buf_len = 0;
7ff9554b
KS
790 free = __LOG_BUF_LEN - log_next_idx;
791 memcpy(log_buf, __log_buf, __LOG_BUF_LEN);
07354eb1 792 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
162a7e75
MT
793
794 pr_info("log_buf_len: %d\n", log_buf_len);
795 pr_info("early log buf free: %d(%d%%)\n",
796 free, (free * 100) / __LOG_BUF_LEN);
797}
1da177e4 798
2fa72c8f
AC
799static bool __read_mostly ignore_loglevel;
800
801static int __init ignore_loglevel_setup(char *str)
802{
803 ignore_loglevel = 1;
27083bac 804 pr_info("debug: ignoring loglevel setting.\n");
2fa72c8f
AC
805
806 return 0;
807}
808
809early_param("ignore_loglevel", ignore_loglevel_setup);
810module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
811MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
812 "print all kernel messages to the console.");
813
bfe8df3d
RD
814#ifdef CONFIG_BOOT_PRINTK_DELAY
815
674dff65 816static int boot_delay; /* msecs delay after each printk during bootup */
3a3b6ed2 817static unsigned long long loops_per_msec; /* based on boot_delay */
bfe8df3d
RD
818
819static int __init boot_delay_setup(char *str)
820{
821 unsigned long lpj;
bfe8df3d
RD
822
823 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
824 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
825
826 get_option(&str, &boot_delay);
827 if (boot_delay > 10 * 1000)
828 boot_delay = 0;
829
3a3b6ed2
DY
830 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
831 "HZ: %d, loops_per_msec: %llu\n",
832 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
29e9d225 833 return 0;
bfe8df3d 834}
29e9d225 835early_param("boot_delay", boot_delay_setup);
bfe8df3d 836
2fa72c8f 837static void boot_delay_msec(int level)
bfe8df3d
RD
838{
839 unsigned long long k;
840 unsigned long timeout;
841
2fa72c8f
AC
842 if ((boot_delay == 0 || system_state != SYSTEM_BOOTING)
843 || (level >= console_loglevel && !ignore_loglevel)) {
bfe8df3d 844 return;
2fa72c8f 845 }
bfe8df3d 846
3a3b6ed2 847 k = (unsigned long long)loops_per_msec * boot_delay;
bfe8df3d
RD
848
849 timeout = jiffies + msecs_to_jiffies(boot_delay);
850 while (k) {
851 k--;
852 cpu_relax();
853 /*
854 * use (volatile) jiffies to prevent
855 * compiler reduction; loop termination via jiffies
856 * is secondary and may or may not happen.
857 */
858 if (time_after(jiffies, timeout))
859 break;
860 touch_nmi_watchdog();
861 }
862}
863#else
2fa72c8f 864static inline void boot_delay_msec(int level)
bfe8df3d
RD
865{
866}
867#endif
868
7ff9554b
KS
869#if defined(CONFIG_PRINTK_TIME)
870static bool printk_time = 1;
871#else
872static bool printk_time;
873#endif
874module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
875
084681d1
KS
876static size_t print_time(u64 ts, char *buf)
877{
878 unsigned long rem_nsec;
879
880 if (!printk_time)
881 return 0;
882
35dac27c
RD
883 rem_nsec = do_div(ts, 1000000000);
884
084681d1 885 if (!buf)
35dac27c 886 return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
084681d1 887
084681d1
KS
888 return sprintf(buf, "[%5lu.%06lu] ",
889 (unsigned long)ts, rem_nsec / 1000);
890}
891
62e32ac3 892static size_t print_prefix(const struct printk_log *msg, bool syslog, char *buf)
649e6ee3 893{
3ce9a7c0 894 size_t len = 0;
43a73a50 895 unsigned int prefix = (msg->facility << 3) | msg->level;
649e6ee3 896
3ce9a7c0
KS
897 if (syslog) {
898 if (buf) {
43a73a50 899 len += sprintf(buf, "<%u>", prefix);
3ce9a7c0
KS
900 } else {
901 len += 3;
43a73a50
KS
902 if (prefix > 999)
903 len += 3;
904 else if (prefix > 99)
905 len += 2;
906 else if (prefix > 9)
3ce9a7c0
KS
907 len++;
908 }
909 }
649e6ee3 910
084681d1 911 len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
3ce9a7c0 912 return len;
649e6ee3
KS
913}
914
62e32ac3 915static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
5becfb1d 916 bool syslog, char *buf, size_t size)
7ff9554b 917{
3ce9a7c0
KS
918 const char *text = log_text(msg);
919 size_t text_size = msg->text_len;
5becfb1d
KS
920 bool prefix = true;
921 bool newline = true;
3ce9a7c0
KS
922 size_t len = 0;
923
5becfb1d
KS
924 if ((prev & LOG_CONT) && !(msg->flags & LOG_PREFIX))
925 prefix = false;
926
927 if (msg->flags & LOG_CONT) {
928 if ((prev & LOG_CONT) && !(prev & LOG_NEWLINE))
929 prefix = false;
930
931 if (!(msg->flags & LOG_NEWLINE))
932 newline = false;
933 }
934
3ce9a7c0
KS
935 do {
936 const char *next = memchr(text, '\n', text_size);
937 size_t text_len;
938
939 if (next) {
940 text_len = next - text;
941 next++;
942 text_size -= next - text;
943 } else {
944 text_len = text_size;
945 }
7ff9554b 946
3ce9a7c0
KS
947 if (buf) {
948 if (print_prefix(msg, syslog, NULL) +
70498253 949 text_len + 1 >= size - len)
3ce9a7c0 950 break;
7ff9554b 951
5becfb1d
KS
952 if (prefix)
953 len += print_prefix(msg, syslog, buf + len);
3ce9a7c0
KS
954 memcpy(buf + len, text, text_len);
955 len += text_len;
5becfb1d
KS
956 if (next || newline)
957 buf[len++] = '\n';
3ce9a7c0
KS
958 } else {
959 /* SYSLOG_ACTION_* buffer size only calculation */
5becfb1d
KS
960 if (prefix)
961 len += print_prefix(msg, syslog, NULL);
962 len += text_len;
963 if (next || newline)
964 len++;
3ce9a7c0 965 }
7ff9554b 966
5becfb1d 967 prefix = true;
3ce9a7c0
KS
968 text = next;
969 } while (text);
7ff9554b 970
7ff9554b
KS
971 return len;
972}
973
974static int syslog_print(char __user *buf, int size)
975{
976 char *text;
62e32ac3 977 struct printk_log *msg;
116e90b2 978 int len = 0;
7ff9554b 979
70498253 980 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
7ff9554b
KS
981 if (!text)
982 return -ENOMEM;
983
116e90b2
JB
984 while (size > 0) {
985 size_t n;
eb02dac9 986 size_t skip;
116e90b2
JB
987
988 raw_spin_lock_irq(&logbuf_lock);
989 if (syslog_seq < log_first_seq) {
990 /* messages are gone, move to first one */
991 syslog_seq = log_first_seq;
992 syslog_idx = log_first_idx;
5becfb1d 993 syslog_prev = 0;
eb02dac9 994 syslog_partial = 0;
116e90b2
JB
995 }
996 if (syslog_seq == log_next_seq) {
997 raw_spin_unlock_irq(&logbuf_lock);
998 break;
999 }
eb02dac9
KS
1000
1001 skip = syslog_partial;
116e90b2 1002 msg = log_from_idx(syslog_idx);
70498253
KS
1003 n = msg_print_text(msg, syslog_prev, true, text,
1004 LOG_LINE_MAX + PREFIX_MAX);
eb02dac9
KS
1005 if (n - syslog_partial <= size) {
1006 /* message fits into buffer, move forward */
116e90b2
JB
1007 syslog_idx = log_next(syslog_idx);
1008 syslog_seq++;
5becfb1d 1009 syslog_prev = msg->flags;
eb02dac9
KS
1010 n -= syslog_partial;
1011 syslog_partial = 0;
1012 } else if (!len){
1013 /* partial read(), remember position */
1014 n = size;
1015 syslog_partial += n;
116e90b2
JB
1016 } else
1017 n = 0;
1018 raw_spin_unlock_irq(&logbuf_lock);
1019
1020 if (!n)
1021 break;
1022
eb02dac9 1023 if (copy_to_user(buf, text + skip, n)) {
116e90b2
JB
1024 if (!len)
1025 len = -EFAULT;
1026 break;
1027 }
eb02dac9
KS
1028
1029 len += n;
1030 size -= n;
1031 buf += n;
7ff9554b 1032 }
7ff9554b
KS
1033
1034 kfree(text);
1035 return len;
1036}
1037
1038static int syslog_print_all(char __user *buf, int size, bool clear)
1039{
1040 char *text;
1041 int len = 0;
1042
70498253 1043 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
7ff9554b
KS
1044 if (!text)
1045 return -ENOMEM;
1046
1047 raw_spin_lock_irq(&logbuf_lock);
1048 if (buf) {
1049 u64 next_seq;
1050 u64 seq;
1051 u32 idx;
5becfb1d 1052 enum log_flags prev;
7ff9554b
KS
1053
1054 if (clear_seq < log_first_seq) {
1055 /* messages are gone, move to first available one */
1056 clear_seq = log_first_seq;
1057 clear_idx = log_first_idx;
1058 }
1059
1060 /*
1061 * Find first record that fits, including all following records,
1062 * into the user-provided buffer for this dump.
e2ae715d 1063 */
7ff9554b
KS
1064 seq = clear_seq;
1065 idx = clear_idx;
5becfb1d 1066 prev = 0;
7ff9554b 1067 while (seq < log_next_seq) {
62e32ac3 1068 struct printk_log *msg = log_from_idx(idx);
3ce9a7c0 1069
5becfb1d 1070 len += msg_print_text(msg, prev, true, NULL, 0);
e3756477 1071 prev = msg->flags;
7ff9554b
KS
1072 idx = log_next(idx);
1073 seq++;
1074 }
e2ae715d
KS
1075
1076 /* move first record forward until length fits into the buffer */
7ff9554b
KS
1077 seq = clear_seq;
1078 idx = clear_idx;
5becfb1d 1079 prev = 0;
7ff9554b 1080 while (len > size && seq < log_next_seq) {
62e32ac3 1081 struct printk_log *msg = log_from_idx(idx);
3ce9a7c0 1082
5becfb1d 1083 len -= msg_print_text(msg, prev, true, NULL, 0);
e3756477 1084 prev = msg->flags;
7ff9554b
KS
1085 idx = log_next(idx);
1086 seq++;
1087 }
1088
e2ae715d 1089 /* last message fitting into this dump */
7ff9554b
KS
1090 next_seq = log_next_seq;
1091
1092 len = 0;
1093 while (len >= 0 && seq < next_seq) {
62e32ac3 1094 struct printk_log *msg = log_from_idx(idx);
7ff9554b
KS
1095 int textlen;
1096
70498253
KS
1097 textlen = msg_print_text(msg, prev, true, text,
1098 LOG_LINE_MAX + PREFIX_MAX);
7ff9554b
KS
1099 if (textlen < 0) {
1100 len = textlen;
1101 break;
1102 }
1103 idx = log_next(idx);
1104 seq++;
5becfb1d 1105 prev = msg->flags;
7ff9554b
KS
1106
1107 raw_spin_unlock_irq(&logbuf_lock);
1108 if (copy_to_user(buf + len, text, textlen))
1109 len = -EFAULT;
1110 else
1111 len += textlen;
1112 raw_spin_lock_irq(&logbuf_lock);
1113
1114 if (seq < log_first_seq) {
1115 /* messages are gone, move to next one */
1116 seq = log_first_seq;
1117 idx = log_first_idx;
5becfb1d 1118 prev = 0;
7ff9554b
KS
1119 }
1120 }
1121 }
1122
1123 if (clear) {
1124 clear_seq = log_next_seq;
1125 clear_idx = log_next_idx;
1126 }
1127 raw_spin_unlock_irq(&logbuf_lock);
1128
1129 kfree(text);
1130 return len;
1131}
1132
00234592 1133int do_syslog(int type, char __user *buf, int len, bool from_file)
1da177e4 1134{
7ff9554b
KS
1135 bool clear = false;
1136 static int saved_console_loglevel = -1;
ee24aebf 1137 int error;
1da177e4 1138
ee24aebf
LT
1139 error = check_syslog_permissions(type, from_file);
1140 if (error)
1141 goto out;
12b3052c
EP
1142
1143 error = security_syslog(type);
1da177e4
LT
1144 if (error)
1145 return error;
1146
1147 switch (type) {
d78ca3cd 1148 case SYSLOG_ACTION_CLOSE: /* Close log */
1da177e4 1149 break;
d78ca3cd 1150 case SYSLOG_ACTION_OPEN: /* Open log */
1da177e4 1151 break;
d78ca3cd 1152 case SYSLOG_ACTION_READ: /* Read from log */
1da177e4
LT
1153 error = -EINVAL;
1154 if (!buf || len < 0)
1155 goto out;
1156 error = 0;
1157 if (!len)
1158 goto out;
1159 if (!access_ok(VERIFY_WRITE, buf, len)) {
1160 error = -EFAULT;
1161 goto out;
1162 }
40dc5651 1163 error = wait_event_interruptible(log_wait,
7ff9554b 1164 syslog_seq != log_next_seq);
cb424ffe 1165 if (error)
1da177e4 1166 goto out;
7ff9554b 1167 error = syslog_print(buf, len);
1da177e4 1168 break;
d78ca3cd
KC
1169 /* Read/clear last kernel messages */
1170 case SYSLOG_ACTION_READ_CLEAR:
7ff9554b 1171 clear = true;
1da177e4 1172 /* FALL THRU */
d78ca3cd
KC
1173 /* Read last kernel messages */
1174 case SYSLOG_ACTION_READ_ALL:
1da177e4
LT
1175 error = -EINVAL;
1176 if (!buf || len < 0)
1177 goto out;
1178 error = 0;
1179 if (!len)
1180 goto out;
1181 if (!access_ok(VERIFY_WRITE, buf, len)) {
1182 error = -EFAULT;
1183 goto out;
1184 }
7ff9554b 1185 error = syslog_print_all(buf, len, clear);
1da177e4 1186 break;
d78ca3cd
KC
1187 /* Clear ring buffer */
1188 case SYSLOG_ACTION_CLEAR:
7ff9554b 1189 syslog_print_all(NULL, 0, true);
4661e356 1190 break;
d78ca3cd
KC
1191 /* Disable logging to console */
1192 case SYSLOG_ACTION_CONSOLE_OFF:
1aaad49e
FP
1193 if (saved_console_loglevel == -1)
1194 saved_console_loglevel = console_loglevel;
1da177e4
LT
1195 console_loglevel = minimum_console_loglevel;
1196 break;
d78ca3cd
KC
1197 /* Enable logging to console */
1198 case SYSLOG_ACTION_CONSOLE_ON:
1aaad49e
FP
1199 if (saved_console_loglevel != -1) {
1200 console_loglevel = saved_console_loglevel;
1201 saved_console_loglevel = -1;
1202 }
1da177e4 1203 break;
d78ca3cd
KC
1204 /* Set level of messages printed to console */
1205 case SYSLOG_ACTION_CONSOLE_LEVEL:
1da177e4
LT
1206 error = -EINVAL;
1207 if (len < 1 || len > 8)
1208 goto out;
1209 if (len < minimum_console_loglevel)
1210 len = minimum_console_loglevel;
1211 console_loglevel = len;
1aaad49e
FP
1212 /* Implicitly re-enable logging to console */
1213 saved_console_loglevel = -1;
1da177e4
LT
1214 error = 0;
1215 break;
d78ca3cd
KC
1216 /* Number of chars in the log buffer */
1217 case SYSLOG_ACTION_SIZE_UNREAD:
7ff9554b
KS
1218 raw_spin_lock_irq(&logbuf_lock);
1219 if (syslog_seq < log_first_seq) {
1220 /* messages are gone, move to first one */
1221 syslog_seq = log_first_seq;
1222 syslog_idx = log_first_idx;
5becfb1d 1223 syslog_prev = 0;
eb02dac9 1224 syslog_partial = 0;
7ff9554b
KS
1225 }
1226 if (from_file) {
1227 /*
1228 * Short-cut for poll(/"proc/kmsg") which simply checks
1229 * for pending data, not the size; return the count of
1230 * records, not the length.
1231 */
1232 error = log_next_idx - syslog_idx;
1233 } else {
5becfb1d
KS
1234 u64 seq = syslog_seq;
1235 u32 idx = syslog_idx;
1236 enum log_flags prev = syslog_prev;
7ff9554b
KS
1237
1238 error = 0;
7ff9554b 1239 while (seq < log_next_seq) {
62e32ac3 1240 struct printk_log *msg = log_from_idx(idx);
3ce9a7c0 1241
5becfb1d 1242 error += msg_print_text(msg, prev, true, NULL, 0);
7ff9554b
KS
1243 idx = log_next(idx);
1244 seq++;
5becfb1d 1245 prev = msg->flags;
7ff9554b 1246 }
eb02dac9 1247 error -= syslog_partial;
7ff9554b
KS
1248 }
1249 raw_spin_unlock_irq(&logbuf_lock);
1da177e4 1250 break;
d78ca3cd
KC
1251 /* Size of the log buffer */
1252 case SYSLOG_ACTION_SIZE_BUFFER:
1da177e4
LT
1253 error = log_buf_len;
1254 break;
1255 default:
1256 error = -EINVAL;
1257 break;
1258 }
1259out:
1260 return error;
1261}
1262
1e7bfb21 1263SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1da177e4 1264{
637241a9 1265 return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1da177e4
LT
1266}
1267
1da177e4
LT
1268/*
1269 * Call the console drivers, asking them to write out
1270 * log_buf[start] to log_buf[end - 1].
ac751efa 1271 * The console_lock must be held.
1da177e4 1272 */
7ff9554b 1273static void call_console_drivers(int level, const char *text, size_t len)
1da177e4 1274{
7ff9554b 1275 struct console *con;
1da177e4 1276
07c65f4d 1277 trace_console(text, len);
7ff9554b
KS
1278
1279 if (level >= console_loglevel && !ignore_loglevel)
1280 return;
1281 if (!console_drivers)
1282 return;
1283
1284 for_each_console(con) {
1285 if (exclusive_console && con != exclusive_console)
1286 continue;
1287 if (!(con->flags & CON_ENABLED))
1288 continue;
1289 if (!con->write)
1290 continue;
1291 if (!cpu_online(smp_processor_id()) &&
1292 !(con->flags & CON_ANYTIME))
1293 continue;
1294 con->write(con, text, len);
1295 }
1da177e4
LT
1296}
1297
1298/*
1299 * Zap console related locks when oopsing. Only zap at most once
1300 * every 10 seconds, to leave time for slow consoles to print a
1301 * full oops.
1302 */
1303static void zap_locks(void)
1304{
1305 static unsigned long oops_timestamp;
1306
1307 if (time_after_eq(jiffies, oops_timestamp) &&
40dc5651 1308 !time_after(jiffies, oops_timestamp + 30 * HZ))
1da177e4
LT
1309 return;
1310
1311 oops_timestamp = jiffies;
1312
94d24fc4 1313 debug_locks_off();
1da177e4 1314 /* If a crash is occurring, make sure we can't deadlock */
07354eb1 1315 raw_spin_lock_init(&logbuf_lock);
1da177e4 1316 /* And make sure that we print immediately */
5b8c4f23 1317 sema_init(&console_sem, 1);
1da177e4
LT
1318}
1319
76a8ad29
ME
1320/* Check if we have any console registered that can be called early in boot. */
1321static int have_callable_console(void)
1322{
1323 struct console *con;
1324
4d091611 1325 for_each_console(con)
76a8ad29
ME
1326 if (con->flags & CON_ANYTIME)
1327 return 1;
1328
1329 return 0;
1330}
1331
266c2e0a
LT
1332/*
1333 * Can we actually use the console at this time on this cpu?
1334 *
1335 * Console drivers may assume that per-cpu resources have
1336 * been allocated. So unless they're explicitly marked as
1337 * being able to cope (CON_ANYTIME) don't call them until
1338 * this CPU is officially up.
1339 */
1340static inline int can_use_console(unsigned int cpu)
1341{
1342 return cpu_online(cpu) || have_callable_console();
1343}
1344
1345/*
1346 * Try to get console ownership to actually show the kernel
1347 * messages from a 'printk'. Return true (and with the
ac751efa 1348 * console_lock held, and 'console_locked' set) if it
266c2e0a
LT
1349 * is successful, false otherwise.
1350 *
1351 * This gets called with the 'logbuf_lock' spinlock held and
1352 * interrupts disabled. It should return with 'lockbuf_lock'
1353 * released but interrupts still disabled.
1354 */
ac751efa 1355static int console_trylock_for_printk(unsigned int cpu)
8155c02a 1356 __releases(&logbuf_lock)
266c2e0a 1357{
0b5e1c52 1358 int retval = 0, wake = 0;
266c2e0a 1359
ac751efa 1360 if (console_trylock()) {
093a07e2
LT
1361 retval = 1;
1362
1363 /*
1364 * If we can't use the console, we need to release
1365 * the console semaphore by hand to avoid flushing
1366 * the buffer. We need to hold the console semaphore
1367 * in order to do this test safely.
1368 */
1369 if (!can_use_console(cpu)) {
1370 console_locked = 0;
0b5e1c52 1371 wake = 1;
093a07e2
LT
1372 retval = 0;
1373 }
1374 }
7ff9554b 1375 logbuf_cpu = UINT_MAX;
dbda92d1 1376 raw_spin_unlock(&logbuf_lock);
0b5e1c52
PZ
1377 if (wake)
1378 up(&console_sem);
266c2e0a
LT
1379 return retval;
1380}
32a76006 1381
af91322e
DY
1382int printk_delay_msec __read_mostly;
1383
1384static inline void printk_delay(void)
1385{
1386 if (unlikely(printk_delay_msec)) {
1387 int m = printk_delay_msec;
1388
1389 while (m--) {
1390 mdelay(1);
1391 touch_nmi_watchdog();
1392 }
1393 }
1394}
1395
084681d1
KS
1396/*
1397 * Continuation lines are buffered, and not committed to the record buffer
1398 * until the line is complete, or a race forces it. The line fragments
1399 * though, are printed immediately to the consoles to ensure everything has
1400 * reached the console in case of a kernel crash.
1401 */
1402static struct cont {
1403 char buf[LOG_LINE_MAX];
1404 size_t len; /* length == 0 means unused buffer */
1405 size_t cons; /* bytes written to console */
1406 struct task_struct *owner; /* task of first print*/
1407 u64 ts_nsec; /* time of first print */
1408 u8 level; /* log level of first message */
1409 u8 facility; /* log level of first message */
eab07260 1410 enum log_flags flags; /* prefix, newline flags */
084681d1
KS
1411 bool flushed:1; /* buffer sealed and committed */
1412} cont;
1413
70498253 1414static void cont_flush(enum log_flags flags)
084681d1
KS
1415{
1416 if (cont.flushed)
1417 return;
1418 if (cont.len == 0)
1419 return;
1420
eab07260
KS
1421 if (cont.cons) {
1422 /*
1423 * If a fragment of this line was directly flushed to the
1424 * console; wait for the console to pick up the rest of the
1425 * line. LOG_NOCONS suppresses a duplicated output.
1426 */
1427 log_store(cont.facility, cont.level, flags | LOG_NOCONS,
1428 cont.ts_nsec, NULL, 0, cont.buf, cont.len);
1429 cont.flags = flags;
1430 cont.flushed = true;
1431 } else {
1432 /*
1433 * If no fragment of this line ever reached the console,
1434 * just submit it to the store and free the buffer.
1435 */
1436 log_store(cont.facility, cont.level, flags, 0,
1437 NULL, 0, cont.buf, cont.len);
1438 cont.len = 0;
1439 }
084681d1
KS
1440}
1441
1442static bool cont_add(int facility, int level, const char *text, size_t len)
1443{
1444 if (cont.len && cont.flushed)
1445 return false;
1446
1447 if (cont.len + len > sizeof(cont.buf)) {
70498253
KS
1448 /* the line gets too long, split it up in separate records */
1449 cont_flush(LOG_CONT);
084681d1
KS
1450 return false;
1451 }
1452
1453 if (!cont.len) {
1454 cont.facility = facility;
1455 cont.level = level;
1456 cont.owner = current;
1457 cont.ts_nsec = local_clock();
eab07260 1458 cont.flags = 0;
084681d1
KS
1459 cont.cons = 0;
1460 cont.flushed = false;
1461 }
1462
1463 memcpy(cont.buf + cont.len, text, len);
1464 cont.len += len;
eab07260
KS
1465
1466 if (cont.len > (sizeof(cont.buf) * 80) / 100)
1467 cont_flush(LOG_CONT);
1468
084681d1
KS
1469 return true;
1470}
1471
1472static size_t cont_print_text(char *text, size_t size)
1473{
1474 size_t textlen = 0;
1475 size_t len;
1476
eab07260 1477 if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
084681d1
KS
1478 textlen += print_time(cont.ts_nsec, text);
1479 size -= textlen;
1480 }
1481
1482 len = cont.len - cont.cons;
1483 if (len > 0) {
1484 if (len+1 > size)
1485 len = size-1;
1486 memcpy(text + textlen, cont.buf + cont.cons, len);
1487 textlen += len;
1488 cont.cons = cont.len;
1489 }
1490
1491 if (cont.flushed) {
eab07260
KS
1492 if (cont.flags & LOG_NEWLINE)
1493 text[textlen++] = '\n';
084681d1
KS
1494 /* got everything, release buffer */
1495 cont.len = 0;
1496 }
1497 return textlen;
1498}
1499
7ff9554b
KS
1500asmlinkage int vprintk_emit(int facility, int level,
1501 const char *dict, size_t dictlen,
1502 const char *fmt, va_list args)
1da177e4 1503{
7ff9554b 1504 static int recursion_bug;
7ff9554b
KS
1505 static char textbuf[LOG_LINE_MAX];
1506 char *text = textbuf;
c313af14 1507 size_t text_len;
5becfb1d 1508 enum log_flags lflags = 0;
ac60ad74 1509 unsigned long flags;
32a76006 1510 int this_cpu;
7ff9554b 1511 int printed_len = 0;
1da177e4 1512
2fa72c8f 1513 boot_delay_msec(level);
af91322e 1514 printk_delay();
bfe8df3d 1515
1da177e4 1516 /* This stops the holder of console_sem just where we want him */
1a9a8aef 1517 local_irq_save(flags);
32a76006
IM
1518 this_cpu = smp_processor_id();
1519
1520 /*
1521 * Ouch, printk recursed into itself!
1522 */
7ff9554b 1523 if (unlikely(logbuf_cpu == this_cpu)) {
32a76006
IM
1524 /*
1525 * If a crash is occurring during printk() on this CPU,
1526 * then try to get the crash message out but make sure
1527 * we can't deadlock. Otherwise just return to avoid the
1528 * recursion and return - but flag the recursion so that
1529 * it can be printed at the next appropriate moment:
1530 */
94d24fc4 1531 if (!oops_in_progress && !lockdep_recursing(current)) {
3b8945e8 1532 recursion_bug = 1;
32a76006
IM
1533 goto out_restore_irqs;
1534 }
1535 zap_locks();
1536 }
1537
a0f1ccfd 1538 lockdep_off();
07354eb1 1539 raw_spin_lock(&logbuf_lock);
7ff9554b 1540 logbuf_cpu = this_cpu;
1da177e4 1541
3b8945e8 1542 if (recursion_bug) {
7ff9554b
KS
1543 static const char recursion_msg[] =
1544 "BUG: recent printk recursion!";
1545
3b8945e8 1546 recursion_bug = 0;
7ff9554b
KS
1547 printed_len += strlen(recursion_msg);
1548 /* emit KERN_CRIT message */
5becfb1d 1549 log_store(0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
084681d1 1550 NULL, 0, recursion_msg, printed_len);
32a76006 1551 }
1da177e4 1552
7ff9554b
KS
1553 /*
1554 * The printf needs to come first; we need the syslog
1555 * prefix which might be passed-in as a parameter.
1556 */
c313af14 1557 text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
5fd29d6c 1558
7ff9554b 1559 /* mark and strip a trailing newline */
c313af14
KS
1560 if (text_len && text[text_len-1] == '\n') {
1561 text_len--;
5becfb1d 1562 lflags |= LOG_NEWLINE;
7ff9554b 1563 }
9d90c8d9 1564
088a52aa
JP
1565 /* strip kernel syslog prefix and extract log level or control flags */
1566 if (facility == 0) {
1567 int kern_level = printk_get_level(text);
1568
1569 if (kern_level) {
1570 const char *end_of_header = printk_skip_level(text);
1571 switch (kern_level) {
1572 case '0' ... '7':
1573 if (level == -1)
1574 level = kern_level - '0';
1575 case 'd': /* KERN_DEFAULT */
1576 lflags |= LOG_PREFIX;
088a52aa 1577 }
e8c42d36
PM
1578 /*
1579 * No need to check length here because vscnprintf
1580 * put '\0' at the end of the string. Only valid and
1581 * newly printed level is detected.
1582 */
088a52aa
JP
1583 text_len -= end_of_header - text;
1584 text = (char *)end_of_header;
5fd29d6c
LT
1585 }
1586 }
1587
c313af14
KS
1588 if (level == -1)
1589 level = default_message_loglevel;
9d90c8d9 1590
5becfb1d
KS
1591 if (dict)
1592 lflags |= LOG_PREFIX|LOG_NEWLINE;
ac60ad74 1593
5becfb1d 1594 if (!(lflags & LOG_NEWLINE)) {
084681d1
KS
1595 /*
1596 * Flush the conflicting buffer. An earlier newline was missing,
1597 * or another task also prints continuation lines.
1598 */
5becfb1d 1599 if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
eab07260 1600 cont_flush(LOG_NEWLINE);
c313af14 1601
084681d1
KS
1602 /* buffer line if possible, otherwise store it right away */
1603 if (!cont_add(facility, level, text, text_len))
5becfb1d 1604 log_store(facility, level, lflags | LOG_CONT, 0,
084681d1 1605 dict, dictlen, text, text_len);
5c5d5ca5 1606 } else {
084681d1 1607 bool stored = false;
c313af14 1608
084681d1 1609 /*
d3620822
SR
1610 * If an earlier newline was missing and it was the same task,
1611 * either merge it with the current buffer and flush, or if
1612 * there was a race with interrupts (prefix == true) then just
1613 * flush it out and store this line separately.
1d3fa370
AK
1614 * If the preceding printk was from a different task and missed
1615 * a newline, flush and append the newline.
084681d1 1616 */
1d3fa370
AK
1617 if (cont.len) {
1618 if (cont.owner == current && !(lflags & LOG_PREFIX))
1619 stored = cont_add(facility, level, text,
1620 text_len);
eab07260 1621 cont_flush(LOG_NEWLINE);
c313af14 1622 }
084681d1
KS
1623
1624 if (!stored)
5becfb1d 1625 log_store(facility, level, lflags, 0,
084681d1 1626 dict, dictlen, text, text_len);
1da177e4 1627 }
084681d1 1628 printed_len += text_len;
1da177e4 1629
266c2e0a 1630 /*
7ff9554b
KS
1631 * Try to acquire and then immediately release the console semaphore.
1632 * The release will print out buffers and wake up /dev/kmsg and syslog()
1633 * users.
266c2e0a 1634 *
7ff9554b
KS
1635 * The console_trylock_for_printk() function will release 'logbuf_lock'
1636 * regardless of whether it actually gets the console semaphore or not.
266c2e0a 1637 */
ac751efa
TH
1638 if (console_trylock_for_printk(this_cpu))
1639 console_unlock();
76a8ad29 1640
266c2e0a 1641 lockdep_on();
32a76006 1642out_restore_irqs:
1a9a8aef 1643 local_irq_restore(flags);
76a8ad29 1644
1da177e4
LT
1645 return printed_len;
1646}
7ff9554b
KS
1647EXPORT_SYMBOL(vprintk_emit);
1648
1649asmlinkage int vprintk(const char *fmt, va_list args)
1650{
1651 return vprintk_emit(0, -1, NULL, 0, fmt, args);
1652}
1da177e4
LT
1653EXPORT_SYMBOL(vprintk);
1654
7ff9554b
KS
1655asmlinkage int printk_emit(int facility, int level,
1656 const char *dict, size_t dictlen,
1657 const char *fmt, ...)
1658{
1659 va_list args;
1660 int r;
1661
1662 va_start(args, fmt);
1663 r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
1664 va_end(args);
1665
1666 return r;
1667}
1668EXPORT_SYMBOL(printk_emit);
1669
1670/**
1671 * printk - print a kernel message
1672 * @fmt: format string
1673 *
1674 * This is printk(). It can be called from any context. We want it to work.
1675 *
1676 * We try to grab the console_lock. If we succeed, it's easy - we log the
1677 * output and call the console drivers. If we fail to get the semaphore, we
1678 * place the output into the log buffer and return. The current holder of
1679 * the console_sem will notice the new output in console_unlock(); and will
1680 * send it to the consoles before releasing the lock.
1681 *
1682 * One effect of this deferred printing is that code which calls printk() and
1683 * then changes console_loglevel may break. This is because console_loglevel
1684 * is inspected when the actual printing occurs.
1685 *
1686 * See also:
1687 * printf(3)
1688 *
1689 * See the vsnprintf() documentation for format string extensions over C99.
1690 */
722a9f92 1691asmlinkage __visible int printk(const char *fmt, ...)
7ff9554b
KS
1692{
1693 va_list args;
1694 int r;
1695
1696#ifdef CONFIG_KGDB_KDB
1697 if (unlikely(kdb_trap_printk)) {
1698 va_start(args, fmt);
1699 r = vkdb_printf(fmt, args);
1700 va_end(args);
1701 return r;
1702 }
1703#endif
1704 va_start(args, fmt);
1705 r = vprintk_emit(0, -1, NULL, 0, fmt, args);
1706 va_end(args);
1707
1708 return r;
1709}
1710EXPORT_SYMBOL(printk);
7f3a781d 1711
96efedf1 1712#else /* CONFIG_PRINTK */
d59745ce 1713
70498253
KS
1714#define LOG_LINE_MAX 0
1715#define PREFIX_MAX 0
7f3a781d 1716#define LOG_LINE_MAX 0
96efedf1
KS
1717static u64 syslog_seq;
1718static u32 syslog_idx;
eab07260
KS
1719static u64 console_seq;
1720static u32 console_idx;
96efedf1
KS
1721static enum log_flags syslog_prev;
1722static u64 log_first_seq;
1723static u32 log_first_idx;
1724static u64 log_next_seq;
eab07260 1725static enum log_flags console_prev;
084681d1
KS
1726static struct cont {
1727 size_t len;
1728 size_t cons;
1729 u8 level;
1730 bool flushed:1;
1731} cont;
62e32ac3 1732static struct printk_log *log_from_idx(u32 idx) { return NULL; }
7f3a781d 1733static u32 log_next(u32 idx) { return 0; }
7f3a781d 1734static void call_console_drivers(int level, const char *text, size_t len) {}
62e32ac3 1735static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
5becfb1d 1736 bool syslog, char *buf, size_t size) { return 0; }
084681d1 1737static size_t cont_print_text(char *text, size_t size) { return 0; }
d59745ce 1738
7f3a781d 1739#endif /* CONFIG_PRINTK */
d59745ce 1740
d0380e6c
TG
1741#ifdef CONFIG_EARLY_PRINTK
1742struct console *early_console;
1743
1744void early_vprintk(const char *fmt, va_list ap)
1745{
1746 if (early_console) {
1747 char buf[512];
1748 int n = vscnprintf(buf, sizeof(buf), fmt, ap);
1749
1750 early_console->write(early_console, buf, n);
1751 }
1752}
1753
722a9f92 1754asmlinkage __visible void early_printk(const char *fmt, ...)
d0380e6c
TG
1755{
1756 va_list ap;
1757
1758 va_start(ap, fmt);
1759 early_vprintk(fmt, ap);
1760 va_end(ap);
1761}
1762#endif
1763
f7511d5f
ST
1764static int __add_preferred_console(char *name, int idx, char *options,
1765 char *brl_options)
1766{
1767 struct console_cmdline *c;
1768 int i;
1769
1770 /*
1771 * See if this tty is not yet registered, and
1772 * if we have a slot free.
1773 */
23475408
JP
1774 for (i = 0, c = console_cmdline;
1775 i < MAX_CMDLINECONSOLES && c->name[0];
1776 i++, c++) {
1777 if (strcmp(c->name, name) == 0 && c->index == idx) {
1778 if (!brl_options)
1779 selected_console = i;
1780 return 0;
f7511d5f 1781 }
23475408 1782 }
f7511d5f
ST
1783 if (i == MAX_CMDLINECONSOLES)
1784 return -E2BIG;
1785 if (!brl_options)
1786 selected_console = i;
f7511d5f
ST
1787 strlcpy(c->name, name, sizeof(c->name));
1788 c->options = options;
bbeddf52
JP
1789 braille_set_options(c, brl_options);
1790
f7511d5f
ST
1791 c->index = idx;
1792 return 0;
1793}
2ea1c539
JB
1794/*
1795 * Set up a list of consoles. Called from init/main.c
1796 */
1797static int __init console_setup(char *str)
1798{
eaa944af 1799 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
f7511d5f 1800 char *s, *options, *brl_options = NULL;
2ea1c539
JB
1801 int idx;
1802
bbeddf52
JP
1803 if (_braille_console_setup(&str, &brl_options))
1804 return 1;
f7511d5f 1805
2ea1c539
JB
1806 /*
1807 * Decode str into name, index, options.
1808 */
1809 if (str[0] >= '0' && str[0] <= '9') {
eaa944af
YL
1810 strcpy(buf, "ttyS");
1811 strncpy(buf + 4, str, sizeof(buf) - 5);
2ea1c539 1812 } else {
eaa944af 1813 strncpy(buf, str, sizeof(buf) - 1);
2ea1c539 1814 }
eaa944af 1815 buf[sizeof(buf) - 1] = 0;
2ea1c539
JB
1816 if ((options = strchr(str, ',')) != NULL)
1817 *(options++) = 0;
1818#ifdef __sparc__
1819 if (!strcmp(str, "ttya"))
eaa944af 1820 strcpy(buf, "ttyS0");
2ea1c539 1821 if (!strcmp(str, "ttyb"))
eaa944af 1822 strcpy(buf, "ttyS1");
2ea1c539 1823#endif
eaa944af 1824 for (s = buf; *s; s++)
2ea1c539
JB
1825 if ((*s >= '0' && *s <= '9') || *s == ',')
1826 break;
1827 idx = simple_strtoul(s, NULL, 10);
1828 *s = 0;
1829
f7511d5f 1830 __add_preferred_console(buf, idx, options, brl_options);
9e124fe1 1831 console_set_on_cmdline = 1;
2ea1c539
JB
1832 return 1;
1833}
1834__setup("console=", console_setup);
1835
3c0547ba
MM
1836/**
1837 * add_preferred_console - add a device to the list of preferred consoles.
ddad86c2
MW
1838 * @name: device name
1839 * @idx: device index
1840 * @options: options for this console
3c0547ba
MM
1841 *
1842 * The last preferred console added will be used for kernel messages
1843 * and stdin/out/err for init. Normally this is used by console_setup
1844 * above to handle user-supplied console arguments; however it can also
1845 * be used by arch-specific code either to override the user or more
1846 * commonly to provide a default console (ie from PROM variables) when
1847 * the user has not supplied one.
1848 */
fb445ee5 1849int add_preferred_console(char *name, int idx, char *options)
3c0547ba 1850{
f7511d5f 1851 return __add_preferred_console(name, idx, options, NULL);
3c0547ba
MM
1852}
1853
b6b1d877 1854int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
18a8bd94
YL
1855{
1856 struct console_cmdline *c;
1857 int i;
1858
23475408
JP
1859 for (i = 0, c = console_cmdline;
1860 i < MAX_CMDLINECONSOLES && c->name[0];
1861 i++, c++)
1862 if (strcmp(c->name, name) == 0 && c->index == idx) {
1863 strlcpy(c->name, name_new, sizeof(c->name));
1864 c->name[sizeof(c->name) - 1] = 0;
1865 c->options = options;
1866 c->index = idx_new;
1867 return i;
18a8bd94
YL
1868 }
1869 /* not found */
1870 return -1;
1871}
1872
2329abfa 1873bool console_suspend_enabled = 1;
8f4ce8c3
AS
1874EXPORT_SYMBOL(console_suspend_enabled);
1875
1876static int __init console_suspend_disable(char *str)
1877{
1878 console_suspend_enabled = 0;
1879 return 1;
1880}
1881__setup("no_console_suspend", console_suspend_disable);
134620f7
YZ
1882module_param_named(console_suspend, console_suspend_enabled,
1883 bool, S_IRUGO | S_IWUSR);
1884MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
1885 " and hibernate operations");
8f4ce8c3 1886
557240b4
LT
1887/**
1888 * suspend_console - suspend the console subsystem
1889 *
1890 * This disables printk() while we go into suspend states
1891 */
1892void suspend_console(void)
1893{
8f4ce8c3
AS
1894 if (!console_suspend_enabled)
1895 return;
0d63081d 1896 printk("Suspending console(s) (use no_console_suspend to debug)\n");
ac751efa 1897 console_lock();
557240b4 1898 console_suspended = 1;
403f3075 1899 up(&console_sem);
72581487 1900 mutex_release(&console_lock_dep_map, 1, _RET_IP_);
557240b4
LT
1901}
1902
1903void resume_console(void)
1904{
8f4ce8c3
AS
1905 if (!console_suspend_enabled)
1906 return;
403f3075 1907 down(&console_sem);
72581487 1908 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);
557240b4 1909 console_suspended = 0;
ac751efa 1910 console_unlock();
557240b4
LT
1911}
1912
034260d6
KC
1913/**
1914 * console_cpu_notify - print deferred console messages after CPU hotplug
1915 * @self: notifier struct
1916 * @action: CPU hotplug event
1917 * @hcpu: unused
1918 *
1919 * If printk() is called from a CPU that is not online yet, the messages
1920 * will be spooled but will not show up on the console. This function is
1921 * called when a new CPU comes online (or fails to come up), and ensures
1922 * that any such output gets printed.
1923 */
0db0628d 1924static int console_cpu_notify(struct notifier_block *self,
034260d6
KC
1925 unsigned long action, void *hcpu)
1926{
1927 switch (action) {
1928 case CPU_ONLINE:
1929 case CPU_DEAD:
034260d6
KC
1930 case CPU_DOWN_FAILED:
1931 case CPU_UP_CANCELED:
ac751efa
TH
1932 console_lock();
1933 console_unlock();
034260d6
KC
1934 }
1935 return NOTIFY_OK;
1936}
1937
1da177e4 1938/**
ac751efa 1939 * console_lock - lock the console system for exclusive use.
1da177e4 1940 *
ac751efa 1941 * Acquires a lock which guarantees that the caller has
1da177e4
LT
1942 * exclusive access to the console system and the console_drivers list.
1943 *
1944 * Can sleep, returns nothing.
1945 */
ac751efa 1946void console_lock(void)
1da177e4 1947{
6b898c07
DV
1948 might_sleep();
1949
1da177e4 1950 down(&console_sem);
403f3075
AH
1951 if (console_suspended)
1952 return;
1da177e4
LT
1953 console_locked = 1;
1954 console_may_schedule = 1;
daee7797 1955 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);
1da177e4 1956}
ac751efa 1957EXPORT_SYMBOL(console_lock);
1da177e4 1958
ac751efa
TH
1959/**
1960 * console_trylock - try to lock the console system for exclusive use.
1961 *
1962 * Tried to acquire a lock which guarantees that the caller has
1963 * exclusive access to the console system and the console_drivers list.
1964 *
1965 * returns 1 on success, and 0 on failure to acquire the lock.
1966 */
1967int console_trylock(void)
1da177e4
LT
1968{
1969 if (down_trylock(&console_sem))
ac751efa 1970 return 0;
403f3075
AH
1971 if (console_suspended) {
1972 up(&console_sem);
ac751efa 1973 return 0;
403f3075 1974 }
1da177e4
LT
1975 console_locked = 1;
1976 console_may_schedule = 0;
daee7797 1977 mutex_acquire(&console_lock_dep_map, 0, 1, _RET_IP_);
ac751efa 1978 return 1;
1da177e4 1979}
ac751efa 1980EXPORT_SYMBOL(console_trylock);
1da177e4
LT
1981
1982int is_console_locked(void)
1983{
1984 return console_locked;
1985}
1da177e4 1986
eab07260
KS
1987static void console_cont_flush(char *text, size_t size)
1988{
1989 unsigned long flags;
1990 size_t len;
1991
1992 raw_spin_lock_irqsave(&logbuf_lock, flags);
1993
1994 if (!cont.len)
1995 goto out;
1996
1997 /*
1998 * We still queue earlier records, likely because the console was
1999 * busy. The earlier ones need to be printed before this one, we
2000 * did not flush any fragment so far, so just let it queue up.
2001 */
2002 if (console_seq < log_next_seq && !cont.cons)
2003 goto out;
2004
2005 len = cont_print_text(text, size);
2006 raw_spin_unlock(&logbuf_lock);
2007 stop_critical_timings();
2008 call_console_drivers(cont.level, text, len);
2009 start_critical_timings();
2010 local_irq_restore(flags);
2011 return;
2012out:
2013 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2014}
7ff9554b 2015
1da177e4 2016/**
ac751efa 2017 * console_unlock - unlock the console system
1da177e4 2018 *
ac751efa 2019 * Releases the console_lock which the caller holds on the console system
1da177e4
LT
2020 * and the console driver list.
2021 *
ac751efa
TH
2022 * While the console_lock was held, console output may have been buffered
2023 * by printk(). If this is the case, console_unlock(); emits
2024 * the output prior to releasing the lock.
1da177e4 2025 *
7f3a781d 2026 * If there is output waiting, we wake /dev/kmsg and syslog() users.
1da177e4 2027 *
ac751efa 2028 * console_unlock(); may be called from any context.
1da177e4 2029 */
ac751efa 2030void console_unlock(void)
1da177e4 2031{
70498253 2032 static char text[LOG_LINE_MAX + PREFIX_MAX];
7ff9554b 2033 static u64 seen_seq;
1da177e4 2034 unsigned long flags;
7ff9554b
KS
2035 bool wake_klogd = false;
2036 bool retry;
1da177e4 2037
557240b4 2038 if (console_suspended) {
403f3075 2039 up(&console_sem);
557240b4
LT
2040 return;
2041 }
78944e54
AD
2042
2043 console_may_schedule = 0;
2044
084681d1 2045 /* flush buffered message fragment immediately to console */
eab07260 2046 console_cont_flush(text, sizeof(text));
4f2a8d3c 2047again:
7ff9554b 2048 for (;;) {
62e32ac3 2049 struct printk_log *msg;
3ce9a7c0 2050 size_t len;
7ff9554b
KS
2051 int level;
2052
07354eb1 2053 raw_spin_lock_irqsave(&logbuf_lock, flags);
7ff9554b
KS
2054 if (seen_seq != log_next_seq) {
2055 wake_klogd = true;
2056 seen_seq = log_next_seq;
2057 }
2058
2059 if (console_seq < log_first_seq) {
2060 /* messages are gone, move to first one */
2061 console_seq = log_first_seq;
2062 console_idx = log_first_idx;
5becfb1d 2063 console_prev = 0;
7ff9554b 2064 }
084681d1 2065skip:
7ff9554b
KS
2066 if (console_seq == log_next_seq)
2067 break;
2068
2069 msg = log_from_idx(console_idx);
084681d1
KS
2070 if (msg->flags & LOG_NOCONS) {
2071 /*
2072 * Skip record we have buffered and already printed
2073 * directly to the console when we received it.
2074 */
2075 console_idx = log_next(console_idx);
2076 console_seq++;
68b6507d
KS
2077 /*
2078 * We will get here again when we register a new
2079 * CON_PRINTBUFFER console. Clear the flag so we
2080 * will properly dump everything later.
2081 */
2082 msg->flags &= ~LOG_NOCONS;
eab07260 2083 console_prev = msg->flags;
084681d1
KS
2084 goto skip;
2085 }
649e6ee3 2086
084681d1 2087 level = msg->level;
5becfb1d
KS
2088 len = msg_print_text(msg, console_prev, false,
2089 text, sizeof(text));
7ff9554b
KS
2090 console_idx = log_next(console_idx);
2091 console_seq++;
5becfb1d 2092 console_prev = msg->flags;
07354eb1 2093 raw_spin_unlock(&logbuf_lock);
7ff9554b 2094
81d68a96 2095 stop_critical_timings(); /* don't trace print latency */
7ff9554b 2096 call_console_drivers(level, text, len);
81d68a96 2097 start_critical_timings();
1da177e4
LT
2098 local_irq_restore(flags);
2099 }
2100 console_locked = 0;
daee7797 2101 mutex_release(&console_lock_dep_map, 1, _RET_IP_);
fe3d8ad3
FT
2102
2103 /* Release the exclusive_console once it is used */
2104 if (unlikely(exclusive_console))
2105 exclusive_console = NULL;
2106
07354eb1 2107 raw_spin_unlock(&logbuf_lock);
4f2a8d3c 2108
0b5e1c52 2109 up(&console_sem);
4f2a8d3c
PZ
2110
2111 /*
2112 * Someone could have filled up the buffer again, so re-check if there's
2113 * something to flush. In case we cannot trylock the console_sem again,
2114 * there's a new owner and the console_unlock() from them will do the
2115 * flush, no worries.
2116 */
07354eb1 2117 raw_spin_lock(&logbuf_lock);
7ff9554b 2118 retry = console_seq != log_next_seq;
09dc3cf9
PZ
2119 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2120
4f2a8d3c
PZ
2121 if (retry && console_trylock())
2122 goto again;
2123
e3e8a75d
KK
2124 if (wake_klogd)
2125 wake_up_klogd();
1da177e4 2126}
ac751efa 2127EXPORT_SYMBOL(console_unlock);
1da177e4 2128
ddad86c2
MW
2129/**
2130 * console_conditional_schedule - yield the CPU if required
1da177e4
LT
2131 *
2132 * If the console code is currently allowed to sleep, and
2133 * if this CPU should yield the CPU to another task, do
2134 * so here.
2135 *
ac751efa 2136 * Must be called within console_lock();.
1da177e4
LT
2137 */
2138void __sched console_conditional_schedule(void)
2139{
2140 if (console_may_schedule)
2141 cond_resched();
2142}
2143EXPORT_SYMBOL(console_conditional_schedule);
2144
1da177e4
LT
2145void console_unblank(void)
2146{
2147 struct console *c;
2148
2149 /*
2150 * console_unblank can no longer be called in interrupt context unless
2151 * oops_in_progress is set to 1..
2152 */
2153 if (oops_in_progress) {
2154 if (down_trylock(&console_sem) != 0)
2155 return;
2156 } else
ac751efa 2157 console_lock();
1da177e4
LT
2158
2159 console_locked = 1;
2160 console_may_schedule = 0;
4d091611 2161 for_each_console(c)
1da177e4
LT
2162 if ((c->flags & CON_ENABLED) && c->unblank)
2163 c->unblank();
ac751efa 2164 console_unlock();
1da177e4 2165}
1da177e4
LT
2166
2167/*
2168 * Return the console tty driver structure and its associated index
2169 */
2170struct tty_driver *console_device(int *index)
2171{
2172 struct console *c;
2173 struct tty_driver *driver = NULL;
2174
ac751efa 2175 console_lock();
4d091611 2176 for_each_console(c) {
1da177e4
LT
2177 if (!c->device)
2178 continue;
2179 driver = c->device(c, index);
2180 if (driver)
2181 break;
2182 }
ac751efa 2183 console_unlock();
1da177e4
LT
2184 return driver;
2185}
2186
2187/*
2188 * Prevent further output on the passed console device so that (for example)
2189 * serial drivers can disable console output before suspending a port, and can
2190 * re-enable output afterwards.
2191 */
2192void console_stop(struct console *console)
2193{
ac751efa 2194 console_lock();
1da177e4 2195 console->flags &= ~CON_ENABLED;
ac751efa 2196 console_unlock();
1da177e4
LT
2197}
2198EXPORT_SYMBOL(console_stop);
2199
2200void console_start(struct console *console)
2201{
ac751efa 2202 console_lock();
1da177e4 2203 console->flags |= CON_ENABLED;
ac751efa 2204 console_unlock();
1da177e4
LT
2205}
2206EXPORT_SYMBOL(console_start);
2207
7bf69395
FDN
2208static int __read_mostly keep_bootcon;
2209
2210static int __init keep_bootcon_setup(char *str)
2211{
2212 keep_bootcon = 1;
27083bac 2213 pr_info("debug: skip boot console de-registration.\n");
7bf69395
FDN
2214
2215 return 0;
2216}
2217
2218early_param("keep_bootcon", keep_bootcon_setup);
2219
1da177e4
LT
2220/*
2221 * The console driver calls this routine during kernel initialization
2222 * to register the console printing procedure with printk() and to
2223 * print any messages that were printed by the kernel before the
2224 * console driver was initialized.
4d091611
RG
2225 *
2226 * This can happen pretty early during the boot process (because of
2227 * early_printk) - sometimes before setup_arch() completes - be careful
2228 * of what kernel features are used - they may not be initialised yet.
2229 *
2230 * There are two types of consoles - bootconsoles (early_printk) and
2231 * "real" consoles (everything which is not a bootconsole) which are
2232 * handled differently.
2233 * - Any number of bootconsoles can be registered at any time.
2234 * - As soon as a "real" console is registered, all bootconsoles
2235 * will be unregistered automatically.
2236 * - Once a "real" console is registered, any attempt to register a
2237 * bootconsoles will be rejected
1da177e4 2238 */
4d091611 2239void register_console(struct console *newcon)
1da177e4 2240{
40dc5651 2241 int i;
1da177e4 2242 unsigned long flags;
4d091611 2243 struct console *bcon = NULL;
23475408 2244 struct console_cmdline *c;
1da177e4 2245
16cf48a6
AB
2246 if (console_drivers)
2247 for_each_console(bcon)
2248 if (WARN(bcon == newcon,
2249 "console '%s%d' already registered\n",
2250 bcon->name, bcon->index))
2251 return;
2252
4d091611
RG
2253 /*
2254 * before we register a new CON_BOOT console, make sure we don't
2255 * already have a valid console
2256 */
2257 if (console_drivers && newcon->flags & CON_BOOT) {
2258 /* find the last or real console */
2259 for_each_console(bcon) {
2260 if (!(bcon->flags & CON_BOOT)) {
27083bac 2261 pr_info("Too late to register bootconsole %s%d\n",
4d091611
RG
2262 newcon->name, newcon->index);
2263 return;
2264 }
2265 }
69331af7
GH
2266 }
2267
4d091611
RG
2268 if (console_drivers && console_drivers->flags & CON_BOOT)
2269 bcon = console_drivers;
2270
2271 if (preferred_console < 0 || bcon || !console_drivers)
1da177e4
LT
2272 preferred_console = selected_console;
2273
4d091611
RG
2274 if (newcon->early_setup)
2275 newcon->early_setup();
18a8bd94 2276
1da177e4
LT
2277 /*
2278 * See if we want to use this console driver. If we
2279 * didn't select a console we take the first one
2280 * that registers here.
2281 */
2282 if (preferred_console < 0) {
4d091611
RG
2283 if (newcon->index < 0)
2284 newcon->index = 0;
2285 if (newcon->setup == NULL ||
2286 newcon->setup(newcon, NULL) == 0) {
2287 newcon->flags |= CON_ENABLED;
2288 if (newcon->device) {
2289 newcon->flags |= CON_CONSDEV;
cd3a1b85
JK
2290 preferred_console = 0;
2291 }
1da177e4
LT
2292 }
2293 }
2294
2295 /*
2296 * See if this console matches one we selected on
2297 * the command line.
2298 */
23475408
JP
2299 for (i = 0, c = console_cmdline;
2300 i < MAX_CMDLINECONSOLES && c->name[0];
2301 i++, c++) {
2302 if (strcmp(c->name, newcon->name) != 0)
1da177e4 2303 continue;
4d091611 2304 if (newcon->index >= 0 &&
23475408 2305 newcon->index != c->index)
1da177e4 2306 continue;
4d091611 2307 if (newcon->index < 0)
23475408 2308 newcon->index = c->index;
bbeddf52 2309
23475408 2310 if (_braille_register_console(newcon, c))
f7511d5f 2311 return;
bbeddf52 2312
4d091611
RG
2313 if (newcon->setup &&
2314 newcon->setup(newcon, console_cmdline[i].options) != 0)
1da177e4 2315 break;
4d091611 2316 newcon->flags |= CON_ENABLED;
23475408 2317 newcon->index = c->index;
ab4af03a 2318 if (i == selected_console) {
4d091611 2319 newcon->flags |= CON_CONSDEV;
ab4af03a
GE
2320 preferred_console = selected_console;
2321 }
1da177e4
LT
2322 break;
2323 }
2324
4d091611 2325 if (!(newcon->flags & CON_ENABLED))
1da177e4
LT
2326 return;
2327
8259cf43
RG
2328 /*
2329 * If we have a bootconsole, and are switching to a real console,
2330 * don't print everything out again, since when the boot console, and
2331 * the real console are the same physical device, it's annoying to
2332 * see the beginning boot messages twice
2333 */
2334 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
4d091611 2335 newcon->flags &= ~CON_PRINTBUFFER;
1da177e4
LT
2336
2337 /*
2338 * Put this console in the list - keep the
2339 * preferred driver at the head of the list.
2340 */
ac751efa 2341 console_lock();
4d091611
RG
2342 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2343 newcon->next = console_drivers;
2344 console_drivers = newcon;
2345 if (newcon->next)
2346 newcon->next->flags &= ~CON_CONSDEV;
1da177e4 2347 } else {
4d091611
RG
2348 newcon->next = console_drivers->next;
2349 console_drivers->next = newcon;
1da177e4 2350 }
4d091611 2351 if (newcon->flags & CON_PRINTBUFFER) {
1da177e4 2352 /*
ac751efa 2353 * console_unlock(); will print out the buffered messages
1da177e4
LT
2354 * for us.
2355 */
07354eb1 2356 raw_spin_lock_irqsave(&logbuf_lock, flags);
7ff9554b
KS
2357 console_seq = syslog_seq;
2358 console_idx = syslog_idx;
5becfb1d 2359 console_prev = syslog_prev;
07354eb1 2360 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
fe3d8ad3
FT
2361 /*
2362 * We're about to replay the log buffer. Only do this to the
2363 * just-registered console to avoid excessive message spam to
2364 * the already-registered consoles.
2365 */
2366 exclusive_console = newcon;
1da177e4 2367 }
ac751efa 2368 console_unlock();
fbc92a34 2369 console_sysfs_notify();
8259cf43
RG
2370
2371 /*
2372 * By unregistering the bootconsoles after we enable the real console
2373 * we get the "console xxx enabled" message on all the consoles -
2374 * boot consoles, real consoles, etc - this is to ensure that end
2375 * users know there might be something in the kernel's log buffer that
2376 * went to the bootconsole (that they do not see on the real console)
2377 */
27083bac 2378 pr_info("%sconsole [%s%d] enabled\n",
6b802394
KC
2379 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2380 newcon->name, newcon->index);
7bf69395
FDN
2381 if (bcon &&
2382 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2383 !keep_bootcon) {
6b802394
KC
2384 /* We need to iterate through all boot consoles, to make
2385 * sure we print everything out, before we unregister them.
8259cf43 2386 */
8259cf43
RG
2387 for_each_console(bcon)
2388 if (bcon->flags & CON_BOOT)
2389 unregister_console(bcon);
8259cf43 2390 }
1da177e4
LT
2391}
2392EXPORT_SYMBOL(register_console);
2393
40dc5651 2394int unregister_console(struct console *console)
1da177e4 2395{
40dc5651 2396 struct console *a, *b;
bbeddf52 2397 int res;
1da177e4 2398
27083bac 2399 pr_info("%sconsole [%s%d] disabled\n",
6b802394
KC
2400 (console->flags & CON_BOOT) ? "boot" : "" ,
2401 console->name, console->index);
2402
bbeddf52
JP
2403 res = _braille_unregister_console(console);
2404 if (res)
2405 return res;
f7511d5f 2406
bbeddf52 2407 res = 1;
ac751efa 2408 console_lock();
1da177e4
LT
2409 if (console_drivers == console) {
2410 console_drivers=console->next;
2411 res = 0;
e9b15b54 2412 } else if (console_drivers) {
1da177e4
LT
2413 for (a=console_drivers->next, b=console_drivers ;
2414 a; b=a, a=b->next) {
2415 if (a == console) {
2416 b->next = a->next;
2417 res = 0;
2418 break;
40dc5651 2419 }
1da177e4
LT
2420 }
2421 }
40dc5651 2422
69331af7 2423 /*
ab4af03a
GE
2424 * If this isn't the last console and it has CON_CONSDEV set, we
2425 * need to set it on the next preferred console.
1da177e4 2426 */
69331af7 2427 if (console_drivers != NULL && console->flags & CON_CONSDEV)
ab4af03a 2428 console_drivers->flags |= CON_CONSDEV;
1da177e4 2429
7fa21dd8 2430 console->flags &= ~CON_ENABLED;
ac751efa 2431 console_unlock();
fbc92a34 2432 console_sysfs_notify();
1da177e4
LT
2433 return res;
2434}
2435EXPORT_SYMBOL(unregister_console);
d59745ce 2436
034260d6 2437static int __init printk_late_init(void)
0c5564bd 2438{
4d091611
RG
2439 struct console *con;
2440
2441 for_each_console(con) {
4c30c6f5 2442 if (!keep_bootcon && con->flags & CON_BOOT) {
42c2c8c8 2443 unregister_console(con);
cb00e99c 2444 }
0c5564bd 2445 }
034260d6 2446 hotcpu_notifier(console_cpu_notify, 0);
0c5564bd
RG
2447 return 0;
2448}
034260d6 2449late_initcall(printk_late_init);
0c5564bd 2450
7ef3d2fd 2451#if defined CONFIG_PRINTK
dc72c32e
FW
2452/*
2453 * Delayed printk version, for scheduler-internal messages:
2454 */
2455#define PRINTK_BUF_SIZE 512
2456
2457#define PRINTK_PENDING_WAKEUP 0x01
2458#define PRINTK_PENDING_SCHED 0x02
2459
2460static DEFINE_PER_CPU(int, printk_pending);
2461static DEFINE_PER_CPU(char [PRINTK_BUF_SIZE], printk_sched_buf);
2462
2463static void wake_up_klogd_work_func(struct irq_work *irq_work)
2464{
2465 int pending = __this_cpu_xchg(printk_pending, 0);
2466
2467 if (pending & PRINTK_PENDING_SCHED) {
2468 char *buf = __get_cpu_var(printk_sched_buf);
27083bac 2469 pr_warn("[sched_delayed] %s", buf);
dc72c32e
FW
2470 }
2471
2472 if (pending & PRINTK_PENDING_WAKEUP)
2473 wake_up_interruptible(&log_wait);
2474}
2475
2476static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
2477 .func = wake_up_klogd_work_func,
2478 .flags = IRQ_WORK_LAZY,
2479};
2480
2481void wake_up_klogd(void)
2482{
2483 preempt_disable();
2484 if (waitqueue_active(&log_wait)) {
2485 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
2486 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
2487 }
2488 preempt_enable();
2489}
717115e1 2490
600e1458
PZ
2491int printk_sched(const char *fmt, ...)
2492{
2493 unsigned long flags;
2494 va_list args;
2495 char *buf;
2496 int r;
2497
2498 local_irq_save(flags);
2499 buf = __get_cpu_var(printk_sched_buf);
2500
2501 va_start(args, fmt);
2502 r = vsnprintf(buf, PRINTK_BUF_SIZE, fmt, args);
2503 va_end(args);
2504
2505 __this_cpu_or(printk_pending, PRINTK_PENDING_SCHED);
74876a98 2506 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
600e1458
PZ
2507 local_irq_restore(flags);
2508
2509 return r;
2510}
2511
1da177e4
LT
2512/*
2513 * printk rate limiting, lifted from the networking subsystem.
2514 *
641de9d8
UKK
2515 * This enforces a rate limit: not more than 10 kernel messages
2516 * every 5s to make a denial-of-service attack impossible.
1da177e4 2517 */
641de9d8
UKK
2518DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
2519
5c828713 2520int __printk_ratelimit(const char *func)
1da177e4 2521{
5c828713 2522 return ___ratelimit(&printk_ratelimit_state, func);
1da177e4 2523}
5c828713 2524EXPORT_SYMBOL(__printk_ratelimit);
f46c4833
AM
2525
2526/**
2527 * printk_timed_ratelimit - caller-controlled printk ratelimiting
2528 * @caller_jiffies: pointer to caller's state
2529 * @interval_msecs: minimum interval between prints
2530 *
2531 * printk_timed_ratelimit() returns true if more than @interval_msecs
2532 * milliseconds have elapsed since the last time printk_timed_ratelimit()
2533 * returned true.
2534 */
2535bool printk_timed_ratelimit(unsigned long *caller_jiffies,
2536 unsigned int interval_msecs)
2537{
f2d28a2e
GK
2538 if (*caller_jiffies == 0
2539 || !time_in_range(jiffies, *caller_jiffies,
2540 *caller_jiffies
2541 + msecs_to_jiffies(interval_msecs))) {
2542 *caller_jiffies = jiffies;
f46c4833
AM
2543 return true;
2544 }
2545 return false;
2546}
2547EXPORT_SYMBOL(printk_timed_ratelimit);
456b565c
SK
2548
2549static DEFINE_SPINLOCK(dump_list_lock);
2550static LIST_HEAD(dump_list);
2551
2552/**
2553 * kmsg_dump_register - register a kernel log dumper.
6485536b 2554 * @dumper: pointer to the kmsg_dumper structure
456b565c
SK
2555 *
2556 * Adds a kernel log dumper to the system. The dump callback in the
2557 * structure will be called when the kernel oopses or panics and must be
2558 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
2559 */
2560int kmsg_dump_register(struct kmsg_dumper *dumper)
2561{
2562 unsigned long flags;
2563 int err = -EBUSY;
2564
2565 /* The dump callback needs to be set */
2566 if (!dumper->dump)
2567 return -EINVAL;
2568
2569 spin_lock_irqsave(&dump_list_lock, flags);
2570 /* Don't allow registering multiple times */
2571 if (!dumper->registered) {
2572 dumper->registered = 1;
fb842b00 2573 list_add_tail_rcu(&dumper->list, &dump_list);
456b565c
SK
2574 err = 0;
2575 }
2576 spin_unlock_irqrestore(&dump_list_lock, flags);
2577
2578 return err;
2579}
2580EXPORT_SYMBOL_GPL(kmsg_dump_register);
2581
2582/**
2583 * kmsg_dump_unregister - unregister a kmsg dumper.
6485536b 2584 * @dumper: pointer to the kmsg_dumper structure
456b565c
SK
2585 *
2586 * Removes a dump device from the system. Returns zero on success and
2587 * %-EINVAL otherwise.
2588 */
2589int kmsg_dump_unregister(struct kmsg_dumper *dumper)
2590{
2591 unsigned long flags;
2592 int err = -EINVAL;
2593
2594 spin_lock_irqsave(&dump_list_lock, flags);
2595 if (dumper->registered) {
2596 dumper->registered = 0;
fb842b00 2597 list_del_rcu(&dumper->list);
456b565c
SK
2598 err = 0;
2599 }
2600 spin_unlock_irqrestore(&dump_list_lock, flags);
fb842b00 2601 synchronize_rcu();
456b565c
SK
2602
2603 return err;
2604}
2605EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
2606
7ff9554b
KS
2607static bool always_kmsg_dump;
2608module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
2609
456b565c
SK
2610/**
2611 * kmsg_dump - dump kernel log to kernel message dumpers.
2612 * @reason: the reason (oops, panic etc) for dumping
2613 *
e2ae715d
KS
2614 * Call each of the registered dumper's dump() callback, which can
2615 * retrieve the kmsg records with kmsg_dump_get_line() or
2616 * kmsg_dump_get_buffer().
456b565c
SK
2617 */
2618void kmsg_dump(enum kmsg_dump_reason reason)
2619{
456b565c 2620 struct kmsg_dumper *dumper;
456b565c
SK
2621 unsigned long flags;
2622
c22ab332
MG
2623 if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
2624 return;
2625
e2ae715d
KS
2626 rcu_read_lock();
2627 list_for_each_entry_rcu(dumper, &dump_list, list) {
2628 if (dumper->max_reason && reason > dumper->max_reason)
2629 continue;
2630
2631 /* initialize iterator with data about the stored records */
2632 dumper->active = true;
2633
2634 raw_spin_lock_irqsave(&logbuf_lock, flags);
2635 dumper->cur_seq = clear_seq;
2636 dumper->cur_idx = clear_idx;
2637 dumper->next_seq = log_next_seq;
2638 dumper->next_idx = log_next_idx;
2639 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2640
2641 /* invoke dumper which will iterate over records */
2642 dumper->dump(dumper, reason);
2643
2644 /* reset iterator */
2645 dumper->active = false;
2646 }
2647 rcu_read_unlock();
2648}
2649
2650/**
533827c9 2651 * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
e2ae715d
KS
2652 * @dumper: registered kmsg dumper
2653 * @syslog: include the "<4>" prefixes
2654 * @line: buffer to copy the line to
2655 * @size: maximum size of the buffer
2656 * @len: length of line placed into buffer
2657 *
2658 * Start at the beginning of the kmsg buffer, with the oldest kmsg
2659 * record, and copy one record into the provided buffer.
2660 *
2661 * Consecutive calls will return the next available record moving
2662 * towards the end of the buffer with the youngest messages.
2663 *
2664 * A return value of FALSE indicates that there are no more records to
2665 * read.
533827c9
AV
2666 *
2667 * The function is similar to kmsg_dump_get_line(), but grabs no locks.
e2ae715d 2668 */
533827c9
AV
2669bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
2670 char *line, size_t size, size_t *len)
e2ae715d 2671{
62e32ac3 2672 struct printk_log *msg;
e2ae715d
KS
2673 size_t l = 0;
2674 bool ret = false;
2675
2676 if (!dumper->active)
2677 goto out;
7ff9554b 2678
e2ae715d
KS
2679 if (dumper->cur_seq < log_first_seq) {
2680 /* messages are gone, move to first available one */
2681 dumper->cur_seq = log_first_seq;
2682 dumper->cur_idx = log_first_idx;
2683 }
456b565c 2684
e2ae715d 2685 /* last entry */
533827c9 2686 if (dumper->cur_seq >= log_next_seq)
e2ae715d 2687 goto out;
456b565c 2688
e2ae715d 2689 msg = log_from_idx(dumper->cur_idx);
5becfb1d 2690 l = msg_print_text(msg, 0, syslog, line, size);
e2ae715d
KS
2691
2692 dumper->cur_idx = log_next(dumper->cur_idx);
2693 dumper->cur_seq++;
2694 ret = true;
e2ae715d
KS
2695out:
2696 if (len)
2697 *len = l;
2698 return ret;
2699}
533827c9
AV
2700
2701/**
2702 * kmsg_dump_get_line - retrieve one kmsg log line
2703 * @dumper: registered kmsg dumper
2704 * @syslog: include the "<4>" prefixes
2705 * @line: buffer to copy the line to
2706 * @size: maximum size of the buffer
2707 * @len: length of line placed into buffer
2708 *
2709 * Start at the beginning of the kmsg buffer, with the oldest kmsg
2710 * record, and copy one record into the provided buffer.
2711 *
2712 * Consecutive calls will return the next available record moving
2713 * towards the end of the buffer with the youngest messages.
2714 *
2715 * A return value of FALSE indicates that there are no more records to
2716 * read.
2717 */
2718bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
2719 char *line, size_t size, size_t *len)
2720{
2721 unsigned long flags;
2722 bool ret;
2723
2724 raw_spin_lock_irqsave(&logbuf_lock, flags);
2725 ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
2726 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2727
2728 return ret;
2729}
e2ae715d
KS
2730EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
2731
2732/**
2733 * kmsg_dump_get_buffer - copy kmsg log lines
2734 * @dumper: registered kmsg dumper
2735 * @syslog: include the "<4>" prefixes
4f0f4af5 2736 * @buf: buffer to copy the line to
e2ae715d
KS
2737 * @size: maximum size of the buffer
2738 * @len: length of line placed into buffer
2739 *
2740 * Start at the end of the kmsg buffer and fill the provided buffer
2741 * with as many of the the *youngest* kmsg records that fit into it.
2742 * If the buffer is large enough, all available kmsg records will be
2743 * copied with a single call.
2744 *
2745 * Consecutive calls will fill the buffer with the next block of
2746 * available older records, not including the earlier retrieved ones.
2747 *
2748 * A return value of FALSE indicates that there are no more records to
2749 * read.
2750 */
2751bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
2752 char *buf, size_t size, size_t *len)
2753{
2754 unsigned long flags;
2755 u64 seq;
2756 u32 idx;
2757 u64 next_seq;
2758 u32 next_idx;
5becfb1d 2759 enum log_flags prev;
e2ae715d
KS
2760 size_t l = 0;
2761 bool ret = false;
2762
2763 if (!dumper->active)
2764 goto out;
2765
2766 raw_spin_lock_irqsave(&logbuf_lock, flags);
2767 if (dumper->cur_seq < log_first_seq) {
2768 /* messages are gone, move to first available one */
2769 dumper->cur_seq = log_first_seq;
2770 dumper->cur_idx = log_first_idx;
2771 }
2772
2773 /* last entry */
2774 if (dumper->cur_seq >= dumper->next_seq) {
2775 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2776 goto out;
2777 }
2778
2779 /* calculate length of entire buffer */
2780 seq = dumper->cur_seq;
2781 idx = dumper->cur_idx;
5becfb1d 2782 prev = 0;
e2ae715d 2783 while (seq < dumper->next_seq) {
62e32ac3 2784 struct printk_log *msg = log_from_idx(idx);
e2ae715d 2785
5becfb1d 2786 l += msg_print_text(msg, prev, true, NULL, 0);
e2ae715d
KS
2787 idx = log_next(idx);
2788 seq++;
5becfb1d 2789 prev = msg->flags;
e2ae715d
KS
2790 }
2791
2792 /* move first record forward until length fits into the buffer */
2793 seq = dumper->cur_seq;
2794 idx = dumper->cur_idx;
5becfb1d 2795 prev = 0;
e2ae715d 2796 while (l > size && seq < dumper->next_seq) {
62e32ac3 2797 struct printk_log *msg = log_from_idx(idx);
456b565c 2798
5becfb1d 2799 l -= msg_print_text(msg, prev, true, NULL, 0);
e2ae715d
KS
2800 idx = log_next(idx);
2801 seq++;
5becfb1d 2802 prev = msg->flags;
456b565c 2803 }
e2ae715d
KS
2804
2805 /* last message in next interation */
2806 next_seq = seq;
2807 next_idx = idx;
2808
2809 l = 0;
2810 while (seq < dumper->next_seq) {
62e32ac3 2811 struct printk_log *msg = log_from_idx(idx);
e2ae715d 2812
5becfb1d 2813 l += msg_print_text(msg, prev, syslog, buf + l, size - l);
e2ae715d
KS
2814 idx = log_next(idx);
2815 seq++;
5becfb1d 2816 prev = msg->flags;
e2ae715d
KS
2817 }
2818
2819 dumper->next_seq = next_seq;
2820 dumper->next_idx = next_idx;
2821 ret = true;
7ff9554b 2822 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
e2ae715d
KS
2823out:
2824 if (len)
2825 *len = l;
2826 return ret;
2827}
2828EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
456b565c 2829
533827c9
AV
2830/**
2831 * kmsg_dump_rewind_nolock - reset the interator (unlocked version)
2832 * @dumper: registered kmsg dumper
2833 *
2834 * Reset the dumper's iterator so that kmsg_dump_get_line() and
2835 * kmsg_dump_get_buffer() can be called again and used multiple
2836 * times within the same dumper.dump() callback.
2837 *
2838 * The function is similar to kmsg_dump_rewind(), but grabs no locks.
2839 */
2840void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
2841{
2842 dumper->cur_seq = clear_seq;
2843 dumper->cur_idx = clear_idx;
2844 dumper->next_seq = log_next_seq;
2845 dumper->next_idx = log_next_idx;
2846}
2847
e2ae715d
KS
2848/**
2849 * kmsg_dump_rewind - reset the interator
2850 * @dumper: registered kmsg dumper
2851 *
2852 * Reset the dumper's iterator so that kmsg_dump_get_line() and
2853 * kmsg_dump_get_buffer() can be called again and used multiple
2854 * times within the same dumper.dump() callback.
2855 */
2856void kmsg_dump_rewind(struct kmsg_dumper *dumper)
2857{
2858 unsigned long flags;
2859
2860 raw_spin_lock_irqsave(&logbuf_lock, flags);
533827c9 2861 kmsg_dump_rewind_nolock(dumper);
e2ae715d 2862 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
456b565c 2863}
e2ae715d 2864EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
196779b9 2865
98e5e1bf
TH
2866static char dump_stack_arch_desc_str[128];
2867
2868/**
2869 * dump_stack_set_arch_desc - set arch-specific str to show with task dumps
2870 * @fmt: printf-style format string
2871 * @...: arguments for the format string
2872 *
2873 * The configured string will be printed right after utsname during task
2874 * dumps. Usually used to add arch-specific system identifiers. If an
2875 * arch wants to make use of such an ID string, it should initialize this
2876 * as soon as possible during boot.
2877 */
2878void __init dump_stack_set_arch_desc(const char *fmt, ...)
2879{
2880 va_list args;
2881
2882 va_start(args, fmt);
2883 vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
2884 fmt, args);
2885 va_end(args);
2886}
2887
196779b9
TH
2888/**
2889 * dump_stack_print_info - print generic debug info for dump_stack()
2890 * @log_lvl: log level
2891 *
2892 * Arch-specific dump_stack() implementations can use this function to
2893 * print out the same debug information as the generic dump_stack().
2894 */
2895void dump_stack_print_info(const char *log_lvl)
2896{
2897 printk("%sCPU: %d PID: %d Comm: %.20s %s %s %.*s\n",
2898 log_lvl, raw_smp_processor_id(), current->pid, current->comm,
2899 print_tainted(), init_utsname()->release,
2900 (int)strcspn(init_utsname()->version, " "),
2901 init_utsname()->version);
98e5e1bf
TH
2902
2903 if (dump_stack_arch_desc_str[0] != '\0')
2904 printk("%sHardware name: %s\n",
2905 log_lvl, dump_stack_arch_desc_str);
3d1cb205
TH
2906
2907 print_worker_info(log_lvl, current);
196779b9
TH
2908}
2909
a43cb95d
TH
2910/**
2911 * show_regs_print_info - print generic debug info for show_regs()
2912 * @log_lvl: log level
2913 *
2914 * show_regs() implementations can use this function to print out generic
2915 * debug information.
2916 */
2917void show_regs_print_info(const char *log_lvl)
2918{
2919 dump_stack_print_info(log_lvl);
2920
2921 printk("%stask: %p ti: %p task.ti: %p\n",
2922 log_lvl, current, current_thread_info(),
2923 task_thread_info(current));
2924}
2925
7ef3d2fd 2926#endif