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