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