]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - kernel/printk.c
gcov-kernel: Make gcov work on vanilla gcc again.
[linux-2.6.git] / kernel / printk.c
1 /*
2  *  linux/kernel/printk.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  *
6  * Modified to make sys_syslog() more flexible: added commands to
7  * return the last 4k of kernel messages, regardless of whether
8  * they've been read or not.  Added option to suppress kernel printk's
9  * to the console.  Added hook for sending the console messages
10  * elsewhere, in preparation for a serial line console (someday).
11  * Ted Ts'o, 2/11/93.
12  * Modified for sysctl support, 1/8/97, Chris Horn.
13  * Fixed SMP synchronization, 08/08/99, Manfred Spraul
14  *     manfred@colorfullife.com
15  * Rewrote bits to get rid of console_lock
16  *      01Mar01 Andrew Morton
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/mm.h>
21 #include <linux/tty.h>
22 #include <linux/tty_driver.h>
23 #include <linux/console.h>
24 #include <linux/init.h>
25 #include <linux/jiffies.h>
26 #include <linux/nmi.h>
27 #include <linux/module.h>
28 #include <linux/moduleparam.h>
29 #include <linux/interrupt.h>                    /* For in_interrupt() */
30 #include <linux/delay.h>
31 #include <linux/smp.h>
32 #include <linux/security.h>
33 #include <linux/bootmem.h>
34 #include <linux/memblock.h>
35 #include <linux/syscalls.h>
36 #include <linux/kexec.h>
37 #include <linux/kdb.h>
38 #include <linux/ratelimit.h>
39 #include <linux/kmsg_dump.h>
40 #include <linux/syslog.h>
41 #include <linux/cpu.h>
42 #include <linux/notifier.h>
43 #include <linux/rculist.h>
44
45 #include <asm/uaccess.h>
46
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/printk.h>
49
50 /*
51  * Architectures can override it:
52  */
53 void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
54 {
55 }
56
57 #define __LOG_BUF_LEN   (1 << CONFIG_LOG_BUF_SHIFT)
58
59 #ifdef        CONFIG_DEBUG_LL
60 extern void printascii(char *);
61 #endif
62
63 /* printk's without a loglevel use this.. */
64 #define DEFAULT_MESSAGE_LOGLEVEL CONFIG_DEFAULT_MESSAGE_LOGLEVEL
65
66 /* We show everything that is MORE important than this.. */
67 #define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
68 #define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
69
70 DECLARE_WAIT_QUEUE_HEAD(log_wait);
71
72 int console_printk[4] = {
73         DEFAULT_CONSOLE_LOGLEVEL,       /* console_loglevel */
74         DEFAULT_MESSAGE_LOGLEVEL,       /* default_message_loglevel */
75         MINIMUM_CONSOLE_LOGLEVEL,       /* minimum_console_loglevel */
76         DEFAULT_CONSOLE_LOGLEVEL,       /* default_console_loglevel */
77 };
78
79 /*
80  * Low level drivers may need that to know if they can schedule in
81  * their unblank() callback or not. So let's export it.
82  */
83 int oops_in_progress;
84 EXPORT_SYMBOL(oops_in_progress);
85
86 /*
87  * console_sem protects the console_drivers list, and also
88  * provides serialisation for access to the entire console
89  * driver system.
90  */
91 static DEFINE_SEMAPHORE(console_sem);
92 struct console *console_drivers;
93 EXPORT_SYMBOL_GPL(console_drivers);
94
95 /*
96  * This is used for debugging the mess that is the VT code by
97  * keeping track if we have the console semaphore held. It's
98  * definitely not the perfect debug tool (we don't know if _WE_
99  * hold it are racing, but it helps tracking those weird code
100  * path in the console code where we end up in places I want
101  * locked without the console sempahore held
102  */
103 static int console_locked, console_suspended;
104
105 /*
106  * logbuf_lock protects log_buf, log_start, log_end, con_start and logged_chars
107  * It is also used in interesting ways to provide interlocking in
108  * console_unlock();.
109  */
110 static DEFINE_RAW_SPINLOCK(logbuf_lock);
111
112 #define LOG_BUF_MASK (log_buf_len-1)
113 #define LOG_BUF(idx) (log_buf[(idx) & LOG_BUF_MASK])
114
115 /*
116  * The indices into log_buf are not constrained to log_buf_len - they
117  * must be masked before subscripting
118  */
119 static unsigned log_start;      /* Index into log_buf: next char to be read by syslog() */
120 static unsigned con_start;      /* Index into log_buf: next char to be sent to consoles */
121 static unsigned log_end;        /* Index into log_buf: most-recently-written-char + 1 */
122
123 /*
124  * If exclusive_console is non-NULL then only this console is to be printed to.
125  */
126 static struct console *exclusive_console;
127
128 /*
129  *      Array of consoles built from command line options (console=)
130  */
131 struct console_cmdline
132 {
133         char    name[8];                        /* Name of the driver       */
134         int     index;                          /* Minor dev. to use        */
135         char    *options;                       /* Options for the driver   */
136 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
137         char    *brl_options;                   /* Options for braille driver */
138 #endif
139 };
140
141 #define MAX_CMDLINECONSOLES 8
142
143 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
144 static int selected_console = -1;
145 static int preferred_console = -1;
146 int console_set_on_cmdline;
147 EXPORT_SYMBOL(console_set_on_cmdline);
148
149 /* Flag: console code may call schedule() */
150 static int console_may_schedule;
151
152 #ifdef CONFIG_PRINTK
153
154 static char __log_buf[__LOG_BUF_LEN];
155 static char *log_buf = __log_buf;
156 static int log_buf_len = __LOG_BUF_LEN;
157 static unsigned logged_chars; /* Number of chars produced since last read+clear operation */
158 static int saved_console_loglevel = -1;
159
160 #ifdef CONFIG_KEXEC
161 /*
162  * This appends the listed symbols to /proc/vmcoreinfo
163  *
164  * /proc/vmcoreinfo is used by various utiilties, like crash and makedumpfile to
165  * obtain access to symbols that are otherwise very difficult to locate.  These
166  * symbols are specifically used so that utilities can access and extract the
167  * dmesg log from a vmcore file after a crash.
168  */
169 void log_buf_kexec_setup(void)
170 {
171         VMCOREINFO_SYMBOL(log_buf);
172         VMCOREINFO_SYMBOL(log_end);
173         VMCOREINFO_SYMBOL(log_buf_len);
174         VMCOREINFO_SYMBOL(logged_chars);
175 }
176 #endif
177
178 /* requested log_buf_len from kernel cmdline */
179 static unsigned long __initdata new_log_buf_len;
180
181 /* save requested log_buf_len since it's too early to process it */
182 static int __init log_buf_len_setup(char *str)
183 {
184         unsigned size = memparse(str, &str);
185
186         if (size)
187                 size = roundup_pow_of_two(size);
188         if (size > log_buf_len)
189                 new_log_buf_len = size;
190
191         return 0;
192 }
193 early_param("log_buf_len", log_buf_len_setup);
194
195 void __init setup_log_buf(int early)
196 {
197         unsigned long flags;
198         unsigned start, dest_idx, offset;
199         char *new_log_buf;
200         int free;
201
202         if (!new_log_buf_len)
203                 return;
204
205         if (early) {
206                 unsigned long mem;
207
208                 mem = memblock_alloc(new_log_buf_len, PAGE_SIZE);
209                 if (!mem)
210                         return;
211                 new_log_buf = __va(mem);
212         } else {
213                 new_log_buf = alloc_bootmem_nopanic(new_log_buf_len);
214         }
215
216         if (unlikely(!new_log_buf)) {
217                 pr_err("log_buf_len: %ld bytes not available\n",
218                         new_log_buf_len);
219                 return;
220         }
221
222         raw_spin_lock_irqsave(&logbuf_lock, flags);
223         log_buf_len = new_log_buf_len;
224         log_buf = new_log_buf;
225         new_log_buf_len = 0;
226         free = __LOG_BUF_LEN - log_end;
227
228         offset = start = min(con_start, log_start);
229         dest_idx = 0;
230         while (start != log_end) {
231                 unsigned log_idx_mask = start & (__LOG_BUF_LEN - 1);
232
233                 log_buf[dest_idx] = __log_buf[log_idx_mask];
234                 start++;
235                 dest_idx++;
236         }
237         log_start -= offset;
238         con_start -= offset;
239         log_end -= offset;
240         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
241
242         pr_info("log_buf_len: %d\n", log_buf_len);
243         pr_info("early log buf free: %d(%d%%)\n",
244                 free, (free * 100) / __LOG_BUF_LEN);
245 }
246
247 #ifdef CONFIG_BOOT_PRINTK_DELAY
248
249 static int boot_delay; /* msecs delay after each printk during bootup */
250 static unsigned long long loops_per_msec;       /* based on boot_delay */
251
252 static int __init boot_delay_setup(char *str)
253 {
254         unsigned long lpj;
255
256         lpj = preset_lpj ? preset_lpj : 1000000;        /* some guess */
257         loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
258
259         get_option(&str, &boot_delay);
260         if (boot_delay > 10 * 1000)
261                 boot_delay = 0;
262
263         pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
264                 "HZ: %d, loops_per_msec: %llu\n",
265                 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
266         return 1;
267 }
268 __setup("boot_delay=", boot_delay_setup);
269
270 static void boot_delay_msec(void)
271 {
272         unsigned long long k;
273         unsigned long timeout;
274
275         if (boot_delay == 0 || system_state != SYSTEM_BOOTING)
276                 return;
277
278         k = (unsigned long long)loops_per_msec * boot_delay;
279
280         timeout = jiffies + msecs_to_jiffies(boot_delay);
281         while (k) {
282                 k--;
283                 cpu_relax();
284                 /*
285                  * use (volatile) jiffies to prevent
286                  * compiler reduction; loop termination via jiffies
287                  * is secondary and may or may not happen.
288                  */
289                 if (time_after(jiffies, timeout))
290                         break;
291                 touch_nmi_watchdog();
292         }
293 }
294 #else
295 static inline void boot_delay_msec(void)
296 {
297 }
298 #endif
299
300 /*
301  * Return the number of unread characters in the log buffer.
302  */
303 static int log_buf_get_len(void)
304 {
305         return logged_chars;
306 }
307
308 /*
309  * Clears the ring-buffer
310  */
311 void log_buf_clear(void)
312 {
313         logged_chars = 0;
314 }
315
316 /*
317  * Copy a range of characters from the log buffer.
318  */
319 int log_buf_copy(char *dest, int idx, int len)
320 {
321         int ret, max;
322         bool took_lock = false;
323
324         if (!oops_in_progress) {
325                 raw_spin_lock_irq(&logbuf_lock);
326                 took_lock = true;
327         }
328
329         max = log_buf_get_len();
330         if (idx < 0 || idx >= max) {
331                 ret = -1;
332         } else {
333                 if (len > max - idx)
334                         len = max - idx;
335                 ret = len;
336                 idx += (log_end - max);
337                 while (len-- > 0)
338                         dest[len] = LOG_BUF(idx + len);
339         }
340
341         if (took_lock)
342                 raw_spin_unlock_irq(&logbuf_lock);
343
344         return ret;
345 }
346
347 #ifdef CONFIG_SECURITY_DMESG_RESTRICT
348 int dmesg_restrict = 1;
349 #else
350 int dmesg_restrict;
351 #endif
352
353 static int syslog_action_restricted(int type)
354 {
355         if (dmesg_restrict)
356                 return 1;
357         /* Unless restricted, we allow "read all" and "get buffer size" for everybody */
358         return type != SYSLOG_ACTION_READ_ALL && type != SYSLOG_ACTION_SIZE_BUFFER;
359 }
360
361 static int check_syslog_permissions(int type, bool from_file)
362 {
363         /*
364          * If this is from /proc/kmsg and we've already opened it, then we've
365          * already done the capabilities checks at open time.
366          */
367         if (from_file && type != SYSLOG_ACTION_OPEN)
368                 return 0;
369
370         if (syslog_action_restricted(type)) {
371                 if (capable(CAP_SYSLOG))
372                         return 0;
373                 /* For historical reasons, accept CAP_SYS_ADMIN too, with a warning */
374                 if (capable(CAP_SYS_ADMIN)) {
375                         printk_once(KERN_WARNING "%s (%d): "
376                                  "Attempt to access syslog with CAP_SYS_ADMIN "
377                                  "but no CAP_SYSLOG (deprecated).\n",
378                                  current->comm, task_pid_nr(current));
379                         return 0;
380                 }
381                 return -EPERM;
382         }
383         return 0;
384 }
385
386 int do_syslog(int type, char __user *buf, int len, bool from_file)
387 {
388         unsigned i, j, limit, count;
389         int do_clear = 0;
390         char c;
391         int error;
392
393         error = check_syslog_permissions(type, from_file);
394         if (error)
395                 goto out;
396
397         error = security_syslog(type);
398         if (error)
399                 return error;
400
401         switch (type) {
402         case SYSLOG_ACTION_CLOSE:       /* Close log */
403                 break;
404         case SYSLOG_ACTION_OPEN:        /* Open log */
405                 break;
406         case SYSLOG_ACTION_READ:        /* Read from log */
407                 error = -EINVAL;
408                 if (!buf || len < 0)
409                         goto out;
410                 error = 0;
411                 if (!len)
412                         goto out;
413                 if (!access_ok(VERIFY_WRITE, buf, len)) {
414                         error = -EFAULT;
415                         goto out;
416                 }
417                 error = wait_event_interruptible(log_wait,
418                                                         (log_start - log_end));
419                 if (error)
420                         goto out;
421                 i = 0;
422                 raw_spin_lock_irq(&logbuf_lock);
423                 while (!error && (log_start != log_end) && i < len) {
424                         c = LOG_BUF(log_start);
425                         log_start++;
426                         raw_spin_unlock_irq(&logbuf_lock);
427                         error = __put_user(c,buf);
428                         buf++;
429                         i++;
430                         cond_resched();
431                         raw_spin_lock_irq(&logbuf_lock);
432                 }
433                 raw_spin_unlock_irq(&logbuf_lock);
434                 if (!error)
435                         error = i;
436                 break;
437         /* Read/clear last kernel messages */
438         case SYSLOG_ACTION_READ_CLEAR:
439                 do_clear = 1;
440                 /* FALL THRU */
441         /* Read last kernel messages */
442         case SYSLOG_ACTION_READ_ALL:
443                 error = -EINVAL;
444                 if (!buf || len < 0)
445                         goto out;
446                 error = 0;
447                 if (!len)
448                         goto out;
449                 if (!access_ok(VERIFY_WRITE, buf, len)) {
450                         error = -EFAULT;
451                         goto out;
452                 }
453                 count = len;
454                 if (count > log_buf_len)
455                         count = log_buf_len;
456                 raw_spin_lock_irq(&logbuf_lock);
457                 if (count > logged_chars)
458                         count = logged_chars;
459                 if (do_clear)
460                         logged_chars = 0;
461                 limit = log_end;
462                 /*
463                  * __put_user() could sleep, and while we sleep
464                  * printk() could overwrite the messages
465                  * we try to copy to user space. Therefore
466                  * the messages are copied in reverse. <manfreds>
467                  */
468                 for (i = 0; i < count && !error; i++) {
469                         j = limit-1-i;
470                         if (j + log_buf_len < log_end)
471                                 break;
472                         c = LOG_BUF(j);
473                         raw_spin_unlock_irq(&logbuf_lock);
474                         error = __put_user(c,&buf[count-1-i]);
475                         cond_resched();
476                         raw_spin_lock_irq(&logbuf_lock);
477                 }
478                 raw_spin_unlock_irq(&logbuf_lock);
479                 if (error)
480                         break;
481                 error = i;
482                 if (i != count) {
483                         int offset = count-error;
484                         /* buffer overflow during copy, correct user buffer. */
485                         for (i = 0; i < error; i++) {
486                                 if (__get_user(c,&buf[i+offset]) ||
487                                     __put_user(c,&buf[i])) {
488                                         error = -EFAULT;
489                                         break;
490                                 }
491                                 cond_resched();
492                         }
493                 }
494                 break;
495         /* Clear ring buffer */
496         case SYSLOG_ACTION_CLEAR:
497                 logged_chars = 0;
498                 break;
499         /* Disable logging to console */
500         case SYSLOG_ACTION_CONSOLE_OFF:
501                 if (saved_console_loglevel == -1)
502                         saved_console_loglevel = console_loglevel;
503                 console_loglevel = minimum_console_loglevel;
504                 break;
505         /* Enable logging to console */
506         case SYSLOG_ACTION_CONSOLE_ON:
507                 if (saved_console_loglevel != -1) {
508                         console_loglevel = saved_console_loglevel;
509                         saved_console_loglevel = -1;
510                 }
511                 break;
512         /* Set level of messages printed to console */
513         case SYSLOG_ACTION_CONSOLE_LEVEL:
514                 error = -EINVAL;
515                 if (len < 1 || len > 8)
516                         goto out;
517                 if (len < minimum_console_loglevel)
518                         len = minimum_console_loglevel;
519                 console_loglevel = len;
520                 /* Implicitly re-enable logging to console */
521                 saved_console_loglevel = -1;
522                 error = 0;
523                 break;
524         /* Number of chars in the log buffer */
525         case SYSLOG_ACTION_SIZE_UNREAD:
526                 error = log_end - log_start;
527                 break;
528         /* Size of the log buffer */
529         case SYSLOG_ACTION_SIZE_BUFFER:
530                 error = log_buf_len;
531                 break;
532         default:
533                 error = -EINVAL;
534                 break;
535         }
536 out:
537         return error;
538 }
539
540 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
541 {
542         return do_syslog(type, buf, len, SYSLOG_FROM_CALL);
543 }
544
545 #ifdef  CONFIG_KGDB_KDB
546 /* kdb dmesg command needs access to the syslog buffer.  do_syslog()
547  * uses locks so it cannot be used during debugging.  Just tell kdb
548  * where the start and end of the physical and logical logs are.  This
549  * is equivalent to do_syslog(3).
550  */
551 void kdb_syslog_data(char *syslog_data[4])
552 {
553         syslog_data[0] = log_buf;
554         syslog_data[1] = log_buf + log_buf_len;
555         syslog_data[2] = log_buf + log_end -
556                 (logged_chars < log_buf_len ? logged_chars : log_buf_len);
557         syslog_data[3] = log_buf + log_end;
558 }
559 #endif  /* CONFIG_KGDB_KDB */
560
561 /*
562  * Call the console drivers on a range of log_buf
563  */
564 static void __call_console_drivers(unsigned start, unsigned end)
565 {
566         struct console *con;
567
568         for_each_console(con) {
569                 if (exclusive_console && con != exclusive_console)
570                         continue;
571                 if ((con->flags & CON_ENABLED) && con->write &&
572                                 (cpu_online(smp_processor_id()) ||
573                                 (con->flags & CON_ANYTIME)))
574                         con->write(con, &LOG_BUF(start), end - start);
575         }
576 }
577
578 static bool __read_mostly ignore_loglevel;
579
580 static int __init ignore_loglevel_setup(char *str)
581 {
582         ignore_loglevel = 1;
583         printk(KERN_INFO "debug: ignoring loglevel setting.\n");
584
585         return 0;
586 }
587
588 early_param("ignore_loglevel", ignore_loglevel_setup);
589 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
590 MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
591         "print all kernel messages to the console.");
592
593 /*
594  * Write out chars from start to end - 1 inclusive
595  */
596 static void _call_console_drivers(unsigned start,
597                                 unsigned end, int msg_log_level)
598 {
599         trace_console(&LOG_BUF(0), start, end, log_buf_len);
600
601         if ((msg_log_level < console_loglevel || ignore_loglevel) &&
602                         console_drivers && start != end) {
603                 if ((start & LOG_BUF_MASK) > (end & LOG_BUF_MASK)) {
604                         /* wrapped write */
605                         __call_console_drivers(start & LOG_BUF_MASK,
606                                                 log_buf_len);
607                         __call_console_drivers(0, end & LOG_BUF_MASK);
608                 } else {
609                         __call_console_drivers(start, end);
610                 }
611         }
612 }
613
614 /*
615  * Parse the syslog header <[0-9]*>. The decimal value represents 32bit, the
616  * lower 3 bit are the log level, the rest are the log facility. In case
617  * userspace passes usual userspace syslog messages to /dev/kmsg or
618  * /dev/ttyprintk, the log prefix might contain the facility. Printk needs
619  * to extract the correct log level for in-kernel processing, and not mangle
620  * the original value.
621  *
622  * If a prefix is found, the length of the prefix is returned. If 'level' is
623  * passed, it will be filled in with the log level without a possible facility
624  * value. If 'special' is passed, the special printk prefix chars are accepted
625  * and returned. If no valid header is found, 0 is returned and the passed
626  * variables are not touched.
627  */
628 static size_t log_prefix(const char *p, unsigned int *level, char *special)
629 {
630         unsigned int lev = 0;
631         char sp = '\0';
632         size_t len;
633
634         if (p[0] != '<' || !p[1])
635                 return 0;
636         if (p[2] == '>') {
637                 /* usual single digit level number or special char */
638                 switch (p[1]) {
639                 case '0' ... '7':
640                         lev = p[1] - '0';
641                         break;
642                 case 'c': /* KERN_CONT */
643                 case 'd': /* KERN_DEFAULT */
644                         sp = p[1];
645                         break;
646                 default:
647                         return 0;
648                 }
649                 len = 3;
650         } else {
651                 /* multi digit including the level and facility number */
652                 char *endp = NULL;
653
654                 lev = (simple_strtoul(&p[1], &endp, 10) & 7);
655                 if (endp == NULL || endp[0] != '>')
656                         return 0;
657                 len = (endp + 1) - p;
658         }
659
660         /* do not accept special char if not asked for */
661         if (sp && !special)
662                 return 0;
663
664         if (special) {
665                 *special = sp;
666                 /* return special char, do not touch level */
667                 if (sp)
668                         return len;
669         }
670
671         if (level)
672                 *level = lev;
673         return len;
674 }
675
676 /*
677  * Call the console drivers, asking them to write out
678  * log_buf[start] to log_buf[end - 1].
679  * The console_lock must be held.
680  */
681 static void call_console_drivers(unsigned start, unsigned end)
682 {
683         unsigned cur_index, start_print;
684         static int msg_level = -1;
685
686         BUG_ON(((int)(start - end)) > 0);
687
688         cur_index = start;
689         start_print = start;
690         while (cur_index != end) {
691                 if (msg_level < 0 && ((end - cur_index) > 2)) {
692                         /* strip log prefix */
693                         cur_index += log_prefix(&LOG_BUF(cur_index), &msg_level, NULL);
694                         start_print = cur_index;
695                 }
696                 while (cur_index != end) {
697                         char c = LOG_BUF(cur_index);
698
699                         cur_index++;
700                         if (c == '\n') {
701                                 if (msg_level < 0) {
702                                         /*
703                                          * printk() has already given us loglevel tags in
704                                          * the buffer.  This code is here in case the
705                                          * log buffer has wrapped right round and scribbled
706                                          * on those tags
707                                          */
708                                         msg_level = default_message_loglevel;
709                                 }
710                                 _call_console_drivers(start_print, cur_index, msg_level);
711                                 msg_level = -1;
712                                 start_print = cur_index;
713                                 break;
714                         }
715                 }
716         }
717         _call_console_drivers(start_print, end, msg_level);
718 }
719
720 static void emit_log_char(char c)
721 {
722         LOG_BUF(log_end) = c;
723         log_end++;
724         if (log_end - log_start > log_buf_len)
725                 log_start = log_end - log_buf_len;
726         if (log_end - con_start > log_buf_len)
727                 con_start = log_end - log_buf_len;
728         if (logged_chars < log_buf_len)
729                 logged_chars++;
730 }
731
732 /*
733  * Zap console related locks when oopsing. Only zap at most once
734  * every 10 seconds, to leave time for slow consoles to print a
735  * full oops.
736  */
737 static void zap_locks(void)
738 {
739         static unsigned long oops_timestamp;
740
741         if (time_after_eq(jiffies, oops_timestamp) &&
742                         !time_after(jiffies, oops_timestamp + 30 * HZ))
743                 return;
744
745         oops_timestamp = jiffies;
746
747         debug_locks_off();
748         /* If a crash is occurring, make sure we can't deadlock */
749         raw_spin_lock_init(&logbuf_lock);
750         /* And make sure that we print immediately */
751         sema_init(&console_sem, 1);
752 }
753
754 #if defined(CONFIG_PRINTK_TIME)
755 static bool printk_time = 1;
756 #else
757 static bool printk_time = 0;
758 #endif
759 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
760
761 static bool always_kmsg_dump;
762 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
763
764 /* Check if we have any console registered that can be called early in boot. */
765 static int have_callable_console(void)
766 {
767         struct console *con;
768
769         for_each_console(con)
770                 if (con->flags & CON_ANYTIME)
771                         return 1;
772
773         return 0;
774 }
775
776 /**
777  * printk - print a kernel message
778  * @fmt: format string
779  *
780  * This is printk().  It can be called from any context.  We want it to work.
781  *
782  * We try to grab the console_lock.  If we succeed, it's easy - we log the output and
783  * call the console drivers.  If we fail to get the semaphore we place the output
784  * into the log buffer and return.  The current holder of the console_sem will
785  * notice the new output in console_unlock(); and will send it to the
786  * consoles before releasing the lock.
787  *
788  * One effect of this deferred printing is that code which calls printk() and
789  * then changes console_loglevel may break. This is because console_loglevel
790  * is inspected when the actual printing occurs.
791  *
792  * See also:
793  * printf(3)
794  *
795  * See the vsnprintf() documentation for format string extensions over C99.
796  */
797
798 asmlinkage int printk(const char *fmt, ...)
799 {
800         va_list args;
801         int r;
802
803 #ifdef CONFIG_KGDB_KDB
804         if (unlikely(kdb_trap_printk)) {
805                 va_start(args, fmt);
806                 r = vkdb_printf(fmt, args);
807                 va_end(args);
808                 return r;
809         }
810 #endif
811         va_start(args, fmt);
812         r = vprintk(fmt, args);
813         va_end(args);
814
815         return r;
816 }
817
818 /* cpu currently holding logbuf_lock */
819 static volatile unsigned int printk_cpu = UINT_MAX;
820
821 /*
822  * Can we actually use the console at this time on this cpu?
823  *
824  * Console drivers may assume that per-cpu resources have
825  * been allocated. So unless they're explicitly marked as
826  * being able to cope (CON_ANYTIME) don't call them until
827  * this CPU is officially up.
828  */
829 static inline int can_use_console(unsigned int cpu)
830 {
831         return cpu_online(cpu) || have_callable_console();
832 }
833
834 /*
835  * Try to get console ownership to actually show the kernel
836  * messages from a 'printk'. Return true (and with the
837  * console_lock held, and 'console_locked' set) if it
838  * is successful, false otherwise.
839  *
840  * This gets called with the 'logbuf_lock' spinlock held and
841  * interrupts disabled. It should return with 'lockbuf_lock'
842  * released but interrupts still disabled.
843  */
844 static int console_trylock_for_printk(unsigned int cpu)
845         __releases(&logbuf_lock)
846 {
847         int retval = 0, wake = 0;
848
849         if (console_trylock()) {
850                 retval = 1;
851
852                 /*
853                  * If we can't use the console, we need to release
854                  * the console semaphore by hand to avoid flushing
855                  * the buffer. We need to hold the console semaphore
856                  * in order to do this test safely.
857                  */
858                 if (!can_use_console(cpu)) {
859                         console_locked = 0;
860                         wake = 1;
861                         retval = 0;
862                 }
863         }
864         printk_cpu = UINT_MAX;
865         if (wake)
866                 up(&console_sem);
867         raw_spin_unlock(&logbuf_lock);
868         return retval;
869 }
870 static const char recursion_bug_msg [] =
871                 KERN_CRIT "BUG: recent printk recursion!\n";
872 static int recursion_bug;
873 static int new_text_line = 1;
874 static char printk_buf[1024];
875
876 int printk_delay_msec __read_mostly;
877
878 static inline void printk_delay(void)
879 {
880         if (unlikely(printk_delay_msec)) {
881                 int m = printk_delay_msec;
882
883                 while (m--) {
884                         mdelay(1);
885                         touch_nmi_watchdog();
886                 }
887         }
888 }
889
890 asmlinkage int vprintk(const char *fmt, va_list args)
891 {
892         int printed_len = 0;
893         int current_log_level = default_message_loglevel;
894         unsigned long flags;
895         int this_cpu;
896         char *p;
897         size_t plen;
898         char special;
899
900         boot_delay_msec();
901         printk_delay();
902
903         /* This stops the holder of console_sem just where we want him */
904         local_irq_save(flags);
905         this_cpu = smp_processor_id();
906
907         /*
908          * Ouch, printk recursed into itself!
909          */
910         if (unlikely(printk_cpu == this_cpu)) {
911                 /*
912                  * If a crash is occurring during printk() on this CPU,
913                  * then try to get the crash message out but make sure
914                  * we can't deadlock. Otherwise just return to avoid the
915                  * recursion and return - but flag the recursion so that
916                  * it can be printed at the next appropriate moment:
917                  */
918                 if (!oops_in_progress && !lockdep_recursing(current)) {
919                         recursion_bug = 1;
920                         goto out_restore_irqs;
921                 }
922                 zap_locks();
923         }
924
925         lockdep_off();
926         raw_spin_lock(&logbuf_lock);
927         printk_cpu = this_cpu;
928
929         if (recursion_bug) {
930                 recursion_bug = 0;
931                 strcpy(printk_buf, recursion_bug_msg);
932                 printed_len = strlen(recursion_bug_msg);
933         }
934         /* Emit the output into the temporary buffer */
935         printed_len += vscnprintf(printk_buf + printed_len,
936                                   sizeof(printk_buf) - printed_len, fmt, args);
937
938 #ifdef  CONFIG_DEBUG_LL
939         printascii(printk_buf);
940 #endif
941
942         p = printk_buf;
943
944         /* Read log level and handle special printk prefix */
945         plen = log_prefix(p, &current_log_level, &special);
946         if (plen) {
947                 p += plen;
948
949                 switch (special) {
950                 case 'c': /* Strip <c> KERN_CONT, continue line */
951                         plen = 0;
952                         break;
953                 case 'd': /* Strip <d> KERN_DEFAULT, start new line */
954                         plen = 0;
955                 default:
956                         if (!new_text_line) {
957                                 emit_log_char('\n');
958                                 new_text_line = 1;
959                         }
960                 }
961         }
962
963         /*
964          * Copy the output into log_buf. If the caller didn't provide
965          * the appropriate log prefix, we insert them here
966          */
967         for (; *p; p++) {
968                 if (new_text_line) {
969                         new_text_line = 0;
970
971                         if (plen) {
972                                 /* Copy original log prefix */
973                                 int i;
974
975                                 for (i = 0; i < plen; i++)
976                                         emit_log_char(printk_buf[i]);
977                                 printed_len += plen;
978                         } else {
979                                 /* Add log prefix */
980                                 emit_log_char('<');
981                                 emit_log_char(current_log_level + '0');
982                                 emit_log_char('>');
983                                 printed_len += 3;
984                         }
985
986                         if (printk_time) {
987                                 /* Add the current time stamp */
988                                 char tbuf[50], *tp;
989                                 unsigned tlen;
990                                 unsigned long long t;
991                                 unsigned long nanosec_rem;
992
993                                 t = cpu_clock(printk_cpu);
994                                 nanosec_rem = do_div(t, 1000000000);
995                                 tlen = sprintf(tbuf, "[%5lu.%06lu] ",
996                                                 (unsigned long) t,
997                                                 nanosec_rem / 1000);
998
999                                 for (tp = tbuf; tp < tbuf + tlen; tp++)
1000                                         emit_log_char(*tp);
1001                                 printed_len += tlen;
1002                         }
1003
1004                         if (!*p)
1005                                 break;
1006                 }
1007
1008                 emit_log_char(*p);
1009                 if (*p == '\n')
1010                         new_text_line = 1;
1011         }
1012
1013         /*
1014          * Try to acquire and then immediately release the
1015          * console semaphore. The release will do all the
1016          * actual magic (print out buffers, wake up klogd,
1017          * etc).
1018          *
1019          * The console_trylock_for_printk() function
1020          * will release 'logbuf_lock' regardless of whether it
1021          * actually gets the semaphore or not.
1022          */
1023         if (console_trylock_for_printk(this_cpu))
1024                 console_unlock();
1025
1026         lockdep_on();
1027 out_restore_irqs:
1028         local_irq_restore(flags);
1029
1030         return printed_len;
1031 }
1032 EXPORT_SYMBOL(printk);
1033 EXPORT_SYMBOL(vprintk);
1034
1035 #else
1036
1037 static void call_console_drivers(unsigned start, unsigned end)
1038 {
1039 }
1040
1041 #endif
1042
1043 static int __add_preferred_console(char *name, int idx, char *options,
1044                                    char *brl_options)
1045 {
1046         struct console_cmdline *c;
1047         int i;
1048
1049         /*
1050          *      See if this tty is not yet registered, and
1051          *      if we have a slot free.
1052          */
1053         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
1054                 if (strcmp(console_cmdline[i].name, name) == 0 &&
1055                           console_cmdline[i].index == idx) {
1056                                 if (!brl_options)
1057                                         selected_console = i;
1058                                 return 0;
1059                 }
1060         if (i == MAX_CMDLINECONSOLES)
1061                 return -E2BIG;
1062         if (!brl_options)
1063                 selected_console = i;
1064         c = &console_cmdline[i];
1065         strlcpy(c->name, name, sizeof(c->name));
1066         c->options = options;
1067 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1068         c->brl_options = brl_options;
1069 #endif
1070         c->index = idx;
1071         return 0;
1072 }
1073 /*
1074  * Set up a list of consoles.  Called from init/main.c
1075  */
1076 static int __init console_setup(char *str)
1077 {
1078         char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
1079         char *s, *options, *brl_options = NULL;
1080         int idx;
1081
1082 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1083         if (!memcmp(str, "brl,", 4)) {
1084                 brl_options = "";
1085                 str += 4;
1086         } else if (!memcmp(str, "brl=", 4)) {
1087                 brl_options = str + 4;
1088                 str = strchr(brl_options, ',');
1089                 if (!str) {
1090                         printk(KERN_ERR "need port name after brl=\n");
1091                         return 1;
1092                 }
1093                 *(str++) = 0;
1094         }
1095 #endif
1096
1097         /*
1098          * Decode str into name, index, options.
1099          */
1100         if (str[0] >= '0' && str[0] <= '9') {
1101                 strcpy(buf, "ttyS");
1102                 strncpy(buf + 4, str, sizeof(buf) - 5);
1103         } else {
1104                 strncpy(buf, str, sizeof(buf) - 1);
1105         }
1106         buf[sizeof(buf) - 1] = 0;
1107         if ((options = strchr(str, ',')) != NULL)
1108                 *(options++) = 0;
1109 #ifdef __sparc__
1110         if (!strcmp(str, "ttya"))
1111                 strcpy(buf, "ttyS0");
1112         if (!strcmp(str, "ttyb"))
1113                 strcpy(buf, "ttyS1");
1114 #endif
1115         for (s = buf; *s; s++)
1116                 if ((*s >= '0' && *s <= '9') || *s == ',')
1117                         break;
1118         idx = simple_strtoul(s, NULL, 10);
1119         *s = 0;
1120
1121         __add_preferred_console(buf, idx, options, brl_options);
1122         console_set_on_cmdline = 1;
1123         return 1;
1124 }
1125 __setup("console=", console_setup);
1126
1127 /**
1128  * add_preferred_console - add a device to the list of preferred consoles.
1129  * @name: device name
1130  * @idx: device index
1131  * @options: options for this console
1132  *
1133  * The last preferred console added will be used for kernel messages
1134  * and stdin/out/err for init.  Normally this is used by console_setup
1135  * above to handle user-supplied console arguments; however it can also
1136  * be used by arch-specific code either to override the user or more
1137  * commonly to provide a default console (ie from PROM variables) when
1138  * the user has not supplied one.
1139  */
1140 int add_preferred_console(char *name, int idx, char *options)
1141 {
1142         return __add_preferred_console(name, idx, options, NULL);
1143 }
1144
1145 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
1146 {
1147         struct console_cmdline *c;
1148         int i;
1149
1150         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
1151                 if (strcmp(console_cmdline[i].name, name) == 0 &&
1152                           console_cmdline[i].index == idx) {
1153                                 c = &console_cmdline[i];
1154                                 strlcpy(c->name, name_new, sizeof(c->name));
1155                                 c->name[sizeof(c->name) - 1] = 0;
1156                                 c->options = options;
1157                                 c->index = idx_new;
1158                                 return i;
1159                 }
1160         /* not found */
1161         return -1;
1162 }
1163
1164 bool console_suspend_enabled = 1;
1165 EXPORT_SYMBOL(console_suspend_enabled);
1166
1167 static int __init console_suspend_disable(char *str)
1168 {
1169         console_suspend_enabled = 0;
1170         return 1;
1171 }
1172 __setup("no_console_suspend", console_suspend_disable);
1173 module_param_named(console_suspend, console_suspend_enabled,
1174                 bool, S_IRUGO | S_IWUSR);
1175 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
1176         " and hibernate operations");
1177
1178 /**
1179  * suspend_console - suspend the console subsystem
1180  *
1181  * This disables printk() while we go into suspend states
1182  */
1183 void suspend_console(void)
1184 {
1185         if (!console_suspend_enabled)
1186                 return;
1187         printk("Suspending console(s) (use no_console_suspend to debug)\n");
1188         console_lock();
1189         console_suspended = 1;
1190         up(&console_sem);
1191 }
1192
1193 void resume_console(void)
1194 {
1195         if (!console_suspend_enabled)
1196                 return;
1197         down(&console_sem);
1198         console_suspended = 0;
1199         console_unlock();
1200 }
1201
1202 /**
1203  * console_cpu_notify - print deferred console messages after CPU hotplug
1204  * @self: notifier struct
1205  * @action: CPU hotplug event
1206  * @hcpu: unused
1207  *
1208  * If printk() is called from a CPU that is not online yet, the messages
1209  * will be spooled but will not show up on the console.  This function is
1210  * called when a new CPU comes online (or fails to come up), and ensures
1211  * that any such output gets printed.
1212  */
1213 static int __cpuinit console_cpu_notify(struct notifier_block *self,
1214         unsigned long action, void *hcpu)
1215 {
1216         switch (action) {
1217         case CPU_ONLINE:
1218         case CPU_DEAD:
1219         case CPU_DOWN_FAILED:
1220         case CPU_UP_CANCELED:
1221                 console_lock();
1222                 console_unlock();
1223         }
1224         return NOTIFY_OK;
1225 }
1226
1227 /**
1228  * console_lock - lock the console system for exclusive use.
1229  *
1230  * Acquires a lock which guarantees that the caller has
1231  * exclusive access to the console system and the console_drivers list.
1232  *
1233  * Can sleep, returns nothing.
1234  */
1235 void console_lock(void)
1236 {
1237         BUG_ON(in_interrupt());
1238         down(&console_sem);
1239         if (console_suspended)
1240                 return;
1241         console_locked = 1;
1242         console_may_schedule = 1;
1243 }
1244 EXPORT_SYMBOL(console_lock);
1245
1246 /**
1247  * console_trylock - try to lock the console system for exclusive use.
1248  *
1249  * Tried to acquire a lock which guarantees that the caller has
1250  * exclusive access to the console system and the console_drivers list.
1251  *
1252  * returns 1 on success, and 0 on failure to acquire the lock.
1253  */
1254 int console_trylock(void)
1255 {
1256         if (down_trylock(&console_sem))
1257                 return 0;
1258         if (console_suspended) {
1259                 up(&console_sem);
1260                 return 0;
1261         }
1262         console_locked = 1;
1263         console_may_schedule = 0;
1264         return 1;
1265 }
1266 EXPORT_SYMBOL(console_trylock);
1267
1268 int is_console_locked(void)
1269 {
1270         return console_locked;
1271 }
1272
1273 /*
1274  * Delayed printk facility, for scheduler-internal messages:
1275  */
1276 #define PRINTK_BUF_SIZE         512
1277
1278 #define PRINTK_PENDING_WAKEUP   0x01
1279 #define PRINTK_PENDING_SCHED    0x02
1280
1281 static DEFINE_PER_CPU(int, printk_pending);
1282 static DEFINE_PER_CPU(char [PRINTK_BUF_SIZE], printk_sched_buf);
1283
1284 void printk_tick(void)
1285 {
1286         if (__this_cpu_read(printk_pending)) {
1287                 int pending = __this_cpu_xchg(printk_pending, 0);
1288                 if (pending & PRINTK_PENDING_SCHED) {
1289                         char *buf = __get_cpu_var(printk_sched_buf);
1290                         printk(KERN_WARNING "[sched_delayed] %s", buf);
1291                 }
1292                 if (pending & PRINTK_PENDING_WAKEUP)
1293                         wake_up_interruptible(&log_wait);
1294         }
1295 }
1296
1297 int printk_needs_cpu(int cpu)
1298 {
1299         if (cpu_is_offline(cpu))
1300                 printk_tick();
1301         return __this_cpu_read(printk_pending);
1302 }
1303
1304 void wake_up_klogd(void)
1305 {
1306         if (waitqueue_active(&log_wait))
1307                 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
1308 }
1309
1310 /**
1311  * console_unlock - unlock the console system
1312  *
1313  * Releases the console_lock which the caller holds on the console system
1314  * and the console driver list.
1315  *
1316  * While the console_lock was held, console output may have been buffered
1317  * by printk().  If this is the case, console_unlock(); emits
1318  * the output prior to releasing the lock.
1319  *
1320  * If there is output waiting for klogd, we wake it up.
1321  *
1322  * console_unlock(); may be called from any context.
1323  */
1324 void console_unlock(void)
1325 {
1326         unsigned long flags;
1327         unsigned _con_start, _log_end;
1328         unsigned wake_klogd = 0, retry = 0;
1329
1330         if (console_suspended) {
1331                 up(&console_sem);
1332                 return;
1333         }
1334
1335         console_may_schedule = 0;
1336
1337 again:
1338         for ( ; ; ) {
1339                 raw_spin_lock_irqsave(&logbuf_lock, flags);
1340                 wake_klogd |= log_start - log_end;
1341                 if (con_start == log_end)
1342                         break;                  /* Nothing to print */
1343                 _con_start = con_start;
1344                 _log_end = log_end;
1345                 con_start = log_end;            /* Flush */
1346                 raw_spin_unlock(&logbuf_lock);
1347                 stop_critical_timings();        /* don't trace print latency */
1348                 call_console_drivers(_con_start, _log_end);
1349                 start_critical_timings();
1350                 local_irq_restore(flags);
1351         }
1352         console_locked = 0;
1353
1354         /* Release the exclusive_console once it is used */
1355         if (unlikely(exclusive_console))
1356                 exclusive_console = NULL;
1357
1358         raw_spin_unlock(&logbuf_lock);
1359
1360         up(&console_sem);
1361
1362         /*
1363          * Someone could have filled up the buffer again, so re-check if there's
1364          * something to flush. In case we cannot trylock the console_sem again,
1365          * there's a new owner and the console_unlock() from them will do the
1366          * flush, no worries.
1367          */
1368         raw_spin_lock(&logbuf_lock);
1369         if (con_start != log_end)
1370                 retry = 1;
1371         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
1372
1373         if (retry && console_trylock())
1374                 goto again;
1375
1376         if (wake_klogd)
1377                 wake_up_klogd();
1378 }
1379 EXPORT_SYMBOL(console_unlock);
1380
1381 /**
1382  * console_conditional_schedule - yield the CPU if required
1383  *
1384  * If the console code is currently allowed to sleep, and
1385  * if this CPU should yield the CPU to another task, do
1386  * so here.
1387  *
1388  * Must be called within console_lock();.
1389  */
1390 void __sched console_conditional_schedule(void)
1391 {
1392         if (console_may_schedule)
1393                 cond_resched();
1394 }
1395 EXPORT_SYMBOL(console_conditional_schedule);
1396
1397 void console_unblank(void)
1398 {
1399         struct console *c;
1400
1401         /*
1402          * console_unblank can no longer be called in interrupt context unless
1403          * oops_in_progress is set to 1..
1404          */
1405         if (oops_in_progress) {
1406                 if (down_trylock(&console_sem) != 0)
1407                         return;
1408         } else
1409                 console_lock();
1410
1411         console_locked = 1;
1412         console_may_schedule = 0;
1413         for_each_console(c)
1414                 if ((c->flags & CON_ENABLED) && c->unblank)
1415                         c->unblank();
1416         console_unlock();
1417 }
1418
1419 /*
1420  * Return the console tty driver structure and its associated index
1421  */
1422 struct tty_driver *console_device(int *index)
1423 {
1424         struct console *c;
1425         struct tty_driver *driver = NULL;
1426
1427         console_lock();
1428         for_each_console(c) {
1429                 if (!c->device)
1430                         continue;
1431                 driver = c->device(c, index);
1432                 if (driver)
1433                         break;
1434         }
1435         console_unlock();
1436         return driver;
1437 }
1438
1439 /*
1440  * Prevent further output on the passed console device so that (for example)
1441  * serial drivers can disable console output before suspending a port, and can
1442  * re-enable output afterwards.
1443  */
1444 void console_stop(struct console *console)
1445 {
1446         console_lock();
1447         console->flags &= ~CON_ENABLED;
1448         console_unlock();
1449 }
1450 EXPORT_SYMBOL(console_stop);
1451
1452 void console_start(struct console *console)
1453 {
1454         console_lock();
1455         console->flags |= CON_ENABLED;
1456         console_unlock();
1457 }
1458 EXPORT_SYMBOL(console_start);
1459
1460 static int __read_mostly keep_bootcon;
1461
1462 static int __init keep_bootcon_setup(char *str)
1463 {
1464         keep_bootcon = 1;
1465         printk(KERN_INFO "debug: skip boot console de-registration.\n");
1466
1467         return 0;
1468 }
1469
1470 early_param("keep_bootcon", keep_bootcon_setup);
1471
1472 /*
1473  * The console driver calls this routine during kernel initialization
1474  * to register the console printing procedure with printk() and to
1475  * print any messages that were printed by the kernel before the
1476  * console driver was initialized.
1477  *
1478  * This can happen pretty early during the boot process (because of
1479  * early_printk) - sometimes before setup_arch() completes - be careful
1480  * of what kernel features are used - they may not be initialised yet.
1481  *
1482  * There are two types of consoles - bootconsoles (early_printk) and
1483  * "real" consoles (everything which is not a bootconsole) which are
1484  * handled differently.
1485  *  - Any number of bootconsoles can be registered at any time.
1486  *  - As soon as a "real" console is registered, all bootconsoles
1487  *    will be unregistered automatically.
1488  *  - Once a "real" console is registered, any attempt to register a
1489  *    bootconsoles will be rejected
1490  */
1491 void register_console(struct console *newcon)
1492 {
1493         int i;
1494         unsigned long flags;
1495         struct console *bcon = NULL;
1496
1497         /*
1498          * before we register a new CON_BOOT console, make sure we don't
1499          * already have a valid console
1500          */
1501         if (console_drivers && newcon->flags & CON_BOOT) {
1502                 /* find the last or real console */
1503                 for_each_console(bcon) {
1504                         if (!(bcon->flags & CON_BOOT)) {
1505                                 printk(KERN_INFO "Too late to register bootconsole %s%d\n",
1506                                         newcon->name, newcon->index);
1507                                 return;
1508                         }
1509                 }
1510         }
1511
1512         if (console_drivers && console_drivers->flags & CON_BOOT)
1513                 bcon = console_drivers;
1514
1515         if (preferred_console < 0 || bcon || !console_drivers)
1516                 preferred_console = selected_console;
1517
1518         if (newcon->early_setup)
1519                 newcon->early_setup();
1520
1521         /*
1522          *      See if we want to use this console driver. If we
1523          *      didn't select a console we take the first one
1524          *      that registers here.
1525          */
1526         if (preferred_console < 0) {
1527                 if (newcon->index < 0)
1528                         newcon->index = 0;
1529                 if (newcon->setup == NULL ||
1530                     newcon->setup(newcon, NULL) == 0) {
1531                         newcon->flags |= CON_ENABLED;
1532                         if (newcon->device) {
1533                                 newcon->flags |= CON_CONSDEV;
1534                                 preferred_console = 0;
1535                         }
1536                 }
1537         }
1538
1539         /*
1540          *      See if this console matches one we selected on
1541          *      the command line.
1542          */
1543         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
1544                         i++) {
1545                 if (strcmp(console_cmdline[i].name, newcon->name) != 0)
1546                         continue;
1547                 if (newcon->index >= 0 &&
1548                     newcon->index != console_cmdline[i].index)
1549                         continue;
1550                 if (newcon->index < 0)
1551                         newcon->index = console_cmdline[i].index;
1552 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1553                 if (console_cmdline[i].brl_options) {
1554                         newcon->flags |= CON_BRL;
1555                         braille_register_console(newcon,
1556                                         console_cmdline[i].index,
1557                                         console_cmdline[i].options,
1558                                         console_cmdline[i].brl_options);
1559                         return;
1560                 }
1561 #endif
1562                 if (newcon->setup &&
1563                     newcon->setup(newcon, console_cmdline[i].options) != 0)
1564                         break;
1565                 newcon->flags |= CON_ENABLED;
1566                 newcon->index = console_cmdline[i].index;
1567                 if (i == selected_console) {
1568                         newcon->flags |= CON_CONSDEV;
1569                         preferred_console = selected_console;
1570                 }
1571                 break;
1572         }
1573
1574         if (!(newcon->flags & CON_ENABLED))
1575                 return;
1576
1577         /*
1578          * If we have a bootconsole, and are switching to a real console,
1579          * don't print everything out again, since when the boot console, and
1580          * the real console are the same physical device, it's annoying to
1581          * see the beginning boot messages twice
1582          */
1583         if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
1584                 newcon->flags &= ~CON_PRINTBUFFER;
1585
1586         /*
1587          *      Put this console in the list - keep the
1588          *      preferred driver at the head of the list.
1589          */
1590         console_lock();
1591         if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
1592                 newcon->next = console_drivers;
1593                 console_drivers = newcon;
1594                 if (newcon->next)
1595                         newcon->next->flags &= ~CON_CONSDEV;
1596         } else {
1597                 newcon->next = console_drivers->next;
1598                 console_drivers->next = newcon;
1599         }
1600         if (newcon->flags & CON_PRINTBUFFER) {
1601                 /*
1602                  * console_unlock(); will print out the buffered messages
1603                  * for us.
1604                  */
1605                 raw_spin_lock_irqsave(&logbuf_lock, flags);
1606                 con_start = log_start;
1607                 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
1608                 /*
1609                  * We're about to replay the log buffer.  Only do this to the
1610                  * just-registered console to avoid excessive message spam to
1611                  * the already-registered consoles.
1612                  */
1613                 exclusive_console = newcon;
1614         }
1615         console_unlock();
1616         console_sysfs_notify();
1617
1618         /*
1619          * By unregistering the bootconsoles after we enable the real console
1620          * we get the "console xxx enabled" message on all the consoles -
1621          * boot consoles, real consoles, etc - this is to ensure that end
1622          * users know there might be something in the kernel's log buffer that
1623          * went to the bootconsole (that they do not see on the real console)
1624          */
1625         if (bcon &&
1626             ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
1627             !keep_bootcon) {
1628                 /* we need to iterate through twice, to make sure we print
1629                  * everything out, before we unregister the console(s)
1630                  */
1631                 printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
1632                         newcon->name, newcon->index);
1633                 for_each_console(bcon)
1634                         if (bcon->flags & CON_BOOT)
1635                                 unregister_console(bcon);
1636         } else {
1637                 printk(KERN_INFO "%sconsole [%s%d] enabled\n",
1638                         (newcon->flags & CON_BOOT) ? "boot" : "" ,
1639                         newcon->name, newcon->index);
1640         }
1641 }
1642 EXPORT_SYMBOL(register_console);
1643
1644 int unregister_console(struct console *console)
1645 {
1646         struct console *a, *b;
1647         int res = 1;
1648
1649 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1650         if (console->flags & CON_BRL)
1651                 return braille_unregister_console(console);
1652 #endif
1653
1654         console_lock();
1655         if (console_drivers == console) {
1656                 console_drivers=console->next;
1657                 res = 0;
1658         } else if (console_drivers) {
1659                 for (a=console_drivers->next, b=console_drivers ;
1660                      a; b=a, a=b->next) {
1661                         if (a == console) {
1662                                 b->next = a->next;
1663                                 res = 0;
1664                                 break;
1665                         }
1666                 }
1667         }
1668
1669         /*
1670          * If this isn't the last console and it has CON_CONSDEV set, we
1671          * need to set it on the next preferred console.
1672          */
1673         if (console_drivers != NULL && console->flags & CON_CONSDEV)
1674                 console_drivers->flags |= CON_CONSDEV;
1675
1676         console_unlock();
1677         console_sysfs_notify();
1678         return res;
1679 }
1680 EXPORT_SYMBOL(unregister_console);
1681
1682 static int __init printk_late_init(void)
1683 {
1684         struct console *con;
1685
1686         for_each_console(con) {
1687                 if (!keep_bootcon && con->flags & CON_BOOT) {
1688                         printk(KERN_INFO "turn off boot console %s%d\n",
1689                                 con->name, con->index);
1690                         unregister_console(con);
1691                 }
1692         }
1693         hotcpu_notifier(console_cpu_notify, 0);
1694         return 0;
1695 }
1696 late_initcall(printk_late_init);
1697
1698 #if defined CONFIG_PRINTK
1699
1700 int printk_sched(const char *fmt, ...)
1701 {
1702         unsigned long flags;
1703         va_list args;
1704         char *buf;
1705         int r;
1706
1707         local_irq_save(flags);
1708         buf = __get_cpu_var(printk_sched_buf);
1709
1710         va_start(args, fmt);
1711         r = vsnprintf(buf, PRINTK_BUF_SIZE, fmt, args);
1712         va_end(args);
1713
1714         __this_cpu_or(printk_pending, PRINTK_PENDING_SCHED);
1715         local_irq_restore(flags);
1716
1717         return r;
1718 }
1719
1720 /*
1721  * printk rate limiting, lifted from the networking subsystem.
1722  *
1723  * This enforces a rate limit: not more than 10 kernel messages
1724  * every 5s to make a denial-of-service attack impossible.
1725  */
1726 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
1727
1728 int __printk_ratelimit(const char *func)
1729 {
1730         return ___ratelimit(&printk_ratelimit_state, func);
1731 }
1732 EXPORT_SYMBOL(__printk_ratelimit);
1733
1734 /**
1735  * printk_timed_ratelimit - caller-controlled printk ratelimiting
1736  * @caller_jiffies: pointer to caller's state
1737  * @interval_msecs: minimum interval between prints
1738  *
1739  * printk_timed_ratelimit() returns true if more than @interval_msecs
1740  * milliseconds have elapsed since the last time printk_timed_ratelimit()
1741  * returned true.
1742  */
1743 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
1744                         unsigned int interval_msecs)
1745 {
1746         if (*caller_jiffies == 0
1747                         || !time_in_range(jiffies, *caller_jiffies,
1748                                         *caller_jiffies
1749                                         + msecs_to_jiffies(interval_msecs))) {
1750                 *caller_jiffies = jiffies;
1751                 return true;
1752         }
1753         return false;
1754 }
1755 EXPORT_SYMBOL(printk_timed_ratelimit);
1756
1757 static DEFINE_SPINLOCK(dump_list_lock);
1758 static LIST_HEAD(dump_list);
1759
1760 /**
1761  * kmsg_dump_register - register a kernel log dumper.
1762  * @dumper: pointer to the kmsg_dumper structure
1763  *
1764  * Adds a kernel log dumper to the system. The dump callback in the
1765  * structure will be called when the kernel oopses or panics and must be
1766  * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
1767  */
1768 int kmsg_dump_register(struct kmsg_dumper *dumper)
1769 {
1770         unsigned long flags;
1771         int err = -EBUSY;
1772
1773         /* The dump callback needs to be set */
1774         if (!dumper->dump)
1775                 return -EINVAL;
1776
1777         spin_lock_irqsave(&dump_list_lock, flags);
1778         /* Don't allow registering multiple times */
1779         if (!dumper->registered) {
1780                 dumper->registered = 1;
1781                 list_add_tail_rcu(&dumper->list, &dump_list);
1782                 err = 0;
1783         }
1784         spin_unlock_irqrestore(&dump_list_lock, flags);
1785
1786         return err;
1787 }
1788 EXPORT_SYMBOL_GPL(kmsg_dump_register);
1789
1790 /**
1791  * kmsg_dump_unregister - unregister a kmsg dumper.
1792  * @dumper: pointer to the kmsg_dumper structure
1793  *
1794  * Removes a dump device from the system. Returns zero on success and
1795  * %-EINVAL otherwise.
1796  */
1797 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
1798 {
1799         unsigned long flags;
1800         int err = -EINVAL;
1801
1802         spin_lock_irqsave(&dump_list_lock, flags);
1803         if (dumper->registered) {
1804                 dumper->registered = 0;
1805                 list_del_rcu(&dumper->list);
1806                 err = 0;
1807         }
1808         spin_unlock_irqrestore(&dump_list_lock, flags);
1809         synchronize_rcu();
1810
1811         return err;
1812 }
1813 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
1814
1815 /**
1816  * kmsg_dump - dump kernel log to kernel message dumpers.
1817  * @reason: the reason (oops, panic etc) for dumping
1818  *
1819  * Iterate through each of the dump devices and call the oops/panic
1820  * callbacks with the log buffer.
1821  */
1822 void kmsg_dump(enum kmsg_dump_reason reason)
1823 {
1824         unsigned long end;
1825         unsigned chars;
1826         struct kmsg_dumper *dumper;
1827         const char *s1, *s2;
1828         unsigned long l1, l2;
1829         unsigned long flags;
1830
1831         if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
1832                 return;
1833
1834         /* Theoretically, the log could move on after we do this, but
1835            there's not a lot we can do about that. The new messages
1836            will overwrite the start of what we dump. */
1837         raw_spin_lock_irqsave(&logbuf_lock, flags);
1838         end = log_end & LOG_BUF_MASK;
1839         chars = logged_chars;
1840         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
1841
1842         if (chars > end) {
1843                 s1 = log_buf + log_buf_len - chars + end;
1844                 l1 = chars - end;
1845
1846                 s2 = log_buf;
1847                 l2 = end;
1848         } else {
1849                 s1 = "";
1850                 l1 = 0;
1851
1852                 s2 = log_buf + end - chars;
1853                 l2 = chars;
1854         }
1855
1856         rcu_read_lock();
1857         list_for_each_entry_rcu(dumper, &dump_list, list)
1858                 dumper->dump(dumper, reason, s1, l1, s2, l2);
1859         rcu_read_unlock();
1860 }
1861 #endif