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