~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/kernel/printk/printk.c

Version: ~ [ linux-5.14-rc1 ] ~ [ linux-5.13.1 ] ~ [ linux-5.12.16 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.49 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.131 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.197 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.239 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.275 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.275 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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
 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/memblock.h>
 35 #include <linux/aio.h>
 36 #include <linux/syscalls.h>
 37 #include <linux/kexec.h>
 38 #include <linux/kdb.h>
 39 #include <linux/ratelimit.h>
 40 #include <linux/kmsg_dump.h>
 41 #include <linux/syslog.h>
 42 #include <linux/cpu.h>
 43 #include <linux/notifier.h>
 44 #include <linux/rculist.h>
 45 #include <linux/poll.h>
 46 #include <linux/irq_work.h>
 47 #include <linux/utsname.h>
 48 #include <linux/ctype.h>
 49 
 50 #include <asm/uaccess.h>
 51 
 52 #define CREATE_TRACE_POINTS
 53 #include <trace/events/printk.h>
 54 
 55 #include "console_cmdline.h"
 56 #include "braille.h"
 57 
 58 int console_printk[4] = {
 59         CONSOLE_LOGLEVEL_DEFAULT,       /* console_loglevel */
 60         MESSAGE_LOGLEVEL_DEFAULT,       /* default_message_loglevel */
 61         CONSOLE_LOGLEVEL_MIN,           /* minimum_console_loglevel */
 62         CONSOLE_LOGLEVEL_DEFAULT,       /* default_console_loglevel */
 63 };
 64 
 65 /* Deferred messaged from sched code are marked by this special level */
 66 #define SCHED_MESSAGE_LOGLEVEL -2
 67 
 68 /*
 69  * Low level drivers may need that to know if they can schedule in
 70  * their unblank() callback or not. So let's export it.
 71  */
 72 int oops_in_progress;
 73 EXPORT_SYMBOL(oops_in_progress);
 74 
 75 /*
 76  * console_sem protects the console_drivers list, and also
 77  * provides serialisation for access to the entire console
 78  * driver system.
 79  */
 80 static DEFINE_SEMAPHORE(console_sem);
 81 struct console *console_drivers;
 82 EXPORT_SYMBOL_GPL(console_drivers);
 83 
 84 #ifdef CONFIG_LOCKDEP
 85 static struct lockdep_map console_lock_dep_map = {
 86         .name = "console_lock"
 87 };
 88 #endif
 89 
 90 /*
 91  * Helper macros to handle lockdep when locking/unlocking console_sem. We use
 92  * macros instead of functions so that _RET_IP_ contains useful information.
 93  */
 94 #define down_console_sem() do { \
 95         down(&console_sem);\
 96         mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
 97 } while (0)
 98 
 99 static int __down_trylock_console_sem(unsigned long ip)
100 {
101         if (down_trylock(&console_sem))
102                 return 1;
103         mutex_acquire(&console_lock_dep_map, 0, 1, ip);
104         return 0;
105 }
106 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
107 
108 #define up_console_sem() do { \
109         mutex_release(&console_lock_dep_map, 1, _RET_IP_);\
110         up(&console_sem);\
111 } while (0)
112 
113 /*
114  * This is used for debugging the mess that is the VT code by
115  * keeping track if we have the console semaphore held. It's
116  * definitely not the perfect debug tool (we don't know if _WE_
117  * hold it and are racing, but it helps tracking those weird code
118  * paths in the console code where we end up in places I want
119  * locked without the console sempahore held).
120  */
121 static int console_locked, console_suspended;
122 
123 /*
124  * If exclusive_console is non-NULL then only this console is to be printed to.
125  */
126 static struct console *exclusive_console;
127 
128 /*
129  *      Array of consoles built from command line options (console=)
130  */
131 
132 #define MAX_CMDLINECONSOLES 8
133 
134 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
135 
136 static int selected_console = -1;
137 static int preferred_console = -1;
138 int console_set_on_cmdline;
139 EXPORT_SYMBOL(console_set_on_cmdline);
140 
141 /* Flag: console code may call schedule() */
142 static int console_may_schedule;
143 
144 /*
145  * The printk log buffer consists of a chain of concatenated variable
146  * length records. Every record starts with a record header, containing
147  * the overall length of the record.
148  *
149  * The heads to the first and last entry in the buffer, as well as the
150  * sequence numbers of these entries are maintained when messages are
151  * stored.
152  *
153  * If the heads indicate available messages, the length in the header
154  * tells the start next message. A length == 0 for the next message
155  * indicates a wrap-around to the beginning of the buffer.
156  *
157  * Every record carries the monotonic timestamp in microseconds, as well as
158  * the standard userspace syslog level and syslog facility. The usual
159  * kernel messages use LOG_KERN; userspace-injected messages always carry
160  * a matching syslog facility, by default LOG_USER. The origin of every
161  * message can be reliably determined that way.
162  *
163  * The human readable log message directly follows the message header. The
164  * length of the message text is stored in the header, the stored message
165  * is not terminated.
166  *
167  * Optionally, a message can carry a dictionary of properties (key/value pairs),
168  * to provide userspace with a machine-readable message context.
169  *
170  * Examples for well-defined, commonly used property names are:
171  *   DEVICE=b12:8               device identifier
172  *                                b12:8         block dev_t
173  *                                c127:3        char dev_t
174  *                                n8            netdev ifindex
175  *                                +sound:card0  subsystem:devname
176  *   SUBSYSTEM=pci              driver-core subsystem name
177  *
178  * Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
179  * follows directly after a '=' character. Every property is terminated by
180  * a '\0' character. The last property is not terminated.
181  *
182  * Example of a message structure:
183  *   0000  ff 8f 00 00 00 00 00 00      monotonic time in nsec
184  *   0008  34 00                        record is 52 bytes long
185  *   000a        0b 00                  text is 11 bytes long
186  *   000c              1f 00            dictionary is 23 bytes long
187  *   000e                    03 00      LOG_KERN (facility) LOG_ERR (level)
188  *   0010  69 74 27 73 20 61 20 6c      "it's a l"
189  *         69 6e 65                     "ine"
190  *   001b           44 45 56 49 43      "DEVIC"
191  *         45 3d 62 38 3a 32 00 44      "E=b8:2\0D"
192  *         52 49 56 45 52 3d 62 75      "RIVER=bu"
193  *         67                           "g"
194  *   0032     00 00 00                  padding to next message header
195  *
196  * The 'struct printk_log' buffer header must never be directly exported to
197  * userspace, it is a kernel-private implementation detail that might
198  * need to be changed in the future, when the requirements change.
199  *
200  * /dev/kmsg exports the structured data in the following line format:
201  *   "level,sequnum,timestamp;<message text>\n"
202  *
203  * The optional key/value pairs are attached as continuation lines starting
204  * with a space character and terminated by a newline. All possible
205  * non-prinatable characters are escaped in the "\xff" notation.
206  *
207  * Users of the export format should ignore possible additional values
208  * separated by ',', and find the message after the ';' character.
209  */
210 
211 enum log_flags {
212         LOG_NOCONS      = 1,    /* already flushed, do not print to console */
213         LOG_NEWLINE     = 2,    /* text ended with a newline */
214         LOG_PREFIX      = 4,    /* text started with a prefix */
215         LOG_CONT        = 8,    /* text is a fragment of a continuation line */
216 };
217 
218 struct printk_log {
219         u64 ts_nsec;            /* timestamp in nanoseconds */
220         u16 len;                /* length of entire record */
221         u16 text_len;           /* length of text buffer */
222         u16 dict_len;           /* length of dictionary buffer */
223         u8 facility;            /* syslog facility */
224         u8 flags:5;             /* internal record flags */
225         u8 level:3;             /* syslog level */
226 };
227 
228 /*
229  * The logbuf_lock protects kmsg buffer, indices, counters.  This can be taken
230  * within the scheduler's rq lock. It must be released before calling
231  * console_unlock() or anything else that might wake up a process.
232  */
233 static DEFINE_RAW_SPINLOCK(logbuf_lock);
234 
235 #ifdef CONFIG_PRINTK
236 DECLARE_WAIT_QUEUE_HEAD(log_wait);
237 /* the next printk record to read by syslog(READ) or /proc/kmsg */
238 static u64 syslog_seq;
239 static u32 syslog_idx;
240 static enum log_flags syslog_prev;
241 static size_t syslog_partial;
242 
243 /* index and sequence number of the first record stored in the buffer */
244 static u64 log_first_seq;
245 static u32 log_first_idx;
246 
247 /* index and sequence number of the next record to store in the buffer */
248 static u64 log_next_seq;
249 static u32 log_next_idx;
250 
251 /* the next printk record to write to the console */
252 static u64 console_seq;
253 static u32 console_idx;
254 static enum log_flags console_prev;
255 
256 /* the next printk record to read after the last 'clear' command */
257 static u64 clear_seq;
258 static u32 clear_idx;
259 
260 #define PREFIX_MAX              32
261 #define LOG_LINE_MAX            (1024 - PREFIX_MAX)
262 
263 /* record buffer */
264 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
265 #define LOG_ALIGN 4
266 #else
267 #define LOG_ALIGN __alignof__(struct printk_log)
268 #endif
269 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
270 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
271 static char *log_buf = __log_buf;
272 static u32 log_buf_len = __LOG_BUF_LEN;
273 
274 /* Return log buffer address */
275 char *log_buf_addr_get(void)
276 {
277         return log_buf;
278 }
279 
280 /* Return log buffer size */
281 u32 log_buf_len_get(void)
282 {
283         return log_buf_len;
284 }
285 
286 /* human readable text of the record */
287 static char *log_text(const struct printk_log *msg)
288 {
289         return (char *)msg + sizeof(struct printk_log);
290 }
291 
292 /* optional key/value pair dictionary attached to the record */
293 static char *log_dict(const struct printk_log *msg)
294 {
295         return (char *)msg + sizeof(struct printk_log) + msg->text_len;
296 }
297 
298 /* get record by index; idx must point to valid msg */
299 static struct printk_log *log_from_idx(u32 idx)
300 {
301         struct printk_log *msg = (struct printk_log *)(log_buf + idx);
302 
303         /*
304          * A length == 0 record is the end of buffer marker. Wrap around and
305          * read the message at the start of the buffer.
306          */
307         if (!msg->len)
308                 return (struct printk_log *)log_buf;
309         return msg;
310 }
311 
312 /* get next record; idx must point to valid msg */
313 static u32 log_next(u32 idx)
314 {
315         struct printk_log *msg = (struct printk_log *)(log_buf + idx);
316 
317         /* length == 0 indicates the end of the buffer; wrap */
318         /*
319          * A length == 0 record is the end of buffer marker. Wrap around and
320          * read the message at the start of the buffer as *this* one, and
321          * return the one after that.
322          */
323         if (!msg->len) {
324                 msg = (struct printk_log *)log_buf;
325                 return msg->len;
326         }
327         return idx + msg->len;
328 }
329 
330 /*
331  * Check whether there is enough free space for the given message.
332  *
333  * The same values of first_idx and next_idx mean that the buffer
334  * is either empty or full.
335  *
336  * If the buffer is empty, we must respect the position of the indexes.
337  * They cannot be reset to the beginning of the buffer.
338  */
339 static int logbuf_has_space(u32 msg_size, bool empty)
340 {
341         u32 free;
342 
343         if (log_next_idx > log_first_idx || empty)
344                 free = max(log_buf_len - log_next_idx, log_first_idx);
345         else
346                 free = log_first_idx - log_next_idx;
347 
348         /*
349          * We need space also for an empty header that signalizes wrapping
350          * of the buffer.
351          */
352         return free >= msg_size + sizeof(struct printk_log);
353 }
354 
355 static int log_make_free_space(u32 msg_size)
356 {
357         while (log_first_seq < log_next_seq) {
358                 if (logbuf_has_space(msg_size, false))
359                         return 0;
360                 /* drop old messages until we have enough contiguous space */
361                 log_first_idx = log_next(log_first_idx);
362                 log_first_seq++;
363         }
364 
365         /* sequence numbers are equal, so the log buffer is empty */
366         if (logbuf_has_space(msg_size, true))
367                 return 0;
368 
369         return -ENOMEM;
370 }
371 
372 /* compute the message size including the padding bytes */
373 static u32 msg_used_size(u16 text_len, u16 dict_len, u32 *pad_len)
374 {
375         u32 size;
376 
377         size = sizeof(struct printk_log) + text_len + dict_len;
378         *pad_len = (-size) & (LOG_ALIGN - 1);
379         size += *pad_len;
380 
381         return size;
382 }
383 
384 /*
385  * Define how much of the log buffer we could take at maximum. The value
386  * must be greater than two. Note that only half of the buffer is available
387  * when the index points to the middle.
388  */
389 #define MAX_LOG_TAKE_PART 4
390 static const char trunc_msg[] = "<truncated>";
391 
392 static u32 truncate_msg(u16 *text_len, u16 *trunc_msg_len,
393                         u16 *dict_len, u32 *pad_len)
394 {
395         /*
396          * The message should not take the whole buffer. Otherwise, it might
397          * get removed too soon.
398          */
399         u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
400         if (*text_len > max_text_len)
401                 *text_len = max_text_len;
402         /* enable the warning message */
403         *trunc_msg_len = strlen(trunc_msg);
404         /* disable the "dict" completely */
405         *dict_len = 0;
406         /* compute the size again, count also the warning message */
407         return msg_used_size(*text_len + *trunc_msg_len, 0, pad_len);
408 }
409 
410 /* insert record into the buffer, discard old ones, update heads */
411 static int log_store(int facility, int level,
412                      enum log_flags flags, u64 ts_nsec,
413                      const char *dict, u16 dict_len,
414                      const char *text, u16 text_len)
415 {
416         struct printk_log *msg;
417         u32 size, pad_len;
418         u16 trunc_msg_len = 0;
419 
420         /* number of '\0' padding bytes to next message */
421         size = msg_used_size(text_len, dict_len, &pad_len);
422 
423         if (log_make_free_space(size)) {
424                 /* truncate the message if it is too long for empty buffer */
425                 size = truncate_msg(&text_len, &trunc_msg_len,
426                                     &dict_len, &pad_len);
427                 /* survive when the log buffer is too small for trunc_msg */
428                 if (log_make_free_space(size))
429                         return 0;
430         }
431 
432         if (log_next_idx + size + sizeof(struct printk_log) > log_buf_len) {
433                 /*
434                  * This message + an additional empty header does not fit
435                  * at the end of the buffer. Add an empty header with len == 0
436                  * to signify a wrap around.
437                  */
438                 memset(log_buf + log_next_idx, 0, sizeof(struct printk_log));
439                 log_next_idx = 0;
440         }
441 
442         /* fill message */
443         msg = (struct printk_log *)(log_buf + log_next_idx);
444         memcpy(log_text(msg), text, text_len);
445         msg->text_len = text_len;
446         if (trunc_msg_len) {
447                 memcpy(log_text(msg) + text_len, trunc_msg, trunc_msg_len);
448                 msg->text_len += trunc_msg_len;
449         }
450         memcpy(log_dict(msg), dict, dict_len);
451         msg->dict_len = dict_len;
452         msg->facility = facility;
453         msg->level = level & 7;
454         msg->flags = flags & 0x1f;
455         if (ts_nsec > 0)
456                 msg->ts_nsec = ts_nsec;
457         else
458                 msg->ts_nsec = local_clock();
459         memset(log_dict(msg) + dict_len, 0, pad_len);
460         msg->len = size;
461 
462         /* insert message */
463         log_next_idx += msg->len;
464         log_next_seq++;
465 
466         return msg->text_len;
467 }
468 
469 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
470 
471 static int syslog_action_restricted(int type)
472 {
473         if (dmesg_restrict)
474                 return 1;
475         /*
476          * Unless restricted, we allow "read all" and "get buffer size"
477          * for everybody.
478          */
479         return type != SYSLOG_ACTION_READ_ALL &&
480                type != SYSLOG_ACTION_SIZE_BUFFER;
481 }
482 
483 static int check_syslog_permissions(int type, bool from_file)
484 {
485         /*
486          * If this is from /proc/kmsg and we've already opened it, then we've
487          * already done the capabilities checks at open time.
488          */
489         if (from_file && type != SYSLOG_ACTION_OPEN)
490                 goto ok;
491 
492         if (syslog_action_restricted(type)) {
493                 if (capable(CAP_SYSLOG))
494                         goto ok;
495                 /*
496                  * For historical reasons, accept CAP_SYS_ADMIN too, with
497                  * a warning.
498                  */
499                 if (capable(CAP_SYS_ADMIN)) {
500                         pr_warn_once("%s (%d): Attempt to access syslog with "
501                                      "CAP_SYS_ADMIN but no CAP_SYSLOG "
502                                      "(deprecated).\n",
503                                  current->comm, task_pid_nr(current));
504                         goto ok;
505                 }
506                 return -EPERM;
507         }
508 ok:
509         return security_syslog(type);
510 }
511 
512 
513 /* /dev/kmsg - userspace message inject/listen interface */
514 struct devkmsg_user {
515         u64 seq;
516         u32 idx;
517         enum log_flags prev;
518         struct mutex lock;
519         char buf[8192];
520 };
521 
522 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
523 {
524         char *buf, *line;
525         int i;
526         int level = default_message_loglevel;
527         int facility = 1;       /* LOG_USER */
528         size_t len = iocb->ki_nbytes;
529         ssize_t ret = len;
530 
531         if (len > LOG_LINE_MAX)
532                 return -EINVAL;
533         buf = kmalloc(len+1, GFP_KERNEL);
534         if (buf == NULL)
535                 return -ENOMEM;
536 
537         buf[len] = '\0';
538         if (copy_from_iter(buf, len, from) != len) {
539                 kfree(buf);
540                 return -EFAULT;
541         }
542 
543         /*
544          * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
545          * the decimal value represents 32bit, the lower 3 bit are the log
546          * level, the rest are the log facility.
547          *
548          * If no prefix or no userspace facility is specified, we
549          * enforce LOG_USER, to be able to reliably distinguish
550          * kernel-generated messages from userspace-injected ones.
551          */
552         line = buf;
553         if (line[0] == '<') {
554                 char *endp = NULL;
555 
556                 i = simple_strtoul(line+1, &endp, 10);
557                 if (endp && endp[0] == '>') {
558                         level = i & 7;
559                         if (i >> 3)
560                                 facility = i >> 3;
561                         endp++;
562                         len -= endp - line;
563                         line = endp;
564                 }
565         }
566 
567         printk_emit(facility, level, NULL, 0, "%s", line);
568         kfree(buf);
569         return ret;
570 }
571 
572 static ssize_t devkmsg_read(struct file *file, char __user *buf,
573                             size_t count, loff_t *ppos)
574 {
575         struct devkmsg_user *user = file->private_data;
576         struct printk_log *msg;
577         u64 ts_usec;
578         size_t i;
579         char cont = '-';
580         size_t len;
581         ssize_t ret;
582 
583         if (!user)
584                 return -EBADF;
585 
586         ret = mutex_lock_interruptible(&user->lock);
587         if (ret)
588                 return ret;
589         raw_spin_lock_irq(&logbuf_lock);
590         while (user->seq == log_next_seq) {
591                 if (file->f_flags & O_NONBLOCK) {
592                         ret = -EAGAIN;
593                         raw_spin_unlock_irq(&logbuf_lock);
594                         goto out;
595                 }
596 
597                 raw_spin_unlock_irq(&logbuf_lock);
598                 ret = wait_event_interruptible(log_wait,
599                                                user->seq != log_next_seq);
600                 if (ret)
601                         goto out;
602                 raw_spin_lock_irq(&logbuf_lock);
603         }
604 
605         if (user->seq < log_first_seq) {
606                 /* our last seen message is gone, return error and reset */
607                 user->idx = log_first_idx;
608                 user->seq = log_first_seq;
609                 ret = -EPIPE;
610                 raw_spin_unlock_irq(&logbuf_lock);
611                 goto out;
612         }
613 
614         msg = log_from_idx(user->idx);
615         ts_usec = msg->ts_nsec;
616         do_div(ts_usec, 1000);
617 
618         /*
619          * If we couldn't merge continuation line fragments during the print,
620          * export the stored flags to allow an optional external merge of the
621          * records. Merging the records isn't always neccessarily correct, like
622          * when we hit a race during printing. In most cases though, it produces
623          * better readable output. 'c' in the record flags mark the first
624          * fragment of a line, '+' the following.
625          */
626         if (msg->flags & LOG_CONT && !(user->prev & LOG_CONT))
627                 cont = 'c';
628         else if ((msg->flags & LOG_CONT) ||
629                  ((user->prev & LOG_CONT) && !(msg->flags & LOG_PREFIX)))
630                 cont = '+';
631 
632         len = sprintf(user->buf, "%u,%llu,%llu,%c;",
633                       (msg->facility << 3) | msg->level,
634                       user->seq, ts_usec, cont);
635         user->prev = msg->flags;
636 
637         /* escape non-printable characters */
638         for (i = 0; i < msg->text_len; i++) {
639                 unsigned char c = log_text(msg)[i];
640 
641                 if (c < ' ' || c >= 127 || c == '\\')
642                         len += sprintf(user->buf + len, "\\x%02x", c);
643                 else
644                         user->buf[len++] = c;
645         }
646         user->buf[len++] = '\n';
647 
648         if (msg->dict_len) {
649                 bool line = true;
650 
651                 for (i = 0; i < msg->dict_len; i++) {
652                         unsigned char c = log_dict(msg)[i];
653 
654                         if (line) {
655                                 user->buf[len++] = ' ';
656                                 line = false;
657                         }
658 
659                         if (c == '\0') {
660                                 user->buf[len++] = '\n';
661                                 line = true;
662                                 continue;
663                         }
664 
665                         if (c < ' ' || c >= 127 || c == '\\') {
666                                 len += sprintf(user->buf + len, "\\x%02x", c);
667                                 continue;
668                         }
669 
670                         user->buf[len++] = c;
671                 }
672                 user->buf[len++] = '\n';
673         }
674 
675         user->idx = log_next(user->idx);
676         user->seq++;
677         raw_spin_unlock_irq(&logbuf_lock);
678 
679         if (len > count) {
680                 ret = -EINVAL;
681                 goto out;
682         }
683 
684         if (copy_to_user(buf, user->buf, len)) {
685                 ret = -EFAULT;
686                 goto out;
687         }
688         ret = len;
689 out:
690         mutex_unlock(&user->lock);
691         return ret;
692 }
693 
694 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
695 {
696         struct devkmsg_user *user = file->private_data;
697         loff_t ret = 0;
698 
699         if (!user)
700                 return -EBADF;
701         if (offset)
702                 return -ESPIPE;
703 
704         raw_spin_lock_irq(&logbuf_lock);
705         switch (whence) {
706         case SEEK_SET:
707                 /* the first record */
708                 user->idx = log_first_idx;
709                 user->seq = log_first_seq;
710                 break;
711         case SEEK_DATA:
712                 /*
713                  * The first record after the last SYSLOG_ACTION_CLEAR,
714                  * like issued by 'dmesg -c'. Reading /dev/kmsg itself
715                  * changes no global state, and does not clear anything.
716                  */
717                 user->idx = clear_idx;
718                 user->seq = clear_seq;
719                 break;
720         case SEEK_END:
721                 /* after the last record */
722                 user->idx = log_next_idx;
723                 user->seq = log_next_seq;
724                 break;
725         default:
726                 ret = -EINVAL;
727         }
728         raw_spin_unlock_irq(&logbuf_lock);
729         return ret;
730 }
731 
732 static unsigned int devkmsg_poll(struct file *file, poll_table *wait)
733 {
734         struct devkmsg_user *user = file->private_data;
735         int ret = 0;
736 
737         if (!user)
738                 return POLLERR|POLLNVAL;
739 
740         poll_wait(file, &log_wait, wait);
741 
742         raw_spin_lock_irq(&logbuf_lock);
743         if (user->seq < log_next_seq) {
744                 /* return error when data has vanished underneath us */
745                 if (user->seq < log_first_seq)
746                         ret = POLLIN|POLLRDNORM|POLLERR|POLLPRI;
747                 else
748                         ret = POLLIN|POLLRDNORM;
749         }
750         raw_spin_unlock_irq(&logbuf_lock);
751 
752         return ret;
753 }
754 
755 static int devkmsg_open(struct inode *inode, struct file *file)
756 {
757         struct devkmsg_user *user;
758         int err;
759 
760         /* write-only does not need any file context */
761         if ((file->f_flags & O_ACCMODE) == O_WRONLY)
762                 return 0;
763 
764         err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
765                                        SYSLOG_FROM_READER);
766         if (err)
767                 return err;
768 
769         user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
770         if (!user)
771                 return -ENOMEM;
772 
773         mutex_init(&user->lock);
774 
775         raw_spin_lock_irq(&logbuf_lock);
776         user->idx = log_first_idx;
777         user->seq = log_first_seq;
778         raw_spin_unlock_irq(&logbuf_lock);
779 
780         file->private_data = user;
781         return 0;
782 }
783 
784 static int devkmsg_release(struct inode *inode, struct file *file)
785 {
786         struct devkmsg_user *user = file->private_data;
787 
788         if (!user)
789                 return 0;
790 
791         mutex_destroy(&user->lock);
792         kfree(user);
793         return 0;
794 }
795 
796 const struct file_operations kmsg_fops = {
797         .open = devkmsg_open,
798         .read = devkmsg_read,
799         .write_iter = devkmsg_write,
800         .llseek = devkmsg_llseek,
801         .poll = devkmsg_poll,
802         .release = devkmsg_release,
803 };
804 
805 #ifdef CONFIG_KEXEC
806 /*
807  * This appends the listed symbols to /proc/vmcore
808  *
809  * /proc/vmcore is used by various utilities, like crash and makedumpfile to
810  * obtain access to symbols that are otherwise very difficult to locate.  These
811  * symbols are specifically used so that utilities can access and extract the
812  * dmesg log from a vmcore file after a crash.
813  */
814 void log_buf_kexec_setup(void)
815 {
816         VMCOREINFO_SYMBOL(log_buf);
817         VMCOREINFO_SYMBOL(log_buf_len);
818         VMCOREINFO_SYMBOL(log_first_idx);
819         VMCOREINFO_SYMBOL(log_next_idx);
820         /*
821          * Export struct printk_log size and field offsets. User space tools can
822          * parse it and detect any changes to structure down the line.
823          */
824         VMCOREINFO_STRUCT_SIZE(printk_log);
825         VMCOREINFO_OFFSET(printk_log, ts_nsec);
826         VMCOREINFO_OFFSET(printk_log, len);
827         VMCOREINFO_OFFSET(printk_log, text_len);
828         VMCOREINFO_OFFSET(printk_log, dict_len);
829 }
830 #endif
831 
832 /* requested log_buf_len from kernel cmdline */
833 static unsigned long __initdata new_log_buf_len;
834 
835 /* we practice scaling the ring buffer by powers of 2 */
836 static void __init log_buf_len_update(unsigned size)
837 {
838         if (size)
839                 size = roundup_pow_of_two(size);
840         if (size > log_buf_len)
841                 new_log_buf_len = size;
842 }
843 
844 /* save requested log_buf_len since it's too early to process it */
845 static int __init log_buf_len_setup(char *str)
846 {
847         unsigned int size;
848 
849         if (!str)
850                 return -EINVAL;
851 
852         size = memparse(str, &str);
853 
854         log_buf_len_update(size);
855 
856         return 0;
857 }
858 early_param("log_buf_len", log_buf_len_setup);
859 
860 #ifdef CONFIG_SMP
861 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
862 
863 static void __init log_buf_add_cpu(void)
864 {
865         unsigned int cpu_extra;
866 
867         /*
868          * archs should set up cpu_possible_bits properly with
869          * set_cpu_possible() after setup_arch() but just in
870          * case lets ensure this is valid.
871          */
872         if (num_possible_cpus() == 1)
873                 return;
874 
875         cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
876 
877         /* by default this will only continue through for large > 64 CPUs */
878         if (cpu_extra <= __LOG_BUF_LEN / 2)
879                 return;
880 
881         pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
882                 __LOG_CPU_MAX_BUF_LEN);
883         pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
884                 cpu_extra);
885         pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
886 
887         log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
888 }
889 #else /* !CONFIG_SMP */
890 static inline void log_buf_add_cpu(void) {}
891 #endif /* CONFIG_SMP */
892 
893 void __init setup_log_buf(int early)
894 {
895         unsigned long flags;
896         char *new_log_buf;
897         int free;
898 
899         if (log_buf != __log_buf)
900                 return;
901 
902         if (!early && !new_log_buf_len)
903                 log_buf_add_cpu();
904 
905         if (!new_log_buf_len)
906                 return;
907 
908         if (early) {
909                 new_log_buf =
910                         memblock_virt_alloc(new_log_buf_len, LOG_ALIGN);
911         } else {
912                 new_log_buf = memblock_virt_alloc_nopanic(new_log_buf_len,
913                                                           LOG_ALIGN);
914         }
915 
916         if (unlikely(!new_log_buf)) {
917                 pr_err("log_buf_len: %ld bytes not available\n",
918                         new_log_buf_len);
919                 return;
920         }
921 
922         raw_spin_lock_irqsave(&logbuf_lock, flags);
923         log_buf_len = new_log_buf_len;
924         log_buf = new_log_buf;
925         new_log_buf_len = 0;
926         free = __LOG_BUF_LEN - log_next_idx;
927         memcpy(log_buf, __log_buf, __LOG_BUF_LEN);
928         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
929 
930         pr_info("log_buf_len: %d bytes\n", log_buf_len);
931         pr_info("early log buf free: %d(%d%%)\n",
932                 free, (free * 100) / __LOG_BUF_LEN);
933 }
934 
935 static bool __read_mostly ignore_loglevel;
936 
937 static int __init ignore_loglevel_setup(char *str)
938 {
939         ignore_loglevel = true;
940         pr_info("debug: ignoring loglevel setting.\n");
941 
942         return 0;
943 }
944 
945 early_param("ignore_loglevel", ignore_loglevel_setup);
946 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
947 MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
948         "print all kernel messages to the console.");
949 
950 #ifdef CONFIG_BOOT_PRINTK_DELAY
951 
952 static int boot_delay; /* msecs delay after each printk during bootup */
953 static unsigned long long loops_per_msec;       /* based on boot_delay */
954 
955 static int __init boot_delay_setup(char *str)
956 {
957         unsigned long lpj;
958 
959         lpj = preset_lpj ? preset_lpj : 1000000;        /* some guess */
960         loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
961 
962         get_option(&str, &boot_delay);
963         if (boot_delay > 10 * 1000)
964                 boot_delay = 0;
965 
966         pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
967                 "HZ: %d, loops_per_msec: %llu\n",
968                 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
969         return 0;
970 }
971 early_param("boot_delay", boot_delay_setup);
972 
973 static void boot_delay_msec(int level)
974 {
975         unsigned long long k;
976         unsigned long timeout;
977 
978         if ((boot_delay == 0 || system_state != SYSTEM_BOOTING)
979                 || (level >= console_loglevel && !ignore_loglevel)) {
980                 return;
981         }
982 
983         k = (unsigned long long)loops_per_msec * boot_delay;
984 
985         timeout = jiffies + msecs_to_jiffies(boot_delay);
986         while (k) {
987                 k--;
988                 cpu_relax();
989                 /*
990                  * use (volatile) jiffies to prevent
991                  * compiler reduction; loop termination via jiffies
992                  * is secondary and may or may not happen.
993                  */
994                 if (time_after(jiffies, timeout))
995                         break;
996                 touch_nmi_watchdog();
997         }
998 }
999 #else
1000 static inline void boot_delay_msec(int level)
1001 {
1002 }
1003 #endif
1004 
1005 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1006 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1007 
1008 static size_t print_time(u64 ts, char *buf)
1009 {
1010         unsigned long rem_nsec;
1011 
1012         if (!printk_time)
1013                 return 0;
1014 
1015         rem_nsec = do_div(ts, 1000000000);
1016 
1017         if (!buf)
1018                 return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
1019 
1020         return sprintf(buf, "[%5lu.%06lu] ",
1021                        (unsigned long)ts, rem_nsec / 1000);
1022 }
1023 
1024 static size_t print_prefix(const struct printk_log *msg, bool syslog, char *buf)
1025 {
1026         size_t len = 0;
1027         unsigned int prefix = (msg->facility << 3) | msg->level;
1028 
1029         if (syslog) {
1030                 if (buf) {
1031                         len += sprintf(buf, "<%u>", prefix);
1032                 } else {
1033                         len += 3;
1034                         if (prefix > 999)
1035                                 len += 3;
1036                         else if (prefix > 99)
1037                                 len += 2;
1038                         else if (prefix > 9)
1039                                 len++;
1040                 }
1041         }
1042 
1043         len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
1044         return len;
1045 }
1046 
1047 static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
1048                              bool syslog, char *buf, size_t size)
1049 {
1050         const char *text = log_text(msg);
1051         size_t text_size = msg->text_len;
1052         bool prefix = true;
1053         bool newline = true;
1054         size_t len = 0;
1055 
1056         if ((prev & LOG_CONT) && !(msg->flags & LOG_PREFIX))
1057                 prefix = false;
1058 
1059         if (msg->flags & LOG_CONT) {
1060                 if ((prev & LOG_CONT) && !(prev & LOG_NEWLINE))
1061                         prefix = false;
1062 
1063                 if (!(msg->flags & LOG_NEWLINE))
1064                         newline = false;
1065         }
1066 
1067         do {
1068                 const char *next = memchr(text, '\n', text_size);
1069                 size_t text_len;
1070 
1071                 if (next) {
1072                         text_len = next - text;
1073                         next++;
1074                         text_size -= next - text;
1075                 } else {
1076                         text_len = text_size;
1077                 }
1078 
1079                 if (buf) {
1080                         if (print_prefix(msg, syslog, NULL) +
1081                             text_len + 1 >= size - len)
1082                                 break;
1083 
1084                         if (prefix)
1085                                 len += print_prefix(msg, syslog, buf + len);
1086                         memcpy(buf + len, text, text_len);
1087                         len += text_len;
1088                         if (next || newline)
1089                                 buf[len++] = '\n';
1090                 } else {
1091                         /* SYSLOG_ACTION_* buffer size only calculation */
1092                         if (prefix)
1093                                 len += print_prefix(msg, syslog, NULL);
1094                         len += text_len;
1095                         if (next || newline)
1096                                 len++;
1097                 }
1098 
1099                 prefix = true;
1100                 text = next;
1101         } while (text);
1102 
1103         return len;
1104 }
1105 
1106 static int syslog_print(char __user *buf, int size)
1107 {
1108         char *text;
1109         struct printk_log *msg;
1110         int len = 0;
1111 
1112         text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1113         if (!text)
1114                 return -ENOMEM;
1115 
1116         while (size > 0) {
1117                 size_t n;
1118                 size_t skip;
1119 
1120                 raw_spin_lock_irq(&logbuf_lock);
1121                 if (syslog_seq < log_first_seq) {
1122                         /* messages are gone, move to first one */
1123                         syslog_seq = log_first_seq;
1124                         syslog_idx = log_first_idx;
1125                         syslog_prev = 0;
1126                         syslog_partial = 0;
1127                 }
1128                 if (syslog_seq == log_next_seq) {
1129                         raw_spin_unlock_irq(&logbuf_lock);
1130                         break;
1131                 }
1132 
1133                 skip = syslog_partial;
1134                 msg = log_from_idx(syslog_idx);
1135                 n = msg_print_text(msg, syslog_prev, true, text,
1136                                    LOG_LINE_MAX + PREFIX_MAX);
1137                 if (n - syslog_partial <= size) {
1138                         /* message fits into buffer, move forward */
1139                         syslog_idx = log_next(syslog_idx);
1140                         syslog_seq++;
1141                         syslog_prev = msg->flags;
1142                         n -= syslog_partial;
1143                         syslog_partial = 0;
1144                 } else if (!len){
1145                         /* partial read(), remember position */
1146                         n = size;
1147                         syslog_partial += n;
1148                 } else
1149                         n = 0;
1150                 raw_spin_unlock_irq(&logbuf_lock);
1151 
1152                 if (!n)
1153                         break;
1154 
1155                 if (copy_to_user(buf, text + skip, n)) {
1156                         if (!len)
1157                                 len = -EFAULT;
1158                         break;
1159                 }
1160 
1161                 len += n;
1162                 size -= n;
1163                 buf += n;
1164         }
1165 
1166         kfree(text);
1167         return len;
1168 }
1169 
1170 static int syslog_print_all(char __user *buf, int size, bool clear)
1171 {
1172         char *text;
1173         int len = 0;
1174 
1175         text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1176         if (!text)
1177                 return -ENOMEM;
1178 
1179         raw_spin_lock_irq(&logbuf_lock);
1180         if (buf) {
1181                 u64 next_seq;
1182                 u64 seq;
1183                 u32 idx;
1184                 enum log_flags prev;
1185 
1186                 if (clear_seq < log_first_seq) {
1187                         /* messages are gone, move to first available one */
1188                         clear_seq = log_first_seq;
1189                         clear_idx = log_first_idx;
1190                 }
1191 
1192                 /*
1193                  * Find first record that fits, including all following records,
1194                  * into the user-provided buffer for this dump.
1195                  */
1196                 seq = clear_seq;
1197                 idx = clear_idx;
1198                 prev = 0;
1199                 while (seq < log_next_seq) {
1200                         struct printk_log *msg = log_from_idx(idx);
1201 
1202                         len += msg_print_text(msg, prev, true, NULL, 0);
1203                         prev = msg->flags;
1204                         idx = log_next(idx);
1205                         seq++;
1206                 }
1207 
1208                 /* move first record forward until length fits into the buffer */
1209                 seq = clear_seq;
1210                 idx = clear_idx;
1211                 prev = 0;
1212                 while (len > size && seq < log_next_seq) {
1213                         struct printk_log *msg = log_from_idx(idx);
1214 
1215                         len -= msg_print_text(msg, prev, true, NULL, 0);
1216                         prev = msg->flags;
1217                         idx = log_next(idx);
1218                         seq++;
1219                 }
1220 
1221                 /* last message fitting into this dump */
1222                 next_seq = log_next_seq;
1223 
1224                 len = 0;
1225                 while (len >= 0 && seq < next_seq) {
1226                         struct printk_log *msg = log_from_idx(idx);
1227                         int textlen;
1228 
1229                         textlen = msg_print_text(msg, prev, true, text,
1230                                                  LOG_LINE_MAX + PREFIX_MAX);
1231                         if (textlen < 0) {
1232                                 len = textlen;
1233                                 break;
1234                         }
1235                         idx = log_next(idx);
1236                         seq++;
1237                         prev = msg->flags;
1238 
1239                         raw_spin_unlock_irq(&logbuf_lock);
1240                         if (copy_to_user(buf + len, text, textlen))
1241                                 len = -EFAULT;
1242                         else
1243                                 len += textlen;
1244                         raw_spin_lock_irq(&logbuf_lock);
1245 
1246                         if (seq < log_first_seq) {
1247                                 /* messages are gone, move to next one */
1248                                 seq = log_first_seq;
1249                                 idx = log_first_idx;
1250                                 prev = 0;
1251                         }
1252                 }
1253         }
1254 
1255         if (clear) {
1256                 clear_seq = log_next_seq;
1257                 clear_idx = log_next_idx;
1258         }
1259         raw_spin_unlock_irq(&logbuf_lock);
1260 
1261         kfree(text);
1262         return len;
1263 }
1264 
1265 int do_syslog(int type, char __user *buf, int len, bool from_file)
1266 {
1267         bool clear = false;
1268         static int saved_console_loglevel = -1;
1269         int error;
1270 
1271         error = check_syslog_permissions(type, from_file);
1272         if (error)
1273                 goto out;
1274 
1275         switch (type) {
1276         case SYSLOG_ACTION_CLOSE:       /* Close log */
1277                 break;
1278         case SYSLOG_ACTION_OPEN:        /* Open log */
1279                 break;
1280         case SYSLOG_ACTION_READ:        /* Read from log */
1281                 error = -EINVAL;
1282                 if (!buf || len < 0)
1283                         goto out;
1284                 error = 0;
1285                 if (!len)
1286                         goto out;
1287                 if (!access_ok(VERIFY_WRITE, buf, len)) {
1288                         error = -EFAULT;
1289                         goto out;
1290                 }
1291                 error = wait_event_interruptible(log_wait,
1292                                                  syslog_seq != log_next_seq);
1293                 if (error)
1294                         goto out;
1295                 error = syslog_print(buf, len);
1296                 break;
1297         /* Read/clear last kernel messages */
1298         case SYSLOG_ACTION_READ_CLEAR:
1299                 clear = true;
1300                 /* FALL THRU */
1301         /* Read last kernel messages */
1302         case SYSLOG_ACTION_READ_ALL:
1303                 error = -EINVAL;
1304                 if (!buf || len < 0)
1305                         goto out;
1306                 error = 0;
1307                 if (!len)
1308                         goto out;
1309                 if (!access_ok(VERIFY_WRITE, buf, len)) {
1310                         error = -EFAULT;
1311                         goto out;
1312                 }
1313                 error = syslog_print_all(buf, len, clear);
1314                 break;
1315         /* Clear ring buffer */
1316         case SYSLOG_ACTION_CLEAR:
1317                 syslog_print_all(NULL, 0, true);
1318                 break;
1319         /* Disable logging to console */
1320         case SYSLOG_ACTION_CONSOLE_OFF:
1321                 if (saved_console_loglevel == -1)
1322                         saved_console_loglevel = console_loglevel;
1323                 console_loglevel = minimum_console_loglevel;
1324                 break;
1325         /* Enable logging to console */
1326         case SYSLOG_ACTION_CONSOLE_ON:
1327                 if (saved_console_loglevel != -1) {
1328                         console_loglevel = saved_console_loglevel;
1329                         saved_console_loglevel = -1;
1330                 }
1331                 break;
1332         /* Set level of messages printed to console */
1333         case SYSLOG_ACTION_CONSOLE_LEVEL:
1334                 error = -EINVAL;
1335                 if (len < 1 || len > 8)
1336                         goto out;
1337                 if (len < minimum_console_loglevel)
1338                         len = minimum_console_loglevel;
1339                 console_loglevel = len;
1340                 /* Implicitly re-enable logging to console */
1341                 saved_console_loglevel = -1;
1342                 error = 0;
1343                 break;
1344         /* Number of chars in the log buffer */
1345         case SYSLOG_ACTION_SIZE_UNREAD:
1346                 raw_spin_lock_irq(&logbuf_lock);
1347                 if (syslog_seq < log_first_seq) {
1348                         /* messages are gone, move to first one */
1349                         syslog_seq = log_first_seq;
1350                         syslog_idx = log_first_idx;
1351                         syslog_prev = 0;
1352                         syslog_partial = 0;
1353                 }
1354                 if (from_file) {
1355                         /*
1356                          * Short-cut for poll(/"proc/kmsg") which simply checks
1357                          * for pending data, not the size; return the count of
1358                          * records, not the length.
1359                          */
1360                         error = log_next_seq - syslog_seq;
1361                 } else {
1362                         u64 seq = syslog_seq;
1363                         u32 idx = syslog_idx;
1364                         enum log_flags prev = syslog_prev;
1365 
1366                         error = 0;
1367                         while (seq < log_next_seq) {
1368                                 struct printk_log *msg = log_from_idx(idx);
1369 
1370                                 error += msg_print_text(msg, prev, true, NULL, 0);
1371                                 idx = log_next(idx);
1372                                 seq++;
1373                                 prev = msg->flags;
1374                         }
1375                         error -= syslog_partial;
1376                 }
1377                 raw_spin_unlock_irq(&logbuf_lock);
1378                 break;
1379         /* Size of the log buffer */
1380         case SYSLOG_ACTION_SIZE_BUFFER:
1381                 error = log_buf_len;
1382                 break;
1383         default:
1384                 error = -EINVAL;
1385                 break;
1386         }
1387 out:
1388         return error;
1389 }
1390 
1391 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1392 {
1393         return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1394 }
1395 
1396 /*
1397  * Call the console drivers, asking them to write out
1398  * log_buf[start] to log_buf[end - 1].
1399  * The console_lock must be held.
1400  */
1401 static void call_console_drivers(int level, const char *text, size_t len)
1402 {
1403         struct console *con;
1404 
1405         trace_console(text, len);
1406 
1407         if (level >= console_loglevel && !ignore_loglevel)
1408                 return;
1409         if (!console_drivers)
1410                 return;
1411 
1412         for_each_console(con) {
1413                 if (exclusive_console && con != exclusive_console)
1414                         continue;
1415                 if (!(con->flags & CON_ENABLED))
1416                         continue;
1417                 if (!con->write)
1418                         continue;
1419                 if (!cpu_online(smp_processor_id()) &&
1420                     !(con->flags & CON_ANYTIME))
1421                         continue;
1422                 con->write(con, text, len);
1423         }
1424 }
1425 
1426 /*
1427  * Zap console related locks when oopsing. Only zap at most once
1428  * every 10 seconds, to leave time for slow consoles to print a
1429  * full oops.
1430  */
1431 static void zap_locks(void)
1432 {
1433         static unsigned long oops_timestamp;
1434 
1435         if (time_after_eq(jiffies, oops_timestamp) &&
1436                         !time_after(jiffies, oops_timestamp + 30 * HZ))
1437                 return;
1438 
1439         oops_timestamp = jiffies;
1440 
1441         debug_locks_off();
1442         /* If a crash is occurring, make sure we can't deadlock */
1443         raw_spin_lock_init(&logbuf_lock);
1444         /* And make sure that we print immediately */
1445         sema_init(&console_sem, 1);
1446 }
1447 
1448 /*
1449  * Check if we have any console that is capable of printing while cpu is
1450  * booting or shutting down. Requires console_sem.
1451  */
1452 static int have_callable_console(void)
1453 {
1454         struct console *con;
1455 
1456         for_each_console(con)
1457                 if (con->flags & CON_ANYTIME)
1458                         return 1;
1459 
1460         return 0;
1461 }
1462 
1463 /*
1464  * Can we actually use the console at this time on this cpu?
1465  *
1466  * Console drivers may assume that per-cpu resources have been allocated. So
1467  * unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
1468  * call them until this CPU is officially up.
1469  */
1470 static inline int can_use_console(unsigned int cpu)
1471 {
1472         return cpu_online(cpu) || have_callable_console();
1473 }
1474 
1475 /*
1476  * Try to get console ownership to actually show the kernel
1477  * messages from a 'printk'. Return true (and with the
1478  * console_lock held, and 'console_locked' set) if it
1479  * is successful, false otherwise.
1480  */
1481 static int console_trylock_for_printk(void)
1482 {
1483         unsigned int cpu = smp_processor_id();
1484 
1485         if (!console_trylock())
1486                 return 0;
1487         /*
1488          * If we can't use the console, we need to release the console
1489          * semaphore by hand to avoid flushing the buffer. We need to hold the
1490          * console semaphore in order to do this test safely.
1491          */
1492         if (!can_use_console(cpu)) {
1493                 console_locked = 0;
1494                 up_console_sem();
1495                 return 0;
1496         }
1497         return 1;
1498 }
1499 
1500 int printk_delay_msec __read_mostly;
1501 
1502 static inline void printk_delay(void)
1503 {
1504         if (unlikely(printk_delay_msec)) {
1505                 int m = printk_delay_msec;
1506 
1507                 while (m--) {
1508                         mdelay(1);
1509                         touch_nmi_watchdog();
1510                 }
1511         }
1512 }
1513 
1514 /*
1515  * Continuation lines are buffered, and not committed to the record buffer
1516  * until the line is complete, or a race forces it. The line fragments
1517  * though, are printed immediately to the consoles to ensure everything has
1518  * reached the console in case of a kernel crash.
1519  */
1520 static struct cont {
1521         char buf[LOG_LINE_MAX];
1522         size_t len;                     /* length == 0 means unused buffer */
1523         size_t cons;                    /* bytes written to console */
1524         struct task_struct *owner;      /* task of first print*/
1525         u64 ts_nsec;                    /* time of first print */
1526         u8 level;                       /* log level of first message */
1527         u8 facility;                    /* log facility of first message */
1528         enum log_flags flags;           /* prefix, newline flags */
1529         bool flushed:1;                 /* buffer sealed and committed */
1530 } cont;
1531 
1532 static void cont_flush(enum log_flags flags)
1533 {
1534         if (cont.flushed)
1535                 return;
1536         if (cont.len == 0)
1537                 return;
1538 
1539         if (cont.cons) {
1540                 /*
1541                  * If a fragment of this line was directly flushed to the
1542                  * console; wait for the console to pick up the rest of the
1543                  * line. LOG_NOCONS suppresses a duplicated output.
1544                  */
1545                 log_store(cont.facility, cont.level, flags | LOG_NOCONS,
1546                           cont.ts_nsec, NULL, 0, cont.buf, cont.len);
1547                 cont.flags = flags;
1548                 cont.flushed = true;
1549         } else {
1550                 /*
1551                  * If no fragment of this line ever reached the console,
1552                  * just submit it to the store and free the buffer.
1553                  */
1554                 log_store(cont.facility, cont.level, flags, 0,
1555                           NULL, 0, cont.buf, cont.len);
1556                 cont.len = 0;
1557         }
1558 }
1559 
1560 static bool cont_add(int facility, int level, const char *text, size_t len)
1561 {
1562         if (cont.len && cont.flushed)
1563                 return false;
1564 
1565         if (cont.len + len > sizeof(cont.buf)) {
1566                 /* the line gets too long, split it up in separate records */
1567                 cont_flush(LOG_CONT);
1568                 return false;
1569         }
1570 
1571         if (!cont.len) {
1572                 cont.facility = facility;
1573                 cont.level = level;
1574                 cont.owner = current;
1575                 cont.ts_nsec = local_clock();
1576                 cont.flags = 0;
1577                 cont.cons = 0;
1578                 cont.flushed = false;
1579         }
1580 
1581         memcpy(cont.buf + cont.len, text, len);
1582         cont.len += len;
1583 
1584         if (cont.len > (sizeof(cont.buf) * 80) / 100)
1585                 cont_flush(LOG_CONT);
1586 
1587         return true;
1588 }
1589 
1590 static size_t cont_print_text(char *text, size_t size)
1591 {
1592         size_t textlen = 0;
1593         size_t len;
1594 
1595         if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
1596                 textlen += print_time(cont.ts_nsec, text);
1597                 size -= textlen;
1598         }
1599 
1600         len = cont.len - cont.cons;
1601         if (len > 0) {
1602                 if (len+1 > size)
1603                         len = size-1;
1604                 memcpy(text + textlen, cont.buf + cont.cons, len);
1605                 textlen += len;
1606                 cont.cons = cont.len;
1607         }
1608 
1609         if (cont.flushed) {
1610                 if (cont.flags & LOG_NEWLINE)
1611                         text[textlen++] = '\n';
1612                 /* got everything, release buffer */
1613                 cont.len = 0;
1614         }
1615         return textlen;
1616 }
1617 
1618 asmlinkage int vprintk_emit(int facility, int level,
1619                             const char *dict, size_t dictlen,
1620                             const char *fmt, va_list args)
1621 {
1622         static int recursion_bug;
1623         static char textbuf[LOG_LINE_MAX];
1624         char *text = textbuf;
1625         size_t text_len = 0;
1626         enum log_flags lflags = 0;
1627         unsigned long flags;
1628         int this_cpu;
1629         int printed_len = 0;
1630         bool in_sched = false;
1631         /* cpu currently holding logbuf_lock in this function */
1632         static volatile unsigned int logbuf_cpu = UINT_MAX;
1633 
1634         if (level == SCHED_MESSAGE_LOGLEVEL) {
1635                 level = -1;
1636                 in_sched = true;
1637         }
1638 
1639         boot_delay_msec(level);
1640         printk_delay();
1641 
1642         /* This stops the holder of console_sem just where we want him */
1643         local_irq_save(flags);
1644         this_cpu = smp_processor_id();
1645 
1646         /*
1647          * Ouch, printk recursed into itself!
1648          */
1649         if (unlikely(logbuf_cpu == this_cpu)) {
1650                 /*
1651                  * If a crash is occurring during printk() on this CPU,
1652                  * then try to get the crash message out but make sure
1653                  * we can't deadlock. Otherwise just return to avoid the
1654                  * recursion and return - but flag the recursion so that
1655                  * it can be printed at the next appropriate moment:
1656                  */
1657                 if (!oops_in_progress && !lockdep_recursing(current)) {
1658                         recursion_bug = 1;
1659                         local_irq_restore(flags);
1660                         return 0;
1661                 }
1662                 zap_locks();
1663         }
1664 
1665         lockdep_off();
1666         raw_spin_lock(&logbuf_lock);
1667         logbuf_cpu = this_cpu;
1668 
1669         if (unlikely(recursion_bug)) {
1670                 static const char recursion_msg[] =
1671                         "BUG: recent printk recursion!";
1672 
1673                 recursion_bug = 0;
1674                 /* emit KERN_CRIT message */
1675                 printed_len += log_store(0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
1676                                          NULL, 0, recursion_msg,
1677                                          strlen(recursion_msg));
1678         }
1679 
1680         /*
1681          * The printf needs to come first; we need the syslog
1682          * prefix which might be passed-in as a parameter.
1683          */
1684         text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
1685 
1686         /* mark and strip a trailing newline */
1687         if (text_len && text[text_len-1] == '\n') {
1688                 text_len--;
1689                 lflags |= LOG_NEWLINE;
1690         }
1691 
1692         /* strip kernel syslog prefix and extract log level or control flags */
1693         if (facility == 0) {
1694                 int kern_level = printk_get_level(text);
1695 
1696                 if (kern_level) {
1697                         const char *end_of_header = printk_skip_level(text);
1698                         switch (kern_level) {
1699                         case '' ... '7':
1700                                 if (level == -1)
1701                                         level = kern_level - '';
1702                         case 'd':       /* KERN_DEFAULT */
1703                                 lflags |= LOG_PREFIX;
1704                         }
1705                         /*
1706                          * No need to check length here because vscnprintf
1707                          * put '\0' at the end of the string. Only valid and
1708                          * newly printed level is detected.
1709                          */
1710                         text_len -= end_of_header - text;
1711                         text = (char *)end_of_header;
1712                 }
1713         }
1714 
1715         if (level == -1)
1716                 level = default_message_loglevel;
1717 
1718         if (dict)
1719                 lflags |= LOG_PREFIX|LOG_NEWLINE;
1720 
1721         if (!(lflags & LOG_NEWLINE)) {
1722                 /*
1723                  * Flush the conflicting buffer. An earlier newline was missing,
1724                  * or another task also prints continuation lines.
1725                  */
1726                 if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
1727                         cont_flush(LOG_NEWLINE);
1728 
1729                 /* buffer line if possible, otherwise store it right away */
1730                 if (cont_add(facility, level, text, text_len))
1731                         printed_len += text_len;
1732                 else
1733                         printed_len += log_store(facility, level,
1734                                                  lflags | LOG_CONT, 0,
1735                                                  dict, dictlen, text, text_len);
1736         } else {
1737                 bool stored = false;
1738 
1739                 /*
1740                  * If an earlier newline was missing and it was the same task,
1741                  * either merge it with the current buffer and flush, or if
1742                  * there was a race with interrupts (prefix == true) then just
1743                  * flush it out and store this line separately.
1744                  * If the preceding printk was from a different task and missed
1745                  * a newline, flush and append the newline.
1746                  */
1747                 if (cont.len) {
1748                         if (cont.owner == current && !(lflags & LOG_PREFIX))
1749                                 stored = cont_add(facility, level, text,
1750                                                   text_len);
1751                         cont_flush(LOG_NEWLINE);
1752                 }
1753 
1754                 if (stored)
1755                         printed_len += text_len;
1756                 else
1757                         printed_len += log_store(facility, level, lflags, 0,
1758                                                  dict, dictlen, text, text_len);
1759         }
1760 
1761         logbuf_cpu = UINT_MAX;
1762         raw_spin_unlock(&logbuf_lock);
1763         lockdep_on();
1764         local_irq_restore(flags);
1765 
1766         /* If called from the scheduler, we can not call up(). */
1767         if (!in_sched) {
1768                 lockdep_off();
1769                 /*
1770                  * Disable preemption to avoid being preempted while holding
1771                  * console_sem which would prevent anyone from printing to
1772                  * console
1773                  */
1774                 preempt_disable();
1775 
1776                 /*
1777                  * Try to acquire and then immediately release the console
1778                  * semaphore.  The release will print out buffers and wake up
1779                  * /dev/kmsg and syslog() users.
1780                  */
1781                 if (console_trylock_for_printk())
1782                         console_unlock();
1783                 preempt_enable();
1784                 lockdep_on();
1785         }
1786 
1787         return printed_len;
1788 }
1789 EXPORT_SYMBOL(vprintk_emit);
1790 
1791 asmlinkage int vprintk(const char *fmt, va_list args)
1792 {
1793         return vprintk_emit(0, -1, NULL, 0, fmt, args);
1794 }
1795 EXPORT_SYMBOL(vprintk);
1796 
1797 asmlinkage int printk_emit(int facility, int level,
1798                            const char *dict, size_t dictlen,
1799                            const char *fmt, ...)
1800 {
1801         va_list args;
1802         int r;
1803 
1804         va_start(args, fmt);
1805         r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
1806         va_end(args);
1807 
1808         return r;
1809 }
1810 EXPORT_SYMBOL(printk_emit);
1811 
1812 /**
1813  * printk - print a kernel message
1814  * @fmt: format string
1815  *
1816  * This is printk(). It can be called from any context. We want it to work.
1817  *
1818  * We try to grab the console_lock. If we succeed, it's easy - we log the
1819  * output and call the console drivers.  If we fail to get the semaphore, we
1820  * place the output into the log buffer and return. The current holder of
1821  * the console_sem will notice the new output in console_unlock(); and will
1822  * send it to the consoles before releasing the lock.
1823  *
1824  * One effect of this deferred printing is that code which calls printk() and
1825  * then changes console_loglevel may break. This is because console_loglevel
1826  * is inspected when the actual printing occurs.
1827  *
1828  * See also:
1829  * printf(3)
1830  *
1831  * See the vsnprintf() documentation for format string extensions over C99.
1832  */
1833 asmlinkage __visible int printk(const char *fmt, ...)
1834 {
1835         va_list args;
1836         int r;
1837 
1838 #ifdef CONFIG_KGDB_KDB
1839         if (unlikely(kdb_trap_printk)) {
1840                 va_start(args, fmt);
1841                 r = vkdb_printf(fmt, args);
1842                 va_end(args);
1843                 return r;
1844         }
1845 #endif
1846         va_start(args, fmt);
1847         r = vprintk_emit(0, -1, NULL, 0, fmt, args);
1848         va_end(args);
1849 
1850         return r;
1851 }
1852 EXPORT_SYMBOL(printk);
1853 
1854 #else /* CONFIG_PRINTK */
1855 
1856 #define LOG_LINE_MAX            0
1857 #define PREFIX_MAX              0
1858 
1859 static u64 syslog_seq;
1860 static u32 syslog_idx;
1861 static u64 console_seq;
1862 static u32 console_idx;
1863 static enum log_flags syslog_prev;
1864 static u64 log_first_seq;
1865 static u32 log_first_idx;
1866 static u64 log_next_seq;
1867 static enum log_flags console_prev;
1868 static struct cont {
1869         size_t len;
1870         size_t cons;
1871         u8 level;
1872         bool flushed:1;
1873 } cont;
1874 static struct printk_log *log_from_idx(u32 idx) { return NULL; }
1875 static u32 log_next(u32 idx) { return 0; }
1876 static void call_console_drivers(int level, const char *text, size_t len) {}
1877 static size_t msg_print_text(const struct printk_log *msg, enum log_flags prev,
1878                              bool syslog, char *buf, size_t size) { return 0; }
1879 static size_t cont_print_text(char *text, size_t size) { return 0; }
1880 
1881 #endif /* CONFIG_PRINTK */
1882 
1883 #ifdef CONFIG_EARLY_PRINTK
1884 struct console *early_console;
1885 
1886 void early_vprintk(const char *fmt, va_list ap)
1887 {
1888         if (early_console) {
1889                 char buf[512];
1890                 int n = vscnprintf(buf, sizeof(buf), fmt, ap);
1891 
1892                 early_console->write(early_console, buf, n);
1893         }
1894 }
1895 
1896 asmlinkage __visible void early_printk(const char *fmt, ...)
1897 {
1898         va_list ap;
1899 
1900         va_start(ap, fmt);
1901         early_vprintk(fmt, ap);
1902         va_end(ap);
1903 }
1904 #endif
1905 
1906 static int __add_preferred_console(char *name, int idx, char *options,
1907                                    char *brl_options)
1908 {
1909         struct console_cmdline *c;
1910         int i;
1911 
1912         /*
1913          *      See if this tty is not yet registered, and
1914          *      if we have a slot free.
1915          */
1916         for (i = 0, c = console_cmdline;
1917              i < MAX_CMDLINECONSOLES && c->name[0];
1918              i++, c++) {
1919                 if (strcmp(c->name, name) == 0 && c->index == idx) {
1920                         if (!brl_options)
1921                                 selected_console = i;
1922                         return 0;
1923                 }
1924         }
1925         if (i == MAX_CMDLINECONSOLES)
1926                 return -E2BIG;
1927         if (!brl_options)
1928                 selected_console = i;
1929         strlcpy(c->name, name, sizeof(c->name));
1930         c->options = options;
1931         braille_set_options(c, brl_options);
1932 
1933         c->index = idx;
1934         return 0;
1935 }
1936 /*
1937  * Set up a console.  Called via do_early_param() in init/main.c
1938  * for each "console=" parameter in the boot command line.
1939  */
1940 static int __init console_setup(char *str)
1941 {
1942         char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
1943         char *s, *options, *brl_options = NULL;
1944         int idx;
1945 
1946         if (_braille_console_setup(&str, &brl_options))
1947                 return 1;
1948 
1949         /*
1950          * Decode str into name, index, options.
1951          */
1952         if (str[0] >= '' && str[0] <= '9') {
1953                 strcpy(buf, "ttyS");
1954                 strncpy(buf + 4, str, sizeof(buf) - 5);
1955         } else {
1956                 strncpy(buf, str, sizeof(buf) - 1);
1957         }
1958         buf[sizeof(buf) - 1] = 0;
1959         options = strchr(str, ',');
1960         if (options)
1961                 *(options++) = 0;
1962 #ifdef __sparc__
1963         if (!strcmp(str, "ttya"))
1964                 strcpy(buf, "ttyS0");
1965         if (!strcmp(str, "ttyb"))
1966                 strcpy(buf, "ttyS1");
1967 #endif
1968         for (s = buf; *s; s++)
1969                 if (isdigit(*s) || *s == ',')
1970                         break;
1971         idx = simple_strtoul(s, NULL, 10);
1972         *s = 0;
1973 
1974         __add_preferred_console(buf, idx, options, brl_options);
1975         console_set_on_cmdline = 1;
1976         return 1;
1977 }
1978 __setup("console=", console_setup);
1979 
1980 /**
1981  * add_preferred_console - add a device to the list of preferred consoles.
1982  * @name: device name
1983  * @idx: device index
1984  * @options: options for this console
1985  *
1986  * The last preferred console added will be used for kernel messages
1987  * and stdin/out/err for init.  Normally this is used by console_setup
1988  * above to handle user-supplied console arguments; however it can also
1989  * be used by arch-specific code either to override the user or more
1990  * commonly to provide a default console (ie from PROM variables) when
1991  * the user has not supplied one.
1992  */
1993 int add_preferred_console(char *name, int idx, char *options)
1994 {
1995         return __add_preferred_console(name, idx, options, NULL);
1996 }
1997 
1998 int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
1999 {
2000         struct console_cmdline *c;
2001         int i;
2002 
2003         for (i = 0, c = console_cmdline;
2004              i < MAX_CMDLINECONSOLES && c->name[0];
2005              i++, c++)
2006                 if (strcmp(c->name, name) == 0 && c->index == idx) {
2007                         strlcpy(c->name, name_new, sizeof(c->name));
2008                         c->options = options;
2009                         c->index = idx_new;
2010                         return i;
2011                 }
2012         /* not found */
2013         return -1;
2014 }
2015 
2016 bool console_suspend_enabled = true;
2017 EXPORT_SYMBOL(console_suspend_enabled);
2018 
2019 static int __init console_suspend_disable(char *str)
2020 {
2021         console_suspend_enabled = false;
2022         return 1;
2023 }
2024 __setup("no_console_suspend", console_suspend_disable);
2025 module_param_named(console_suspend, console_suspend_enabled,
2026                 bool, S_IRUGO | S_IWUSR);
2027 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2028         " and hibernate operations");
2029 
2030 /**
2031  * suspend_console - suspend the console subsystem
2032  *
2033  * This disables printk() while we go into suspend states
2034  */
2035 void suspend_console(void)
2036 {
2037         if (!console_suspend_enabled)
2038                 return;
2039         printk("Suspending console(s) (use no_console_suspend to debug)\n");
2040         console_lock();
2041         console_suspended = 1;
2042         up_console_sem();
2043 }
2044 
2045 void resume_console(void)
2046 {
2047         if (!console_suspend_enabled)
2048                 return;
2049         down_console_sem();
2050         console_suspended = 0;
2051         console_unlock();
2052 }
2053 
2054 /**
2055  * console_cpu_notify - print deferred console messages after CPU hotplug
2056  * @self: notifier struct
2057  * @action: CPU hotplug event
2058  * @hcpu: unused
2059  *
2060  * If printk() is called from a CPU that is not online yet, the messages
2061  * will be spooled but will not show up on the console.  This function is
2062  * called when a new CPU comes online (or fails to come up), and ensures
2063  * that any such output gets printed.
2064  */
2065 static int console_cpu_notify(struct notifier_block *self,
2066         unsigned long action, void *hcpu)
2067 {
2068         switch (action) {
2069         case CPU_ONLINE:
2070         case CPU_DEAD:
2071         case CPU_DOWN_FAILED:
2072         case CPU_UP_CANCELED:
2073                 console_lock();
2074                 console_unlock();
2075         }
2076         return NOTIFY_OK;
2077 }
2078 
2079 /**
2080  * console_lock - lock the console system for exclusive use.
2081  *
2082  * Acquires a lock which guarantees that the caller has
2083  * exclusive access to the console system and the console_drivers list.
2084  *
2085  * Can sleep, returns nothing.
2086  */
2087 void console_lock(void)
2088 {
2089         might_sleep();
2090 
2091         down_console_sem();
2092         if (console_suspended)
2093                 return;
2094         console_locked = 1;
2095         console_may_schedule = 1;
2096 }
2097 EXPORT_SYMBOL(console_lock);
2098 
2099 /**
2100  * console_trylock - try to lock the console system for exclusive use.
2101  *
2102  * Try to acquire a lock which guarantees that the caller has exclusive
2103  * access to the console system and the console_drivers list.
2104  *
2105  * returns 1 on success, and 0 on failure to acquire the lock.
2106  */
2107 int console_trylock(void)
2108 {
2109         if (down_trylock_console_sem())
2110                 return 0;
2111         if (console_suspended) {
2112                 up_console_sem();
2113                 return 0;
2114         }
2115         console_locked = 1;
2116         console_may_schedule = 0;
2117         return 1;
2118 }
2119 EXPORT_SYMBOL(console_trylock);
2120 
2121 int is_console_locked(void)
2122 {
2123         return console_locked;
2124 }
2125 
2126 static void console_cont_flush(char *text, size_t size)
2127 {
2128         unsigned long flags;
2129         size_t len;
2130 
2131         raw_spin_lock_irqsave(&logbuf_lock, flags);
2132 
2133         if (!cont.len)
2134                 goto out;
2135 
2136         /*
2137          * We still queue earlier records, likely because the console was
2138          * busy. The earlier ones need to be printed before this one, we
2139          * did not flush any fragment so far, so just let it queue up.
2140          */
2141         if (console_seq < log_next_seq && !cont.cons)
2142                 goto out;
2143 
2144         len = cont_print_text(text, size);
2145         raw_spin_unlock(&logbuf_lock);
2146         stop_critical_timings();
2147         call_console_drivers(cont.level, text, len);
2148         start_critical_timings();
2149         local_irq_restore(flags);
2150         return;
2151 out:
2152         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2153 }
2154 
2155 /**
2156  * console_unlock - unlock the console system
2157  *
2158  * Releases the console_lock which the caller holds on the console system
2159  * and the console driver list.
2160  *
2161  * While the console_lock was held, console output may have been buffered
2162  * by printk().  If this is the case, console_unlock(); emits
2163  * the output prior to releasing the lock.
2164  *
2165  * If there is output waiting, we wake /dev/kmsg and syslog() users.
2166  *
2167  * console_unlock(); may be called from any context.
2168  */
2169 void console_unlock(void)
2170 {
2171         static char text[LOG_LINE_MAX + PREFIX_MAX];
2172         static u64 seen_seq;
2173         unsigned long flags;
2174         bool wake_klogd = false;
2175         bool do_cond_resched, retry;
2176 
2177         if (console_suspended) {
2178                 up_console_sem();
2179                 return;
2180         }
2181 
2182         /*
2183          * Console drivers are called under logbuf_lock, so
2184          * @console_may_schedule should be cleared before; however, we may
2185          * end up dumping a lot of lines, for example, if called from
2186          * console registration path, and should invoke cond_resched()
2187          * between lines if allowable.  Not doing so can cause a very long
2188          * scheduling stall on a slow console leading to RCU stall and
2189          * softlockup warnings which exacerbate the issue with more
2190          * messages practically incapacitating the system.
2191          */
2192         do_cond_resched = console_may_schedule;
2193         console_may_schedule = 0;
2194 
2195         /* flush buffered message fragment immediately to console */
2196         console_cont_flush(text, sizeof(text));
2197 again:
2198         for (;;) {
2199                 struct printk_log *msg;
2200                 size_t len;
2201                 int level;
2202 
2203                 raw_spin_lock_irqsave(&logbuf_lock, flags);
2204                 if (seen_seq != log_next_seq) {
2205                         wake_klogd = true;
2206                         seen_seq = log_next_seq;
2207                 }
2208 
2209                 if (console_seq < log_first_seq) {
2210                         len = sprintf(text, "** %u printk messages dropped ** ",
2211                                       (unsigned)(log_first_seq - console_seq));
2212 
2213                         /* messages are gone, move to first one */
2214                         console_seq = log_first_seq;
2215                         console_idx = log_first_idx;
2216                         console_prev = 0;
2217                 } else {
2218                         len = 0;
2219                 }
2220 skip:
2221                 if (console_seq == log_next_seq)
2222                         break;
2223 
2224                 msg = log_from_idx(console_idx);
2225                 if (msg->flags & LOG_NOCONS) {
2226                         /*
2227                          * Skip record we have buffered and already printed
2228                          * directly to the console when we received it.
2229                          */
2230                         console_idx = log_next(console_idx);
2231                         console_seq++;
2232                         /*
2233                          * We will get here again when we register a new
2234                          * CON_PRINTBUFFER console. Clear the flag so we
2235                          * will properly dump everything later.
2236                          */
2237                         msg->flags &= ~LOG_NOCONS;
2238                         console_prev = msg->flags;
2239                         goto skip;
2240                 }
2241 
2242                 level = msg->level;
2243                 len += msg_print_text(msg, console_prev, false,
2244                                       text + len, sizeof(text) - len);
2245                 console_idx = log_next(console_idx);
2246                 console_seq++;
2247                 console_prev = msg->flags;
2248                 raw_spin_unlock(&logbuf_lock);
2249 
2250                 stop_critical_timings();        /* don't trace print latency */
2251                 call_console_drivers(level, text, len);
2252                 start_critical_timings();
2253                 local_irq_restore(flags);
2254 
2255                 if (do_cond_resched)
2256                         cond_resched();
2257         }
2258         console_locked = 0;
2259 
2260         /* Release the exclusive_console once it is used */
2261         if (unlikely(exclusive_console))
2262                 exclusive_console = NULL;
2263 
2264         raw_spin_unlock(&logbuf_lock);
2265 
2266         up_console_sem();
2267 
2268         /*
2269          * Someone could have filled up the buffer again, so re-check if there's
2270          * something to flush. In case we cannot trylock the console_sem again,
2271          * there's a new owner and the console_unlock() from them will do the
2272          * flush, no worries.
2273          */
2274         raw_spin_lock(&logbuf_lock);
2275         retry = console_seq != log_next_seq;
2276         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2277 
2278         if (retry && console_trylock())
2279                 goto again;
2280 
2281         if (wake_klogd)
2282                 wake_up_klogd();
2283 }
2284 EXPORT_SYMBOL(console_unlock);
2285 
2286 /**
2287  * console_conditional_schedule - yield the CPU if required
2288  *
2289  * If the console code is currently allowed to sleep, and
2290  * if this CPU should yield the CPU to another task, do
2291  * so here.
2292  *
2293  * Must be called within console_lock();.
2294  */
2295 void __sched console_conditional_schedule(void)
2296 {
2297         if (console_may_schedule)
2298                 cond_resched();
2299 }
2300 EXPORT_SYMBOL(console_conditional_schedule);
2301 
2302 void console_unblank(void)
2303 {
2304         struct console *c;
2305 
2306         /*
2307          * console_unblank can no longer be called in interrupt context unless
2308          * oops_in_progress is set to 1..
2309          */
2310         if (oops_in_progress) {
2311                 if (down_trylock_console_sem() != 0)
2312                         return;
2313         } else
2314                 console_lock();
2315 
2316         console_locked = 1;
2317         console_may_schedule = 0;
2318         for_each_console(c)
2319                 if ((c->flags & CON_ENABLED) && c->unblank)
2320                         c->unblank();
2321         console_unlock();
2322 }
2323 
2324 /**
2325  * console_flush_on_panic - flush console content on panic
2326  *
2327  * Immediately output all pending messages no matter what.
2328  */
2329 void console_flush_on_panic(void)
2330 {
2331         /*
2332          * If someone else is holding the console lock, trylock will fail
2333          * and may_schedule may be set.  Ignore and proceed to unlock so
2334          * that messages are flushed out.  As this can be called from any
2335          * context and we don't want to get preempted while flushing,
2336          * ensure may_schedule is cleared.
2337          */
2338         console_trylock();
2339         console_may_schedule = 0;
2340         console_unlock();
2341 }
2342 
2343 /*
2344  * Return the console tty driver structure and its associated index
2345  */
2346 struct tty_driver *console_device(int *index)
2347 {
2348         struct console *c;
2349         struct tty_driver *driver = NULL;
2350 
2351         console_lock();
2352         for_each_console(c) {
2353                 if (!c->device)
2354                         continue;
2355                 driver = c->device(c, index);
2356                 if (driver)
2357                         break;
2358         }
2359         console_unlock();
2360         return driver;
2361 }
2362 
2363 /*
2364  * Prevent further output on the passed console device so that (for example)
2365  * serial drivers can disable console output before suspending a port, and can
2366  * re-enable output afterwards.
2367  */
2368 void console_stop(struct console *console)
2369 {
2370         console_lock();
2371         console->flags &= ~CON_ENABLED;
2372         console_unlock();
2373 }
2374 EXPORT_SYMBOL(console_stop);
2375 
2376 void console_start(struct console *console)
2377 {
2378         console_lock();
2379         console->flags |= CON_ENABLED;
2380         console_unlock();
2381 }
2382 EXPORT_SYMBOL(console_start);
2383 
2384 static int __read_mostly keep_bootcon;
2385 
2386 static int __init keep_bootcon_setup(char *str)
2387 {
2388         keep_bootcon = 1;
2389         pr_info("debug: skip boot console de-registration.\n");
2390 
2391         return 0;
2392 }
2393 
2394 early_param("keep_bootcon", keep_bootcon_setup);
2395 
2396 /*
2397  * The console driver calls this routine during kernel initialization
2398  * to register the console printing procedure with printk() and to
2399  * print any messages that were printed by the kernel before the
2400  * console driver was initialized.
2401  *
2402  * This can happen pretty early during the boot process (because of
2403  * early_printk) - sometimes before setup_arch() completes - be careful
2404  * of what kernel features are used - they may not be initialised yet.
2405  *
2406  * There are two types of consoles - bootconsoles (early_printk) and
2407  * "real" consoles (everything which is not a bootconsole) which are
2408  * handled differently.
2409  *  - Any number of bootconsoles can be registered at any time.
2410  *  - As soon as a "real" console is registered, all bootconsoles
2411  *    will be unregistered automatically.
2412  *  - Once a "real" console is registered, any attempt to register a
2413  *    bootconsoles will be rejected
2414  */
2415 void register_console(struct console *newcon)
2416 {
2417         int i;
2418         unsigned long flags;
2419         struct console *bcon = NULL;
2420         struct console_cmdline *c;
2421 
2422         if (console_drivers)
2423                 for_each_console(bcon)
2424                         if (WARN(bcon == newcon,
2425                                         "console '%s%d' already registered\n",
2426                                         bcon->name, bcon->index))
2427                                 return;
2428 
2429         /*
2430          * before we register a new CON_BOOT console, make sure we don't
2431          * already have a valid console
2432          */
2433         if (console_drivers && newcon->flags & CON_BOOT) {
2434                 /* find the last or real console */
2435                 for_each_console(bcon) {
2436                         if (!(bcon->flags & CON_BOOT)) {
2437                                 pr_info("Too late to register bootconsole %s%d\n",
2438                                         newcon->name, newcon->index);
2439                                 return;
2440                         }
2441                 }
2442         }
2443 
2444         if (console_drivers && console_drivers->flags & CON_BOOT)
2445                 bcon = console_drivers;
2446 
2447         if (preferred_console < 0 || bcon || !console_drivers)
2448                 preferred_console = selected_console;
2449 
2450         if (newcon->early_setup)
2451                 newcon->early_setup();
2452 
2453         /*
2454          *      See if we want to use this console driver. If we
2455          *      didn't select a console we take the first one
2456          *      that registers here.
2457          */
2458         if (preferred_console < 0) {
2459                 if (newcon->index < 0)
2460                         newcon->index = 0;
2461                 if (newcon->setup == NULL ||
2462                     newcon->setup(newcon, NULL) == 0) {
2463                         newcon->flags |= CON_ENABLED;
2464                         if (newcon->device) {
2465                                 newcon->flags |= CON_CONSDEV;
2466                                 preferred_console = 0;
2467                         }
2468                 }
2469         }
2470 
2471         /*
2472          *      See if this console matches one we selected on
2473          *      the command line.
2474          */
2475         for (i = 0, c = console_cmdline;
2476              i < MAX_CMDLINECONSOLES && c->name[0];
2477              i++, c++) {
2478                 BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
2479                 if (strcmp(c->name, newcon->name) != 0)
2480                         continue;
2481                 if (newcon->index >= 0 &&
2482                     newcon->index != c->index)
2483                         continue;
2484                 if (newcon->index < 0)
2485                         newcon->index = c->index;
2486 
2487                 if (_braille_register_console(newcon, c))
2488                         return;
2489 
2490                 if (newcon->setup &&
2491                     newcon->setup(newcon, console_cmdline[i].options) != 0)
2492                         break;
2493                 newcon->flags |= CON_ENABLED;
2494                 newcon->index = c->index;
2495                 if (i == selected_console) {
2496                         newcon->flags |= CON_CONSDEV;
2497                         preferred_console = selected_console;
2498                 }
2499                 break;
2500         }
2501 
2502         if (!(newcon->flags & CON_ENABLED))
2503                 return;
2504 
2505         /*
2506          * If we have a bootconsole, and are switching to a real console,
2507          * don't print everything out again, since when the boot console, and
2508          * the real console are the same physical device, it's annoying to
2509          * see the beginning boot messages twice
2510          */
2511         if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
2512                 newcon->flags &= ~CON_PRINTBUFFER;
2513 
2514         /*
2515          *      Put this console in the list - keep the
2516          *      preferred driver at the head of the list.
2517          */
2518         console_lock();
2519         if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2520                 newcon->next = console_drivers;
2521                 console_drivers = newcon;
2522                 if (newcon->next)
2523                         newcon->next->flags &= ~CON_CONSDEV;
2524         } else {
2525                 newcon->next = console_drivers->next;
2526                 console_drivers->next = newcon;
2527         }
2528         if (newcon->flags & CON_PRINTBUFFER) {
2529                 /*
2530                  * console_unlock(); will print out the buffered messages
2531                  * for us.
2532                  */
2533                 raw_spin_lock_irqsave(&logbuf_lock, flags);
2534                 console_seq = syslog_seq;
2535                 console_idx = syslog_idx;
2536                 console_prev = syslog_prev;
2537                 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2538                 /*
2539                  * We're about to replay the log buffer.  Only do this to the
2540                  * just-registered console to avoid excessive message spam to
2541                  * the already-registered consoles.
2542                  */
2543                 exclusive_console = newcon;
2544         }
2545         console_unlock();
2546         console_sysfs_notify();
2547 
2548         /*
2549          * By unregistering the bootconsoles after we enable the real console
2550          * we get the "console xxx enabled" message on all the consoles -
2551          * boot consoles, real consoles, etc - this is to ensure that end
2552          * users know there might be something in the kernel's log buffer that
2553          * went to the bootconsole (that they do not see on the real console)
2554          */
2555         pr_info("%sconsole [%s%d] enabled\n",
2556                 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2557                 newcon->name, newcon->index);
2558         if (bcon &&
2559             ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2560             !keep_bootcon) {
2561                 /* We need to iterate through all boot consoles, to make
2562                  * sure we print everything out, before we unregister them.
2563                  */
2564                 for_each_console(bcon)
2565                         if (bcon->flags & CON_BOOT)
2566                                 unregister_console(bcon);
2567         }
2568 }
2569 EXPORT_SYMBOL(register_console);
2570 
2571 int unregister_console(struct console *console)
2572 {
2573         struct console *a, *b;
2574         int res;
2575 
2576         pr_info("%sconsole [%s%d] disabled\n",
2577                 (console->flags & CON_BOOT) ? "boot" : "" ,
2578                 console->name, console->index);
2579 
2580         res = _braille_unregister_console(console);
2581         if (res)
2582                 return res;
2583 
2584         res = 1;
2585         console_lock();
2586         if (console_drivers == console) {
2587                 console_drivers=console->next;
2588                 res = 0;
2589         } else if (console_drivers) {
2590                 for (a=console_drivers->next, b=console_drivers ;
2591                      a; b=a, a=b->next) {
2592                         if (a == console) {
2593                                 b->next = a->next;
2594                                 res = 0;
2595                                 break;
2596                         }
2597                 }
2598         }
2599 
2600         /*
2601          * If this isn't the last console and it has CON_CONSDEV set, we
2602          * need to set it on the next preferred console.
2603          */
2604         if (console_drivers != NULL && console->flags & CON_CONSDEV)
2605                 console_drivers->flags |= CON_CONSDEV;
2606 
2607         console->flags &= ~CON_ENABLED;
2608         console_unlock();
2609         console_sysfs_notify();
2610         return res;
2611 }
2612 EXPORT_SYMBOL(unregister_console);
2613 
2614 static int __init printk_late_init(void)
2615 {
2616         struct console *con;
2617 
2618         for_each_console(con) {
2619                 if (!keep_bootcon && con->flags & CON_BOOT) {
2620                         unregister_console(con);
2621                 }
2622         }
2623         hotcpu_notifier(console_cpu_notify, 0);
2624         return 0;
2625 }
2626 late_initcall(printk_late_init);
2627 
2628 #if defined CONFIG_PRINTK
2629 /*
2630  * Delayed printk version, for scheduler-internal messages:
2631  */
2632 #define PRINTK_PENDING_WAKEUP   0x01
2633 #define PRINTK_PENDING_OUTPUT   0x02
2634 
2635 static DEFINE_PER_CPU(int, printk_pending);
2636 
2637 static void wake_up_klogd_work_func(struct irq_work *irq_work)
2638 {
2639         int pending = __this_cpu_xchg(printk_pending, 0);
2640 
2641         if (pending & PRINTK_PENDING_OUTPUT) {
2642                 /* If trylock fails, someone else is doing the printing */
2643                 if (console_trylock())
2644                         console_unlock();
2645         }
2646 
2647         if (pending & PRINTK_PENDING_WAKEUP)
2648                 wake_up_interruptible(&log_wait);
2649 }
2650 
2651 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
2652         .func = wake_up_klogd_work_func,
2653         .flags = IRQ_WORK_LAZY,
2654 };
2655 
2656 void wake_up_klogd(void)
2657 {
2658         preempt_disable();
2659         if (waitqueue_active(&log_wait)) {
2660                 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
2661                 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
2662         }
2663         preempt_enable();
2664 }
2665 
2666 int printk_deferred(const char *fmt, ...)
2667 {
2668         va_list args;
2669         int r;
2670 
2671         preempt_disable();
2672         va_start(args, fmt);
2673         r = vprintk_emit(0, SCHED_MESSAGE_LOGLEVEL, NULL, 0, fmt, args);
2674         va_end(args);
2675 
2676         __this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
2677         irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
2678         preempt_enable();
2679 
2680         return r;
2681 }
2682 
2683 /*
2684  * printk rate limiting, lifted from the networking subsystem.
2685  *
2686  * This enforces a rate limit: not more than 10 kernel messages
2687  * every 5s to make a denial-of-service attack impossible.
2688  */
2689 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
2690 
2691 int __printk_ratelimit(const char *func)
2692 {
2693         return ___ratelimit(&printk_ratelimit_state, func);
2694 }
2695 EXPORT_SYMBOL(__printk_ratelimit);
2696 
2697 /**
2698  * printk_timed_ratelimit - caller-controlled printk ratelimiting
2699  * @caller_jiffies: pointer to caller's state
2700  * @interval_msecs: minimum interval between prints
2701  *
2702  * printk_timed_ratelimit() returns true if more than @interval_msecs
2703  * milliseconds have elapsed since the last time printk_timed_ratelimit()
2704  * returned true.
2705  */
2706 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
2707                         unsigned int interval_msecs)
2708 {
2709         unsigned long elapsed = jiffies - *caller_jiffies;
2710 
2711         if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
2712                 return false;
2713 
2714         *caller_jiffies = jiffies;
2715         return true;
2716 }
2717 EXPORT_SYMBOL(printk_timed_ratelimit);
2718 
2719 static DEFINE_SPINLOCK(dump_list_lock);
2720 static LIST_HEAD(dump_list);
2721 
2722 /**
2723  * kmsg_dump_register - register a kernel log dumper.
2724  * @dumper: pointer to the kmsg_dumper structure
2725  *
2726  * Adds a kernel log dumper to the system. The dump callback in the
2727  * structure will be called when the kernel oopses or panics and must be
2728  * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
2729  */
2730 int kmsg_dump_register(struct kmsg_dumper *dumper)
2731 {
2732         unsigned long flags;
2733         int err = -EBUSY;
2734 
2735         /* The dump callback needs to be set */
2736         if (!dumper->dump)
2737                 return -EINVAL;
2738 
2739         spin_lock_irqsave(&dump_list_lock, flags);
2740         /* Don't allow registering multiple times */
2741         if (!dumper->registered) {
2742                 dumper->registered = 1;
2743                 list_add_tail_rcu(&dumper->list, &dump_list);
2744                 err = 0;
2745         }
2746         spin_unlock_irqrestore(&dump_list_lock, flags);
2747 
2748         return err;
2749 }
2750 EXPORT_SYMBOL_GPL(kmsg_dump_register);
2751 
2752 /**
2753  * kmsg_dump_unregister - unregister a kmsg dumper.
2754  * @dumper: pointer to the kmsg_dumper structure
2755  *
2756  * Removes a dump device from the system. Returns zero on success and
2757  * %-EINVAL otherwise.
2758  */
2759 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
2760 {
2761         unsigned long flags;
2762         int err = -EINVAL;
2763 
2764         spin_lock_irqsave(&dump_list_lock, flags);
2765         if (dumper->registered) {
2766                 dumper->registered = 0;
2767                 list_del_rcu(&dumper->list);
2768                 err = 0;
2769         }
2770         spin_unlock_irqrestore(&dump_list_lock, flags);
2771         synchronize_rcu();
2772 
2773         return err;
2774 }
2775 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
2776 
2777 static bool always_kmsg_dump;
2778 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
2779 
2780 /**
2781  * kmsg_dump - dump kernel log to kernel message dumpers.
2782  * @reason: the reason (oops, panic etc) for dumping
2783  *
2784  * Call each of the registered dumper's dump() callback, which can
2785  * retrieve the kmsg records with kmsg_dump_get_line() or
2786  * kmsg_dump_get_buffer().
2787  */
2788 void kmsg_dump(enum kmsg_dump_reason reason)
2789 {
2790         struct kmsg_dumper *dumper;
2791         unsigned long flags;
2792 
2793         if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
2794                 return;
2795 
2796         rcu_read_lock();
2797         list_for_each_entry_rcu(dumper, &dump_list, list) {
2798                 if (dumper->max_reason && reason > dumper->max_reason)
2799                         continue;
2800 
2801                 /* initialize iterator with data about the stored records */
2802                 dumper->active = true;
2803 
2804                 raw_spin_lock_irqsave(&logbuf_lock, flags);
2805                 dumper->cur_seq = clear_seq;
2806                 dumper->cur_idx = clear_idx;
2807                 dumper->next_seq = log_next_seq;
2808                 dumper->next_idx = log_next_idx;
2809                 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2810 
2811                 /* invoke dumper which will iterate over records */
2812                 dumper->dump(dumper, reason);
2813 
2814                 /* reset iterator */
2815                 dumper->active = false;
2816         }
2817         rcu_read_unlock();
2818 }
2819 
2820 /**
2821  * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
2822  * @dumper: registered kmsg dumper
2823  * @syslog: include the "<4>" prefixes
2824  * @line: buffer to copy the line to
2825  * @size: maximum size of the buffer
2826  * @len: length of line placed into buffer
2827  *
2828  * Start at the beginning of the kmsg buffer, with the oldest kmsg
2829  * record, and copy one record into the provided buffer.
2830  *
2831  * Consecutive calls will return the next available record moving
2832  * towards the end of the buffer with the youngest messages.
2833  *
2834  * A return value of FALSE indicates that there are no more records to
2835  * read.
2836  *
2837  * The function is similar to kmsg_dump_get_line(), but grabs no locks.
2838  */
2839 bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
2840                                char *line, size_t size, size_t *len)
2841 {
2842         struct printk_log *msg;
2843         size_t l = 0;
2844         bool ret = false;
2845 
2846         if (!dumper->active)
2847                 goto out;
2848 
2849         if (dumper->cur_seq < log_first_seq) {
2850                 /* messages are gone, move to first available one */
2851                 dumper->cur_seq = log_first_seq;
2852                 dumper->cur_idx = log_first_idx;
2853         }
2854 
2855         /* last entry */
2856         if (dumper->cur_seq >= log_next_seq)
2857                 goto out;
2858 
2859         msg = log_from_idx(dumper->cur_idx);
2860         l = msg_print_text(msg, 0, syslog, line, size);
2861 
2862         dumper->cur_idx = log_next(dumper->cur_idx);
2863         dumper->cur_seq++;
2864         ret = true;
2865 out:
2866         if (len)
2867                 *len = l;
2868         return ret;
2869 }
2870 
2871 /**
2872  * kmsg_dump_get_line - retrieve one kmsg log line
2873  * @dumper: registered kmsg dumper
2874  * @syslog: include the "<4>" prefixes
2875  * @line: buffer to copy the line to
2876  * @size: maximum size of the buffer
2877  * @len: length of line placed into buffer
2878  *
2879  * Start at the beginning of the kmsg buffer, with the oldest kmsg
2880  * record, and copy one record into the provided buffer.
2881  *
2882  * Consecutive calls will return the next available record moving
2883  * towards the end of the buffer with the youngest messages.
2884  *
2885  * A return value of FALSE indicates that there are no more records to
2886  * read.
2887  */
2888 bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
2889                         char *line, size_t size, size_t *len)
2890 {
2891         unsigned long flags;
2892         bool ret;
2893 
2894         raw_spin_lock_irqsave(&logbuf_lock, flags);
2895         ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
2896         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2897 
2898         return ret;
2899 }
2900 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
2901 
2902 /**
2903  * kmsg_dump_get_buffer - copy kmsg log lines
2904  * @dumper: registered kmsg dumper
2905  * @syslog: include the "<4>" prefixes
2906  * @buf: buffer to copy the line to
2907  * @size: maximum size of the buffer
2908  * @len: length of line placed into buffer
2909  *
2910  * Start at the end of the kmsg buffer and fill the provided buffer
2911  * with as many of the the *youngest* kmsg records that fit into it.
2912  * If the buffer is large enough, all available kmsg records will be
2913  * copied with a single call.
2914  *
2915  * Consecutive calls will fill the buffer with the next block of
2916  * available older records, not including the earlier retrieved ones.
2917  *
2918  * A return value of FALSE indicates that there are no more records to
2919  * read.
2920  */
2921 bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
2922                           char *buf, size_t size, size_t *len)
2923 {
2924         unsigned long flags;
2925         u64 seq;
2926         u32 idx;
2927         u64 next_seq;
2928         u32 next_idx;
2929         enum log_flags prev;
2930         size_t l = 0;
2931         bool ret = false;
2932 
2933         if (!dumper->active)
2934                 goto out;
2935 
2936         raw_spin_lock_irqsave(&logbuf_lock, flags);
2937         if (dumper->cur_seq < log_first_seq) {
2938                 /* messages are gone, move to first available one */
2939                 dumper->cur_seq = log_first_seq;
2940                 dumper->cur_idx = log_first_idx;
2941         }
2942 
2943         /* last entry */
2944         if (dumper->cur_seq >= dumper->next_seq) {
2945                 raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2946                 goto out;
2947         }
2948 
2949         /* calculate length of entire buffer */
2950         seq = dumper->cur_seq;
2951         idx = dumper->cur_idx;
2952         prev = 0;
2953         while (seq < dumper->next_seq) {
2954                 struct printk_log *msg = log_from_idx(idx);
2955 
2956                 l += msg_print_text(msg, prev, true, NULL, 0);
2957                 idx = log_next(idx);
2958                 seq++;
2959                 prev = msg->flags;
2960         }
2961 
2962         /* move first record forward until length fits into the buffer */
2963         seq = dumper->cur_seq;
2964         idx = dumper->cur_idx;
2965         prev = 0;
2966         while (l > size && seq < dumper->next_seq) {
2967                 struct printk_log *msg = log_from_idx(idx);
2968 
2969                 l -= msg_print_text(msg, prev, true, NULL, 0);
2970                 idx = log_next(idx);
2971                 seq++;
2972                 prev = msg->flags;
2973         }
2974 
2975         /* last message in next interation */
2976         next_seq = seq;
2977         next_idx = idx;
2978 
2979         l = 0;
2980         while (seq < dumper->next_seq) {
2981                 struct printk_log *msg = log_from_idx(idx);
2982 
2983                 l += msg_print_text(msg, prev, syslog, buf + l, size - l);
2984                 idx = log_next(idx);
2985                 seq++;
2986                 prev = msg->flags;
2987         }
2988 
2989         dumper->next_seq = next_seq;
2990         dumper->next_idx = next_idx;
2991         ret = true;
2992         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
2993 out:
2994         if (len)
2995                 *len = l;
2996         return ret;
2997 }
2998 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
2999 
3000 /**
3001  * kmsg_dump_rewind_nolock - reset the interator (unlocked version)
3002  * @dumper: registered kmsg dumper
3003  *
3004  * Reset the dumper's iterator so that kmsg_dump_get_line() and
3005  * kmsg_dump_get_buffer() can be called again and used multiple
3006  * times within the same dumper.dump() callback.
3007  *
3008  * The function is similar to kmsg_dump_rewind(), but grabs no locks.
3009  */
3010 void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
3011 {
3012         dumper->cur_seq = clear_seq;
3013         dumper->cur_idx = clear_idx;
3014         dumper->next_seq = log_next_seq;
3015         dumper->next_idx = log_next_idx;
3016 }
3017 
3018 /**
3019  * kmsg_dump_rewind - reset the interator
3020  * @dumper: registered kmsg dumper
3021  *
3022  * Reset the dumper's iterator so that kmsg_dump_get_line() and
3023  * kmsg_dump_get_buffer() can be called again and used multiple
3024  * times within the same dumper.dump() callback.
3025  */
3026 void kmsg_dump_rewind(struct kmsg_dumper *dumper)
3027 {
3028         unsigned long flags;
3029 
3030         raw_spin_lock_irqsave(&logbuf_lock, flags);
3031         kmsg_dump_rewind_nolock(dumper);
3032         raw_spin_unlock_irqrestore(&logbuf_lock, flags);
3033 }
3034 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
3035 
3036 static char dump_stack_arch_desc_str[128];
3037 
3038 /**
3039  * dump_stack_set_arch_desc - set arch-specific str to show with task dumps
3040  * @fmt: printf-style format string
3041  * @...: arguments for the format string
3042  *
3043  * The configured string will be printed right after utsname during task
3044  * dumps.  Usually used to add arch-specific system identifiers.  If an
3045  * arch wants to make use of such an ID string, it should initialize this
3046  * as soon as possible during boot.
3047  */
3048 void __init dump_stack_set_arch_desc(const char *fmt, ...)
3049 {
3050         va_list args;
3051 
3052         va_start(args, fmt);
3053         vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
3054                   fmt, args);
3055         va_end(args);
3056 }
3057 
3058 /**
3059  * dump_stack_print_info - print generic debug info for dump_stack()
3060  * @log_lvl: log level
3061  *
3062  * Arch-specific dump_stack() implementations can use this function to
3063  * print out the same debug information as the generic dump_stack().
3064  */
3065 void dump_stack_print_info(const char *log_lvl)
3066 {
3067         printk("%sCPU: %d PID: %d Comm: %.20s %s %s %.*s\n",
3068                log_lvl, raw_smp_processor_id(), current->pid, current->comm,
3069                print_tainted(), init_utsname()->release,
3070                (int)strcspn(init_utsname()->version, " "),
3071                init_utsname()->version);
3072 
3073         if (dump_stack_arch_desc_str[0] != '\0')
3074                 printk("%sHardware name: %s\n",
3075                        log_lvl, dump_stack_arch_desc_str);
3076 
3077         print_worker_info(log_lvl, current);
3078 }
3079 
3080 /**
3081  * show_regs_print_info - print generic debug info for show_regs()
3082  * @log_lvl: log level
3083  *
3084  * show_regs() implementations can use this function to print out generic
3085  * debug information.
3086  */
3087 void show_regs_print_info(const char *log_lvl)
3088 {
3089         dump_stack_print_info(log_lvl);
3090 
3091         printk("%stask: %p ti: %p task.ti: %p\n",
3092                log_lvl, current, current_thread_info(),
3093                task_thread_info(current));
3094 }
3095 
3096 #endif
3097 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp