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