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