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