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