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