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