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