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