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