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