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