ARM: Make low-level printk work
[firefly-linux-kernel-4.4.55.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/syscalls.h>
35 #include <linux/kexec.h>
36
37 #include <asm/uaccess.h>
38
39 /*
40  * for_each_console() allows you to iterate on each console
41  */
42 #define for_each_console(con) \
43         for (con = console_drivers; con != NULL; con = con->next)
44
45 /*
46  * Architectures can override it:
47  */
48 void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
49 {
50 }
51
52 #define __LOG_BUF_LEN   (1 << CONFIG_LOG_BUF_SHIFT)
53
54 #ifdef        CONFIG_DEBUG_LL
55 extern void printascii(char *);
56 #endif
57
58 /* printk's without a loglevel use this.. */
59 #define DEFAULT_MESSAGE_LOGLEVEL 4 /* KERN_WARNING */
60
61 /* We show everything that is MORE important than this.. */
62 #define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
63 #define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
64
65 DECLARE_WAIT_QUEUE_HEAD(log_wait);
66
67 int console_printk[4] = {
68         DEFAULT_CONSOLE_LOGLEVEL,       /* console_loglevel */
69         DEFAULT_MESSAGE_LOGLEVEL,       /* default_message_loglevel */
70         MINIMUM_CONSOLE_LOGLEVEL,       /* minimum_console_loglevel */
71         DEFAULT_CONSOLE_LOGLEVEL,       /* default_console_loglevel */
72 };
73
74 static int saved_console_loglevel = -1;
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 DECLARE_MUTEX(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  * release_console_sem().
106  */
107 static DEFINE_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 static unsigned log_start;      /* Index into log_buf: next char to be read by syslog() */
117 static unsigned con_start;      /* Index into log_buf: next char to be sent to consoles */
118 static unsigned log_end;        /* Index into log_buf: most-recently-written-char + 1 */
119
120 /*
121  *      Array of consoles built from command line options (console=)
122  */
123 struct console_cmdline
124 {
125         char    name[8];                        /* Name of the driver       */
126         int     index;                          /* Minor dev. to use        */
127         char    *options;                       /* Options for the driver   */
128 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
129         char    *brl_options;                   /* Options for braille driver */
130 #endif
131 };
132
133 #define MAX_CMDLINECONSOLES 8
134
135 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
136 static int selected_console = -1;
137 static int preferred_console = -1;
138 int console_set_on_cmdline;
139 EXPORT_SYMBOL(console_set_on_cmdline);
140
141 /* Flag: console code may call schedule() */
142 static int console_may_schedule;
143
144 #ifdef CONFIG_PRINTK
145
146 static char __log_buf[__LOG_BUF_LEN];
147 static char *log_buf = __log_buf;
148 static int log_buf_len = __LOG_BUF_LEN;
149 static unsigned logged_chars; /* Number of chars produced since last read+clear operation */
150
151 #ifdef CONFIG_KEXEC
152 /*
153  * This appends the listed symbols to /proc/vmcoreinfo
154  *
155  * /proc/vmcoreinfo is used by various utiilties, like crash and makedumpfile to
156  * obtain access to symbols that are otherwise very difficult to locate.  These
157  * symbols are specifically used so that utilities can access and extract the
158  * dmesg log from a vmcore file after a crash.
159  */
160 void log_buf_kexec_setup(void)
161 {
162         VMCOREINFO_SYMBOL(log_buf);
163         VMCOREINFO_SYMBOL(log_end);
164         VMCOREINFO_SYMBOL(log_buf_len);
165         VMCOREINFO_SYMBOL(logged_chars);
166 }
167 #endif
168
169 static int __init log_buf_len_setup(char *str)
170 {
171         unsigned size = memparse(str, &str);
172         unsigned long flags;
173
174         if (size)
175                 size = roundup_pow_of_two(size);
176         if (size > log_buf_len) {
177                 unsigned start, dest_idx, offset;
178                 char *new_log_buf;
179
180                 new_log_buf = alloc_bootmem(size);
181                 if (!new_log_buf) {
182                         printk(KERN_WARNING "log_buf_len: allocation failed\n");
183                         goto out;
184                 }
185
186                 spin_lock_irqsave(&logbuf_lock, flags);
187                 log_buf_len = size;
188                 log_buf = new_log_buf;
189
190                 offset = start = min(con_start, log_start);
191                 dest_idx = 0;
192                 while (start != log_end) {
193                         log_buf[dest_idx] = __log_buf[start & (__LOG_BUF_LEN - 1)];
194                         start++;
195                         dest_idx++;
196                 }
197                 log_start -= offset;
198                 con_start -= offset;
199                 log_end -= offset;
200                 spin_unlock_irqrestore(&logbuf_lock, flags);
201
202                 printk(KERN_NOTICE "log_buf_len: %d\n", log_buf_len);
203         }
204 out:
205         return 1;
206 }
207
208 __setup("log_buf_len=", log_buf_len_setup);
209
210 #ifdef CONFIG_BOOT_PRINTK_DELAY
211
212 static unsigned int boot_delay; /* msecs delay after each printk during bootup */
213 static unsigned long long loops_per_msec;       /* based on boot_delay */
214
215 static int __init boot_delay_setup(char *str)
216 {
217         unsigned long lpj;
218
219         lpj = preset_lpj ? preset_lpj : 1000000;        /* some guess */
220         loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
221
222         get_option(&str, &boot_delay);
223         if (boot_delay > 10 * 1000)
224                 boot_delay = 0;
225
226         pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
227                 "HZ: %d, loops_per_msec: %llu\n",
228                 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
229         return 1;
230 }
231 __setup("boot_delay=", boot_delay_setup);
232
233 static void boot_delay_msec(void)
234 {
235         unsigned long long k;
236         unsigned long timeout;
237
238         if (boot_delay == 0 || system_state != SYSTEM_BOOTING)
239                 return;
240
241         k = (unsigned long long)loops_per_msec * boot_delay;
242
243         timeout = jiffies + msecs_to_jiffies(boot_delay);
244         while (k) {
245                 k--;
246                 cpu_relax();
247                 /*
248                  * use (volatile) jiffies to prevent
249                  * compiler reduction; loop termination via jiffies
250                  * is secondary and may or may not happen.
251                  */
252                 if (time_after(jiffies, timeout))
253                         break;
254                 touch_nmi_watchdog();
255         }
256 }
257 #else
258 static inline void boot_delay_msec(void)
259 {
260 }
261 #endif
262
263 /*
264  * Commands to do_syslog:
265  *
266  *      0 -- Close the log.  Currently a NOP.
267  *      1 -- Open the log. Currently a NOP.
268  *      2 -- Read from the log.
269  *      3 -- Read all messages remaining in the ring buffer.
270  *      4 -- Read and clear all messages remaining in the ring buffer
271  *      5 -- Clear ring buffer.
272  *      6 -- Disable printk's to console
273  *      7 -- Enable printk's to console
274  *      8 -- Set level of messages printed to console
275  *      9 -- Return number of unread characters in the log buffer
276  *     10 -- Return size of the log buffer
277  */
278 int do_syslog(int type, char __user *buf, int len)
279 {
280         unsigned i, j, limit, count;
281         int do_clear = 0;
282         char c;
283         int error = 0;
284
285         error = security_syslog(type);
286         if (error)
287                 return error;
288
289         switch (type) {
290         case 0:         /* Close log */
291                 break;
292         case 1:         /* Open log */
293                 break;
294         case 2:         /* Read from log */
295                 error = -EINVAL;
296                 if (!buf || len < 0)
297                         goto out;
298                 error = 0;
299                 if (!len)
300                         goto out;
301                 if (!access_ok(VERIFY_WRITE, buf, len)) {
302                         error = -EFAULT;
303                         goto out;
304                 }
305                 error = wait_event_interruptible(log_wait,
306                                                         (log_start - log_end));
307                 if (error)
308                         goto out;
309                 i = 0;
310                 spin_lock_irq(&logbuf_lock);
311                 while (!error && (log_start != log_end) && i < len) {
312                         c = LOG_BUF(log_start);
313                         log_start++;
314                         spin_unlock_irq(&logbuf_lock);
315                         error = __put_user(c,buf);
316                         buf++;
317                         i++;
318                         cond_resched();
319                         spin_lock_irq(&logbuf_lock);
320                 }
321                 spin_unlock_irq(&logbuf_lock);
322                 if (!error)
323                         error = i;
324                 break;
325         case 4:         /* Read/clear last kernel messages */
326                 do_clear = 1;
327                 /* FALL THRU */
328         case 3:         /* Read last kernel messages */
329                 error = -EINVAL;
330                 if (!buf || len < 0)
331                         goto out;
332                 error = 0;
333                 if (!len)
334                         goto out;
335                 if (!access_ok(VERIFY_WRITE, buf, len)) {
336                         error = -EFAULT;
337                         goto out;
338                 }
339                 count = len;
340                 if (count > log_buf_len)
341                         count = log_buf_len;
342                 spin_lock_irq(&logbuf_lock);
343                 if (count > logged_chars)
344                         count = logged_chars;
345                 if (do_clear)
346                         logged_chars = 0;
347                 limit = log_end;
348                 /*
349                  * __put_user() could sleep, and while we sleep
350                  * printk() could overwrite the messages
351                  * we try to copy to user space. Therefore
352                  * the messages are copied in reverse. <manfreds>
353                  */
354                 for (i = 0; i < count && !error; i++) {
355                         j = limit-1-i;
356                         if (j + log_buf_len < log_end)
357                                 break;
358                         c = LOG_BUF(j);
359                         spin_unlock_irq(&logbuf_lock);
360                         error = __put_user(c,&buf[count-1-i]);
361                         cond_resched();
362                         spin_lock_irq(&logbuf_lock);
363                 }
364                 spin_unlock_irq(&logbuf_lock);
365                 if (error)
366                         break;
367                 error = i;
368                 if (i != count) {
369                         int offset = count-error;
370                         /* buffer overflow during copy, correct user buffer. */
371                         for (i = 0; i < error; i++) {
372                                 if (__get_user(c,&buf[i+offset]) ||
373                                     __put_user(c,&buf[i])) {
374                                         error = -EFAULT;
375                                         break;
376                                 }
377                                 cond_resched();
378                         }
379                 }
380                 break;
381         case 5:         /* Clear ring buffer */
382                 logged_chars = 0;
383                 break;
384         case 6:         /* Disable logging to console */
385                 if (saved_console_loglevel == -1)
386                         saved_console_loglevel = console_loglevel;
387                 console_loglevel = minimum_console_loglevel;
388                 break;
389         case 7:         /* Enable logging to console */
390                 if (saved_console_loglevel != -1) {
391                         console_loglevel = saved_console_loglevel;
392                         saved_console_loglevel = -1;
393                 }
394                 break;
395         case 8:         /* Set level of messages printed to console */
396                 error = -EINVAL;
397                 if (len < 1 || len > 8)
398                         goto out;
399                 if (len < minimum_console_loglevel)
400                         len = minimum_console_loglevel;
401                 console_loglevel = len;
402                 /* Implicitly re-enable logging to console */
403                 saved_console_loglevel = -1;
404                 error = 0;
405                 break;
406         case 9:         /* Number of chars in the log buffer */
407                 error = log_end - log_start;
408                 break;
409         case 10:        /* Size of the log buffer */
410                 error = log_buf_len;
411                 break;
412         default:
413                 error = -EINVAL;
414                 break;
415         }
416 out:
417         return error;
418 }
419
420 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
421 {
422         return do_syslog(type, buf, len);
423 }
424
425 /*
426  * Call the console drivers on a range of log_buf
427  */
428 static void __call_console_drivers(unsigned start, unsigned end)
429 {
430         struct console *con;
431
432         for_each_console(con) {
433                 if ((con->flags & CON_ENABLED) && con->write &&
434                                 (cpu_online(smp_processor_id()) ||
435                                 (con->flags & CON_ANYTIME)))
436                         con->write(con, &LOG_BUF(start), end - start);
437         }
438 }
439
440 static int __read_mostly ignore_loglevel;
441
442 static int __init ignore_loglevel_setup(char *str)
443 {
444         ignore_loglevel = 1;
445         printk(KERN_INFO "debug: ignoring loglevel setting.\n");
446
447         return 0;
448 }
449
450 early_param("ignore_loglevel", ignore_loglevel_setup);
451
452 /*
453  * Write out chars from start to end - 1 inclusive
454  */
455 static void _call_console_drivers(unsigned start,
456                                 unsigned end, int msg_log_level)
457 {
458         if ((msg_log_level < console_loglevel || ignore_loglevel) &&
459                         console_drivers && start != end) {
460                 if ((start & LOG_BUF_MASK) > (end & LOG_BUF_MASK)) {
461                         /* wrapped write */
462                         __call_console_drivers(start & LOG_BUF_MASK,
463                                                 log_buf_len);
464                         __call_console_drivers(0, end & LOG_BUF_MASK);
465                 } else {
466                         __call_console_drivers(start, end);
467                 }
468         }
469 }
470
471 /*
472  * Call the console drivers, asking them to write out
473  * log_buf[start] to log_buf[end - 1].
474  * The console_sem must be held.
475  */
476 static void call_console_drivers(unsigned start, unsigned end)
477 {
478         unsigned cur_index, start_print;
479         static int msg_level = -1;
480
481         BUG_ON(((int)(start - end)) > 0);
482
483         cur_index = start;
484         start_print = start;
485         while (cur_index != end) {
486                 if (msg_level < 0 && ((end - cur_index) > 2) &&
487                                 LOG_BUF(cur_index + 0) == '<' &&
488                                 LOG_BUF(cur_index + 1) >= '0' &&
489                                 LOG_BUF(cur_index + 1) <= '7' &&
490                                 LOG_BUF(cur_index + 2) == '>') {
491                         msg_level = LOG_BUF(cur_index + 1) - '0';
492                         cur_index += 3;
493                         start_print = cur_index;
494                 }
495                 while (cur_index != end) {
496                         char c = LOG_BUF(cur_index);
497
498                         cur_index++;
499                         if (c == '\n') {
500                                 if (msg_level < 0) {
501                                         /*
502                                          * printk() has already given us loglevel tags in
503                                          * the buffer.  This code is here in case the
504                                          * log buffer has wrapped right round and scribbled
505                                          * on those tags
506                                          */
507                                         msg_level = default_message_loglevel;
508                                 }
509                                 _call_console_drivers(start_print, cur_index, msg_level);
510                                 msg_level = -1;
511                                 start_print = cur_index;
512                                 break;
513                         }
514                 }
515         }
516         _call_console_drivers(start_print, end, msg_level);
517 }
518
519 static void emit_log_char(char c)
520 {
521         LOG_BUF(log_end) = c;
522         log_end++;
523         if (log_end - log_start > log_buf_len)
524                 log_start = log_end - log_buf_len;
525         if (log_end - con_start > log_buf_len)
526                 con_start = log_end - log_buf_len;
527         if (logged_chars < log_buf_len)
528                 logged_chars++;
529 }
530
531 /*
532  * Zap console related locks when oopsing. Only zap at most once
533  * every 10 seconds, to leave time for slow consoles to print a
534  * full oops.
535  */
536 static void zap_locks(void)
537 {
538         static unsigned long oops_timestamp;
539
540         if (time_after_eq(jiffies, oops_timestamp) &&
541                         !time_after(jiffies, oops_timestamp + 30 * HZ))
542                 return;
543
544         oops_timestamp = jiffies;
545
546         /* If a crash is occurring, make sure we can't deadlock */
547         spin_lock_init(&logbuf_lock);
548         /* And make sure that we print immediately */
549         init_MUTEX(&console_sem);
550 }
551
552 #if defined(CONFIG_PRINTK_TIME)
553 static int printk_time = 1;
554 #else
555 static int printk_time = 0;
556 #endif
557 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
558
559 /* Check if we have any console registered that can be called early in boot. */
560 static int have_callable_console(void)
561 {
562         struct console *con;
563
564         for_each_console(con)
565                 if (con->flags & CON_ANYTIME)
566                         return 1;
567
568         return 0;
569 }
570
571 /**
572  * printk - print a kernel message
573  * @fmt: format string
574  *
575  * This is printk().  It can be called from any context.  We want it to work.
576  *
577  * We try to grab the console_sem.  If we succeed, it's easy - we log the output and
578  * call the console drivers.  If we fail to get the semaphore we place the output
579  * into the log buffer and return.  The current holder of the console_sem will
580  * notice the new output in release_console_sem() and will send it to the
581  * consoles before releasing the semaphore.
582  *
583  * One effect of this deferred printing is that code which calls printk() and
584  * then changes console_loglevel may break. This is because console_loglevel
585  * is inspected when the actual printing occurs.
586  *
587  * See also:
588  * printf(3)
589  *
590  * See the vsnprintf() documentation for format string extensions over C99.
591  */
592
593 asmlinkage int printk(const char *fmt, ...)
594 {
595         va_list args;
596         int r;
597
598         va_start(args, fmt);
599         r = vprintk(fmt, args);
600         va_end(args);
601
602         return r;
603 }
604
605 /* cpu currently holding logbuf_lock */
606 static volatile unsigned int printk_cpu = UINT_MAX;
607
608 /*
609  * Can we actually use the console at this time on this cpu?
610  *
611  * Console drivers may assume that per-cpu resources have
612  * been allocated. So unless they're explicitly marked as
613  * being able to cope (CON_ANYTIME) don't call them until
614  * this CPU is officially up.
615  */
616 static inline int can_use_console(unsigned int cpu)
617 {
618         return cpu_online(cpu) || have_callable_console();
619 }
620
621 /*
622  * Try to get console ownership to actually show the kernel
623  * messages from a 'printk'. Return true (and with the
624  * console_semaphore held, and 'console_locked' set) if it
625  * is successful, false otherwise.
626  *
627  * This gets called with the 'logbuf_lock' spinlock held and
628  * interrupts disabled. It should return with 'lockbuf_lock'
629  * released but interrupts still disabled.
630  */
631 static int acquire_console_semaphore_for_printk(unsigned int cpu)
632 {
633         int retval = 0;
634
635         if (!try_acquire_console_sem()) {
636                 retval = 1;
637
638                 /*
639                  * If we can't use the console, we need to release
640                  * the console semaphore by hand to avoid flushing
641                  * the buffer. We need to hold the console semaphore
642                  * in order to do this test safely.
643                  */
644                 if (!can_use_console(cpu)) {
645                         console_locked = 0;
646                         up(&console_sem);
647                         retval = 0;
648                 }
649         }
650         printk_cpu = UINT_MAX;
651         spin_unlock(&logbuf_lock);
652         return retval;
653 }
654 static const char recursion_bug_msg [] =
655                 KERN_CRIT "BUG: recent printk recursion!\n";
656 static int recursion_bug;
657 static int new_text_line = 1;
658 static char printk_buf[1024];
659
660 int printk_delay_msec __read_mostly;
661
662 static inline void printk_delay(void)
663 {
664         if (unlikely(printk_delay_msec)) {
665                 int m = printk_delay_msec;
666
667                 while (m--) {
668                         mdelay(1);
669                         touch_nmi_watchdog();
670                 }
671         }
672 }
673
674 asmlinkage int vprintk(const char *fmt, va_list args)
675 {
676         int printed_len = 0;
677         int current_log_level = default_message_loglevel;
678         unsigned long flags;
679         int this_cpu;
680         char *p;
681
682         boot_delay_msec();
683         printk_delay();
684
685         preempt_disable();
686         /* This stops the holder of console_sem just where we want him */
687         raw_local_irq_save(flags);
688         this_cpu = smp_processor_id();
689
690         /*
691          * Ouch, printk recursed into itself!
692          */
693         if (unlikely(printk_cpu == this_cpu)) {
694                 /*
695                  * If a crash is occurring during printk() on this CPU,
696                  * then try to get the crash message out but make sure
697                  * we can't deadlock. Otherwise just return to avoid the
698                  * recursion and return - but flag the recursion so that
699                  * it can be printed at the next appropriate moment:
700                  */
701                 if (!oops_in_progress) {
702                         recursion_bug = 1;
703                         goto out_restore_irqs;
704                 }
705                 zap_locks();
706         }
707
708         lockdep_off();
709         spin_lock(&logbuf_lock);
710         printk_cpu = this_cpu;
711
712         if (recursion_bug) {
713                 recursion_bug = 0;
714                 strcpy(printk_buf, recursion_bug_msg);
715                 printed_len = strlen(recursion_bug_msg);
716         }
717         /* Emit the output into the temporary buffer */
718         printed_len += vscnprintf(printk_buf + printed_len,
719                                   sizeof(printk_buf) - printed_len, fmt, args);
720
721 #ifdef  CONFIG_DEBUG_LL
722         printascii(printk_buf);
723 #endif
724
725         p = printk_buf;
726
727         /* Do we have a loglevel in the string? */
728         if (p[0] == '<') {
729                 unsigned char c = p[1];
730                 if (c && p[2] == '>') {
731                         switch (c) {
732                         case '0' ... '7': /* loglevel */
733                                 current_log_level = c - '0';
734                         /* Fallthrough - make sure we're on a new line */
735                         case 'd': /* KERN_DEFAULT */
736                                 if (!new_text_line) {
737                                         emit_log_char('\n');
738                                         new_text_line = 1;
739                                 }
740                         /* Fallthrough - skip the loglevel */
741                         case 'c': /* KERN_CONT */
742                                 p += 3;
743                                 break;
744                         }
745                 }
746         }
747
748         /*
749          * Copy the output into log_buf.  If the caller didn't provide
750          * appropriate log level tags, we insert them here
751          */
752         for ( ; *p; p++) {
753                 if (new_text_line) {
754                         /* Always output the token */
755                         emit_log_char('<');
756                         emit_log_char(current_log_level + '0');
757                         emit_log_char('>');
758                         printed_len += 3;
759                         new_text_line = 0;
760
761                         if (printk_time) {
762                                 /* Follow the token with the time */
763                                 char tbuf[50], *tp;
764                                 unsigned tlen;
765                                 unsigned long long t;
766                                 unsigned long nanosec_rem;
767
768                                 t = cpu_clock(printk_cpu);
769                                 nanosec_rem = do_div(t, 1000000000);
770                                 tlen = sprintf(tbuf, "[%5lu.%06lu] ",
771                                                 (unsigned long) t,
772                                                 nanosec_rem / 1000);
773
774                                 for (tp = tbuf; tp < tbuf + tlen; tp++)
775                                         emit_log_char(*tp);
776                                 printed_len += tlen;
777                         }
778
779                         if (!*p)
780                                 break;
781                 }
782
783                 emit_log_char(*p);
784                 if (*p == '\n')
785                         new_text_line = 1;
786         }
787
788         /*
789          * Try to acquire and then immediately release the
790          * console semaphore. The release will do all the
791          * actual magic (print out buffers, wake up klogd,
792          * etc). 
793          *
794          * The acquire_console_semaphore_for_printk() function
795          * will release 'logbuf_lock' regardless of whether it
796          * actually gets the semaphore or not.
797          */
798         if (acquire_console_semaphore_for_printk(this_cpu))
799                 release_console_sem();
800
801         lockdep_on();
802 out_restore_irqs:
803         raw_local_irq_restore(flags);
804
805         preempt_enable();
806         return printed_len;
807 }
808 EXPORT_SYMBOL(printk);
809 EXPORT_SYMBOL(vprintk);
810
811 #else
812
813 static void call_console_drivers(unsigned start, unsigned end)
814 {
815 }
816
817 #endif
818
819 static int __add_preferred_console(char *name, int idx, char *options,
820                                    char *brl_options)
821 {
822         struct console_cmdline *c;
823         int i;
824
825         /*
826          *      See if this tty is not yet registered, and
827          *      if we have a slot free.
828          */
829         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
830                 if (strcmp(console_cmdline[i].name, name) == 0 &&
831                           console_cmdline[i].index == idx) {
832                                 if (!brl_options)
833                                         selected_console = i;
834                                 return 0;
835                 }
836         if (i == MAX_CMDLINECONSOLES)
837                 return -E2BIG;
838         if (!brl_options)
839                 selected_console = i;
840         c = &console_cmdline[i];
841         strlcpy(c->name, name, sizeof(c->name));
842         c->options = options;
843 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
844         c->brl_options = brl_options;
845 #endif
846         c->index = idx;
847         return 0;
848 }
849 /*
850  * Set up a list of consoles.  Called from init/main.c
851  */
852 static int __init console_setup(char *str)
853 {
854         char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
855         char *s, *options, *brl_options = NULL;
856         int idx;
857
858 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
859         if (!memcmp(str, "brl,", 4)) {
860                 brl_options = "";
861                 str += 4;
862         } else if (!memcmp(str, "brl=", 4)) {
863                 brl_options = str + 4;
864                 str = strchr(brl_options, ',');
865                 if (!str) {
866                         printk(KERN_ERR "need port name after brl=\n");
867                         return 1;
868                 }
869                 *(str++) = 0;
870         }
871 #endif
872
873         /*
874          * Decode str into name, index, options.
875          */
876         if (str[0] >= '0' && str[0] <= '9') {
877                 strcpy(buf, "ttyS");
878                 strncpy(buf + 4, str, sizeof(buf) - 5);
879         } else {
880                 strncpy(buf, str, sizeof(buf) - 1);
881         }
882         buf[sizeof(buf) - 1] = 0;
883         if ((options = strchr(str, ',')) != NULL)
884                 *(options++) = 0;
885 #ifdef __sparc__
886         if (!strcmp(str, "ttya"))
887                 strcpy(buf, "ttyS0");
888         if (!strcmp(str, "ttyb"))
889                 strcpy(buf, "ttyS1");
890 #endif
891         for (s = buf; *s; s++)
892                 if ((*s >= '0' && *s <= '9') || *s == ',')
893                         break;
894         idx = simple_strtoul(s, NULL, 10);
895         *s = 0;
896
897         __add_preferred_console(buf, idx, options, brl_options);
898         console_set_on_cmdline = 1;
899         return 1;
900 }
901 __setup("console=", console_setup);
902
903 /**
904  * add_preferred_console - add a device to the list of preferred consoles.
905  * @name: device name
906  * @idx: device index
907  * @options: options for this console
908  *
909  * The last preferred console added will be used for kernel messages
910  * and stdin/out/err for init.  Normally this is used by console_setup
911  * above to handle user-supplied console arguments; however it can also
912  * be used by arch-specific code either to override the user or more
913  * commonly to provide a default console (ie from PROM variables) when
914  * the user has not supplied one.
915  */
916 int add_preferred_console(char *name, int idx, char *options)
917 {
918         return __add_preferred_console(name, idx, options, NULL);
919 }
920
921 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
922 {
923         struct console_cmdline *c;
924         int i;
925
926         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
927                 if (strcmp(console_cmdline[i].name, name) == 0 &&
928                           console_cmdline[i].index == idx) {
929                                 c = &console_cmdline[i];
930                                 strlcpy(c->name, name_new, sizeof(c->name));
931                                 c->name[sizeof(c->name) - 1] = 0;
932                                 c->options = options;
933                                 c->index = idx_new;
934                                 return i;
935                 }
936         /* not found */
937         return -1;
938 }
939
940 int console_suspend_enabled = 1;
941 EXPORT_SYMBOL(console_suspend_enabled);
942
943 static int __init console_suspend_disable(char *str)
944 {
945         console_suspend_enabled = 0;
946         return 1;
947 }
948 __setup("no_console_suspend", console_suspend_disable);
949
950 /**
951  * suspend_console - suspend the console subsystem
952  *
953  * This disables printk() while we go into suspend states
954  */
955 void suspend_console(void)
956 {
957         if (!console_suspend_enabled)
958                 return;
959         printk("Suspending console(s) (use no_console_suspend to debug)\n");
960         acquire_console_sem();
961         console_suspended = 1;
962         up(&console_sem);
963 }
964
965 void resume_console(void)
966 {
967         if (!console_suspend_enabled)
968                 return;
969         down(&console_sem);
970         console_suspended = 0;
971         release_console_sem();
972 }
973
974 /**
975  * acquire_console_sem - lock the console system for exclusive use.
976  *
977  * Acquires a semaphore which guarantees that the caller has
978  * exclusive access to the console system and the console_drivers list.
979  *
980  * Can sleep, returns nothing.
981  */
982 void acquire_console_sem(void)
983 {
984         BUG_ON(in_interrupt());
985         down(&console_sem);
986         if (console_suspended)
987                 return;
988         console_locked = 1;
989         console_may_schedule = 1;
990 }
991 EXPORT_SYMBOL(acquire_console_sem);
992
993 int try_acquire_console_sem(void)
994 {
995         if (down_trylock(&console_sem))
996                 return -1;
997         if (console_suspended) {
998                 up(&console_sem);
999                 return -1;
1000         }
1001         console_locked = 1;
1002         console_may_schedule = 0;
1003         return 0;
1004 }
1005 EXPORT_SYMBOL(try_acquire_console_sem);
1006
1007 int is_console_locked(void)
1008 {
1009         return console_locked;
1010 }
1011
1012 static DEFINE_PER_CPU(int, printk_pending);
1013
1014 void printk_tick(void)
1015 {
1016         if (__get_cpu_var(printk_pending)) {
1017                 __get_cpu_var(printk_pending) = 0;
1018                 wake_up_interruptible(&log_wait);
1019         }
1020 }
1021
1022 int printk_needs_cpu(int cpu)
1023 {
1024         return per_cpu(printk_pending, cpu);
1025 }
1026
1027 void wake_up_klogd(void)
1028 {
1029         if (waitqueue_active(&log_wait))
1030                 __raw_get_cpu_var(printk_pending) = 1;
1031 }
1032
1033 /**
1034  * release_console_sem - unlock the console system
1035  *
1036  * Releases the semaphore which the caller holds on the console system
1037  * and the console driver list.
1038  *
1039  * While the semaphore was held, console output may have been buffered
1040  * by printk().  If this is the case, release_console_sem() emits
1041  * the output prior to releasing the semaphore.
1042  *
1043  * If there is output waiting for klogd, we wake it up.
1044  *
1045  * release_console_sem() may be called from any context.
1046  */
1047 void release_console_sem(void)
1048 {
1049         unsigned long flags;
1050         unsigned _con_start, _log_end;
1051         unsigned wake_klogd = 0;
1052
1053         if (console_suspended) {
1054                 up(&console_sem);
1055                 return;
1056         }
1057
1058         console_may_schedule = 0;
1059
1060         for ( ; ; ) {
1061                 spin_lock_irqsave(&logbuf_lock, flags);
1062                 wake_klogd |= log_start - log_end;
1063                 if (con_start == log_end)
1064                         break;                  /* Nothing to print */
1065                 _con_start = con_start;
1066                 _log_end = log_end;
1067                 con_start = log_end;            /* Flush */
1068                 spin_unlock(&logbuf_lock);
1069                 stop_critical_timings();        /* don't trace print latency */
1070                 call_console_drivers(_con_start, _log_end);
1071                 start_critical_timings();
1072                 local_irq_restore(flags);
1073         }
1074         console_locked = 0;
1075         up(&console_sem);
1076         spin_unlock_irqrestore(&logbuf_lock, flags);
1077         if (wake_klogd)
1078                 wake_up_klogd();
1079 }
1080 EXPORT_SYMBOL(release_console_sem);
1081
1082 /**
1083  * console_conditional_schedule - yield the CPU if required
1084  *
1085  * If the console code is currently allowed to sleep, and
1086  * if this CPU should yield the CPU to another task, do
1087  * so here.
1088  *
1089  * Must be called within acquire_console_sem().
1090  */
1091 void __sched console_conditional_schedule(void)
1092 {
1093         if (console_may_schedule)
1094                 cond_resched();
1095 }
1096 EXPORT_SYMBOL(console_conditional_schedule);
1097
1098 void console_unblank(void)
1099 {
1100         struct console *c;
1101
1102         /*
1103          * console_unblank can no longer be called in interrupt context unless
1104          * oops_in_progress is set to 1..
1105          */
1106         if (oops_in_progress) {
1107                 if (down_trylock(&console_sem) != 0)
1108                         return;
1109         } else
1110                 acquire_console_sem();
1111
1112         console_locked = 1;
1113         console_may_schedule = 0;
1114         for_each_console(c)
1115                 if ((c->flags & CON_ENABLED) && c->unblank)
1116                         c->unblank();
1117         release_console_sem();
1118 }
1119
1120 /*
1121  * Return the console tty driver structure and its associated index
1122  */
1123 struct tty_driver *console_device(int *index)
1124 {
1125         struct console *c;
1126         struct tty_driver *driver = NULL;
1127
1128         acquire_console_sem();
1129         for_each_console(c) {
1130                 if (!c->device)
1131                         continue;
1132                 driver = c->device(c, index);
1133                 if (driver)
1134                         break;
1135         }
1136         release_console_sem();
1137         return driver;
1138 }
1139
1140 /*
1141  * Prevent further output on the passed console device so that (for example)
1142  * serial drivers can disable console output before suspending a port, and can
1143  * re-enable output afterwards.
1144  */
1145 void console_stop(struct console *console)
1146 {
1147         acquire_console_sem();
1148         console->flags &= ~CON_ENABLED;
1149         release_console_sem();
1150 }
1151 EXPORT_SYMBOL(console_stop);
1152
1153 void console_start(struct console *console)
1154 {
1155         acquire_console_sem();
1156         console->flags |= CON_ENABLED;
1157         release_console_sem();
1158 }
1159 EXPORT_SYMBOL(console_start);
1160
1161 /*
1162  * The console driver calls this routine during kernel initialization
1163  * to register the console printing procedure with printk() and to
1164  * print any messages that were printed by the kernel before the
1165  * console driver was initialized.
1166  *
1167  * This can happen pretty early during the boot process (because of
1168  * early_printk) - sometimes before setup_arch() completes - be careful
1169  * of what kernel features are used - they may not be initialised yet.
1170  *
1171  * There are two types of consoles - bootconsoles (early_printk) and
1172  * "real" consoles (everything which is not a bootconsole) which are
1173  * handled differently.
1174  *  - Any number of bootconsoles can be registered at any time.
1175  *  - As soon as a "real" console is registered, all bootconsoles
1176  *    will be unregistered automatically.
1177  *  - Once a "real" console is registered, any attempt to register a
1178  *    bootconsoles will be rejected
1179  */
1180 void register_console(struct console *newcon)
1181 {
1182         int i;
1183         unsigned long flags;
1184         struct console *bcon = NULL;
1185
1186         /*
1187          * before we register a new CON_BOOT console, make sure we don't
1188          * already have a valid console
1189          */
1190         if (console_drivers && newcon->flags & CON_BOOT) {
1191                 /* find the last or real console */
1192                 for_each_console(bcon) {
1193                         if (!(bcon->flags & CON_BOOT)) {
1194                                 printk(KERN_INFO "Too late to register bootconsole %s%d\n",
1195                                         newcon->name, newcon->index);
1196                                 return;
1197                         }
1198                 }
1199         }
1200
1201         if (console_drivers && console_drivers->flags & CON_BOOT)
1202                 bcon = console_drivers;
1203
1204         if (preferred_console < 0 || bcon || !console_drivers)
1205                 preferred_console = selected_console;
1206
1207         if (newcon->early_setup)
1208                 newcon->early_setup();
1209
1210         /*
1211          *      See if we want to use this console driver. If we
1212          *      didn't select a console we take the first one
1213          *      that registers here.
1214          */
1215         if (preferred_console < 0) {
1216                 if (newcon->index < 0)
1217                         newcon->index = 0;
1218                 if (newcon->setup == NULL ||
1219                     newcon->setup(newcon, NULL) == 0) {
1220                         newcon->flags |= CON_ENABLED;
1221                         if (newcon->device) {
1222                                 newcon->flags |= CON_CONSDEV;
1223                                 preferred_console = 0;
1224                         }
1225                 }
1226         }
1227
1228         /*
1229          *      See if this console matches one we selected on
1230          *      the command line.
1231          */
1232         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
1233                         i++) {
1234                 if (strcmp(console_cmdline[i].name, newcon->name) != 0)
1235                         continue;
1236                 if (newcon->index >= 0 &&
1237                     newcon->index != console_cmdline[i].index)
1238                         continue;
1239                 if (newcon->index < 0)
1240                         newcon->index = console_cmdline[i].index;
1241 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1242                 if (console_cmdline[i].brl_options) {
1243                         newcon->flags |= CON_BRL;
1244                         braille_register_console(newcon,
1245                                         console_cmdline[i].index,
1246                                         console_cmdline[i].options,
1247                                         console_cmdline[i].brl_options);
1248                         return;
1249                 }
1250 #endif
1251                 if (newcon->setup &&
1252                     newcon->setup(newcon, console_cmdline[i].options) != 0)
1253                         break;
1254                 newcon->flags |= CON_ENABLED;
1255                 newcon->index = console_cmdline[i].index;
1256                 if (i == selected_console) {
1257                         newcon->flags |= CON_CONSDEV;
1258                         preferred_console = selected_console;
1259                 }
1260                 break;
1261         }
1262
1263         if (!(newcon->flags & CON_ENABLED))
1264                 return;
1265
1266         /*
1267          * If we have a bootconsole, and are switching to a real console,
1268          * don't print everything out again, since when the boot console, and
1269          * the real console are the same physical device, it's annoying to
1270          * see the beginning boot messages twice
1271          */
1272         if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
1273                 newcon->flags &= ~CON_PRINTBUFFER;
1274
1275         /*
1276          *      Put this console in the list - keep the
1277          *      preferred driver at the head of the list.
1278          */
1279         acquire_console_sem();
1280         if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
1281                 newcon->next = console_drivers;
1282                 console_drivers = newcon;
1283                 if (newcon->next)
1284                         newcon->next->flags &= ~CON_CONSDEV;
1285         } else {
1286                 newcon->next = console_drivers->next;
1287                 console_drivers->next = newcon;
1288         }
1289         if (newcon->flags & CON_PRINTBUFFER) {
1290                 /*
1291                  * release_console_sem() will print out the buffered messages
1292                  * for us.
1293                  */
1294                 spin_lock_irqsave(&logbuf_lock, flags);
1295                 con_start = log_start;
1296                 spin_unlock_irqrestore(&logbuf_lock, flags);
1297         }
1298         release_console_sem();
1299
1300         /*
1301          * By unregistering the bootconsoles after we enable the real console
1302          * we get the "console xxx enabled" message on all the consoles -
1303          * boot consoles, real consoles, etc - this is to ensure that end
1304          * users know there might be something in the kernel's log buffer that
1305          * went to the bootconsole (that they do not see on the real console)
1306          */
1307         if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
1308                 /* we need to iterate through twice, to make sure we print
1309                  * everything out, before we unregister the console(s)
1310                  */
1311                 printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
1312                         newcon->name, newcon->index);
1313                 for_each_console(bcon)
1314                         if (bcon->flags & CON_BOOT)
1315                                 unregister_console(bcon);
1316         } else {
1317                 printk(KERN_INFO "%sconsole [%s%d] enabled\n",
1318                         (newcon->flags & CON_BOOT) ? "boot" : "" ,
1319                         newcon->name, newcon->index);
1320         }
1321 }
1322 EXPORT_SYMBOL(register_console);
1323
1324 int unregister_console(struct console *console)
1325 {
1326         struct console *a, *b;
1327         int res = 1;
1328
1329 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1330         if (console->flags & CON_BRL)
1331                 return braille_unregister_console(console);
1332 #endif
1333
1334         acquire_console_sem();
1335         if (console_drivers == console) {
1336                 console_drivers=console->next;
1337                 res = 0;
1338         } else if (console_drivers) {
1339                 for (a=console_drivers->next, b=console_drivers ;
1340                      a; b=a, a=b->next) {
1341                         if (a == console) {
1342                                 b->next = a->next;
1343                                 res = 0;
1344                                 break;
1345                         }
1346                 }
1347         }
1348
1349         /*
1350          * If this isn't the last console and it has CON_CONSDEV set, we
1351          * need to set it on the next preferred console.
1352          */
1353         if (console_drivers != NULL && console->flags & CON_CONSDEV)
1354                 console_drivers->flags |= CON_CONSDEV;
1355
1356         release_console_sem();
1357         return res;
1358 }
1359 EXPORT_SYMBOL(unregister_console);
1360
1361 static int __init disable_boot_consoles(void)
1362 {
1363         struct console *con;
1364
1365         for_each_console(con) {
1366                 if (con->flags & CON_BOOT) {
1367                         printk(KERN_INFO "turn off boot console %s%d\n",
1368                                 con->name, con->index);
1369                         unregister_console(con);
1370                 }
1371         }
1372         return 0;
1373 }
1374 late_initcall(disable_boot_consoles);
1375
1376 #if defined CONFIG_PRINTK
1377
1378 /*
1379  * printk rate limiting, lifted from the networking subsystem.
1380  *
1381  * This enforces a rate limit: not more than 10 kernel messages
1382  * every 5s to make a denial-of-service attack impossible.
1383  */
1384 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
1385
1386 int printk_ratelimit(void)
1387 {
1388         return __ratelimit(&printk_ratelimit_state);
1389 }
1390 EXPORT_SYMBOL(printk_ratelimit);
1391
1392 /**
1393  * printk_timed_ratelimit - caller-controlled printk ratelimiting
1394  * @caller_jiffies: pointer to caller's state
1395  * @interval_msecs: minimum interval between prints
1396  *
1397  * printk_timed_ratelimit() returns true if more than @interval_msecs
1398  * milliseconds have elapsed since the last time printk_timed_ratelimit()
1399  * returned true.
1400  */
1401 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
1402                         unsigned int interval_msecs)
1403 {
1404         if (*caller_jiffies == 0
1405                         || !time_in_range(jiffies, *caller_jiffies,
1406                                         *caller_jiffies
1407                                         + msecs_to_jiffies(interval_msecs))) {
1408                 *caller_jiffies = jiffies;
1409                 return true;
1410         }
1411         return false;
1412 }
1413 EXPORT_SYMBOL(printk_timed_ratelimit);
1414 #endif