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