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