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