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