printk: refactor processing of line severity tokens
[linux-2.6.git] / kernel / printk.c
1 /*
2  *  linux/kernel/printk.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  *
6  * Modified to make sys_syslog() more flexible: added commands to
7  * return the last 4k of kernel messages, regardless of whether
8  * they've been read or not.  Added option to suppress kernel printk's
9  * to the console.  Added hook for sending the console messages
10  * elsewhere, in preparation for a serial line console (someday).
11  * Ted Ts'o, 2/11/93.
12  * Modified for sysctl support, 1/8/97, Chris Horn.
13  * Fixed SMP synchronization, 08/08/99, Manfred Spraul
14  *     manfred@colorfullife.com
15  * Rewrote bits to get rid of console_lock
16  *      01Mar01 Andrew Morton <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
125 /* Flag: console code may call schedule() */
126 static int console_may_schedule;
127
128 #ifdef CONFIG_PRINTK
129
130 static char __log_buf[__LOG_BUF_LEN];
131 static char *log_buf = __log_buf;
132 static int log_buf_len = __LOG_BUF_LEN;
133 static unsigned logged_chars; /* Number of chars produced since last read+clear operation */
134
135 static int __init log_buf_len_setup(char *str)
136 {
137         unsigned size = memparse(str, &str);
138         unsigned long flags;
139
140         if (size)
141                 size = roundup_pow_of_two(size);
142         if (size > log_buf_len) {
143                 unsigned start, dest_idx, offset;
144                 char *new_log_buf;
145
146                 new_log_buf = alloc_bootmem(size);
147                 if (!new_log_buf) {
148                         printk(KERN_WARNING "log_buf_len: allocation failed\n");
149                         goto out;
150                 }
151
152                 spin_lock_irqsave(&logbuf_lock, flags);
153                 log_buf_len = size;
154                 log_buf = new_log_buf;
155
156                 offset = start = min(con_start, log_start);
157                 dest_idx = 0;
158                 while (start != log_end) {
159                         log_buf[dest_idx] = __log_buf[start & (__LOG_BUF_LEN - 1)];
160                         start++;
161                         dest_idx++;
162                 }
163                 log_start -= offset;
164                 con_start -= offset;
165                 log_end -= offset;
166                 spin_unlock_irqrestore(&logbuf_lock, flags);
167
168                 printk(KERN_NOTICE "log_buf_len: %d\n", log_buf_len);
169         }
170 out:
171         return 1;
172 }
173
174 __setup("log_buf_len=", log_buf_len_setup);
175
176 #ifdef CONFIG_BOOT_PRINTK_DELAY
177
178 static unsigned int boot_delay; /* msecs delay after each printk during bootup */
179 static unsigned long long printk_delay_msec; /* per msec, based on boot_delay */
180
181 static int __init boot_delay_setup(char *str)
182 {
183         unsigned long lpj;
184         unsigned long long loops_per_msec;
185
186         lpj = preset_lpj ? preset_lpj : 1000000;        /* some guess */
187         loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
188
189         get_option(&str, &boot_delay);
190         if (boot_delay > 10 * 1000)
191                 boot_delay = 0;
192
193         printk_delay_msec = loops_per_msec;
194         printk(KERN_DEBUG "boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
195                 "HZ: %d, printk_delay_msec: %llu\n",
196                 boot_delay, preset_lpj, lpj, HZ, printk_delay_msec);
197         return 1;
198 }
199 __setup("boot_delay=", boot_delay_setup);
200
201 static void boot_delay_msec(void)
202 {
203         unsigned long long k;
204         unsigned long timeout;
205
206         if (boot_delay == 0 || system_state != SYSTEM_BOOTING)
207                 return;
208
209         k = (unsigned long long)printk_delay_msec * boot_delay;
210
211         timeout = jiffies + msecs_to_jiffies(boot_delay);
212         while (k) {
213                 k--;
214                 cpu_relax();
215                 /*
216                  * use (volatile) jiffies to prevent
217                  * compiler reduction; loop termination via jiffies
218                  * is secondary and may or may not happen.
219                  */
220                 if (time_after(jiffies, timeout))
221                         break;
222                 touch_nmi_watchdog();
223         }
224 }
225 #else
226 static inline void boot_delay_msec(void)
227 {
228 }
229 #endif
230
231 /*
232  * Return the number of unread characters in the log buffer.
233  */
234 static int log_buf_get_len(void)
235 {
236         return logged_chars;
237 }
238
239 /*
240  * Copy a range of characters from the log buffer.
241  */
242 int log_buf_copy(char *dest, int idx, int len)
243 {
244         int ret, max;
245         bool took_lock = false;
246
247         if (!oops_in_progress) {
248                 spin_lock_irq(&logbuf_lock);
249                 took_lock = true;
250         }
251
252         max = log_buf_get_len();
253         if (idx < 0 || idx >= max) {
254                 ret = -1;
255         } else {
256                 if (len > max)
257                         len = max;
258                 ret = len;
259                 idx += (log_end - max);
260                 while (len-- > 0)
261                         dest[len] = LOG_BUF(idx + len);
262         }
263
264         if (took_lock)
265                 spin_unlock_irq(&logbuf_lock);
266
267         return ret;
268 }
269
270 /*
271  * Commands to do_syslog:
272  *
273  *      0 -- Close the log.  Currently a NOP.
274  *      1 -- Open the log. Currently a NOP.
275  *      2 -- Read from the log.
276  *      3 -- Read all messages remaining in the ring buffer.
277  *      4 -- Read and clear all messages remaining in the ring buffer
278  *      5 -- Clear ring buffer.
279  *      6 -- Disable printk's to console
280  *      7 -- Enable printk's to console
281  *      8 -- Set level of messages printed to console
282  *      9 -- Return number of unread characters in the log buffer
283  *     10 -- Return size of the log buffer
284  */
285 int do_syslog(int type, char __user *buf, int len)
286 {
287         unsigned i, j, limit, count;
288         int do_clear = 0;
289         char c;
290         int error = 0;
291
292         error = security_syslog(type);
293         if (error)
294                 return error;
295
296         switch (type) {
297         case 0:         /* Close log */
298                 break;
299         case 1:         /* Open log */
300                 break;
301         case 2:         /* Read from log */
302                 error = -EINVAL;
303                 if (!buf || len < 0)
304                         goto out;
305                 error = 0;
306                 if (!len)
307                         goto out;
308                 if (!access_ok(VERIFY_WRITE, buf, len)) {
309                         error = -EFAULT;
310                         goto out;
311                 }
312                 error = wait_event_interruptible(log_wait,
313                                                         (log_start - log_end));
314                 if (error)
315                         goto out;
316                 i = 0;
317                 spin_lock_irq(&logbuf_lock);
318                 while (!error && (log_start != log_end) && i < len) {
319                         c = LOG_BUF(log_start);
320                         log_start++;
321                         spin_unlock_irq(&logbuf_lock);
322                         error = __put_user(c,buf);
323                         buf++;
324                         i++;
325                         cond_resched();
326                         spin_lock_irq(&logbuf_lock);
327                 }
328                 spin_unlock_irq(&logbuf_lock);
329                 if (!error)
330                         error = i;
331                 break;
332         case 4:         /* Read/clear last kernel messages */
333                 do_clear = 1;
334                 /* FALL THRU */
335         case 3:         /* Read last kernel messages */
336                 error = -EINVAL;
337                 if (!buf || len < 0)
338                         goto out;
339                 error = 0;
340                 if (!len)
341                         goto out;
342                 if (!access_ok(VERIFY_WRITE, buf, len)) {
343                         error = -EFAULT;
344                         goto out;
345                 }
346                 count = len;
347                 if (count > log_buf_len)
348                         count = log_buf_len;
349                 spin_lock_irq(&logbuf_lock);
350                 if (count > logged_chars)
351                         count = logged_chars;
352                 if (do_clear)
353                         logged_chars = 0;
354                 limit = log_end;
355                 /*
356                  * __put_user() could sleep, and while we sleep
357                  * printk() could overwrite the messages
358                  * we try to copy to user space. Therefore
359                  * the messages are copied in reverse. <manfreds>
360                  */
361                 for (i = 0; i < count && !error; i++) {
362                         j = limit-1-i;
363                         if (j + log_buf_len < log_end)
364                                 break;
365                         c = LOG_BUF(j);
366                         spin_unlock_irq(&logbuf_lock);
367                         error = __put_user(c,&buf[count-1-i]);
368                         cond_resched();
369                         spin_lock_irq(&logbuf_lock);
370                 }
371                 spin_unlock_irq(&logbuf_lock);
372                 if (error)
373                         break;
374                 error = i;
375                 if (i != count) {
376                         int offset = count-error;
377                         /* buffer overflow during copy, correct user buffer. */
378                         for (i = 0; i < error; i++) {
379                                 if (__get_user(c,&buf[i+offset]) ||
380                                     __put_user(c,&buf[i])) {
381                                         error = -EFAULT;
382                                         break;
383                                 }
384                                 cond_resched();
385                         }
386                 }
387                 break;
388         case 5:         /* Clear ring buffer */
389                 logged_chars = 0;
390                 break;
391         case 6:         /* Disable logging to console */
392                 console_loglevel = minimum_console_loglevel;
393                 break;
394         case 7:         /* Enable logging to console */
395                 console_loglevel = default_console_loglevel;
396                 break;
397         case 8:         /* Set level of messages printed to console */
398                 error = -EINVAL;
399                 if (len < 1 || len > 8)
400                         goto out;
401                 if (len < minimum_console_loglevel)
402                         len = minimum_console_loglevel;
403                 console_loglevel = len;
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 asmlinkage long sys_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 (con = console_drivers; con; con = con->next) {
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 (con = console_drivers; con; con = con->next)
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  * Be aware of the fact that if oops_in_progress is not set, we might try to
577  * wake klogd up which could deadlock on runqueue lock if printk() is called
578  * from scheduler code.
579  *
580  * We try to grab the console_sem.  If we succeed, it's easy - we log the output and
581  * call the console drivers.  If we fail to get the semaphore we place the output
582  * into the log buffer and return.  The current holder of the console_sem will
583  * notice the new output in release_console_sem() and will send it to the
584  * consoles before releasing the semaphore.
585  *
586  * One effect of this deferred printing is that code which calls printk() and
587  * then changes console_loglevel may break. This is because console_loglevel
588  * is inspected when the actual printing occurs.
589  *
590  * See also:
591  * printf(3)
592  */
593
594 asmlinkage int printk(const char *fmt, ...)
595 {
596         va_list args;
597         int r;
598
599         va_start(args, fmt);
600         r = vprintk(fmt, args);
601         va_end(args);
602
603         return r;
604 }
605
606 /* cpu currently holding logbuf_lock */
607 static volatile unsigned int printk_cpu = UINT_MAX;
608
609 /*
610  * Can we actually use the console at this time on this cpu?
611  *
612  * Console drivers may assume that per-cpu resources have
613  * been allocated. So unless they're explicitly marked as
614  * being able to cope (CON_ANYTIME) don't call them until
615  * this CPU is officially up.
616  */
617 static inline int can_use_console(unsigned int cpu)
618 {
619         return cpu_online(cpu) || have_callable_console();
620 }
621
622 /*
623  * Try to get console ownership to actually show the kernel
624  * messages from a 'printk'. Return true (and with the
625  * console_semaphore held, and 'console_locked' set) if it
626  * is successful, false otherwise.
627  *
628  * This gets called with the 'logbuf_lock' spinlock held and
629  * interrupts disabled. It should return with 'lockbuf_lock'
630  * released but interrupts still disabled.
631  */
632 static int acquire_console_semaphore_for_printk(unsigned int cpu)
633 {
634         int retval = 0;
635
636         if (!try_acquire_console_sem()) {
637                 retval = 1;
638
639                 /*
640                  * If we can't use the console, we need to release
641                  * the console semaphore by hand to avoid flushing
642                  * the buffer. We need to hold the console semaphore
643                  * in order to do this test safely.
644                  */
645                 if (!can_use_console(cpu)) {
646                         console_locked = 0;
647                         up(&console_sem);
648                         retval = 0;
649                 }
650         }
651         printk_cpu = UINT_MAX;
652         spin_unlock(&logbuf_lock);
653         return retval;
654 }
655 static const char recursion_bug_msg [] =
656                 KERN_CRIT "BUG: recent printk recursion!\n";
657 static int recursion_bug;
658         static int new_text_line = 1;
659 static char printk_buf[1024];
660
661 asmlinkage int vprintk(const char *fmt, va_list args)
662 {
663         int printed_len = 0;
664         unsigned long flags;
665         int this_cpu;
666         char *p;
667
668         boot_delay_msec();
669
670         preempt_disable();
671         /* This stops the holder of console_sem just where we want him */
672         raw_local_irq_save(flags);
673         this_cpu = smp_processor_id();
674
675         /*
676          * Ouch, printk recursed into itself!
677          */
678         if (unlikely(printk_cpu == this_cpu)) {
679                 /*
680                  * If a crash is occurring during printk() on this CPU,
681                  * then try to get the crash message out but make sure
682                  * we can't deadlock. Otherwise just return to avoid the
683                  * recursion and return - but flag the recursion so that
684                  * it can be printed at the next appropriate moment:
685                  */
686                 if (!oops_in_progress) {
687                         recursion_bug = 1;
688                         goto out_restore_irqs;
689                 }
690                 zap_locks();
691         }
692
693         lockdep_off();
694         spin_lock(&logbuf_lock);
695         printk_cpu = this_cpu;
696
697         if (recursion_bug) {
698                 recursion_bug = 0;
699                 strcpy(printk_buf, recursion_bug_msg);
700                 printed_len = sizeof(recursion_bug_msg);
701         }
702         /* Emit the output into the temporary buffer */
703         printed_len += vscnprintf(printk_buf + printed_len,
704                                   sizeof(printk_buf) - printed_len, fmt, args);
705
706
707         /*
708          * Copy the output into log_buf.  If the caller didn't provide
709          * appropriate log level tags, we insert them here
710          */
711         for (p = printk_buf; *p; p++) {
712                 if (new_text_line) {
713                         int current_log_level = default_message_loglevel;
714                         /* If a token, set current_log_level and skip over */
715                         if (p[0] == '<' && p[1] >= '0' && p[1] <= '7' &&
716                             p[2] == '>') {
717                                 current_log_level = p[1] - '0';
718                                 p += 3;
719                                 printed_len -= 3;
720                         }
721
722                         /* Always output the token */
723                         emit_log_char('<');
724                         emit_log_char(current_log_level + '0');
725                         emit_log_char('>');
726                         printed_len += 3;
727                         new_text_line = 0;
728
729                         if (printk_time) {
730                                 /* Follow the token with the time */
731                                 char tbuf[50], *tp;
732                                 unsigned tlen;
733                                 unsigned long long t;
734                                 unsigned long nanosec_rem;
735
736                                 t = cpu_clock(printk_cpu);
737                                 nanosec_rem = do_div(t, 1000000000);
738                                 tlen = sprintf(tbuf, "[%5lu.%06lu] ",
739                                                 (unsigned long) t,
740                                                 nanosec_rem / 1000);
741
742                                 for (tp = tbuf; tp < tbuf + tlen; tp++)
743                                         emit_log_char(*tp);
744                                 printed_len += tlen;
745                         }
746
747                         if (!*p)
748                                 break;
749                 }
750
751                 emit_log_char(*p);
752                 if (*p == '\n')
753                         new_text_line = 1;
754         }
755
756         /*
757          * Try to acquire and then immediately release the
758          * console semaphore. The release will do all the
759          * actual magic (print out buffers, wake up klogd,
760          * etc). 
761          *
762          * The acquire_console_semaphore_for_printk() function
763          * will release 'logbuf_lock' regardless of whether it
764          * actually gets the semaphore or not.
765          */
766         if (acquire_console_semaphore_for_printk(this_cpu))
767                 release_console_sem();
768
769         lockdep_on();
770 out_restore_irqs:
771         raw_local_irq_restore(flags);
772
773         preempt_enable();
774         return printed_len;
775 }
776 EXPORT_SYMBOL(printk);
777 EXPORT_SYMBOL(vprintk);
778
779 #else
780
781 asmlinkage long sys_syslog(int type, char __user *buf, int len)
782 {
783         return -ENOSYS;
784 }
785
786 static void call_console_drivers(unsigned start, unsigned end)
787 {
788 }
789
790 #endif
791
792 static int __add_preferred_console(char *name, int idx, char *options,
793                                    char *brl_options)
794 {
795         struct console_cmdline *c;
796         int i;
797
798         /*
799          *      See if this tty is not yet registered, and
800          *      if we have a slot free.
801          */
802         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
803                 if (strcmp(console_cmdline[i].name, name) == 0 &&
804                           console_cmdline[i].index == idx) {
805                                 if (!brl_options)
806                                         selected_console = i;
807                                 return 0;
808                 }
809         if (i == MAX_CMDLINECONSOLES)
810                 return -E2BIG;
811         if (!brl_options)
812                 selected_console = i;
813         c = &console_cmdline[i];
814         strlcpy(c->name, name, sizeof(c->name));
815         c->options = options;
816 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
817         c->brl_options = brl_options;
818 #endif
819         c->index = idx;
820         return 0;
821 }
822 /*
823  * Set up a list of consoles.  Called from init/main.c
824  */
825 static int __init console_setup(char *str)
826 {
827         char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
828         char *s, *options, *brl_options = NULL;
829         int idx;
830
831 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
832         if (!memcmp(str, "brl,", 4)) {
833                 brl_options = "";
834                 str += 4;
835         } else if (!memcmp(str, "brl=", 4)) {
836                 brl_options = str + 4;
837                 str = strchr(brl_options, ',');
838                 if (!str) {
839                         printk(KERN_ERR "need port name after brl=\n");
840                         return 1;
841                 }
842                 *(str++) = 0;
843         }
844 #endif
845
846         /*
847          * Decode str into name, index, options.
848          */
849         if (str[0] >= '0' && str[0] <= '9') {
850                 strcpy(buf, "ttyS");
851                 strncpy(buf + 4, str, sizeof(buf) - 5);
852         } else {
853                 strncpy(buf, str, sizeof(buf) - 1);
854         }
855         buf[sizeof(buf) - 1] = 0;
856         if ((options = strchr(str, ',')) != NULL)
857                 *(options++) = 0;
858 #ifdef __sparc__
859         if (!strcmp(str, "ttya"))
860                 strcpy(buf, "ttyS0");
861         if (!strcmp(str, "ttyb"))
862                 strcpy(buf, "ttyS1");
863 #endif
864         for (s = buf; *s; s++)
865                 if ((*s >= '0' && *s <= '9') || *s == ',')
866                         break;
867         idx = simple_strtoul(s, NULL, 10);
868         *s = 0;
869
870         __add_preferred_console(buf, idx, options, brl_options);
871         return 1;
872 }
873 __setup("console=", console_setup);
874
875 /**
876  * add_preferred_console - add a device to the list of preferred consoles.
877  * @name: device name
878  * @idx: device index
879  * @options: options for this console
880  *
881  * The last preferred console added will be used for kernel messages
882  * and stdin/out/err for init.  Normally this is used by console_setup
883  * above to handle user-supplied console arguments; however it can also
884  * be used by arch-specific code either to override the user or more
885  * commonly to provide a default console (ie from PROM variables) when
886  * the user has not supplied one.
887  */
888 int add_preferred_console(char *name, int idx, char *options)
889 {
890         return __add_preferred_console(name, idx, options, NULL);
891 }
892
893 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
894 {
895         struct console_cmdline *c;
896         int i;
897
898         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
899                 if (strcmp(console_cmdline[i].name, name) == 0 &&
900                           console_cmdline[i].index == idx) {
901                                 c = &console_cmdline[i];
902                                 strlcpy(c->name, name_new, sizeof(c->name));
903                                 c->name[sizeof(c->name) - 1] = 0;
904                                 c->options = options;
905                                 c->index = idx_new;
906                                 return i;
907                 }
908         /* not found */
909         return -1;
910 }
911
912 int console_suspend_enabled = 1;
913 EXPORT_SYMBOL(console_suspend_enabled);
914
915 static int __init console_suspend_disable(char *str)
916 {
917         console_suspend_enabled = 0;
918         return 1;
919 }
920 __setup("no_console_suspend", console_suspend_disable);
921
922 /**
923  * suspend_console - suspend the console subsystem
924  *
925  * This disables printk() while we go into suspend states
926  */
927 void suspend_console(void)
928 {
929         if (!console_suspend_enabled)
930                 return;
931         printk("Suspending console(s)\n");
932         acquire_console_sem();
933         console_suspended = 1;
934 }
935
936 void resume_console(void)
937 {
938         if (!console_suspend_enabled)
939                 return;
940         console_suspended = 0;
941         release_console_sem();
942 }
943
944 /**
945  * acquire_console_sem - lock the console system for exclusive use.
946  *
947  * Acquires a semaphore which guarantees that the caller has
948  * exclusive access to the console system and the console_drivers list.
949  *
950  * Can sleep, returns nothing.
951  */
952 void acquire_console_sem(void)
953 {
954         BUG_ON(in_interrupt());
955         if (console_suspended) {
956                 down(&secondary_console_sem);
957                 return;
958         }
959         down(&console_sem);
960         console_locked = 1;
961         console_may_schedule = 1;
962 }
963 EXPORT_SYMBOL(acquire_console_sem);
964
965 int try_acquire_console_sem(void)
966 {
967         if (down_trylock(&console_sem))
968                 return -1;
969         console_locked = 1;
970         console_may_schedule = 0;
971         return 0;
972 }
973 EXPORT_SYMBOL(try_acquire_console_sem);
974
975 int is_console_locked(void)
976 {
977         return console_locked;
978 }
979
980 void wake_up_klogd(void)
981 {
982         if (!oops_in_progress && waitqueue_active(&log_wait))
983                 wake_up_interruptible(&log_wait);
984 }
985
986 /**
987  * release_console_sem - unlock the console system
988  *
989  * Releases the semaphore which the caller holds on the console system
990  * and the console driver list.
991  *
992  * While the semaphore was held, console output may have been buffered
993  * by printk().  If this is the case, release_console_sem() emits
994  * the output prior to releasing the semaphore.
995  *
996  * If there is output waiting for klogd, we wake it up.
997  *
998  * release_console_sem() may be called from any context.
999  */
1000 void release_console_sem(void)
1001 {
1002         unsigned long flags;
1003         unsigned _con_start, _log_end;
1004         unsigned wake_klogd = 0;
1005
1006         if (console_suspended) {
1007                 up(&secondary_console_sem);
1008                 return;
1009         }
1010
1011         console_may_schedule = 0;
1012
1013         for ( ; ; ) {
1014                 spin_lock_irqsave(&logbuf_lock, flags);
1015                 wake_klogd |= log_start - log_end;
1016                 if (con_start == log_end)
1017                         break;                  /* Nothing to print */
1018                 _con_start = con_start;
1019                 _log_end = log_end;
1020                 con_start = log_end;            /* Flush */
1021                 spin_unlock(&logbuf_lock);
1022                 call_console_drivers(_con_start, _log_end);
1023                 local_irq_restore(flags);
1024         }
1025         console_locked = 0;
1026         up(&console_sem);
1027         spin_unlock_irqrestore(&logbuf_lock, flags);
1028         if (wake_klogd)
1029                 wake_up_klogd();
1030 }
1031 EXPORT_SYMBOL(release_console_sem);
1032
1033 /**
1034  * console_conditional_schedule - yield the CPU if required
1035  *
1036  * If the console code is currently allowed to sleep, and
1037  * if this CPU should yield the CPU to another task, do
1038  * so here.
1039  *
1040  * Must be called within acquire_console_sem().
1041  */
1042 void __sched console_conditional_schedule(void)
1043 {
1044         if (console_may_schedule)
1045                 cond_resched();
1046 }
1047 EXPORT_SYMBOL(console_conditional_schedule);
1048
1049 void console_print(const char *s)
1050 {
1051         printk(KERN_EMERG "%s", s);
1052 }
1053 EXPORT_SYMBOL(console_print);
1054
1055 void console_unblank(void)
1056 {
1057         struct console *c;
1058
1059         /*
1060          * console_unblank can no longer be called in interrupt context unless
1061          * oops_in_progress is set to 1..
1062          */
1063         if (oops_in_progress) {
1064                 if (down_trylock(&console_sem) != 0)
1065                         return;
1066         } else
1067                 acquire_console_sem();
1068
1069         console_locked = 1;
1070         console_may_schedule = 0;
1071         for (c = console_drivers; c != NULL; c = c->next)
1072                 if ((c->flags & CON_ENABLED) && c->unblank)
1073                         c->unblank();
1074         release_console_sem();
1075 }
1076
1077 /*
1078  * Return the console tty driver structure and its associated index
1079  */
1080 struct tty_driver *console_device(int *index)
1081 {
1082         struct console *c;
1083         struct tty_driver *driver = NULL;
1084
1085         acquire_console_sem();
1086         for (c = console_drivers; c != NULL; c = c->next) {
1087                 if (!c->device)
1088                         continue;
1089                 driver = c->device(c, index);
1090                 if (driver)
1091                         break;
1092         }
1093         release_console_sem();
1094         return driver;
1095 }
1096
1097 /*
1098  * Prevent further output on the passed console device so that (for example)
1099  * serial drivers can disable console output before suspending a port, and can
1100  * re-enable output afterwards.
1101  */
1102 void console_stop(struct console *console)
1103 {
1104         acquire_console_sem();
1105         console->flags &= ~CON_ENABLED;
1106         release_console_sem();
1107 }
1108 EXPORT_SYMBOL(console_stop);
1109
1110 void console_start(struct console *console)
1111 {
1112         acquire_console_sem();
1113         console->flags |= CON_ENABLED;
1114         release_console_sem();
1115 }
1116 EXPORT_SYMBOL(console_start);
1117
1118 /*
1119  * The console driver calls this routine during kernel initialization
1120  * to register the console printing procedure with printk() and to
1121  * print any messages that were printed by the kernel before the
1122  * console driver was initialized.
1123  */
1124 void register_console(struct console *console)
1125 {
1126         int i;
1127         unsigned long flags;
1128         struct console *bootconsole = NULL;
1129
1130         if (console_drivers) {
1131                 if (console->flags & CON_BOOT)
1132                         return;
1133                 if (console_drivers->flags & CON_BOOT)
1134                         bootconsole = console_drivers;
1135         }
1136
1137         if (preferred_console < 0 || bootconsole || !console_drivers)
1138                 preferred_console = selected_console;
1139
1140         if (console->early_setup)
1141                 console->early_setup();
1142
1143         /*
1144          *      See if we want to use this console driver. If we
1145          *      didn't select a console we take the first one
1146          *      that registers here.
1147          */
1148         if (preferred_console < 0) {
1149                 if (console->index < 0)
1150                         console->index = 0;
1151                 if (console->setup == NULL ||
1152                     console->setup(console, NULL) == 0) {
1153                         console->flags |= CON_ENABLED;
1154                         if (console->device) {
1155                                 console->flags |= CON_CONSDEV;
1156                                 preferred_console = 0;
1157                         }
1158                 }
1159         }
1160
1161         /*
1162          *      See if this console matches one we selected on
1163          *      the command line.
1164          */
1165         for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
1166                         i++) {
1167                 if (strcmp(console_cmdline[i].name, console->name) != 0)
1168                         continue;
1169                 if (console->index >= 0 &&
1170                     console->index != console_cmdline[i].index)
1171                         continue;
1172                 if (console->index < 0)
1173                         console->index = console_cmdline[i].index;
1174 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1175                 if (console_cmdline[i].brl_options) {
1176                         console->flags |= CON_BRL;
1177                         braille_register_console(console,
1178                                         console_cmdline[i].index,
1179                                         console_cmdline[i].options,
1180                                         console_cmdline[i].brl_options);
1181                         return;
1182                 }
1183 #endif
1184                 if (console->setup &&
1185                     console->setup(console, console_cmdline[i].options) != 0)
1186                         break;
1187                 console->flags |= CON_ENABLED;
1188                 console->index = console_cmdline[i].index;
1189                 if (i == selected_console) {
1190                         console->flags |= CON_CONSDEV;
1191                         preferred_console = selected_console;
1192                 }
1193                 break;
1194         }
1195
1196         if (!(console->flags & CON_ENABLED))
1197                 return;
1198
1199         if (bootconsole && (console->flags & CON_CONSDEV)) {
1200                 printk(KERN_INFO "console handover: boot [%s%d] -> real [%s%d]\n",
1201                        bootconsole->name, bootconsole->index,
1202                        console->name, console->index);
1203                 unregister_console(bootconsole);
1204                 console->flags &= ~CON_PRINTBUFFER;
1205         } else {
1206                 printk(KERN_INFO "console [%s%d] enabled\n",
1207                        console->name, console->index);
1208         }
1209
1210         /*
1211          *      Put this console in the list - keep the
1212          *      preferred driver at the head of the list.
1213          */
1214         acquire_console_sem();
1215         if ((console->flags & CON_CONSDEV) || console_drivers == NULL) {
1216                 console->next = console_drivers;
1217                 console_drivers = console;
1218                 if (console->next)
1219                         console->next->flags &= ~CON_CONSDEV;
1220         } else {
1221                 console->next = console_drivers->next;
1222                 console_drivers->next = console;
1223         }
1224         if (console->flags & CON_PRINTBUFFER) {
1225                 /*
1226                  * release_console_sem() will print out the buffered messages
1227                  * for us.
1228                  */
1229                 spin_lock_irqsave(&logbuf_lock, flags);
1230                 con_start = log_start;
1231                 spin_unlock_irqrestore(&logbuf_lock, flags);
1232         }
1233         release_console_sem();
1234 }
1235 EXPORT_SYMBOL(register_console);
1236
1237 int unregister_console(struct console *console)
1238 {
1239         struct console *a, *b;
1240         int res = 1;
1241
1242 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
1243         if (console->flags & CON_BRL)
1244                 return braille_unregister_console(console);
1245 #endif
1246
1247         acquire_console_sem();
1248         if (console_drivers == console) {
1249                 console_drivers=console->next;
1250                 res = 0;
1251         } else if (console_drivers) {
1252                 for (a=console_drivers->next, b=console_drivers ;
1253                      a; b=a, a=b->next) {
1254                         if (a == console) {
1255                                 b->next = a->next;
1256                                 res = 0;
1257                                 break;
1258                         }
1259                 }
1260         }
1261
1262         /*
1263          * If this isn't the last console and it has CON_CONSDEV set, we
1264          * need to set it on the next preferred console.
1265          */
1266         if (console_drivers != NULL && console->flags & CON_CONSDEV)
1267                 console_drivers->flags |= CON_CONSDEV;
1268
1269         release_console_sem();
1270         return res;
1271 }
1272 EXPORT_SYMBOL(unregister_console);
1273
1274 static int __init disable_boot_consoles(void)
1275 {
1276         if (console_drivers != NULL) {
1277                 if (console_drivers->flags & CON_BOOT) {
1278                         printk(KERN_INFO "turn off boot console %s%d\n",
1279                                 console_drivers->name, console_drivers->index);
1280                         return unregister_console(console_drivers);
1281                 }
1282         }
1283         return 0;
1284 }
1285 late_initcall(disable_boot_consoles);
1286
1287 /**
1288  * tty_write_message - write a message to a certain tty, not just the console.
1289  * @tty: the destination tty_struct
1290  * @msg: the message to write
1291  *
1292  * This is used for messages that need to be redirected to a specific tty.
1293  * We don't put it into the syslog queue right now maybe in the future if
1294  * really needed.
1295  */
1296 void tty_write_message(struct tty_struct *tty, char *msg)
1297 {
1298         if (tty && tty->ops->write)
1299                 tty->ops->write(tty, msg, strlen(msg));
1300         return;
1301 }
1302
1303 #if defined CONFIG_PRINTK
1304 /*
1305  * printk rate limiting, lifted from the networking subsystem.
1306  *
1307  * This enforces a rate limit: not more than one kernel message
1308  * every printk_ratelimit_jiffies to make a denial-of-service
1309  * attack impossible.
1310  */
1311 int __printk_ratelimit(int ratelimit_jiffies, int ratelimit_burst)
1312 {
1313         return __ratelimit(ratelimit_jiffies, ratelimit_burst);
1314 }
1315 EXPORT_SYMBOL(__printk_ratelimit);
1316
1317 /* minimum time in jiffies between messages */
1318 int printk_ratelimit_jiffies = 5 * HZ;
1319
1320 /* number of messages we send before ratelimiting */
1321 int printk_ratelimit_burst = 10;
1322
1323 int printk_ratelimit(void)
1324 {
1325         return __printk_ratelimit(printk_ratelimit_jiffies,
1326                                 printk_ratelimit_burst);
1327 }
1328 EXPORT_SYMBOL(printk_ratelimit);
1329
1330 /**
1331  * printk_timed_ratelimit - caller-controlled printk ratelimiting
1332  * @caller_jiffies: pointer to caller's state
1333  * @interval_msecs: minimum interval between prints
1334  *
1335  * printk_timed_ratelimit() returns true if more than @interval_msecs
1336  * milliseconds have elapsed since the last time printk_timed_ratelimit()
1337  * returned true.
1338  */
1339 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
1340                         unsigned int interval_msecs)
1341 {
1342         if (*caller_jiffies == 0 || time_after(jiffies, *caller_jiffies)) {
1343                 *caller_jiffies = jiffies + msecs_to_jiffies(interval_msecs);
1344                 return true;
1345         }
1346         return false;
1347 }
1348 EXPORT_SYMBOL(printk_timed_ratelimit);
1349 #endif