Revert "Input: gpio_input: Fix keys with keycode 0x100-0x1ff"
[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 #ifdef CONFIG_RK29_LAST_LOG
812 void switch_log_buf(char *new_log_buf, int size)
813 {
814         unsigned long flags;
815
816         if (!new_log_buf || log_buf_len > size)
817                 return;
818
819         spin_lock_irqsave(&logbuf_lock, flags);
820         memcpy(new_log_buf, log_buf, min(log_buf_len, size));
821         log_buf = new_log_buf;
822         log_buf_len = size;
823         spin_unlock_irqrestore(&logbuf_lock, flags);
824 }
825 #endif /* CONFIG_RK29_LAST_LOG */
826 #else
827
828 static void call_console_drivers(unsigned start, unsigned end)
829 {
830 }
831
832 #endif
833
834 static int __add_preferred_console(char *name, int idx, char *options,
835                                    char *brl_options)
836 {
837         struct console_cmdline *c;
838         int i;
839
840         /*
841          *      See if this tty is not yet registered, and
842          *      if we have a slot free.
843          */
844         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
845                 if (strcmp(console_cmdline[i].name, name) == 0 &&
846                           console_cmdline[i].index == idx) {
847                                 if (!brl_options)
848                                         selected_console = i;
849                                 return 0;
850                 }
851         if (i == MAX_CMDLINECONSOLES)
852                 return -E2BIG;
853         if (!brl_options)
854                 selected_console = i;
855         c = &console_cmdline[i];
856         strlcpy(c->name, name, sizeof(c->name));
857         c->options = options;
858 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
859         c->brl_options = brl_options;
860 #endif
861         c->index = idx;
862         return 0;
863 }
864 /*
865  * Set up a list of consoles.  Called from init/main.c
866  */
867 static int __init console_setup(char *str)
868 {
869         char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
870         char *s, *options, *brl_options = NULL;
871         int idx;
872
873 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
874         if (!memcmp(str, "brl,", 4)) {
875                 brl_options = "";
876                 str += 4;
877         } else if (!memcmp(str, "brl=", 4)) {
878                 brl_options = str + 4;
879                 str = strchr(brl_options, ',');
880                 if (!str) {
881                         printk(KERN_ERR "need port name after brl=\n");
882                         return 1;
883                 }
884                 *(str++) = 0;
885         }
886 #endif
887
888         /*
889          * Decode str into name, index, options.
890          */
891         if (str[0] >= '0' && str[0] <= '9') {
892                 strcpy(buf, "ttyS");
893                 strncpy(buf + 4, str, sizeof(buf) - 5);
894         } else {
895                 strncpy(buf, str, sizeof(buf) - 1);
896         }
897         buf[sizeof(buf) - 1] = 0;
898         if ((options = strchr(str, ',')) != NULL)
899                 *(options++) = 0;
900 #ifdef __sparc__
901         if (!strcmp(str, "ttya"))
902                 strcpy(buf, "ttyS0");
903         if (!strcmp(str, "ttyb"))
904                 strcpy(buf, "ttyS1");
905 #endif
906         for (s = buf; *s; s++)
907                 if ((*s >= '0' && *s <= '9') || *s == ',')
908                         break;
909         idx = simple_strtoul(s, NULL, 10);
910         *s = 0;
911
912         __add_preferred_console(buf, idx, options, brl_options);
913         console_set_on_cmdline = 1;
914         return 1;
915 }
916 __setup("console=", console_setup);
917
918 /**
919  * add_preferred_console - add a device to the list of preferred consoles.
920  * @name: device name
921  * @idx: device index
922  * @options: options for this console
923  *
924  * The last preferred console added will be used for kernel messages
925  * and stdin/out/err for init.  Normally this is used by console_setup
926  * above to handle user-supplied console arguments; however it can also
927  * be used by arch-specific code either to override the user or more
928  * commonly to provide a default console (ie from PROM variables) when
929  * the user has not supplied one.
930  */
931 int add_preferred_console(char *name, int idx, char *options)
932 {
933         return __add_preferred_console(name, idx, options, NULL);
934 }
935
936 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
937 {
938         struct console_cmdline *c;
939         int i;
940
941         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
942                 if (strcmp(console_cmdline[i].name, name) == 0 &&
943                           console_cmdline[i].index == idx) {
944                                 c = &console_cmdline[i];
945                                 strlcpy(c->name, name_new, sizeof(c->name));
946                                 c->name[sizeof(c->name) - 1] = 0;
947                                 c->options = options;
948                                 c->index = idx_new;
949                                 return i;
950                 }
951         /* not found */
952         return -1;
953 }
954
955 int console_suspend_enabled = 1;
956 EXPORT_SYMBOL(console_suspend_enabled);
957
958 static int __init console_suspend_disable(char *str)
959 {
960         console_suspend_enabled = 0;
961         return 1;
962 }
963 __setup("no_console_suspend", console_suspend_disable);
964
965 /**
966  * suspend_console - suspend the console subsystem
967  *
968  * This disables printk() while we go into suspend states
969  */
970 void suspend_console(void)
971 {
972         if (!console_suspend_enabled)
973                 return;
974         printk("Suspending console(s) (use no_console_suspend to debug)\n");
975         acquire_console_sem();
976         console_suspended = 1;
977         up(&console_sem);
978 }
979
980 void resume_console(void)
981 {
982         if (!console_suspend_enabled)
983                 return;
984         down(&console_sem);
985         console_suspended = 0;
986         release_console_sem();
987 }
988
989 /**
990  * acquire_console_sem - lock the console system for exclusive use.
991  *
992  * Acquires a semaphore which guarantees that the caller has
993  * exclusive access to the console system and the console_drivers list.
994  *
995  * Can sleep, returns nothing.
996  */
997 void acquire_console_sem(void)
998 {
999         BUG_ON(in_interrupt());
1000         down(&console_sem);
1001         if (console_suspended)
1002                 return;
1003         console_locked = 1;
1004         console_may_schedule = 1;
1005 }
1006 EXPORT_SYMBOL(acquire_console_sem);
1007
1008 int try_acquire_console_sem(void)
1009 {
1010         if (down_trylock(&console_sem))
1011                 return -1;
1012         if (console_suspended) {
1013                 up(&console_sem);
1014                 return -1;
1015         }
1016         console_locked = 1;
1017         console_may_schedule = 0;
1018         return 0;
1019 }
1020 EXPORT_SYMBOL(try_acquire_console_sem);
1021
1022 int is_console_locked(void)
1023 {
1024         return console_locked;
1025 }
1026
1027 static DEFINE_PER_CPU(int, printk_pending);
1028
1029 void printk_tick(void)
1030 {
1031         if (__get_cpu_var(printk_pending)) {
1032                 __get_cpu_var(printk_pending) = 0;
1033                 wake_up_interruptible(&log_wait);
1034         }
1035 }
1036
1037 int printk_needs_cpu(int cpu)
1038 {
1039         return per_cpu(printk_pending, cpu);
1040 }
1041
1042 void wake_up_klogd(void)
1043 {
1044         if (waitqueue_active(&log_wait))
1045                 __raw_get_cpu_var(printk_pending) = 1;
1046 }
1047
1048 /**
1049  * release_console_sem - unlock the console system
1050  *
1051  * Releases the semaphore which the caller holds on the console system
1052  * and the console driver list.
1053  *
1054  * While the semaphore was held, console output may have been buffered
1055  * by printk().  If this is the case, release_console_sem() emits
1056  * the output prior to releasing the semaphore.
1057  *
1058  * If there is output waiting for klogd, we wake it up.
1059  *
1060  * release_console_sem() may be called from any context.
1061  */
1062 void release_console_sem(void)
1063 {
1064         unsigned long flags;
1065         unsigned _con_start, _log_end;
1066         unsigned wake_klogd = 0;
1067
1068         if (console_suspended) {
1069                 up(&console_sem);
1070                 return;
1071         }
1072
1073         console_may_schedule = 0;
1074
1075         for ( ; ; ) {
1076                 spin_lock_irqsave(&logbuf_lock, flags);
1077                 wake_klogd |= log_start - log_end;
1078                 if (con_start == log_end)
1079                         break;                  /* Nothing to print */
1080                 _con_start = con_start;
1081                 _log_end = log_end;
1082                 con_start = log_end;            /* Flush */
1083                 spin_unlock(&logbuf_lock);
1084                 stop_critical_timings();        /* don't trace print latency */
1085                 call_console_drivers(_con_start, _log_end);
1086                 start_critical_timings();
1087                 local_irq_restore(flags);
1088         }
1089         console_locked = 0;
1090         up(&console_sem);
1091         spin_unlock_irqrestore(&logbuf_lock, flags);
1092         if (wake_klogd)
1093                 wake_up_klogd();
1094 }
1095 EXPORT_SYMBOL(release_console_sem);
1096
1097 /**
1098  * console_conditional_schedule - yield the CPU if required
1099  *
1100  * If the console code is currently allowed to sleep, and
1101  * if this CPU should yield the CPU to another task, do
1102  * so here.
1103  *
1104  * Must be called within acquire_console_sem().
1105  */
1106 void __sched console_conditional_schedule(void)
1107 {
1108         if (console_may_schedule)
1109                 cond_resched();
1110 }
1111 EXPORT_SYMBOL(console_conditional_schedule);
1112
1113 void console_unblank(void)
1114 {
1115         struct console *c;
1116
1117         /*
1118          * console_unblank can no longer be called in interrupt context unless
1119          * oops_in_progress is set to 1..
1120          */
1121         if (oops_in_progress) {
1122                 if (down_trylock(&console_sem) != 0)
1123                         return;
1124         } else
1125                 acquire_console_sem();
1126
1127         console_locked = 1;
1128         console_may_schedule = 0;
1129         for_each_console(c)
1130                 if ((c->flags & CON_ENABLED) && c->unblank)
1131                         c->unblank();
1132         release_console_sem();
1133 }
1134
1135 /*
1136  * Return the console tty driver structure and its associated index
1137  */
1138 struct tty_driver *console_device(int *index)
1139 {
1140         struct console *c;
1141         struct tty_driver *driver = NULL;
1142
1143         acquire_console_sem();
1144         for_each_console(c) {
1145                 if (!c->device)
1146                         continue;
1147                 driver = c->device(c, index);
1148                 if (driver)
1149                         break;
1150         }
1151         release_console_sem();
1152         return driver;
1153 }
1154
1155 /*
1156  * Prevent further output on the passed console device so that (for example)
1157  * serial drivers can disable console output before suspending a port, and can
1158  * re-enable output afterwards.
1159  */
1160 void console_stop(struct console *console)
1161 {
1162         acquire_console_sem();
1163         console->flags &= ~CON_ENABLED;
1164         release_console_sem();
1165 }
1166 EXPORT_SYMBOL(console_stop);
1167
1168 void console_start(struct console *console)
1169 {
1170         acquire_console_sem();
1171         console->flags |= CON_ENABLED;
1172         release_console_sem();
1173 }
1174 EXPORT_SYMBOL(console_start);
1175
1176 /*
1177  * The console driver calls this routine during kernel initialization
1178  * to register the console printing procedure with printk() and to
1179  * print any messages that were printed by the kernel before the
1180  * console driver was initialized.
1181  *
1182  * This can happen pretty early during the boot process (because of
1183  * early_printk) - sometimes before setup_arch() completes - be careful
1184  * of what kernel features are used - they may not be initialised yet.
1185  *
1186  * There are two types of consoles - bootconsoles (early_printk) and
1187  * "real" consoles (everything which is not a bootconsole) which are
1188  * handled differently.
1189  *  - Any number of bootconsoles can be registered at any time.
1190  *  - As soon as a "real" console is registered, all bootconsoles
1191  *    will be unregistered automatically.
1192  *  - Once a "real" console is registered, any attempt to register a
1193  *    bootconsoles will be rejected
1194  */
1195 void register_console(struct console *newcon)
1196 {
1197         int i;
1198         unsigned long flags;
1199         struct console *bcon = NULL;
1200
1201         /*
1202          * before we register a new CON_BOOT console, make sure we don't
1203          * already have a valid console
1204          */
1205         if (console_drivers && newcon->flags & CON_BOOT) {
1206                 /* find the last or real console */
1207                 for_each_console(bcon) {
1208                         if (!(bcon->flags & CON_BOOT)) {
1209                                 printk(KERN_INFO "Too late to register bootconsole %s%d\n",
1210                                         newcon->name, newcon->index);
1211                                 return;
1212                         }
1213                 }
1214         }
1215
1216         if (console_drivers && console_drivers->flags & CON_BOOT)
1217                 bcon = console_drivers;
1218
1219         if (preferred_console < 0 || bcon || !console_drivers)
1220                 preferred_console = selected_console;
1221
1222         if (newcon->early_setup)
1223                 newcon->early_setup();
1224
1225         /*
1226          *      See if we want to use this console driver. If we
1227          *      didn't select a console we take the first one
1228          *      that registers here.
1229          */
1230         if (preferred_console < 0) {
1231                 if (newcon->index < 0)
1232                         newcon->index = 0;
1233                 if (newcon->setup == NULL ||
1234                     newcon->setup(newcon, NULL) == 0) {
1235                         newcon->flags |= CON_ENABLED;
1236                         if (newcon->device) {
1237                                 newcon->flags |= CON_CONSDEV;
1238                                 preferred_console = 0;
1239                         }
1240                 }
1241         }
1242
1243         /*
1244          *      See if this console matches one we selected on
1245          *      the command line.
1246          */
1247         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
1248                         i++) {
1249                 if (strcmp(console_cmdline[i].name, newcon->name) != 0)
1250                         continue;
1251                 if (newcon->index >= 0 &&
1252                     newcon->index != console_cmdline[i].index)
1253                         continue;
1254                 if (newcon->index < 0)
1255                         newcon->index = console_cmdline[i].index;
1256 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1257                 if (console_cmdline[i].brl_options) {
1258                         newcon->flags |= CON_BRL;
1259                         braille_register_console(newcon,
1260                                         console_cmdline[i].index,
1261                                         console_cmdline[i].options,
1262                                         console_cmdline[i].brl_options);
1263                         return;
1264                 }
1265 #endif
1266                 if (newcon->setup &&
1267                     newcon->setup(newcon, console_cmdline[i].options) != 0)
1268                         break;
1269                 newcon->flags |= CON_ENABLED;
1270                 newcon->index = console_cmdline[i].index;
1271                 if (i == selected_console) {
1272                         newcon->flags |= CON_CONSDEV;
1273                         preferred_console = selected_console;
1274                 }
1275                 break;
1276         }
1277
1278         if (!(newcon->flags & CON_ENABLED))
1279                 return;
1280
1281         /*
1282          * If we have a bootconsole, and are switching to a real console,
1283          * don't print everything out again, since when the boot console, and
1284          * the real console are the same physical device, it's annoying to
1285          * see the beginning boot messages twice
1286          */
1287         if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
1288                 newcon->flags &= ~CON_PRINTBUFFER;
1289
1290         /*
1291          *      Put this console in the list - keep the
1292          *      preferred driver at the head of the list.
1293          */
1294         acquire_console_sem();
1295         if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
1296                 newcon->next = console_drivers;
1297                 console_drivers = newcon;
1298                 if (newcon->next)
1299                         newcon->next->flags &= ~CON_CONSDEV;
1300         } else {
1301                 newcon->next = console_drivers->next;
1302                 console_drivers->next = newcon;
1303         }
1304         if (newcon->flags & CON_PRINTBUFFER) {
1305                 /*
1306                  * release_console_sem() will print out the buffered messages
1307                  * for us.
1308                  */
1309                 spin_lock_irqsave(&logbuf_lock, flags);
1310                 con_start = log_start;
1311                 spin_unlock_irqrestore(&logbuf_lock, flags);
1312         }
1313         release_console_sem();
1314
1315         /*
1316          * By unregistering the bootconsoles after we enable the real console
1317          * we get the "console xxx enabled" message on all the consoles -
1318          * boot consoles, real consoles, etc - this is to ensure that end
1319          * users know there might be something in the kernel's log buffer that
1320          * went to the bootconsole (that they do not see on the real console)
1321          */
1322         if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
1323                 /* we need to iterate through twice, to make sure we print
1324                  * everything out, before we unregister the console(s)
1325                  */
1326                 printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
1327                         newcon->name, newcon->index);
1328                 for_each_console(bcon)
1329                         if (bcon->flags & CON_BOOT)
1330                                 unregister_console(bcon);
1331         } else {
1332                 printk(KERN_INFO "%sconsole [%s%d] enabled\n",
1333                         (newcon->flags & CON_BOOT) ? "boot" : "" ,
1334                         newcon->name, newcon->index);
1335         }
1336 }
1337 EXPORT_SYMBOL(register_console);
1338
1339 int unregister_console(struct console *console)
1340 {
1341         struct console *a, *b;
1342         int res = 1;
1343
1344 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1345         if (console->flags & CON_BRL)
1346                 return braille_unregister_console(console);
1347 #endif
1348
1349         acquire_console_sem();
1350         if (console_drivers == console) {
1351                 console_drivers=console->next;
1352                 res = 0;
1353         } else if (console_drivers) {
1354                 for (a=console_drivers->next, b=console_drivers ;
1355                      a; b=a, a=b->next) {
1356                         if (a == console) {
1357                                 b->next = a->next;
1358                                 res = 0;
1359                                 break;
1360                         }
1361                 }
1362         }
1363
1364         /*
1365          * If this isn't the last console and it has CON_CONSDEV set, we
1366          * need to set it on the next preferred console.
1367          */
1368         if (console_drivers != NULL && console->flags & CON_CONSDEV)
1369                 console_drivers->flags |= CON_CONSDEV;
1370
1371         release_console_sem();
1372         return res;
1373 }
1374 EXPORT_SYMBOL(unregister_console);
1375
1376 static int __init disable_boot_consoles(void)
1377 {
1378         struct console *con;
1379
1380         for_each_console(con) {
1381                 if (con->flags & CON_BOOT) {
1382                         printk(KERN_INFO "turn off boot console %s%d\n",
1383                                 con->name, con->index);
1384                         unregister_console(con);
1385                 }
1386         }
1387         return 0;
1388 }
1389 late_initcall(disable_boot_consoles);
1390
1391 #if defined CONFIG_PRINTK
1392
1393 /*
1394  * printk rate limiting, lifted from the networking subsystem.
1395  *
1396  * This enforces a rate limit: not more than 10 kernel messages
1397  * every 5s to make a denial-of-service attack impossible.
1398  */
1399 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
1400
1401 int printk_ratelimit(void)
1402 {
1403         return __ratelimit(&printk_ratelimit_state);
1404 }
1405 EXPORT_SYMBOL(printk_ratelimit);
1406
1407 /**
1408  * printk_timed_ratelimit - caller-controlled printk ratelimiting
1409  * @caller_jiffies: pointer to caller's state
1410  * @interval_msecs: minimum interval between prints
1411  *
1412  * printk_timed_ratelimit() returns true if more than @interval_msecs
1413  * milliseconds have elapsed since the last time printk_timed_ratelimit()
1414  * returned true.
1415  */
1416 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
1417                         unsigned int interval_msecs)
1418 {
1419         if (*caller_jiffies == 0
1420                         || !time_in_range(jiffies, *caller_jiffies,
1421                                         *caller_jiffies
1422                                         + msecs_to_jiffies(interval_msecs))) {
1423                 *caller_jiffies = jiffies;
1424                 return true;
1425         }
1426         return false;
1427 }
1428 EXPORT_SYMBOL(printk_timed_ratelimit);
1429 #endif