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