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