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