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