printk: enable interrupts before calling console_trylock_for_printk()
[deliverable/linux.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 *
5874af20
JK
1453 * Console drivers may assume that per-cpu resources have been allocated. So
1454 * unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
1455 * call them until this CPU is officially up.
266c2e0a
LT
1456 */
1457static inline int can_use_console(unsigned int cpu)
1458{
1459 return cpu_online(cpu) || have_callable_console();
1460}
1461
1462/*
1463 * Try to get console ownership to actually show the kernel
1464 * messages from a 'printk'. Return true (and with the
ac751efa 1465 * console_lock held, and 'console_locked' set) if it
266c2e0a 1466 * is successful, false otherwise.
266c2e0a 1467 */
5874af20 1468static int console_trylock_for_printk(void)
266c2e0a 1469{
5874af20
JK
1470 unsigned int cpu = smp_processor_id();
1471
608873ca
JK
1472 if (!console_trylock())
1473 return 0;
1474 /*
1475 * If we can't use the console, we need to release the console
1476 * semaphore by hand to avoid flushing the buffer. We need to hold the
1477 * console semaphore in order to do this test safely.
1478 */
1479 if (!can_use_console(cpu)) {
1480 console_locked = 0;
bd8d7cf5 1481 up_console_sem();
608873ca
JK
1482 return 0;
1483 }
1484 return 1;
266c2e0a 1485}
32a76006 1486
af91322e
DY
1487int printk_delay_msec __read_mostly;
1488
1489static inline void printk_delay(void)
1490{
1491 if (unlikely(printk_delay_msec)) {
1492 int m = printk_delay_msec;
1493
1494 while (m--) {
1495 mdelay(1);
1496 touch_nmi_watchdog();
1497 }
1498 }
1499}
1500
084681d1
KS
1501/*
1502 * Continuation lines are buffered, and not committed to the record buffer
1503 * until the line is complete, or a race forces it. The line fragments
1504 * though, are printed immediately to the consoles to ensure everything has
1505 * reached the console in case of a kernel crash.
1506 */
1507static struct cont {
1508 char buf[LOG_LINE_MAX];
1509 size_t len; /* length == 0 means unused buffer */
1510 size_t cons; /* bytes written to console */
1511 struct task_struct *owner; /* task of first print*/
1512 u64 ts_nsec; /* time of first print */
1513 u8 level; /* log level of first message */
0b90fec3 1514 u8 facility; /* log facility of first message */
eab07260 1515 enum log_flags flags; /* prefix, newline flags */
084681d1
KS
1516 bool flushed:1; /* buffer sealed and committed */
1517} cont;
1518
70498253 1519static void cont_flush(enum log_flags flags)
084681d1
KS
1520{
1521 if (cont.flushed)
1522 return;
1523 if (cont.len == 0)
1524 return;
1525
eab07260
KS
1526 if (cont.cons) {
1527 /*
1528 * If a fragment of this line was directly flushed to the
1529 * console; wait for the console to pick up the rest of the
1530 * line. LOG_NOCONS suppresses a duplicated output.
1531 */
1532 log_store(cont.facility, cont.level, flags | LOG_NOCONS,
1533 cont.ts_nsec, NULL, 0, cont.buf, cont.len);
1534 cont.flags = flags;
1535 cont.flushed = true;
1536 } else {
1537 /*
1538 * If no fragment of this line ever reached the console,
1539 * just submit it to the store and free the buffer.
1540 */
1541 log_store(cont.facility, cont.level, flags, 0,
1542 NULL, 0, cont.buf, cont.len);
1543 cont.len = 0;
1544 }
084681d1
KS
1545}
1546
1547static bool cont_add(int facility, int level, const char *text, size_t len)
1548{
1549 if (cont.len && cont.flushed)
1550 return false;
1551
1552 if (cont.len + len > sizeof(cont.buf)) {
70498253
KS
1553 /* the line gets too long, split it up in separate records */
1554 cont_flush(LOG_CONT);
084681d1
KS
1555 return false;
1556 }
1557
1558 if (!cont.len) {
1559 cont.facility = facility;
1560 cont.level = level;
1561 cont.owner = current;
1562 cont.ts_nsec = local_clock();
eab07260 1563 cont.flags = 0;
084681d1
KS
1564 cont.cons = 0;
1565 cont.flushed = false;
1566 }
1567
1568 memcpy(cont.buf + cont.len, text, len);
1569 cont.len += len;
eab07260
KS
1570
1571 if (cont.len > (sizeof(cont.buf) * 80) / 100)
1572 cont_flush(LOG_CONT);
1573
084681d1
KS
1574 return true;
1575}
1576
1577static size_t cont_print_text(char *text, size_t size)
1578{
1579 size_t textlen = 0;
1580 size_t len;
1581
eab07260 1582 if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
084681d1
KS
1583 textlen += print_time(cont.ts_nsec, text);
1584 size -= textlen;
1585 }
1586
1587 len = cont.len - cont.cons;
1588 if (len > 0) {
1589 if (len+1 > size)
1590 len = size-1;
1591 memcpy(text + textlen, cont.buf + cont.cons, len);
1592 textlen += len;
1593 cont.cons = cont.len;
1594 }
1595
1596 if (cont.flushed) {
eab07260
KS
1597 if (cont.flags & LOG_NEWLINE)
1598 text[textlen++] = '\n';
084681d1
KS
1599 /* got everything, release buffer */
1600 cont.len = 0;
1601 }
1602 return textlen;
1603}
1604
7ff9554b
KS
1605asmlinkage int vprintk_emit(int facility, int level,
1606 const char *dict, size_t dictlen,
1607 const char *fmt, va_list args)
1da177e4 1608{
7ff9554b 1609 static int recursion_bug;
7ff9554b
KS
1610 static char textbuf[LOG_LINE_MAX];
1611 char *text = textbuf;
458df9fd 1612 size_t text_len = 0;
5becfb1d 1613 enum log_flags lflags = 0;
ac60ad74 1614 unsigned long flags;
32a76006 1615 int this_cpu;
7ff9554b 1616 int printed_len = 0;
458df9fd 1617 bool in_sched = false;
608873ca
JK
1618 /* cpu currently holding logbuf_lock in this function */
1619 static volatile unsigned int logbuf_cpu = UINT_MAX;
1620
458df9fd
SR
1621 if (level == SCHED_MESSAGE_LOGLEVEL) {
1622 level = -1;
1623 in_sched = true;
1624 }
1da177e4 1625
2fa72c8f 1626 boot_delay_msec(level);
af91322e 1627 printk_delay();
bfe8df3d 1628
1da177e4 1629 /* This stops the holder of console_sem just where we want him */
1a9a8aef 1630 local_irq_save(flags);
32a76006
IM
1631 this_cpu = smp_processor_id();
1632
1633 /*
1634 * Ouch, printk recursed into itself!
1635 */
7ff9554b 1636 if (unlikely(logbuf_cpu == this_cpu)) {
32a76006
IM
1637 /*
1638 * If a crash is occurring during printk() on this CPU,
1639 * then try to get the crash message out but make sure
1640 * we can't deadlock. Otherwise just return to avoid the
1641 * recursion and return - but flag the recursion so that
1642 * it can be printed at the next appropriate moment:
1643 */
94d24fc4 1644 if (!oops_in_progress && !lockdep_recursing(current)) {
3b8945e8 1645 recursion_bug = 1;
5874af20
JK
1646 local_irq_restore(flags);
1647 return 0;
32a76006
IM
1648 }
1649 zap_locks();
1650 }
1651
a0f1ccfd 1652 lockdep_off();
07354eb1 1653 raw_spin_lock(&logbuf_lock);
7ff9554b 1654 logbuf_cpu = this_cpu;
1da177e4 1655
3b8945e8 1656 if (recursion_bug) {
7ff9554b
KS
1657 static const char recursion_msg[] =
1658 "BUG: recent printk recursion!";
1659
3b8945e8 1660 recursion_bug = 0;
034633cc 1661 text_len = strlen(recursion_msg);
7ff9554b 1662 /* emit KERN_CRIT message */
034633cc
PM
1663 printed_len += log_store(0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
1664 NULL, 0, recursion_msg, text_len);
32a76006 1665 }
1da177e4 1666
7ff9554b
KS
1667 /*
1668 * The printf needs to come first; we need the syslog
1669 * prefix which might be passed-in as a parameter.
1670 */
458df9fd
SR
1671 if (in_sched)
1672 text_len = scnprintf(text, sizeof(textbuf),
1673 KERN_WARNING "[sched_delayed] ");
1674
1675 text_len += vscnprintf(text + text_len,
1676 sizeof(textbuf) - text_len, fmt, args);
5fd29d6c 1677
7ff9554b 1678 /* mark and strip a trailing newline */
c313af14
KS
1679 if (text_len && text[text_len-1] == '\n') {
1680 text_len--;
5becfb1d 1681 lflags |= LOG_NEWLINE;
7ff9554b 1682 }
9d90c8d9 1683
088a52aa
JP
1684 /* strip kernel syslog prefix and extract log level or control flags */
1685 if (facility == 0) {
1686 int kern_level = printk_get_level(text);
1687
1688 if (kern_level) {
1689 const char *end_of_header = printk_skip_level(text);
1690 switch (kern_level) {
1691 case '0' ... '7':
1692 if (level == -1)
1693 level = kern_level - '0';
1694 case 'd': /* KERN_DEFAULT */
1695 lflags |= LOG_PREFIX;
088a52aa 1696 }
e8c42d36
PM
1697 /*
1698 * No need to check length here because vscnprintf
1699 * put '\0' at the end of the string. Only valid and
1700 * newly printed level is detected.
1701 */
088a52aa
JP
1702 text_len -= end_of_header - text;
1703 text = (char *)end_of_header;
5fd29d6c
LT
1704 }
1705 }
1706
c313af14
KS
1707 if (level == -1)
1708 level = default_message_loglevel;
9d90c8d9 1709
5becfb1d
KS
1710 if (dict)
1711 lflags |= LOG_PREFIX|LOG_NEWLINE;
ac60ad74 1712
5becfb1d 1713 if (!(lflags & LOG_NEWLINE)) {
084681d1
KS
1714 /*
1715 * Flush the conflicting buffer. An earlier newline was missing,
1716 * or another task also prints continuation lines.
1717 */
5becfb1d 1718 if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
eab07260 1719 cont_flush(LOG_NEWLINE);
c313af14 1720
084681d1 1721 /* buffer line if possible, otherwise store it right away */
034633cc
PM
1722 if (cont_add(facility, level, text, text_len))
1723 printed_len += text_len;
1724 else
1725 printed_len += log_store(facility, level,
1726 lflags | LOG_CONT, 0,
1727 dict, dictlen, text, text_len);
5c5d5ca5 1728 } else {
084681d1 1729 bool stored = false;
c313af14 1730
084681d1 1731 /*
d3620822
SR
1732 * If an earlier newline was missing and it was the same task,
1733 * either merge it with the current buffer and flush, or if
1734 * there was a race with interrupts (prefix == true) then just
1735 * flush it out and store this line separately.
1d3fa370
AK
1736 * If the preceding printk was from a different task and missed
1737 * a newline, flush and append the newline.
084681d1 1738 */
1d3fa370
AK
1739 if (cont.len) {
1740 if (cont.owner == current && !(lflags & LOG_PREFIX))
1741 stored = cont_add(facility, level, text,
1742 text_len);
eab07260 1743 cont_flush(LOG_NEWLINE);
c313af14 1744 }
084681d1 1745
034633cc
PM
1746 if (stored)
1747 printed_len += text_len;
1748 else
1749 printed_len += log_store(facility, level, lflags, 0,
1750 dict, dictlen, text, text_len);
1da177e4
LT
1751 }
1752
608873ca
JK
1753 logbuf_cpu = UINT_MAX;
1754 raw_spin_unlock(&logbuf_lock);
5874af20
JK
1755 lockdep_on();
1756 local_irq_restore(flags);
939f04be 1757
458df9fd 1758 /* If called from the scheduler, we can not call up(). */
d18bbc21 1759 if (!in_sched) {
5874af20
JK
1760 lockdep_off();
1761 /*
1762 * Disable preemption to avoid being preempted while holding
1763 * console_sem which would prevent anyone from printing to
1764 * console
1765 */
1766 preempt_disable();
1767
d18bbc21
AM
1768 /*
1769 * Try to acquire and then immediately release the console
1770 * semaphore. The release will print out buffers and wake up
1771 * /dev/kmsg and syslog() users.
1772 */
5874af20 1773 if (console_trylock_for_printk())
d18bbc21 1774 console_unlock();
5874af20
JK
1775 preempt_enable();
1776 lockdep_on();
d18bbc21 1777 }
76a8ad29 1778
1da177e4
LT
1779 return printed_len;
1780}
7ff9554b
KS
1781EXPORT_SYMBOL(vprintk_emit);
1782
1783asmlinkage int vprintk(const char *fmt, va_list args)
1784{
1785 return vprintk_emit(0, -1, NULL, 0, fmt, args);
1786}
1da177e4
LT
1787EXPORT_SYMBOL(vprintk);
1788
7ff9554b
KS
1789asmlinkage int printk_emit(int facility, int level,
1790 const char *dict, size_t dictlen,
1791 const char *fmt, ...)
1792{
1793 va_list args;
1794 int r;
1795
1796 va_start(args, fmt);
1797 r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
1798 va_end(args);
1799
1800 return r;
1801}
1802EXPORT_SYMBOL(printk_emit);
1803
1804/**
1805 * printk - print a kernel message
1806 * @fmt: format string
1807 *
1808 * This is printk(). It can be called from any context. We want it to work.
1809 *
1810 * We try to grab the console_lock. If we succeed, it's easy - we log the
1811 * output and call the console drivers. If we fail to get the semaphore, we
1812 * place the output into the log buffer and return. The current holder of
1813 * the console_sem will notice the new output in console_unlock(); and will
1814 * send it to the consoles before releasing the lock.
1815 *
1816 * One effect of this deferred printing is that code which calls printk() and
1817 * then changes console_loglevel may break. This is because console_loglevel
1818 * is inspected when the actual printing occurs.
1819 *
1820 * See also:
1821 * printf(3)
1822 *
1823 * See the vsnprintf() documentation for format string extensions over C99.
1824 */
722a9f92 1825asmlinkage __visible int printk(const char *fmt, ...)
7ff9554b
KS
1826{
1827 va_list args;
1828 int r;
1829
1830#ifdef CONFIG_KGDB_KDB
1831 if (unlikely(kdb_trap_printk)) {
1832 va_start(args, fmt);
1833 r = vkdb_printf(fmt, args);
1834 va_end(args);
1835 return r;
1836 }
1837#endif
1838 va_start(args, fmt);
1839 r = vprintk_emit(0, -1, NULL, 0, fmt, args);
1840 va_end(args);
1841
1842 return r;
1843}
1844EXPORT_SYMBOL(printk);
7f3a781d 1845
96efedf1 1846#else /* CONFIG_PRINTK */
d59745ce 1847
70498253
KS
1848#define LOG_LINE_MAX 0
1849#define PREFIX_MAX 0
249771b8 1850
96efedf1
KS
1851static u64 syslog_seq;
1852static u32 syslog_idx;
eab07260
KS
1853static u64 console_seq;
1854static u32 console_idx;
96efedf1
KS
1855static enum log_flags syslog_prev;
1856static u64 log_first_seq;
1857static u32 log_first_idx;
1858static u64 log_next_seq;
eab07260 1859static enum log_flags console_prev;
084681d1
KS
1860static struct cont {
1861 size_t len;
1862 size_t cons;
1863 u8 level;
1864 bool flushed:1;
1865} cont;
62e32ac3 1866static struct printk_log *log_from_idx(u32 idx) { return NULL; }
7f3a781d 1867static u32 log_next(u32 idx) { return 0; }
7f3a781d 1868static void call_console_drivers(int level, const char *text, size_t len) {}
62e32ac3 1869static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
5becfb1d 1870 bool syslog, char *buf, size_t size) { return 0; }
084681d1 1871static size_t cont_print_text(char *text, size_t size) { return 0; }
d59745ce 1872
7f3a781d 1873#endif /* CONFIG_PRINTK */
d59745ce 1874
d0380e6c
TG
1875#ifdef CONFIG_EARLY_PRINTK
1876struct console *early_console;
1877
1878void early_vprintk(const char *fmt, va_list ap)
1879{
1880 if (early_console) {
1881 char buf[512];
1882 int n = vscnprintf(buf, sizeof(buf), fmt, ap);
1883
1884 early_console->write(early_console, buf, n);
1885 }
1886}
1887
722a9f92 1888asmlinkage __visible void early_printk(const char *fmt, ...)
d0380e6c
TG
1889{
1890 va_list ap;
1891
1892 va_start(ap, fmt);
1893 early_vprintk(fmt, ap);
1894 va_end(ap);
1895}
1896#endif
1897
f7511d5f
ST
1898static int __add_preferred_console(char *name, int idx, char *options,
1899 char *brl_options)
1900{
1901 struct console_cmdline *c;
1902 int i;
1903
1904 /*
1905 * See if this tty is not yet registered, and
1906 * if we have a slot free.
1907 */
23475408
JP
1908 for (i = 0, c = console_cmdline;
1909 i < MAX_CMDLINECONSOLES && c->name[0];
1910 i++, c++) {
1911 if (strcmp(c->name, name) == 0 && c->index == idx) {
1912 if (!brl_options)
1913 selected_console = i;
1914 return 0;
f7511d5f 1915 }
23475408 1916 }
f7511d5f
ST
1917 if (i == MAX_CMDLINECONSOLES)
1918 return -E2BIG;
1919 if (!brl_options)
1920 selected_console = i;
f7511d5f
ST
1921 strlcpy(c->name, name, sizeof(c->name));
1922 c->options = options;
bbeddf52
JP
1923 braille_set_options(c, brl_options);
1924
f7511d5f
ST
1925 c->index = idx;
1926 return 0;
1927}
2ea1c539 1928/*
0b90fec3
AE
1929 * Set up a console. Called via do_early_param() in init/main.c
1930 * for each "console=" parameter in the boot command line.
2ea1c539
JB
1931 */
1932static int __init console_setup(char *str)
1933{
0b90fec3 1934 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
f7511d5f 1935 char *s, *options, *brl_options = NULL;
2ea1c539
JB
1936 int idx;
1937
bbeddf52
JP
1938 if (_braille_console_setup(&str, &brl_options))
1939 return 1;
f7511d5f 1940
2ea1c539
JB
1941 /*
1942 * Decode str into name, index, options.
1943 */
1944 if (str[0] >= '0' && str[0] <= '9') {
eaa944af
YL
1945 strcpy(buf, "ttyS");
1946 strncpy(buf + 4, str, sizeof(buf) - 5);
2ea1c539 1947 } else {
eaa944af 1948 strncpy(buf, str, sizeof(buf) - 1);
2ea1c539 1949 }
eaa944af 1950 buf[sizeof(buf) - 1] = 0;
249771b8
AE
1951 options = strchr(str, ',');
1952 if (options)
2ea1c539
JB
1953 *(options++) = 0;
1954#ifdef __sparc__
1955 if (!strcmp(str, "ttya"))
eaa944af 1956 strcpy(buf, "ttyS0");
2ea1c539 1957 if (!strcmp(str, "ttyb"))
eaa944af 1958 strcpy(buf, "ttyS1");
2ea1c539 1959#endif
eaa944af 1960 for (s = buf; *s; s++)
249771b8 1961 if (isdigit(*s) || *s == ',')
2ea1c539
JB
1962 break;
1963 idx = simple_strtoul(s, NULL, 10);
1964 *s = 0;
1965
f7511d5f 1966 __add_preferred_console(buf, idx, options, brl_options);
9e124fe1 1967 console_set_on_cmdline = 1;
2ea1c539
JB
1968 return 1;
1969}
1970__setup("console=", console_setup);
1971
3c0547ba
MM
1972/**
1973 * add_preferred_console - add a device to the list of preferred consoles.
ddad86c2
MW
1974 * @name: device name
1975 * @idx: device index
1976 * @options: options for this console
3c0547ba
MM
1977 *
1978 * The last preferred console added will be used for kernel messages
1979 * and stdin/out/err for init. Normally this is used by console_setup
1980 * above to handle user-supplied console arguments; however it can also
1981 * be used by arch-specific code either to override the user or more
1982 * commonly to provide a default console (ie from PROM variables) when
1983 * the user has not supplied one.
1984 */
fb445ee5 1985int add_preferred_console(char *name, int idx, char *options)
3c0547ba 1986{
f7511d5f 1987 return __add_preferred_console(name, idx, options, NULL);
3c0547ba
MM
1988}
1989
b6b1d877 1990int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
18a8bd94
YL
1991{
1992 struct console_cmdline *c;
1993 int i;
1994
23475408
JP
1995 for (i = 0, c = console_cmdline;
1996 i < MAX_CMDLINECONSOLES && c->name[0];
1997 i++, c++)
1998 if (strcmp(c->name, name) == 0 && c->index == idx) {
1999 strlcpy(c->name, name_new, sizeof(c->name));
23475408
JP
2000 c->options = options;
2001 c->index = idx_new;
2002 return i;
18a8bd94
YL
2003 }
2004 /* not found */
2005 return -1;
2006}
2007
2329abfa 2008bool console_suspend_enabled = 1;
8f4ce8c3
AS
2009EXPORT_SYMBOL(console_suspend_enabled);
2010
2011static int __init console_suspend_disable(char *str)
2012{
2013 console_suspend_enabled = 0;
2014 return 1;
2015}
2016__setup("no_console_suspend", console_suspend_disable);
134620f7
YZ
2017module_param_named(console_suspend, console_suspend_enabled,
2018 bool, S_IRUGO | S_IWUSR);
2019MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2020 " and hibernate operations");
8f4ce8c3 2021
557240b4
LT
2022/**
2023 * suspend_console - suspend the console subsystem
2024 *
2025 * This disables printk() while we go into suspend states
2026 */
2027void suspend_console(void)
2028{
8f4ce8c3
AS
2029 if (!console_suspend_enabled)
2030 return;
0d63081d 2031 printk("Suspending console(s) (use no_console_suspend to debug)\n");
ac751efa 2032 console_lock();
557240b4 2033 console_suspended = 1;
bd8d7cf5 2034 up_console_sem();
557240b4
LT
2035}
2036
2037void resume_console(void)
2038{
8f4ce8c3
AS
2039 if (!console_suspend_enabled)
2040 return;
bd8d7cf5 2041 down_console_sem();
557240b4 2042 console_suspended = 0;
ac751efa 2043 console_unlock();
557240b4
LT
2044}
2045
034260d6
KC
2046/**
2047 * console_cpu_notify - print deferred console messages after CPU hotplug
2048 * @self: notifier struct
2049 * @action: CPU hotplug event
2050 * @hcpu: unused
2051 *
2052 * If printk() is called from a CPU that is not online yet, the messages
2053 * will be spooled but will not show up on the console. This function is
2054 * called when a new CPU comes online (or fails to come up), and ensures
2055 * that any such output gets printed.
2056 */
0db0628d 2057static int console_cpu_notify(struct notifier_block *self,
034260d6
KC
2058 unsigned long action, void *hcpu)
2059{
2060 switch (action) {
2061 case CPU_ONLINE:
2062 case CPU_DEAD:
034260d6
KC
2063 case CPU_DOWN_FAILED:
2064 case CPU_UP_CANCELED:
ac751efa
TH
2065 console_lock();
2066 console_unlock();
034260d6
KC
2067 }
2068 return NOTIFY_OK;
2069}
2070
1da177e4 2071/**
ac751efa 2072 * console_lock - lock the console system for exclusive use.
1da177e4 2073 *
ac751efa 2074 * Acquires a lock which guarantees that the caller has
1da177e4
LT
2075 * exclusive access to the console system and the console_drivers list.
2076 *
2077 * Can sleep, returns nothing.
2078 */
ac751efa 2079void console_lock(void)
1da177e4 2080{
6b898c07
DV
2081 might_sleep();
2082
bd8d7cf5 2083 down_console_sem();
403f3075
AH
2084 if (console_suspended)
2085 return;
1da177e4
LT
2086 console_locked = 1;
2087 console_may_schedule = 1;
2088}
ac751efa 2089EXPORT_SYMBOL(console_lock);
1da177e4 2090
ac751efa
TH
2091/**
2092 * console_trylock - try to lock the console system for exclusive use.
2093 *
0b90fec3
AE
2094 * Try to acquire a lock which guarantees that the caller has exclusive
2095 * access to the console system and the console_drivers list.
ac751efa
TH
2096 *
2097 * returns 1 on success, and 0 on failure to acquire the lock.
2098 */
2099int console_trylock(void)
1da177e4 2100{
bd8d7cf5 2101 if (down_trylock_console_sem())
ac751efa 2102 return 0;
403f3075 2103 if (console_suspended) {
bd8d7cf5 2104 up_console_sem();
ac751efa 2105 return 0;
403f3075 2106 }
1da177e4
LT
2107 console_locked = 1;
2108 console_may_schedule = 0;
ac751efa 2109 return 1;
1da177e4 2110}
ac751efa 2111EXPORT_SYMBOL(console_trylock);
1da177e4
LT
2112
2113int is_console_locked(void)
2114{
2115 return console_locked;
2116}
1da177e4 2117
eab07260
KS
2118static void console_cont_flush(char *text, size_t size)
2119{
2120 unsigned long flags;
2121 size_t len;
2122
2123 raw_spin_lock_irqsave(&logbuf_lock, flags);
2124
2125 if (!cont.len)
2126 goto out;
2127
2128 /*
2129 * We still queue earlier records, likely because the console was
2130 * busy. The earlier ones need to be printed before this one, we
2131 * did not flush any fragment so far, so just let it queue up.
2132 */
2133 if (console_seq < log_next_seq && !cont.cons)
2134 goto out;
2135
2136 len = cont_print_text(text, size);
2137 raw_spin_unlock(&logbuf_lock);
2138 stop_critical_timings();
2139 call_console_drivers(cont.level, text, len);
2140 start_critical_timings();
2141 local_irq_restore(flags);
2142 return;
2143out:
2144 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2145}
7ff9554b 2146
1da177e4 2147/**
ac751efa 2148 * console_unlock - unlock the console system
1da177e4 2149 *
ac751efa 2150 * Releases the console_lock which the caller holds on the console system
1da177e4
LT
2151 * and the console driver list.
2152 *
ac751efa
TH
2153 * While the console_lock was held, console output may have been buffered
2154 * by printk(). If this is the case, console_unlock(); emits
2155 * the output prior to releasing the lock.
1da177e4 2156 *
7f3a781d 2157 * If there is output waiting, we wake /dev/kmsg and syslog() users.
1da177e4 2158 *
ac751efa 2159 * console_unlock(); may be called from any context.
1da177e4 2160 */
ac751efa 2161void console_unlock(void)
1da177e4 2162{
70498253 2163 static char text[LOG_LINE_MAX + PREFIX_MAX];
7ff9554b 2164 static u64 seen_seq;
1da177e4 2165 unsigned long flags;
7ff9554b
KS
2166 bool wake_klogd = false;
2167 bool retry;
1da177e4 2168
557240b4 2169 if (console_suspended) {
bd8d7cf5 2170 up_console_sem();
557240b4
LT
2171 return;
2172 }
78944e54
AD
2173
2174 console_may_schedule = 0;
2175
084681d1 2176 /* flush buffered message fragment immediately to console */
eab07260 2177 console_cont_flush(text, sizeof(text));
4f2a8d3c 2178again:
7ff9554b 2179 for (;;) {
62e32ac3 2180 struct printk_log *msg;
3ce9a7c0 2181 size_t len;
7ff9554b
KS
2182 int level;
2183
07354eb1 2184 raw_spin_lock_irqsave(&logbuf_lock, flags);
7ff9554b
KS
2185 if (seen_seq != log_next_seq) {
2186 wake_klogd = true;
2187 seen_seq = log_next_seq;
2188 }
2189
2190 if (console_seq < log_first_seq) {
84b5ec8a
WD
2191 len = sprintf(text, "** %u printk messages dropped ** ",
2192 (unsigned)(log_first_seq - console_seq));
2193
7ff9554b
KS
2194 /* messages are gone, move to first one */
2195 console_seq = log_first_seq;
2196 console_idx = log_first_idx;
5becfb1d 2197 console_prev = 0;
84b5ec8a
WD
2198 } else {
2199 len = 0;
7ff9554b 2200 }
084681d1 2201skip:
7ff9554b
KS
2202 if (console_seq == log_next_seq)
2203 break;
2204
2205 msg = log_from_idx(console_idx);
084681d1
KS
2206 if (msg->flags & LOG_NOCONS) {
2207 /*
2208 * Skip record we have buffered and already printed
2209 * directly to the console when we received it.
2210 */
2211 console_idx = log_next(console_idx);
2212 console_seq++;
68b6507d
KS
2213 /*
2214 * We will get here again when we register a new
2215 * CON_PRINTBUFFER console. Clear the flag so we
2216 * will properly dump everything later.
2217 */
2218 msg->flags &= ~LOG_NOCONS;
eab07260 2219 console_prev = msg->flags;
084681d1
KS
2220 goto skip;
2221 }
649e6ee3 2222
084681d1 2223 level = msg->level;
84b5ec8a
WD
2224 len += msg_print_text(msg, console_prev, false,
2225 text + len, sizeof(text) - len);
7ff9554b
KS
2226 console_idx = log_next(console_idx);
2227 console_seq++;
5becfb1d 2228 console_prev = msg->flags;
07354eb1 2229 raw_spin_unlock(&logbuf_lock);
7ff9554b 2230
81d68a96 2231 stop_critical_timings(); /* don't trace print latency */
7ff9554b 2232 call_console_drivers(level, text, len);
81d68a96 2233 start_critical_timings();
1da177e4
LT
2234 local_irq_restore(flags);
2235 }
2236 console_locked = 0;
fe3d8ad3
FT
2237
2238 /* Release the exclusive_console once it is used */
2239 if (unlikely(exclusive_console))
2240 exclusive_console = NULL;
2241
07354eb1 2242 raw_spin_unlock(&logbuf_lock);
4f2a8d3c 2243
bd8d7cf5 2244 up_console_sem();
4f2a8d3c
PZ
2245
2246 /*
2247 * Someone could have filled up the buffer again, so re-check if there's
2248 * something to flush. In case we cannot trylock the console_sem again,
2249 * there's a new owner and the console_unlock() from them will do the
2250 * flush, no worries.
2251 */
07354eb1 2252 raw_spin_lock(&logbuf_lock);
7ff9554b 2253 retry = console_seq != log_next_seq;
09dc3cf9
PZ
2254 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2255
4f2a8d3c
PZ
2256 if (retry && console_trylock())
2257 goto again;
2258
e3e8a75d
KK
2259 if (wake_klogd)
2260 wake_up_klogd();
1da177e4 2261}
ac751efa 2262EXPORT_SYMBOL(console_unlock);
1da177e4 2263
ddad86c2
MW
2264/**
2265 * console_conditional_schedule - yield the CPU if required
1da177e4
LT
2266 *
2267 * If the console code is currently allowed to sleep, and
2268 * if this CPU should yield the CPU to another task, do
2269 * so here.
2270 *
ac751efa 2271 * Must be called within console_lock();.
1da177e4
LT
2272 */
2273void __sched console_conditional_schedule(void)
2274{
2275 if (console_may_schedule)
2276 cond_resched();
2277}
2278EXPORT_SYMBOL(console_conditional_schedule);
2279
1da177e4
LT
2280void console_unblank(void)
2281{
2282 struct console *c;
2283
2284 /*
2285 * console_unblank can no longer be called in interrupt context unless
2286 * oops_in_progress is set to 1..
2287 */
2288 if (oops_in_progress) {
bd8d7cf5 2289 if (down_trylock_console_sem() != 0)
1da177e4
LT
2290 return;
2291 } else
ac751efa 2292 console_lock();
1da177e4
LT
2293
2294 console_locked = 1;
2295 console_may_schedule = 0;
4d091611 2296 for_each_console(c)
1da177e4
LT
2297 if ((c->flags & CON_ENABLED) && c->unblank)
2298 c->unblank();
ac751efa 2299 console_unlock();
1da177e4 2300}
1da177e4
LT
2301
2302/*
2303 * Return the console tty driver structure and its associated index
2304 */
2305struct tty_driver *console_device(int *index)
2306{
2307 struct console *c;
2308 struct tty_driver *driver = NULL;
2309
ac751efa 2310 console_lock();
4d091611 2311 for_each_console(c) {
1da177e4
LT
2312 if (!c->device)
2313 continue;
2314 driver = c->device(c, index);
2315 if (driver)
2316 break;
2317 }
ac751efa 2318 console_unlock();
1da177e4
LT
2319 return driver;
2320}
2321
2322/*
2323 * Prevent further output on the passed console device so that (for example)
2324 * serial drivers can disable console output before suspending a port, and can
2325 * re-enable output afterwards.
2326 */
2327void console_stop(struct console *console)
2328{
ac751efa 2329 console_lock();
1da177e4 2330 console->flags &= ~CON_ENABLED;
ac751efa 2331 console_unlock();
1da177e4
LT
2332}
2333EXPORT_SYMBOL(console_stop);
2334
2335void console_start(struct console *console)
2336{
ac751efa 2337 console_lock();
1da177e4 2338 console->flags |= CON_ENABLED;
ac751efa 2339 console_unlock();
1da177e4
LT
2340}
2341EXPORT_SYMBOL(console_start);
2342
7bf69395
FDN
2343static int __read_mostly keep_bootcon;
2344
2345static int __init keep_bootcon_setup(char *str)
2346{
2347 keep_bootcon = 1;
27083bac 2348 pr_info("debug: skip boot console de-registration.\n");
7bf69395
FDN
2349
2350 return 0;
2351}
2352
2353early_param("keep_bootcon", keep_bootcon_setup);
2354
1da177e4
LT
2355/*
2356 * The console driver calls this routine during kernel initialization
2357 * to register the console printing procedure with printk() and to
2358 * print any messages that were printed by the kernel before the
2359 * console driver was initialized.
4d091611
RG
2360 *
2361 * This can happen pretty early during the boot process (because of
2362 * early_printk) - sometimes before setup_arch() completes - be careful
2363 * of what kernel features are used - they may not be initialised yet.
2364 *
2365 * There are two types of consoles - bootconsoles (early_printk) and
2366 * "real" consoles (everything which is not a bootconsole) which are
2367 * handled differently.
2368 * - Any number of bootconsoles can be registered at any time.
2369 * - As soon as a "real" console is registered, all bootconsoles
2370 * will be unregistered automatically.
2371 * - Once a "real" console is registered, any attempt to register a
2372 * bootconsoles will be rejected
1da177e4 2373 */
4d091611 2374void register_console(struct console *newcon)
1da177e4 2375{
40dc5651 2376 int i;
1da177e4 2377 unsigned long flags;
4d091611 2378 struct console *bcon = NULL;
23475408 2379 struct console_cmdline *c;
1da177e4 2380
16cf48a6
AB
2381 if (console_drivers)
2382 for_each_console(bcon)
2383 if (WARN(bcon == newcon,
2384 "console '%s%d' already registered\n",
2385 bcon->name, bcon->index))
2386 return;
2387
4d091611
RG
2388 /*
2389 * before we register a new CON_BOOT console, make sure we don't
2390 * already have a valid console
2391 */
2392 if (console_drivers && newcon->flags & CON_BOOT) {
2393 /* find the last or real console */
2394 for_each_console(bcon) {
2395 if (!(bcon->flags & CON_BOOT)) {
27083bac 2396 pr_info("Too late to register bootconsole %s%d\n",
4d091611
RG
2397 newcon->name, newcon->index);
2398 return;
2399 }
2400 }
69331af7
GH
2401 }
2402
4d091611
RG
2403 if (console_drivers && console_drivers->flags & CON_BOOT)
2404 bcon = console_drivers;
2405
2406 if (preferred_console < 0 || bcon || !console_drivers)
1da177e4
LT
2407 preferred_console = selected_console;
2408
4d091611
RG
2409 if (newcon->early_setup)
2410 newcon->early_setup();
18a8bd94 2411
1da177e4
LT
2412 /*
2413 * See if we want to use this console driver. If we
2414 * didn't select a console we take the first one
2415 * that registers here.
2416 */
2417 if (preferred_console < 0) {
4d091611
RG
2418 if (newcon->index < 0)
2419 newcon->index = 0;
2420 if (newcon->setup == NULL ||
2421 newcon->setup(newcon, NULL) == 0) {
2422 newcon->flags |= CON_ENABLED;
2423 if (newcon->device) {
2424 newcon->flags |= CON_CONSDEV;
cd3a1b85
JK
2425 preferred_console = 0;
2426 }
1da177e4
LT
2427 }
2428 }
2429
2430 /*
2431 * See if this console matches one we selected on
2432 * the command line.
2433 */
23475408
JP
2434 for (i = 0, c = console_cmdline;
2435 i < MAX_CMDLINECONSOLES && c->name[0];
2436 i++, c++) {
2437 if (strcmp(c->name, newcon->name) != 0)
1da177e4 2438 continue;
4d091611 2439 if (newcon->index >= 0 &&
23475408 2440 newcon->index != c->index)
1da177e4 2441 continue;
4d091611 2442 if (newcon->index < 0)
23475408 2443 newcon->index = c->index;
bbeddf52 2444
23475408 2445 if (_braille_register_console(newcon, c))
f7511d5f 2446 return;
bbeddf52 2447
4d091611
RG
2448 if (newcon->setup &&
2449 newcon->setup(newcon, console_cmdline[i].options) != 0)
1da177e4 2450 break;
4d091611 2451 newcon->flags |= CON_ENABLED;
23475408 2452 newcon->index = c->index;
ab4af03a 2453 if (i == selected_console) {
4d091611 2454 newcon->flags |= CON_CONSDEV;
ab4af03a
GE
2455 preferred_console = selected_console;
2456 }
1da177e4
LT
2457 break;
2458 }
2459
4d091611 2460 if (!(newcon->flags & CON_ENABLED))
1da177e4
LT
2461 return;
2462
8259cf43
RG
2463 /*
2464 * If we have a bootconsole, and are switching to a real console,
2465 * don't print everything out again, since when the boot console, and
2466 * the real console are the same physical device, it's annoying to
2467 * see the beginning boot messages twice
2468 */
2469 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
4d091611 2470 newcon->flags &= ~CON_PRINTBUFFER;
1da177e4
LT
2471
2472 /*
2473 * Put this console in the list - keep the
2474 * preferred driver at the head of the list.
2475 */
ac751efa 2476 console_lock();
4d091611
RG
2477 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2478 newcon->next = console_drivers;
2479 console_drivers = newcon;
2480 if (newcon->next)
2481 newcon->next->flags &= ~CON_CONSDEV;
1da177e4 2482 } else {
4d091611
RG
2483 newcon->next = console_drivers->next;
2484 console_drivers->next = newcon;
1da177e4 2485 }
4d091611 2486 if (newcon->flags & CON_PRINTBUFFER) {
1da177e4 2487 /*
ac751efa 2488 * console_unlock(); will print out the buffered messages
1da177e4
LT
2489 * for us.
2490 */
07354eb1 2491 raw_spin_lock_irqsave(&logbuf_lock, flags);
7ff9554b
KS
2492 console_seq = syslog_seq;
2493 console_idx = syslog_idx;
5becfb1d 2494 console_prev = syslog_prev;
07354eb1 2495 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
fe3d8ad3
FT
2496 /*
2497 * We're about to replay the log buffer. Only do this to the
2498 * just-registered console to avoid excessive message spam to
2499 * the already-registered consoles.
2500 */
2501 exclusive_console = newcon;
1da177e4 2502 }
ac751efa 2503 console_unlock();
fbc92a34 2504 console_sysfs_notify();
8259cf43
RG
2505
2506 /*
2507 * By unregistering the bootconsoles after we enable the real console
2508 * we get the "console xxx enabled" message on all the consoles -
2509 * boot consoles, real consoles, etc - this is to ensure that end
2510 * users know there might be something in the kernel's log buffer that
2511 * went to the bootconsole (that they do not see on the real console)
2512 */
27083bac 2513 pr_info("%sconsole [%s%d] enabled\n",
6b802394
KC
2514 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2515 newcon->name, newcon->index);
7bf69395
FDN
2516 if (bcon &&
2517 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2518 !keep_bootcon) {
6b802394
KC
2519 /* We need to iterate through all boot consoles, to make
2520 * sure we print everything out, before we unregister them.
8259cf43 2521 */
8259cf43
RG
2522 for_each_console(bcon)
2523 if (bcon->flags & CON_BOOT)
2524 unregister_console(bcon);
8259cf43 2525 }
1da177e4
LT
2526}
2527EXPORT_SYMBOL(register_console);
2528
40dc5651 2529int unregister_console(struct console *console)
1da177e4 2530{
40dc5651 2531 struct console *a, *b;
bbeddf52 2532 int res;
1da177e4 2533
27083bac 2534 pr_info("%sconsole [%s%d] disabled\n",
6b802394
KC
2535 (console->flags & CON_BOOT) ? "boot" : "" ,
2536 console->name, console->index);
2537
bbeddf52
JP
2538 res = _braille_unregister_console(console);
2539 if (res)
2540 return res;
f7511d5f 2541
bbeddf52 2542 res = 1;
ac751efa 2543 console_lock();
1da177e4
LT
2544 if (console_drivers == console) {
2545 console_drivers=console->next;
2546 res = 0;
e9b15b54 2547 } else if (console_drivers) {
1da177e4
LT
2548 for (a=console_drivers->next, b=console_drivers ;
2549 a; b=a, a=b->next) {
2550 if (a == console) {
2551 b->next = a->next;
2552 res = 0;
2553 break;
40dc5651 2554 }
1da177e4
LT
2555 }
2556 }
40dc5651 2557
69331af7 2558 /*
ab4af03a
GE
2559 * If this isn't the last console and it has CON_CONSDEV set, we
2560 * need to set it on the next preferred console.
1da177e4 2561 */
69331af7 2562 if (console_drivers != NULL && console->flags & CON_CONSDEV)
ab4af03a 2563 console_drivers->flags |= CON_CONSDEV;
1da177e4 2564
7fa21dd8 2565 console->flags &= ~CON_ENABLED;
ac751efa 2566 console_unlock();
fbc92a34 2567 console_sysfs_notify();
1da177e4
LT
2568 return res;
2569}
2570EXPORT_SYMBOL(unregister_console);
d59745ce 2571
034260d6 2572static int __init printk_late_init(void)
0c5564bd 2573{
4d091611
RG
2574 struct console *con;
2575
2576 for_each_console(con) {
4c30c6f5 2577 if (!keep_bootcon && con->flags & CON_BOOT) {
42c2c8c8 2578 unregister_console(con);
cb00e99c 2579 }
0c5564bd 2580 }
034260d6 2581 hotcpu_notifier(console_cpu_notify, 0);
0c5564bd
RG
2582 return 0;
2583}
034260d6 2584late_initcall(printk_late_init);
0c5564bd 2585
7ef3d2fd 2586#if defined CONFIG_PRINTK
dc72c32e
FW
2587/*
2588 * Delayed printk version, for scheduler-internal messages:
2589 */
dc72c32e 2590#define PRINTK_PENDING_WAKEUP 0x01
458df9fd 2591#define PRINTK_PENDING_OUTPUT 0x02
dc72c32e
FW
2592
2593static DEFINE_PER_CPU(int, printk_pending);
dc72c32e
FW
2594
2595static void wake_up_klogd_work_func(struct irq_work *irq_work)
2596{
2597 int pending = __this_cpu_xchg(printk_pending, 0);
2598
458df9fd
SR
2599 if (pending & PRINTK_PENDING_OUTPUT) {
2600 /* If trylock fails, someone else is doing the printing */
2601 if (console_trylock())
2602 console_unlock();
dc72c32e
FW
2603 }
2604
2605 if (pending & PRINTK_PENDING_WAKEUP)
2606 wake_up_interruptible(&log_wait);
2607}
2608
2609static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
2610 .func = wake_up_klogd_work_func,
2611 .flags = IRQ_WORK_LAZY,
2612};
2613
2614void wake_up_klogd(void)
2615{
2616 preempt_disable();
2617 if (waitqueue_active(&log_wait)) {
2618 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
2619 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
2620 }
2621 preempt_enable();
2622}
717115e1 2623
aac74dc4 2624int printk_deferred(const char *fmt, ...)
600e1458 2625{
600e1458 2626 va_list args;
600e1458
PZ
2627 int r;
2628
81954606 2629 preempt_disable();
600e1458 2630 va_start(args, fmt);
458df9fd 2631 r = vprintk_emit(0, SCHED_MESSAGE_LOGLEVEL, NULL, 0, fmt, args);
600e1458
PZ
2632 va_end(args);
2633
458df9fd 2634 __this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
74876a98 2635 irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
81954606 2636 preempt_enable();
600e1458
PZ
2637
2638 return r;
2639}
2640
1da177e4
LT
2641/*
2642 * printk rate limiting, lifted from the networking subsystem.
2643 *
641de9d8
UKK
2644 * This enforces a rate limit: not more than 10 kernel messages
2645 * every 5s to make a denial-of-service attack impossible.
1da177e4 2646 */
641de9d8
UKK
2647DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
2648
5c828713 2649int __printk_ratelimit(const char *func)
1da177e4 2650{
5c828713 2651 return ___ratelimit(&printk_ratelimit_state, func);
1da177e4 2652}
5c828713 2653EXPORT_SYMBOL(__printk_ratelimit);
f46c4833
AM
2654
2655/**
2656 * printk_timed_ratelimit - caller-controlled printk ratelimiting
2657 * @caller_jiffies: pointer to caller's state
2658 * @interval_msecs: minimum interval between prints
2659 *
2660 * printk_timed_ratelimit() returns true if more than @interval_msecs
2661 * milliseconds have elapsed since the last time printk_timed_ratelimit()
2662 * returned true.
2663 */
2664bool printk_timed_ratelimit(unsigned long *caller_jiffies,
2665 unsigned int interval_msecs)
2666{
249771b8
AE
2667 unsigned long elapsed = jiffies - *caller_jiffies;
2668
2669 if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
2670 return false;
2671
2672 *caller_jiffies = jiffies;
2673 return true;
f46c4833
AM
2674}
2675EXPORT_SYMBOL(printk_timed_ratelimit);
456b565c
SK
2676
2677static DEFINE_SPINLOCK(dump_list_lock);
2678static LIST_HEAD(dump_list);
2679
2680/**
2681 * kmsg_dump_register - register a kernel log dumper.
6485536b 2682 * @dumper: pointer to the kmsg_dumper structure
456b565c
SK
2683 *
2684 * Adds a kernel log dumper to the system. The dump callback in the
2685 * structure will be called when the kernel oopses or panics and must be
2686 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
2687 */
2688int kmsg_dump_register(struct kmsg_dumper *dumper)
2689{
2690 unsigned long flags;
2691 int err = -EBUSY;
2692
2693 /* The dump callback needs to be set */
2694 if (!dumper->dump)
2695 return -EINVAL;
2696
2697 spin_lock_irqsave(&dump_list_lock, flags);
2698 /* Don't allow registering multiple times */
2699 if (!dumper->registered) {
2700 dumper->registered = 1;
fb842b00 2701 list_add_tail_rcu(&dumper->list, &dump_list);
456b565c
SK
2702 err = 0;
2703 }
2704 spin_unlock_irqrestore(&dump_list_lock, flags);
2705
2706 return err;
2707}
2708EXPORT_SYMBOL_GPL(kmsg_dump_register);
2709
2710/**
2711 * kmsg_dump_unregister - unregister a kmsg dumper.
6485536b 2712 * @dumper: pointer to the kmsg_dumper structure
456b565c
SK
2713 *
2714 * Removes a dump device from the system. Returns zero on success and
2715 * %-EINVAL otherwise.
2716 */
2717int kmsg_dump_unregister(struct kmsg_dumper *dumper)
2718{
2719 unsigned long flags;
2720 int err = -EINVAL;
2721
2722 spin_lock_irqsave(&dump_list_lock, flags);
2723 if (dumper->registered) {
2724 dumper->registered = 0;
fb842b00 2725 list_del_rcu(&dumper->list);
456b565c
SK
2726 err = 0;
2727 }
2728 spin_unlock_irqrestore(&dump_list_lock, flags);
fb842b00 2729 synchronize_rcu();
456b565c
SK
2730
2731 return err;
2732}
2733EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
2734
7ff9554b
KS
2735static bool always_kmsg_dump;
2736module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
2737
456b565c
SK
2738/**
2739 * kmsg_dump - dump kernel log to kernel message dumpers.
2740 * @reason: the reason (oops, panic etc) for dumping
2741 *
e2ae715d
KS
2742 * Call each of the registered dumper's dump() callback, which can
2743 * retrieve the kmsg records with kmsg_dump_get_line() or
2744 * kmsg_dump_get_buffer().
456b565c
SK
2745 */
2746void kmsg_dump(enum kmsg_dump_reason reason)
2747{
456b565c 2748 struct kmsg_dumper *dumper;
456b565c
SK
2749 unsigned long flags;
2750
c22ab332
MG
2751 if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
2752 return;
2753
e2ae715d
KS
2754 rcu_read_lock();
2755 list_for_each_entry_rcu(dumper, &dump_list, list) {
2756 if (dumper->max_reason && reason > dumper->max_reason)
2757 continue;
2758
2759 /* initialize iterator with data about the stored records */
2760 dumper->active = true;
2761
2762 raw_spin_lock_irqsave(&logbuf_lock, flags);
2763 dumper->cur_seq = clear_seq;
2764 dumper->cur_idx = clear_idx;
2765 dumper->next_seq = log_next_seq;
2766 dumper->next_idx = log_next_idx;
2767 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2768
2769 /* invoke dumper which will iterate over records */
2770 dumper->dump(dumper, reason);
2771
2772 /* reset iterator */
2773 dumper->active = false;
2774 }
2775 rcu_read_unlock();
2776}
2777
2778/**
533827c9 2779 * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
e2ae715d
KS
2780 * @dumper: registered kmsg dumper
2781 * @syslog: include the "<4>" prefixes
2782 * @line: buffer to copy the line to
2783 * @size: maximum size of the buffer
2784 * @len: length of line placed into buffer
2785 *
2786 * Start at the beginning of the kmsg buffer, with the oldest kmsg
2787 * record, and copy one record into the provided buffer.
2788 *
2789 * Consecutive calls will return the next available record moving
2790 * towards the end of the buffer with the youngest messages.
2791 *
2792 * A return value of FALSE indicates that there are no more records to
2793 * read.
533827c9
AV
2794 *
2795 * The function is similar to kmsg_dump_get_line(), but grabs no locks.
e2ae715d 2796 */
533827c9
AV
2797bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
2798 char *line, size_t size, size_t *len)
e2ae715d 2799{
62e32ac3 2800 struct printk_log *msg;
e2ae715d
KS
2801 size_t l = 0;
2802 bool ret = false;
2803
2804 if (!dumper->active)
2805 goto out;
7ff9554b 2806
e2ae715d
KS
2807 if (dumper->cur_seq < log_first_seq) {
2808 /* messages are gone, move to first available one */
2809 dumper->cur_seq = log_first_seq;
2810 dumper->cur_idx = log_first_idx;
2811 }
456b565c 2812
e2ae715d 2813 /* last entry */
533827c9 2814 if (dumper->cur_seq >= log_next_seq)
e2ae715d 2815 goto out;
456b565c 2816
e2ae715d 2817 msg = log_from_idx(dumper->cur_idx);
5becfb1d 2818 l = msg_print_text(msg, 0, syslog, line, size);
e2ae715d
KS
2819
2820 dumper->cur_idx = log_next(dumper->cur_idx);
2821 dumper->cur_seq++;
2822 ret = true;
e2ae715d
KS
2823out:
2824 if (len)
2825 *len = l;
2826 return ret;
2827}
533827c9
AV
2828
2829/**
2830 * kmsg_dump_get_line - retrieve one kmsg log line
2831 * @dumper: registered kmsg dumper
2832 * @syslog: include the "<4>" prefixes
2833 * @line: buffer to copy the line to
2834 * @size: maximum size of the buffer
2835 * @len: length of line placed into buffer
2836 *
2837 * Start at the beginning of the kmsg buffer, with the oldest kmsg
2838 * record, and copy one record into the provided buffer.
2839 *
2840 * Consecutive calls will return the next available record moving
2841 * towards the end of the buffer with the youngest messages.
2842 *
2843 * A return value of FALSE indicates that there are no more records to
2844 * read.
2845 */
2846bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
2847 char *line, size_t size, size_t *len)
2848{
2849 unsigned long flags;
2850 bool ret;
2851
2852 raw_spin_lock_irqsave(&logbuf_lock, flags);
2853 ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
2854 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2855
2856 return ret;
2857}
e2ae715d
KS
2858EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
2859
2860/**
2861 * kmsg_dump_get_buffer - copy kmsg log lines
2862 * @dumper: registered kmsg dumper
2863 * @syslog: include the "<4>" prefixes
4f0f4af5 2864 * @buf: buffer to copy the line to
e2ae715d
KS
2865 * @size: maximum size of the buffer
2866 * @len: length of line placed into buffer
2867 *
2868 * Start at the end of the kmsg buffer and fill the provided buffer
2869 * with as many of the the *youngest* kmsg records that fit into it.
2870 * If the buffer is large enough, all available kmsg records will be
2871 * copied with a single call.
2872 *
2873 * Consecutive calls will fill the buffer with the next block of
2874 * available older records, not including the earlier retrieved ones.
2875 *
2876 * A return value of FALSE indicates that there are no more records to
2877 * read.
2878 */
2879bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
2880 char *buf, size_t size, size_t *len)
2881{
2882 unsigned long flags;
2883 u64 seq;
2884 u32 idx;
2885 u64 next_seq;
2886 u32 next_idx;
5becfb1d 2887 enum log_flags prev;
e2ae715d
KS
2888 size_t l = 0;
2889 bool ret = false;
2890
2891 if (!dumper->active)
2892 goto out;
2893
2894 raw_spin_lock_irqsave(&logbuf_lock, flags);
2895 if (dumper->cur_seq < log_first_seq) {
2896 /* messages are gone, move to first available one */
2897 dumper->cur_seq = log_first_seq;
2898 dumper->cur_idx = log_first_idx;
2899 }
2900
2901 /* last entry */
2902 if (dumper->cur_seq >= dumper->next_seq) {
2903 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2904 goto out;
2905 }
2906
2907 /* calculate length of entire buffer */
2908 seq = dumper->cur_seq;
2909 idx = dumper->cur_idx;
5becfb1d 2910 prev = 0;
e2ae715d 2911 while (seq < dumper->next_seq) {
62e32ac3 2912 struct printk_log *msg = log_from_idx(idx);
e2ae715d 2913
5becfb1d 2914 l += msg_print_text(msg, prev, true, NULL, 0);
e2ae715d
KS
2915 idx = log_next(idx);
2916 seq++;
5becfb1d 2917 prev = msg->flags;
e2ae715d
KS
2918 }
2919
2920 /* move first record forward until length fits into the buffer */
2921 seq = dumper->cur_seq;
2922 idx = dumper->cur_idx;
5becfb1d 2923 prev = 0;
e2ae715d 2924 while (l > size && seq < dumper->next_seq) {
62e32ac3 2925 struct printk_log *msg = log_from_idx(idx);
456b565c 2926
5becfb1d 2927 l -= msg_print_text(msg, prev, true, NULL, 0);
e2ae715d
KS
2928 idx = log_next(idx);
2929 seq++;
5becfb1d 2930 prev = msg->flags;
456b565c 2931 }
e2ae715d
KS
2932
2933 /* last message in next interation */
2934 next_seq = seq;
2935 next_idx = idx;
2936
2937 l = 0;
2938 while (seq < dumper->next_seq) {
62e32ac3 2939 struct printk_log *msg = log_from_idx(idx);
e2ae715d 2940
5becfb1d 2941 l += msg_print_text(msg, prev, syslog, buf + l, size - l);
e2ae715d
KS
2942 idx = log_next(idx);
2943 seq++;
5becfb1d 2944 prev = msg->flags;
e2ae715d
KS
2945 }
2946
2947 dumper->next_seq = next_seq;
2948 dumper->next_idx = next_idx;
2949 ret = true;
7ff9554b 2950 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
e2ae715d
KS
2951out:
2952 if (len)
2953 *len = l;
2954 return ret;
2955}
2956EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
456b565c 2957
533827c9
AV
2958/**
2959 * kmsg_dump_rewind_nolock - reset the interator (unlocked version)
2960 * @dumper: registered kmsg dumper
2961 *
2962 * Reset the dumper's iterator so that kmsg_dump_get_line() and
2963 * kmsg_dump_get_buffer() can be called again and used multiple
2964 * times within the same dumper.dump() callback.
2965 *
2966 * The function is similar to kmsg_dump_rewind(), but grabs no locks.
2967 */
2968void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
2969{
2970 dumper->cur_seq = clear_seq;
2971 dumper->cur_idx = clear_idx;
2972 dumper->next_seq = log_next_seq;
2973 dumper->next_idx = log_next_idx;
2974}
2975
e2ae715d
KS
2976/**
2977 * kmsg_dump_rewind - reset the interator
2978 * @dumper: registered kmsg dumper
2979 *
2980 * Reset the dumper's iterator so that kmsg_dump_get_line() and
2981 * kmsg_dump_get_buffer() can be called again and used multiple
2982 * times within the same dumper.dump() callback.
2983 */
2984void kmsg_dump_rewind(struct kmsg_dumper *dumper)
2985{
2986 unsigned long flags;
2987
2988 raw_spin_lock_irqsave(&logbuf_lock, flags);
533827c9 2989 kmsg_dump_rewind_nolock(dumper);
e2ae715d 2990 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
456b565c 2991}
e2ae715d 2992EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
196779b9 2993
98e5e1bf
TH
2994static char dump_stack_arch_desc_str[128];
2995
2996/**
2997 * dump_stack_set_arch_desc - set arch-specific str to show with task dumps
2998 * @fmt: printf-style format string
2999 * @...: arguments for the format string
3000 *
3001 * The configured string will be printed right after utsname during task
3002 * dumps. Usually used to add arch-specific system identifiers. If an
3003 * arch wants to make use of such an ID string, it should initialize this
3004 * as soon as possible during boot.
3005 */
3006void __init dump_stack_set_arch_desc(const char *fmt, ...)
3007{
3008 va_list args;
3009
3010 va_start(args, fmt);
3011 vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
3012 fmt, args);
3013 va_end(args);
3014}
3015
196779b9
TH
3016/**
3017 * dump_stack_print_info - print generic debug info for dump_stack()
3018 * @log_lvl: log level
3019 *
3020 * Arch-specific dump_stack() implementations can use this function to
3021 * print out the same debug information as the generic dump_stack().
3022 */
3023void dump_stack_print_info(const char *log_lvl)
3024{
3025 printk("%sCPU: %d PID: %d Comm: %.20s %s %s %.*s\n",
3026 log_lvl, raw_smp_processor_id(), current->pid, current->comm,
3027 print_tainted(), init_utsname()->release,
3028 (int)strcspn(init_utsname()->version, " "),
3029 init_utsname()->version);
98e5e1bf
TH
3030
3031 if (dump_stack_arch_desc_str[0] != '\0')
3032 printk("%sHardware name: %s\n",
3033 log_lvl, dump_stack_arch_desc_str);
3d1cb205
TH
3034
3035 print_worker_info(log_lvl, current);
196779b9
TH
3036}
3037
a43cb95d
TH
3038/**
3039 * show_regs_print_info - print generic debug info for show_regs()
3040 * @log_lvl: log level
3041 *
3042 * show_regs() implementations can use this function to print out generic
3043 * debug information.
3044 */
3045void show_regs_print_info(const char *log_lvl)
3046{
3047 dump_stack_print_info(log_lvl);
3048
3049 printk("%stask: %p ti: %p task.ti: %p\n",
3050 log_lvl, current, current_thread_info(),
3051 task_thread_info(current));
3052}
3053
7ef3d2fd 3054#endif
This page took 1.027578 seconds and 5 git commands to generate.