Revert "printk: remove @console_locked"
[linux-2.6-microblaze.git] / kernel / printk / printk.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/kernel/printk.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  *
7  * Modified to make sys_syslog() more flexible: added commands to
8  * return the last 4k of kernel messages, regardless of whether
9  * they've been read or not.  Added option to suppress kernel printk's
10  * to the console.  Added hook for sending the console messages
11  * elsewhere, in preparation for a serial line console (someday).
12  * Ted Ts'o, 2/11/93.
13  * Modified for sysctl support, 1/8/97, Chris Horn.
14  * Fixed SMP synchronization, 08/08/99, Manfred Spraul
15  *     manfred@colorfullife.com
16  * Rewrote bits to get rid of console_lock
17  *      01Mar01 Andrew Morton
18  */
19
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21
22 #include <linux/kernel.h>
23 #include <linux/mm.h>
24 #include <linux/tty.h>
25 #include <linux/tty_driver.h>
26 #include <linux/console.h>
27 #include <linux/init.h>
28 #include <linux/jiffies.h>
29 #include <linux/nmi.h>
30 #include <linux/module.h>
31 #include <linux/moduleparam.h>
32 #include <linux/delay.h>
33 #include <linux/smp.h>
34 #include <linux/security.h>
35 #include <linux/memblock.h>
36 #include <linux/syscalls.h>
37 #include <linux/crash_core.h>
38 #include <linux/ratelimit.h>
39 #include <linux/kmsg_dump.h>
40 #include <linux/syslog.h>
41 #include <linux/cpu.h>
42 #include <linux/rculist.h>
43 #include <linux/poll.h>
44 #include <linux/irq_work.h>
45 #include <linux/ctype.h>
46 #include <linux/uio.h>
47 #include <linux/sched/clock.h>
48 #include <linux/sched/debug.h>
49 #include <linux/sched/task_stack.h>
50
51 #include <linux/uaccess.h>
52 #include <asm/sections.h>
53
54 #include <trace/events/initcall.h>
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/printk.h>
57
58 #include "printk_ringbuffer.h"
59 #include "console_cmdline.h"
60 #include "braille.h"
61 #include "internal.h"
62
63 int console_printk[4] = {
64         CONSOLE_LOGLEVEL_DEFAULT,       /* console_loglevel */
65         MESSAGE_LOGLEVEL_DEFAULT,       /* default_message_loglevel */
66         CONSOLE_LOGLEVEL_MIN,           /* minimum_console_loglevel */
67         CONSOLE_LOGLEVEL_DEFAULT,       /* default_console_loglevel */
68 };
69 EXPORT_SYMBOL_GPL(console_printk);
70
71 atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
72 EXPORT_SYMBOL(ignore_console_lock_warning);
73
74 /*
75  * Low level drivers may need that to know if they can schedule in
76  * their unblank() callback or not. So let's export it.
77  */
78 int oops_in_progress;
79 EXPORT_SYMBOL(oops_in_progress);
80
81 /*
82  * console_sem protects the console_drivers list, and also
83  * provides serialisation for access to the entire console
84  * driver system.
85  */
86 static DEFINE_SEMAPHORE(console_sem);
87 struct console *console_drivers;
88 EXPORT_SYMBOL_GPL(console_drivers);
89
90 /*
91  * System may need to suppress printk message under certain
92  * circumstances, like after kernel panic happens.
93  */
94 int __read_mostly suppress_printk;
95
96 /*
97  * During panic, heavy printk by other CPUs can delay the
98  * panic and risk deadlock on console resources.
99  */
100 static int __read_mostly suppress_panic_printk;
101
102 #ifdef CONFIG_LOCKDEP
103 static struct lockdep_map console_lock_dep_map = {
104         .name = "console_lock"
105 };
106 #endif
107
108 enum devkmsg_log_bits {
109         __DEVKMSG_LOG_BIT_ON = 0,
110         __DEVKMSG_LOG_BIT_OFF,
111         __DEVKMSG_LOG_BIT_LOCK,
112 };
113
114 enum devkmsg_log_masks {
115         DEVKMSG_LOG_MASK_ON             = BIT(__DEVKMSG_LOG_BIT_ON),
116         DEVKMSG_LOG_MASK_OFF            = BIT(__DEVKMSG_LOG_BIT_OFF),
117         DEVKMSG_LOG_MASK_LOCK           = BIT(__DEVKMSG_LOG_BIT_LOCK),
118 };
119
120 /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
121 #define DEVKMSG_LOG_MASK_DEFAULT        0
122
123 static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
124
125 static int __control_devkmsg(char *str)
126 {
127         size_t len;
128
129         if (!str)
130                 return -EINVAL;
131
132         len = str_has_prefix(str, "on");
133         if (len) {
134                 devkmsg_log = DEVKMSG_LOG_MASK_ON;
135                 return len;
136         }
137
138         len = str_has_prefix(str, "off");
139         if (len) {
140                 devkmsg_log = DEVKMSG_LOG_MASK_OFF;
141                 return len;
142         }
143
144         len = str_has_prefix(str, "ratelimit");
145         if (len) {
146                 devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
147                 return len;
148         }
149
150         return -EINVAL;
151 }
152
153 static int __init control_devkmsg(char *str)
154 {
155         if (__control_devkmsg(str) < 0) {
156                 pr_warn("printk.devkmsg: bad option string '%s'\n", str);
157                 return 1;
158         }
159
160         /*
161          * Set sysctl string accordingly:
162          */
163         if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
164                 strcpy(devkmsg_log_str, "on");
165         else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
166                 strcpy(devkmsg_log_str, "off");
167         /* else "ratelimit" which is set by default. */
168
169         /*
170          * Sysctl cannot change it anymore. The kernel command line setting of
171          * this parameter is to force the setting to be permanent throughout the
172          * runtime of the system. This is a precation measure against userspace
173          * trying to be a smarta** and attempting to change it up on us.
174          */
175         devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
176
177         return 1;
178 }
179 __setup("printk.devkmsg=", control_devkmsg);
180
181 char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
182 #if defined(CONFIG_PRINTK) && defined(CONFIG_SYSCTL)
183 int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
184                               void *buffer, size_t *lenp, loff_t *ppos)
185 {
186         char old_str[DEVKMSG_STR_MAX_SIZE];
187         unsigned int old;
188         int err;
189
190         if (write) {
191                 if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
192                         return -EINVAL;
193
194                 old = devkmsg_log;
195                 strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
196         }
197
198         err = proc_dostring(table, write, buffer, lenp, ppos);
199         if (err)
200                 return err;
201
202         if (write) {
203                 err = __control_devkmsg(devkmsg_log_str);
204
205                 /*
206                  * Do not accept an unknown string OR a known string with
207                  * trailing crap...
208                  */
209                 if (err < 0 || (err + 1 != *lenp)) {
210
211                         /* ... and restore old setting. */
212                         devkmsg_log = old;
213                         strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
214
215                         return -EINVAL;
216                 }
217         }
218
219         return 0;
220 }
221 #endif /* CONFIG_PRINTK && CONFIG_SYSCTL */
222
223 /* Number of registered extended console drivers. */
224 static int nr_ext_console_drivers;
225
226 /*
227  * Used to synchronize printing kthreads against direct printing via
228  * console_trylock/console_unlock.
229  *
230  * Values:
231  * -1 = console kthreads atomically blocked (via global trylock)
232  *  0 = no kthread printing, console not locked (via trylock)
233  * >0 = kthread(s) actively printing
234  *
235  * Note: For synchronizing against direct printing via
236  *       console_lock/console_unlock, see the @lock variable in
237  *       struct console.
238  */
239 static atomic_t console_kthreads_active = ATOMIC_INIT(0);
240
241 #define console_kthreads_atomic_tryblock() \
242         (atomic_cmpxchg(&console_kthreads_active, 0, -1) == 0)
243 #define console_kthreads_atomic_unblock() \
244         atomic_cmpxchg(&console_kthreads_active, -1, 0)
245 #define console_kthreads_atomically_blocked() \
246         (atomic_read(&console_kthreads_active) == -1)
247
248 #define console_kthread_printing_tryenter() \
249         atomic_inc_unless_negative(&console_kthreads_active)
250 #define console_kthread_printing_exit() \
251         atomic_dec(&console_kthreads_active)
252
253 /*
254  * Helper macros to handle lockdep when locking/unlocking console_sem. We use
255  * macros instead of functions so that _RET_IP_ contains useful information.
256  */
257 #define down_console_sem() do { \
258         down(&console_sem);\
259         mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
260 } while (0)
261
262 static int __down_trylock_console_sem(unsigned long ip)
263 {
264         int lock_failed;
265         unsigned long flags;
266
267         /*
268          * Here and in __up_console_sem() we need to be in safe mode,
269          * because spindump/WARN/etc from under console ->lock will
270          * deadlock in printk()->down_trylock_console_sem() otherwise.
271          */
272         printk_safe_enter_irqsave(flags);
273         lock_failed = down_trylock(&console_sem);
274         printk_safe_exit_irqrestore(flags);
275
276         if (lock_failed)
277                 return 1;
278         mutex_acquire(&console_lock_dep_map, 0, 1, ip);
279         return 0;
280 }
281 #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
282
283 static void __up_console_sem(unsigned long ip)
284 {
285         unsigned long flags;
286
287         mutex_release(&console_lock_dep_map, ip);
288
289         printk_safe_enter_irqsave(flags);
290         up(&console_sem);
291         printk_safe_exit_irqrestore(flags);
292 }
293 #define up_console_sem() __up_console_sem(_RET_IP_)
294
295 static bool panic_in_progress(void)
296 {
297         return unlikely(atomic_read(&panic_cpu) != PANIC_CPU_INVALID);
298 }
299
300 /*
301  * Tracks whether kthread printers are all blocked. A value of true implies
302  * that the console is locked via console_lock() or the console is suspended.
303  * Writing to this variable requires holding @console_sem.
304  */
305 static bool console_kthreads_blocked;
306
307 /*
308  * Block all kthread printers from a schedulable context.
309  *
310  * Requires holding @console_sem.
311  */
312 static void console_kthreads_block(void)
313 {
314         struct console *con;
315
316         for_each_console(con) {
317                 mutex_lock(&con->lock);
318                 con->blocked = true;
319                 mutex_unlock(&con->lock);
320         }
321
322         console_kthreads_blocked = true;
323 }
324
325 /*
326  * Unblock all kthread printers from a schedulable context.
327  *
328  * Requires holding @console_sem.
329  */
330 static void console_kthreads_unblock(void)
331 {
332         struct console *con;
333
334         for_each_console(con) {
335                 mutex_lock(&con->lock);
336                 con->blocked = false;
337                 mutex_unlock(&con->lock);
338         }
339
340         console_kthreads_blocked = false;
341 }
342
343 /*
344  * This is used for debugging the mess that is the VT code by
345  * keeping track if we have the console semaphore held. It's
346  * definitely not the perfect debug tool (we don't know if _WE_
347  * hold it and are racing, but it helps tracking those weird code
348  * paths in the console code where we end up in places I want
349  * locked without the console semaphore held).
350  */
351 static int console_locked, console_suspended;
352
353 /*
354  *      Array of consoles built from command line options (console=)
355  */
356
357 #define MAX_CMDLINECONSOLES 8
358
359 static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
360
361 static int preferred_console = -1;
362 int console_set_on_cmdline;
363 EXPORT_SYMBOL(console_set_on_cmdline);
364
365 /* Flag: console code may call schedule() */
366 static int console_may_schedule;
367
368 enum con_msg_format_flags {
369         MSG_FORMAT_DEFAULT      = 0,
370         MSG_FORMAT_SYSLOG       = (1 << 0),
371 };
372
373 static int console_msg_format = MSG_FORMAT_DEFAULT;
374
375 /*
376  * The printk log buffer consists of a sequenced collection of records, each
377  * containing variable length message text. Every record also contains its
378  * own meta-data (@info).
379  *
380  * Every record meta-data carries the timestamp in microseconds, as well as
381  * the standard userspace syslog level and syslog facility. The usual kernel
382  * messages use LOG_KERN; userspace-injected messages always carry a matching
383  * syslog facility, by default LOG_USER. The origin of every message can be
384  * reliably determined that way.
385  *
386  * The human readable log message of a record is available in @text, the
387  * length of the message text in @text_len. The stored message is not
388  * terminated.
389  *
390  * Optionally, a record can carry a dictionary of properties (key/value
391  * pairs), to provide userspace with a machine-readable message context.
392  *
393  * Examples for well-defined, commonly used property names are:
394  *   DEVICE=b12:8               device identifier
395  *                                b12:8         block dev_t
396  *                                c127:3        char dev_t
397  *                                n8            netdev ifindex
398  *                                +sound:card0  subsystem:devname
399  *   SUBSYSTEM=pci              driver-core subsystem name
400  *
401  * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
402  * and values are terminated by a '\0' character.
403  *
404  * Example of record values:
405  *   record.text_buf                = "it's a line" (unterminated)
406  *   record.info.seq                = 56
407  *   record.info.ts_nsec            = 36863
408  *   record.info.text_len           = 11
409  *   record.info.facility           = 0 (LOG_KERN)
410  *   record.info.flags              = 0
411  *   record.info.level              = 3 (LOG_ERR)
412  *   record.info.caller_id          = 299 (task 299)
413  *   record.info.dev_info.subsystem = "pci" (terminated)
414  *   record.info.dev_info.device    = "+pci:0000:00:01.0" (terminated)
415  *
416  * The 'struct printk_info' buffer must never be directly exported to
417  * userspace, it is a kernel-private implementation detail that might
418  * need to be changed in the future, when the requirements change.
419  *
420  * /dev/kmsg exports the structured data in the following line format:
421  *   "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
422  *
423  * Users of the export format should ignore possible additional values
424  * separated by ',', and find the message after the ';' character.
425  *
426  * The optional key/value pairs are attached as continuation lines starting
427  * with a space character and terminated by a newline. All possible
428  * non-prinatable characters are escaped in the "\xff" notation.
429  */
430
431 /* syslog_lock protects syslog_* variables and write access to clear_seq. */
432 static DEFINE_MUTEX(syslog_lock);
433
434 /*
435  * A flag to signify if printk_activate_kthreads() has already started the
436  * kthread printers. If true, any later registered consoles must start their
437  * own kthread directly. The flag is write protected by the console_lock.
438  */
439 static bool printk_kthreads_available;
440
441 #ifdef CONFIG_PRINTK
442 static atomic_t printk_prefer_direct = ATOMIC_INIT(0);
443
444 /**
445  * printk_prefer_direct_enter - cause printk() calls to attempt direct
446  *                              printing to all enabled consoles
447  *
448  * Since it is not possible to call into the console printing code from any
449  * context, there is no guarantee that direct printing will occur.
450  *
451  * This globally effects all printk() callers.
452  *
453  * Context: Any context.
454  */
455 void printk_prefer_direct_enter(void)
456 {
457         atomic_inc(&printk_prefer_direct);
458 }
459
460 /**
461  * printk_prefer_direct_exit - restore printk() behavior
462  *
463  * Context: Any context.
464  */
465 void printk_prefer_direct_exit(void)
466 {
467         WARN_ON(atomic_dec_if_positive(&printk_prefer_direct) < 0);
468 }
469
470 /*
471  * Calling printk() always wakes kthread printers so that they can
472  * flush the new message to their respective consoles. Also, if direct
473  * printing is allowed, printk() tries to flush the messages directly.
474  *
475  * Direct printing is allowed in situations when the kthreads
476  * are not available or the system is in a problematic state.
477  *
478  * See the implementation about possible races.
479  */
480 static inline bool allow_direct_printing(void)
481 {
482         /*
483          * Checking kthread availability is a possible race because the
484          * kthread printers can become permanently disabled during runtime.
485          * However, doing that requires holding the console_lock, so any
486          * pending messages will be direct printed by console_unlock().
487          */
488         if (!printk_kthreads_available)
489                 return true;
490
491         /*
492          * Prefer direct printing when the system is in a problematic state.
493          * The context that sets this state will always see the updated value.
494          * The other contexts do not care. Anyway, direct printing is just a
495          * best effort. The direct output is only possible when console_lock
496          * is not already taken and no kthread printers are actively printing.
497          */
498         return (system_state > SYSTEM_RUNNING ||
499                 oops_in_progress ||
500                 atomic_read(&printk_prefer_direct));
501 }
502
503 DECLARE_WAIT_QUEUE_HEAD(log_wait);
504 /* All 3 protected by @syslog_lock. */
505 /* the next printk record to read by syslog(READ) or /proc/kmsg */
506 static u64 syslog_seq;
507 static size_t syslog_partial;
508 static bool syslog_time;
509
510 struct latched_seq {
511         seqcount_latch_t        latch;
512         u64                     val[2];
513 };
514
515 /*
516  * The next printk record to read after the last 'clear' command. There are
517  * two copies (updated with seqcount_latch) so that reads can locklessly
518  * access a valid value. Writers are synchronized by @syslog_lock.
519  */
520 static struct latched_seq clear_seq = {
521         .latch          = SEQCNT_LATCH_ZERO(clear_seq.latch),
522         .val[0]         = 0,
523         .val[1]         = 0,
524 };
525
526 #ifdef CONFIG_PRINTK_CALLER
527 #define PREFIX_MAX              48
528 #else
529 #define PREFIX_MAX              32
530 #endif
531
532 /* the maximum size of a formatted record (i.e. with prefix added per line) */
533 #define CONSOLE_LOG_MAX         1024
534
535 /* the maximum size for a dropped text message */
536 #define DROPPED_TEXT_MAX        64
537
538 /* the maximum size allowed to be reserved for a record */
539 #define LOG_LINE_MAX            (CONSOLE_LOG_MAX - PREFIX_MAX)
540
541 #define LOG_LEVEL(v)            ((v) & 0x07)
542 #define LOG_FACILITY(v)         ((v) >> 3 & 0xff)
543
544 /* record buffer */
545 #define LOG_ALIGN __alignof__(unsigned long)
546 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
547 #define LOG_BUF_LEN_MAX (u32)(1 << 31)
548 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
549 static char *log_buf = __log_buf;
550 static u32 log_buf_len = __LOG_BUF_LEN;
551
552 /*
553  * Define the average message size. This only affects the number of
554  * descriptors that will be available. Underestimating is better than
555  * overestimating (too many available descriptors is better than not enough).
556  */
557 #define PRB_AVGBITS 5   /* 32 character average length */
558
559 #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
560 #error CONFIG_LOG_BUF_SHIFT value too small.
561 #endif
562 _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
563                  PRB_AVGBITS, &__log_buf[0]);
564
565 static struct printk_ringbuffer printk_rb_dynamic;
566
567 static struct printk_ringbuffer *prb = &printk_rb_static;
568
569 /*
570  * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
571  * per_cpu_areas are initialised. This variable is set to true when
572  * it's safe to access per-CPU data.
573  */
574 static bool __printk_percpu_data_ready __read_mostly;
575
576 bool printk_percpu_data_ready(void)
577 {
578         return __printk_percpu_data_ready;
579 }
580
581 /* Must be called under syslog_lock. */
582 static void latched_seq_write(struct latched_seq *ls, u64 val)
583 {
584         raw_write_seqcount_latch(&ls->latch);
585         ls->val[0] = val;
586         raw_write_seqcount_latch(&ls->latch);
587         ls->val[1] = val;
588 }
589
590 /* Can be called from any context. */
591 static u64 latched_seq_read_nolock(struct latched_seq *ls)
592 {
593         unsigned int seq;
594         unsigned int idx;
595         u64 val;
596
597         do {
598                 seq = raw_read_seqcount_latch(&ls->latch);
599                 idx = seq & 0x1;
600                 val = ls->val[idx];
601         } while (read_seqcount_latch_retry(&ls->latch, seq));
602
603         return val;
604 }
605
606 /* Return log buffer address */
607 char *log_buf_addr_get(void)
608 {
609         return log_buf;
610 }
611
612 /* Return log buffer size */
613 u32 log_buf_len_get(void)
614 {
615         return log_buf_len;
616 }
617
618 /*
619  * Define how much of the log buffer we could take at maximum. The value
620  * must be greater than two. Note that only half of the buffer is available
621  * when the index points to the middle.
622  */
623 #define MAX_LOG_TAKE_PART 4
624 static const char trunc_msg[] = "<truncated>";
625
626 static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
627 {
628         /*
629          * The message should not take the whole buffer. Otherwise, it might
630          * get removed too soon.
631          */
632         u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
633
634         if (*text_len > max_text_len)
635                 *text_len = max_text_len;
636
637         /* enable the warning message (if there is room) */
638         *trunc_msg_len = strlen(trunc_msg);
639         if (*text_len >= *trunc_msg_len)
640                 *text_len -= *trunc_msg_len;
641         else
642                 *trunc_msg_len = 0;
643 }
644
645 int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
646
647 static int syslog_action_restricted(int type)
648 {
649         if (dmesg_restrict)
650                 return 1;
651         /*
652          * Unless restricted, we allow "read all" and "get buffer size"
653          * for everybody.
654          */
655         return type != SYSLOG_ACTION_READ_ALL &&
656                type != SYSLOG_ACTION_SIZE_BUFFER;
657 }
658
659 static int check_syslog_permissions(int type, int source)
660 {
661         /*
662          * If this is from /proc/kmsg and we've already opened it, then we've
663          * already done the capabilities checks at open time.
664          */
665         if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
666                 goto ok;
667
668         if (syslog_action_restricted(type)) {
669                 if (capable(CAP_SYSLOG))
670                         goto ok;
671                 /*
672                  * For historical reasons, accept CAP_SYS_ADMIN too, with
673                  * a warning.
674                  */
675                 if (capable(CAP_SYS_ADMIN)) {
676                         pr_warn_once("%s (%d): Attempt to access syslog with "
677                                      "CAP_SYS_ADMIN but no CAP_SYSLOG "
678                                      "(deprecated).\n",
679                                  current->comm, task_pid_nr(current));
680                         goto ok;
681                 }
682                 return -EPERM;
683         }
684 ok:
685         return security_syslog(type);
686 }
687
688 static void append_char(char **pp, char *e, char c)
689 {
690         if (*pp < e)
691                 *(*pp)++ = c;
692 }
693
694 static ssize_t info_print_ext_header(char *buf, size_t size,
695                                      struct printk_info *info)
696 {
697         u64 ts_usec = info->ts_nsec;
698         char caller[20];
699 #ifdef CONFIG_PRINTK_CALLER
700         u32 id = info->caller_id;
701
702         snprintf(caller, sizeof(caller), ",caller=%c%u",
703                  id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
704 #else
705         caller[0] = '\0';
706 #endif
707
708         do_div(ts_usec, 1000);
709
710         return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
711                          (info->facility << 3) | info->level, info->seq,
712                          ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
713 }
714
715 static ssize_t msg_add_ext_text(char *buf, size_t size,
716                                 const char *text, size_t text_len,
717                                 unsigned char endc)
718 {
719         char *p = buf, *e = buf + size;
720         size_t i;
721
722         /* escape non-printable characters */
723         for (i = 0; i < text_len; i++) {
724                 unsigned char c = text[i];
725
726                 if (c < ' ' || c >= 127 || c == '\\')
727                         p += scnprintf(p, e - p, "\\x%02x", c);
728                 else
729                         append_char(&p, e, c);
730         }
731         append_char(&p, e, endc);
732
733         return p - buf;
734 }
735
736 static ssize_t msg_add_dict_text(char *buf, size_t size,
737                                  const char *key, const char *val)
738 {
739         size_t val_len = strlen(val);
740         ssize_t len;
741
742         if (!val_len)
743                 return 0;
744
745         len = msg_add_ext_text(buf, size, "", 0, ' ');  /* dict prefix */
746         len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
747         len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
748
749         return len;
750 }
751
752 static ssize_t msg_print_ext_body(char *buf, size_t size,
753                                   char *text, size_t text_len,
754                                   struct dev_printk_info *dev_info)
755 {
756         ssize_t len;
757
758         len = msg_add_ext_text(buf, size, text, text_len, '\n');
759
760         if (!dev_info)
761                 goto out;
762
763         len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
764                                  dev_info->subsystem);
765         len += msg_add_dict_text(buf + len, size - len, "DEVICE",
766                                  dev_info->device);
767 out:
768         return len;
769 }
770
771 /* /dev/kmsg - userspace message inject/listen interface */
772 struct devkmsg_user {
773         atomic64_t seq;
774         struct ratelimit_state rs;
775         struct mutex lock;
776         char buf[CONSOLE_EXT_LOG_MAX];
777
778         struct printk_info info;
779         char text_buf[CONSOLE_EXT_LOG_MAX];
780         struct printk_record record;
781 };
782
783 static __printf(3, 4) __cold
784 int devkmsg_emit(int facility, int level, const char *fmt, ...)
785 {
786         va_list args;
787         int r;
788
789         va_start(args, fmt);
790         r = vprintk_emit(facility, level, NULL, fmt, args);
791         va_end(args);
792
793         return r;
794 }
795
796 static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
797 {
798         char *buf, *line;
799         int level = default_message_loglevel;
800         int facility = 1;       /* LOG_USER */
801         struct file *file = iocb->ki_filp;
802         struct devkmsg_user *user = file->private_data;
803         size_t len = iov_iter_count(from);
804         ssize_t ret = len;
805
806         if (!user || len > LOG_LINE_MAX)
807                 return -EINVAL;
808
809         /* Ignore when user logging is disabled. */
810         if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
811                 return len;
812
813         /* Ratelimit when not explicitly enabled. */
814         if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
815                 if (!___ratelimit(&user->rs, current->comm))
816                         return ret;
817         }
818
819         buf = kmalloc(len+1, GFP_KERNEL);
820         if (buf == NULL)
821                 return -ENOMEM;
822
823         buf[len] = '\0';
824         if (!copy_from_iter_full(buf, len, from)) {
825                 kfree(buf);
826                 return -EFAULT;
827         }
828
829         /*
830          * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
831          * the decimal value represents 32bit, the lower 3 bit are the log
832          * level, the rest are the log facility.
833          *
834          * If no prefix or no userspace facility is specified, we
835          * enforce LOG_USER, to be able to reliably distinguish
836          * kernel-generated messages from userspace-injected ones.
837          */
838         line = buf;
839         if (line[0] == '<') {
840                 char *endp = NULL;
841                 unsigned int u;
842
843                 u = simple_strtoul(line + 1, &endp, 10);
844                 if (endp && endp[0] == '>') {
845                         level = LOG_LEVEL(u);
846                         if (LOG_FACILITY(u) != 0)
847                                 facility = LOG_FACILITY(u);
848                         endp++;
849                         line = endp;
850                 }
851         }
852
853         devkmsg_emit(facility, level, "%s", line);
854         kfree(buf);
855         return ret;
856 }
857
858 static ssize_t devkmsg_read(struct file *file, char __user *buf,
859                             size_t count, loff_t *ppos)
860 {
861         struct devkmsg_user *user = file->private_data;
862         struct printk_record *r = &user->record;
863         size_t len;
864         ssize_t ret;
865
866         if (!user)
867                 return -EBADF;
868
869         ret = mutex_lock_interruptible(&user->lock);
870         if (ret)
871                 return ret;
872
873         if (!prb_read_valid(prb, atomic64_read(&user->seq), r)) {
874                 if (file->f_flags & O_NONBLOCK) {
875                         ret = -EAGAIN;
876                         goto out;
877                 }
878
879                 /*
880                  * Guarantee this task is visible on the waitqueue before
881                  * checking the wake condition.
882                  *
883                  * The full memory barrier within set_current_state() of
884                  * prepare_to_wait_event() pairs with the full memory barrier
885                  * within wq_has_sleeper().
886                  *
887                  * This pairs with __wake_up_klogd:A.
888                  */
889                 ret = wait_event_interruptible(log_wait,
890                                 prb_read_valid(prb,
891                                         atomic64_read(&user->seq), r)); /* LMM(devkmsg_read:A) */
892                 if (ret)
893                         goto out;
894         }
895
896         if (r->info->seq != atomic64_read(&user->seq)) {
897                 /* our last seen message is gone, return error and reset */
898                 atomic64_set(&user->seq, r->info->seq);
899                 ret = -EPIPE;
900                 goto out;
901         }
902
903         len = info_print_ext_header(user->buf, sizeof(user->buf), r->info);
904         len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
905                                   &r->text_buf[0], r->info->text_len,
906                                   &r->info->dev_info);
907
908         atomic64_set(&user->seq, r->info->seq + 1);
909
910         if (len > count) {
911                 ret = -EINVAL;
912                 goto out;
913         }
914
915         if (copy_to_user(buf, user->buf, len)) {
916                 ret = -EFAULT;
917                 goto out;
918         }
919         ret = len;
920 out:
921         mutex_unlock(&user->lock);
922         return ret;
923 }
924
925 /*
926  * Be careful when modifying this function!!!
927  *
928  * Only few operations are supported because the device works only with the
929  * entire variable length messages (records). Non-standard values are
930  * returned in the other cases and has been this way for quite some time.
931  * User space applications might depend on this behavior.
932  */
933 static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
934 {
935         struct devkmsg_user *user = file->private_data;
936         loff_t ret = 0;
937
938         if (!user)
939                 return -EBADF;
940         if (offset)
941                 return -ESPIPE;
942
943         switch (whence) {
944         case SEEK_SET:
945                 /* the first record */
946                 atomic64_set(&user->seq, prb_first_valid_seq(prb));
947                 break;
948         case SEEK_DATA:
949                 /*
950                  * The first record after the last SYSLOG_ACTION_CLEAR,
951                  * like issued by 'dmesg -c'. Reading /dev/kmsg itself
952                  * changes no global state, and does not clear anything.
953                  */
954                 atomic64_set(&user->seq, latched_seq_read_nolock(&clear_seq));
955                 break;
956         case SEEK_END:
957                 /* after the last record */
958                 atomic64_set(&user->seq, prb_next_seq(prb));
959                 break;
960         default:
961                 ret = -EINVAL;
962         }
963         return ret;
964 }
965
966 static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
967 {
968         struct devkmsg_user *user = file->private_data;
969         struct printk_info info;
970         __poll_t ret = 0;
971
972         if (!user)
973                 return EPOLLERR|EPOLLNVAL;
974
975         poll_wait(file, &log_wait, wait);
976
977         if (prb_read_valid_info(prb, atomic64_read(&user->seq), &info, NULL)) {
978                 /* return error when data has vanished underneath us */
979                 if (info.seq != atomic64_read(&user->seq))
980                         ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
981                 else
982                         ret = EPOLLIN|EPOLLRDNORM;
983         }
984
985         return ret;
986 }
987
988 static int devkmsg_open(struct inode *inode, struct file *file)
989 {
990         struct devkmsg_user *user;
991         int err;
992
993         if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
994                 return -EPERM;
995
996         /* write-only does not need any file context */
997         if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
998                 err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
999                                                SYSLOG_FROM_READER);
1000                 if (err)
1001                         return err;
1002         }
1003
1004         user = kvmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
1005         if (!user)
1006                 return -ENOMEM;
1007
1008         ratelimit_default_init(&user->rs);
1009         ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
1010
1011         mutex_init(&user->lock);
1012
1013         prb_rec_init_rd(&user->record, &user->info,
1014                         &user->text_buf[0], sizeof(user->text_buf));
1015
1016         atomic64_set(&user->seq, prb_first_valid_seq(prb));
1017
1018         file->private_data = user;
1019         return 0;
1020 }
1021
1022 static int devkmsg_release(struct inode *inode, struct file *file)
1023 {
1024         struct devkmsg_user *user = file->private_data;
1025
1026         if (!user)
1027                 return 0;
1028
1029         ratelimit_state_exit(&user->rs);
1030
1031         mutex_destroy(&user->lock);
1032         kvfree(user);
1033         return 0;
1034 }
1035
1036 const struct file_operations kmsg_fops = {
1037         .open = devkmsg_open,
1038         .read = devkmsg_read,
1039         .write_iter = devkmsg_write,
1040         .llseek = devkmsg_llseek,
1041         .poll = devkmsg_poll,
1042         .release = devkmsg_release,
1043 };
1044
1045 #ifdef CONFIG_CRASH_CORE
1046 /*
1047  * This appends the listed symbols to /proc/vmcore
1048  *
1049  * /proc/vmcore is used by various utilities, like crash and makedumpfile to
1050  * obtain access to symbols that are otherwise very difficult to locate.  These
1051  * symbols are specifically used so that utilities can access and extract the
1052  * dmesg log from a vmcore file after a crash.
1053  */
1054 void log_buf_vmcoreinfo_setup(void)
1055 {
1056         struct dev_printk_info *dev_info = NULL;
1057
1058         VMCOREINFO_SYMBOL(prb);
1059         VMCOREINFO_SYMBOL(printk_rb_static);
1060         VMCOREINFO_SYMBOL(clear_seq);
1061
1062         /*
1063          * Export struct size and field offsets. User space tools can
1064          * parse it and detect any changes to structure down the line.
1065          */
1066
1067         VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
1068         VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
1069         VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
1070         VMCOREINFO_OFFSET(printk_ringbuffer, fail);
1071
1072         VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
1073         VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
1074         VMCOREINFO_OFFSET(prb_desc_ring, descs);
1075         VMCOREINFO_OFFSET(prb_desc_ring, infos);
1076         VMCOREINFO_OFFSET(prb_desc_ring, head_id);
1077         VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
1078
1079         VMCOREINFO_STRUCT_SIZE(prb_desc);
1080         VMCOREINFO_OFFSET(prb_desc, state_var);
1081         VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
1082
1083         VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
1084         VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
1085         VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
1086
1087         VMCOREINFO_STRUCT_SIZE(printk_info);
1088         VMCOREINFO_OFFSET(printk_info, seq);
1089         VMCOREINFO_OFFSET(printk_info, ts_nsec);
1090         VMCOREINFO_OFFSET(printk_info, text_len);
1091         VMCOREINFO_OFFSET(printk_info, caller_id);
1092         VMCOREINFO_OFFSET(printk_info, dev_info);
1093
1094         VMCOREINFO_STRUCT_SIZE(dev_printk_info);
1095         VMCOREINFO_OFFSET(dev_printk_info, subsystem);
1096         VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
1097         VMCOREINFO_OFFSET(dev_printk_info, device);
1098         VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
1099
1100         VMCOREINFO_STRUCT_SIZE(prb_data_ring);
1101         VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1102         VMCOREINFO_OFFSET(prb_data_ring, data);
1103         VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1104         VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1105
1106         VMCOREINFO_SIZE(atomic_long_t);
1107         VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
1108
1109         VMCOREINFO_STRUCT_SIZE(latched_seq);
1110         VMCOREINFO_OFFSET(latched_seq, val);
1111 }
1112 #endif
1113
1114 /* requested log_buf_len from kernel cmdline */
1115 static unsigned long __initdata new_log_buf_len;
1116
1117 /* we practice scaling the ring buffer by powers of 2 */
1118 static void __init log_buf_len_update(u64 size)
1119 {
1120         if (size > (u64)LOG_BUF_LEN_MAX) {
1121                 size = (u64)LOG_BUF_LEN_MAX;
1122                 pr_err("log_buf over 2G is not supported.\n");
1123         }
1124
1125         if (size)
1126                 size = roundup_pow_of_two(size);
1127         if (size > log_buf_len)
1128                 new_log_buf_len = (unsigned long)size;
1129 }
1130
1131 /* save requested log_buf_len since it's too early to process it */
1132 static int __init log_buf_len_setup(char *str)
1133 {
1134         u64 size;
1135
1136         if (!str)
1137                 return -EINVAL;
1138
1139         size = memparse(str, &str);
1140
1141         log_buf_len_update(size);
1142
1143         return 0;
1144 }
1145 early_param("log_buf_len", log_buf_len_setup);
1146
1147 #ifdef CONFIG_SMP
1148 #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
1149
1150 static void __init log_buf_add_cpu(void)
1151 {
1152         unsigned int cpu_extra;
1153
1154         /*
1155          * archs should set up cpu_possible_bits properly with
1156          * set_cpu_possible() after setup_arch() but just in
1157          * case lets ensure this is valid.
1158          */
1159         if (num_possible_cpus() == 1)
1160                 return;
1161
1162         cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
1163
1164         /* by default this will only continue through for large > 64 CPUs */
1165         if (cpu_extra <= __LOG_BUF_LEN / 2)
1166                 return;
1167
1168         pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
1169                 __LOG_CPU_MAX_BUF_LEN);
1170         pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
1171                 cpu_extra);
1172         pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1173
1174         log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1175 }
1176 #else /* !CONFIG_SMP */
1177 static inline void log_buf_add_cpu(void) {}
1178 #endif /* CONFIG_SMP */
1179
1180 static void __init set_percpu_data_ready(void)
1181 {
1182         __printk_percpu_data_ready = true;
1183 }
1184
1185 static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1186                                      struct printk_record *r)
1187 {
1188         struct prb_reserved_entry e;
1189         struct printk_record dest_r;
1190
1191         prb_rec_init_wr(&dest_r, r->info->text_len);
1192
1193         if (!prb_reserve(&e, rb, &dest_r))
1194                 return 0;
1195
1196         memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1197         dest_r.info->text_len = r->info->text_len;
1198         dest_r.info->facility = r->info->facility;
1199         dest_r.info->level = r->info->level;
1200         dest_r.info->flags = r->info->flags;
1201         dest_r.info->ts_nsec = r->info->ts_nsec;
1202         dest_r.info->caller_id = r->info->caller_id;
1203         memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1204
1205         prb_final_commit(&e);
1206
1207         return prb_record_text_space(&e);
1208 }
1209
1210 static char setup_text_buf[LOG_LINE_MAX] __initdata;
1211
1212 void __init setup_log_buf(int early)
1213 {
1214         struct printk_info *new_infos;
1215         unsigned int new_descs_count;
1216         struct prb_desc *new_descs;
1217         struct printk_info info;
1218         struct printk_record r;
1219         unsigned int text_size;
1220         size_t new_descs_size;
1221         size_t new_infos_size;
1222         unsigned long flags;
1223         char *new_log_buf;
1224         unsigned int free;
1225         u64 seq;
1226
1227         /*
1228          * Some archs call setup_log_buf() multiple times - first is very
1229          * early, e.g. from setup_arch(), and second - when percpu_areas
1230          * are initialised.
1231          */
1232         if (!early)
1233                 set_percpu_data_ready();
1234
1235         if (log_buf != __log_buf)
1236                 return;
1237
1238         if (!early && !new_log_buf_len)
1239                 log_buf_add_cpu();
1240
1241         if (!new_log_buf_len)
1242                 return;
1243
1244         new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1245         if (new_descs_count == 0) {
1246                 pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1247                 return;
1248         }
1249
1250         new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1251         if (unlikely(!new_log_buf)) {
1252                 pr_err("log_buf_len: %lu text bytes not available\n",
1253                        new_log_buf_len);
1254                 return;
1255         }
1256
1257         new_descs_size = new_descs_count * sizeof(struct prb_desc);
1258         new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1259         if (unlikely(!new_descs)) {
1260                 pr_err("log_buf_len: %zu desc bytes not available\n",
1261                        new_descs_size);
1262                 goto err_free_log_buf;
1263         }
1264
1265         new_infos_size = new_descs_count * sizeof(struct printk_info);
1266         new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1267         if (unlikely(!new_infos)) {
1268                 pr_err("log_buf_len: %zu info bytes not available\n",
1269                        new_infos_size);
1270                 goto err_free_descs;
1271         }
1272
1273         prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1274
1275         prb_init(&printk_rb_dynamic,
1276                  new_log_buf, ilog2(new_log_buf_len),
1277                  new_descs, ilog2(new_descs_count),
1278                  new_infos);
1279
1280         local_irq_save(flags);
1281
1282         log_buf_len = new_log_buf_len;
1283         log_buf = new_log_buf;
1284         new_log_buf_len = 0;
1285
1286         free = __LOG_BUF_LEN;
1287         prb_for_each_record(0, &printk_rb_static, seq, &r) {
1288                 text_size = add_to_rb(&printk_rb_dynamic, &r);
1289                 if (text_size > free)
1290                         free = 0;
1291                 else
1292                         free -= text_size;
1293         }
1294
1295         prb = &printk_rb_dynamic;
1296
1297         local_irq_restore(flags);
1298
1299         /*
1300          * Copy any remaining messages that might have appeared from
1301          * NMI context after copying but before switching to the
1302          * dynamic buffer.
1303          */
1304         prb_for_each_record(seq, &printk_rb_static, seq, &r) {
1305                 text_size = add_to_rb(&printk_rb_dynamic, &r);
1306                 if (text_size > free)
1307                         free = 0;
1308                 else
1309                         free -= text_size;
1310         }
1311
1312         if (seq != prb_next_seq(&printk_rb_static)) {
1313                 pr_err("dropped %llu messages\n",
1314                        prb_next_seq(&printk_rb_static) - seq);
1315         }
1316
1317         pr_info("log_buf_len: %u bytes\n", log_buf_len);
1318         pr_info("early log buf free: %u(%u%%)\n",
1319                 free, (free * 100) / __LOG_BUF_LEN);
1320         return;
1321
1322 err_free_descs:
1323         memblock_free(new_descs, new_descs_size);
1324 err_free_log_buf:
1325         memblock_free(new_log_buf, new_log_buf_len);
1326 }
1327
1328 static bool __read_mostly ignore_loglevel;
1329
1330 static int __init ignore_loglevel_setup(char *str)
1331 {
1332         ignore_loglevel = true;
1333         pr_info("debug: ignoring loglevel setting.\n");
1334
1335         return 0;
1336 }
1337
1338 early_param("ignore_loglevel", ignore_loglevel_setup);
1339 module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1340 MODULE_PARM_DESC(ignore_loglevel,
1341                  "ignore loglevel setting (prints all kernel messages to the console)");
1342
1343 static bool suppress_message_printing(int level)
1344 {
1345         return (level >= console_loglevel && !ignore_loglevel);
1346 }
1347
1348 #ifdef CONFIG_BOOT_PRINTK_DELAY
1349
1350 static int boot_delay; /* msecs delay after each printk during bootup */
1351 static unsigned long long loops_per_msec;       /* based on boot_delay */
1352
1353 static int __init boot_delay_setup(char *str)
1354 {
1355         unsigned long lpj;
1356
1357         lpj = preset_lpj ? preset_lpj : 1000000;        /* some guess */
1358         loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1359
1360         get_option(&str, &boot_delay);
1361         if (boot_delay > 10 * 1000)
1362                 boot_delay = 0;
1363
1364         pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1365                 "HZ: %d, loops_per_msec: %llu\n",
1366                 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1367         return 0;
1368 }
1369 early_param("boot_delay", boot_delay_setup);
1370
1371 static void boot_delay_msec(int level)
1372 {
1373         unsigned long long k;
1374         unsigned long timeout;
1375
1376         if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1377                 || suppress_message_printing(level)) {
1378                 return;
1379         }
1380
1381         k = (unsigned long long)loops_per_msec * boot_delay;
1382
1383         timeout = jiffies + msecs_to_jiffies(boot_delay);
1384         while (k) {
1385                 k--;
1386                 cpu_relax();
1387                 /*
1388                  * use (volatile) jiffies to prevent
1389                  * compiler reduction; loop termination via jiffies
1390                  * is secondary and may or may not happen.
1391                  */
1392                 if (time_after(jiffies, timeout))
1393                         break;
1394                 touch_nmi_watchdog();
1395         }
1396 }
1397 #else
1398 static inline void boot_delay_msec(int level)
1399 {
1400 }
1401 #endif
1402
1403 static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1404 module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1405
1406 static size_t print_syslog(unsigned int level, char *buf)
1407 {
1408         return sprintf(buf, "<%u>", level);
1409 }
1410
1411 static size_t print_time(u64 ts, char *buf)
1412 {
1413         unsigned long rem_nsec = do_div(ts, 1000000000);
1414
1415         return sprintf(buf, "[%5lu.%06lu]",
1416                        (unsigned long)ts, rem_nsec / 1000);
1417 }
1418
1419 #ifdef CONFIG_PRINTK_CALLER
1420 static size_t print_caller(u32 id, char *buf)
1421 {
1422         char caller[12];
1423
1424         snprintf(caller, sizeof(caller), "%c%u",
1425                  id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1426         return sprintf(buf, "[%6s]", caller);
1427 }
1428 #else
1429 #define print_caller(id, buf) 0
1430 #endif
1431
1432 static size_t info_print_prefix(const struct printk_info  *info, bool syslog,
1433                                 bool time, char *buf)
1434 {
1435         size_t len = 0;
1436
1437         if (syslog)
1438                 len = print_syslog((info->facility << 3) | info->level, buf);
1439
1440         if (time)
1441                 len += print_time(info->ts_nsec, buf + len);
1442
1443         len += print_caller(info->caller_id, buf + len);
1444
1445         if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1446                 buf[len++] = ' ';
1447                 buf[len] = '\0';
1448         }
1449
1450         return len;
1451 }
1452
1453 /*
1454  * Prepare the record for printing. The text is shifted within the given
1455  * buffer to avoid a need for another one. The following operations are
1456  * done:
1457  *
1458  *   - Add prefix for each line.
1459  *   - Drop truncated lines that no longer fit into the buffer.
1460  *   - Add the trailing newline that has been removed in vprintk_store().
1461  *   - Add a string terminator.
1462  *
1463  * Since the produced string is always terminated, the maximum possible
1464  * return value is @r->text_buf_size - 1;
1465  *
1466  * Return: The length of the updated/prepared text, including the added
1467  * prefixes and the newline. The terminator is not counted. The dropped
1468  * line(s) are not counted.
1469  */
1470 static size_t record_print_text(struct printk_record *r, bool syslog,
1471                                 bool time)
1472 {
1473         size_t text_len = r->info->text_len;
1474         size_t buf_size = r->text_buf_size;
1475         char *text = r->text_buf;
1476         char prefix[PREFIX_MAX];
1477         bool truncated = false;
1478         size_t prefix_len;
1479         size_t line_len;
1480         size_t len = 0;
1481         char *next;
1482
1483         /*
1484          * If the message was truncated because the buffer was not large
1485          * enough, treat the available text as if it were the full text.
1486          */
1487         if (text_len > buf_size)
1488                 text_len = buf_size;
1489
1490         prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1491
1492         /*
1493          * @text_len: bytes of unprocessed text
1494          * @line_len: bytes of current line _without_ newline
1495          * @text:     pointer to beginning of current line
1496          * @len:      number of bytes prepared in r->text_buf
1497          */
1498         for (;;) {
1499                 next = memchr(text, '\n', text_len);
1500                 if (next) {
1501                         line_len = next - text;
1502                 } else {
1503                         /* Drop truncated line(s). */
1504                         if (truncated)
1505                                 break;
1506                         line_len = text_len;
1507                 }
1508
1509                 /*
1510                  * Truncate the text if there is not enough space to add the
1511                  * prefix and a trailing newline and a terminator.
1512                  */
1513                 if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1514                         /* Drop even the current line if no space. */
1515                         if (len + prefix_len + line_len + 1 + 1 > buf_size)
1516                                 break;
1517
1518                         text_len = buf_size - len - prefix_len - 1 - 1;
1519                         truncated = true;
1520                 }
1521
1522                 memmove(text + prefix_len, text, text_len);
1523                 memcpy(text, prefix, prefix_len);
1524
1525                 /*
1526                  * Increment the prepared length to include the text and
1527                  * prefix that were just moved+copied. Also increment for the
1528                  * newline at the end of this line. If this is the last line,
1529                  * there is no newline, but it will be added immediately below.
1530                  */
1531                 len += prefix_len + line_len + 1;
1532                 if (text_len == line_len) {
1533                         /*
1534                          * This is the last line. Add the trailing newline
1535                          * removed in vprintk_store().
1536                          */
1537                         text[prefix_len + line_len] = '\n';
1538                         break;
1539                 }
1540
1541                 /*
1542                  * Advance beyond the added prefix and the related line with
1543                  * its newline.
1544                  */
1545                 text += prefix_len + line_len + 1;
1546
1547                 /*
1548                  * The remaining text has only decreased by the line with its
1549                  * newline.
1550                  *
1551                  * Note that @text_len can become zero. It happens when @text
1552                  * ended with a newline (either due to truncation or the
1553                  * original string ending with "\n\n"). The loop is correctly
1554                  * repeated and (if not truncated) an empty line with a prefix
1555                  * will be prepared.
1556                  */
1557                 text_len -= line_len + 1;
1558         }
1559
1560         /*
1561          * If a buffer was provided, it will be terminated. Space for the
1562          * string terminator is guaranteed to be available. The terminator is
1563          * not counted in the return value.
1564          */
1565         if (buf_size > 0)
1566                 r->text_buf[len] = 0;
1567
1568         return len;
1569 }
1570
1571 static size_t get_record_print_text_size(struct printk_info *info,
1572                                          unsigned int line_count,
1573                                          bool syslog, bool time)
1574 {
1575         char prefix[PREFIX_MAX];
1576         size_t prefix_len;
1577
1578         prefix_len = info_print_prefix(info, syslog, time, prefix);
1579
1580         /*
1581          * Each line will be preceded with a prefix. The intermediate
1582          * newlines are already within the text, but a final trailing
1583          * newline will be added.
1584          */
1585         return ((prefix_len * line_count) + info->text_len + 1);
1586 }
1587
1588 /*
1589  * Beginning with @start_seq, find the first record where it and all following
1590  * records up to (but not including) @max_seq fit into @size.
1591  *
1592  * @max_seq is simply an upper bound and does not need to exist. If the caller
1593  * does not require an upper bound, -1 can be used for @max_seq.
1594  */
1595 static u64 find_first_fitting_seq(u64 start_seq, u64 max_seq, size_t size,
1596                                   bool syslog, bool time)
1597 {
1598         struct printk_info info;
1599         unsigned int line_count;
1600         size_t len = 0;
1601         u64 seq;
1602
1603         /* Determine the size of the records up to @max_seq. */
1604         prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1605                 if (info.seq >= max_seq)
1606                         break;
1607                 len += get_record_print_text_size(&info, line_count, syslog, time);
1608         }
1609
1610         /*
1611          * Adjust the upper bound for the next loop to avoid subtracting
1612          * lengths that were never added.
1613          */
1614         if (seq < max_seq)
1615                 max_seq = seq;
1616
1617         /*
1618          * Move first record forward until length fits into the buffer. Ignore
1619          * newest messages that were not counted in the above cycle. Messages
1620          * might appear and get lost in the meantime. This is a best effort
1621          * that prevents an infinite loop that could occur with a retry.
1622          */
1623         prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
1624                 if (len <= size || info.seq >= max_seq)
1625                         break;
1626                 len -= get_record_print_text_size(&info, line_count, syslog, time);
1627         }
1628
1629         return seq;
1630 }
1631
1632 /* The caller is responsible for making sure @size is greater than 0. */
1633 static int syslog_print(char __user *buf, int size)
1634 {
1635         struct printk_info info;
1636         struct printk_record r;
1637         char *text;
1638         int len = 0;
1639         u64 seq;
1640
1641         text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
1642         if (!text)
1643                 return -ENOMEM;
1644
1645         prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
1646
1647         mutex_lock(&syslog_lock);
1648
1649         /*
1650          * Wait for the @syslog_seq record to be available. @syslog_seq may
1651          * change while waiting.
1652          */
1653         do {
1654                 seq = syslog_seq;
1655
1656                 mutex_unlock(&syslog_lock);
1657                 /*
1658                  * Guarantee this task is visible on the waitqueue before
1659                  * checking the wake condition.
1660                  *
1661                  * The full memory barrier within set_current_state() of
1662                  * prepare_to_wait_event() pairs with the full memory barrier
1663                  * within wq_has_sleeper().
1664                  *
1665                  * This pairs with __wake_up_klogd:A.
1666                  */
1667                 len = wait_event_interruptible(log_wait,
1668                                 prb_read_valid(prb, seq, NULL)); /* LMM(syslog_print:A) */
1669                 mutex_lock(&syslog_lock);
1670
1671                 if (len)
1672                         goto out;
1673         } while (syslog_seq != seq);
1674
1675         /*
1676          * Copy records that fit into the buffer. The above cycle makes sure
1677          * that the first record is always available.
1678          */
1679         do {
1680                 size_t n;
1681                 size_t skip;
1682                 int err;
1683
1684                 if (!prb_read_valid(prb, syslog_seq, &r))
1685                         break;
1686
1687                 if (r.info->seq != syslog_seq) {
1688                         /* message is gone, move to next valid one */
1689                         syslog_seq = r.info->seq;
1690                         syslog_partial = 0;
1691                 }
1692
1693                 /*
1694                  * To keep reading/counting partial line consistent,
1695                  * use printk_time value as of the beginning of a line.
1696                  */
1697                 if (!syslog_partial)
1698                         syslog_time = printk_time;
1699
1700                 skip = syslog_partial;
1701                 n = record_print_text(&r, true, syslog_time);
1702                 if (n - syslog_partial <= size) {
1703                         /* message fits into buffer, move forward */
1704                         syslog_seq = r.info->seq + 1;
1705                         n -= syslog_partial;
1706                         syslog_partial = 0;
1707                 } else if (!len){
1708                         /* partial read(), remember position */
1709                         n = size;
1710                         syslog_partial += n;
1711                 } else
1712                         n = 0;
1713
1714                 if (!n)
1715                         break;
1716
1717                 mutex_unlock(&syslog_lock);
1718                 err = copy_to_user(buf, text + skip, n);
1719                 mutex_lock(&syslog_lock);
1720
1721                 if (err) {
1722                         if (!len)
1723                                 len = -EFAULT;
1724                         break;
1725                 }
1726
1727                 len += n;
1728                 size -= n;
1729                 buf += n;
1730         } while (size);
1731 out:
1732         mutex_unlock(&syslog_lock);
1733         kfree(text);
1734         return len;
1735 }
1736
1737 static int syslog_print_all(char __user *buf, int size, bool clear)
1738 {
1739         struct printk_info info;
1740         struct printk_record r;
1741         char *text;
1742         int len = 0;
1743         u64 seq;
1744         bool time;
1745
1746         text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
1747         if (!text)
1748                 return -ENOMEM;
1749
1750         time = printk_time;
1751         /*
1752          * Find first record that fits, including all following records,
1753          * into the user-provided buffer for this dump.
1754          */
1755         seq = find_first_fitting_seq(latched_seq_read_nolock(&clear_seq), -1,
1756                                      size, true, time);
1757
1758         prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
1759
1760         len = 0;
1761         prb_for_each_record(seq, prb, seq, &r) {
1762                 int textlen;
1763
1764                 textlen = record_print_text(&r, true, time);
1765
1766                 if (len + textlen > size) {
1767                         seq--;
1768                         break;
1769                 }
1770
1771                 if (copy_to_user(buf + len, text, textlen))
1772                         len = -EFAULT;
1773                 else
1774                         len += textlen;
1775
1776                 if (len < 0)
1777                         break;
1778         }
1779
1780         if (clear) {
1781                 mutex_lock(&syslog_lock);
1782                 latched_seq_write(&clear_seq, seq);
1783                 mutex_unlock(&syslog_lock);
1784         }
1785
1786         kfree(text);
1787         return len;
1788 }
1789
1790 static void syslog_clear(void)
1791 {
1792         mutex_lock(&syslog_lock);
1793         latched_seq_write(&clear_seq, prb_next_seq(prb));
1794         mutex_unlock(&syslog_lock);
1795 }
1796
1797 int do_syslog(int type, char __user *buf, int len, int source)
1798 {
1799         struct printk_info info;
1800         bool clear = false;
1801         static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1802         int error;
1803
1804         error = check_syslog_permissions(type, source);
1805         if (error)
1806                 return error;
1807
1808         switch (type) {
1809         case SYSLOG_ACTION_CLOSE:       /* Close log */
1810                 break;
1811         case SYSLOG_ACTION_OPEN:        /* Open log */
1812                 break;
1813         case SYSLOG_ACTION_READ:        /* Read from log */
1814                 if (!buf || len < 0)
1815                         return -EINVAL;
1816                 if (!len)
1817                         return 0;
1818                 if (!access_ok(buf, len))
1819                         return -EFAULT;
1820                 error = syslog_print(buf, len);
1821                 break;
1822         /* Read/clear last kernel messages */
1823         case SYSLOG_ACTION_READ_CLEAR:
1824                 clear = true;
1825                 fallthrough;
1826         /* Read last kernel messages */
1827         case SYSLOG_ACTION_READ_ALL:
1828                 if (!buf || len < 0)
1829                         return -EINVAL;
1830                 if (!len)
1831                         return 0;
1832                 if (!access_ok(buf, len))
1833                         return -EFAULT;
1834                 error = syslog_print_all(buf, len, clear);
1835                 break;
1836         /* Clear ring buffer */
1837         case SYSLOG_ACTION_CLEAR:
1838                 syslog_clear();
1839                 break;
1840         /* Disable logging to console */
1841         case SYSLOG_ACTION_CONSOLE_OFF:
1842                 if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1843                         saved_console_loglevel = console_loglevel;
1844                 console_loglevel = minimum_console_loglevel;
1845                 break;
1846         /* Enable logging to console */
1847         case SYSLOG_ACTION_CONSOLE_ON:
1848                 if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1849                         console_loglevel = saved_console_loglevel;
1850                         saved_console_loglevel = LOGLEVEL_DEFAULT;
1851                 }
1852                 break;
1853         /* Set level of messages printed to console */
1854         case SYSLOG_ACTION_CONSOLE_LEVEL:
1855                 if (len < 1 || len > 8)
1856                         return -EINVAL;
1857                 if (len < minimum_console_loglevel)
1858                         len = minimum_console_loglevel;
1859                 console_loglevel = len;
1860                 /* Implicitly re-enable logging to console */
1861                 saved_console_loglevel = LOGLEVEL_DEFAULT;
1862                 break;
1863         /* Number of chars in the log buffer */
1864         case SYSLOG_ACTION_SIZE_UNREAD:
1865                 mutex_lock(&syslog_lock);
1866                 if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1867                         /* No unread messages. */
1868                         mutex_unlock(&syslog_lock);
1869                         return 0;
1870                 }
1871                 if (info.seq != syslog_seq) {
1872                         /* messages are gone, move to first one */
1873                         syslog_seq = info.seq;
1874                         syslog_partial = 0;
1875                 }
1876                 if (source == SYSLOG_FROM_PROC) {
1877                         /*
1878                          * Short-cut for poll(/"proc/kmsg") which simply checks
1879                          * for pending data, not the size; return the count of
1880                          * records, not the length.
1881                          */
1882                         error = prb_next_seq(prb) - syslog_seq;
1883                 } else {
1884                         bool time = syslog_partial ? syslog_time : printk_time;
1885                         unsigned int line_count;
1886                         u64 seq;
1887
1888                         prb_for_each_info(syslog_seq, prb, seq, &info,
1889                                           &line_count) {
1890                                 error += get_record_print_text_size(&info, line_count,
1891                                                                     true, time);
1892                                 time = printk_time;
1893                         }
1894                         error -= syslog_partial;
1895                 }
1896                 mutex_unlock(&syslog_lock);
1897                 break;
1898         /* Size of the log buffer */
1899         case SYSLOG_ACTION_SIZE_BUFFER:
1900                 error = log_buf_len;
1901                 break;
1902         default:
1903                 error = -EINVAL;
1904                 break;
1905         }
1906
1907         return error;
1908 }
1909
1910 SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1911 {
1912         return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1913 }
1914
1915 /*
1916  * Special console_lock variants that help to reduce the risk of soft-lockups.
1917  * They allow to pass console_lock to another printk() call using a busy wait.
1918  */
1919
1920 #ifdef CONFIG_LOCKDEP
1921 static struct lockdep_map console_owner_dep_map = {
1922         .name = "console_owner"
1923 };
1924 #endif
1925
1926 static DEFINE_RAW_SPINLOCK(console_owner_lock);
1927 static struct task_struct *console_owner;
1928 static bool console_waiter;
1929
1930 /**
1931  * console_lock_spinning_enable - mark beginning of code where another
1932  *      thread might safely busy wait
1933  *
1934  * This basically converts console_lock into a spinlock. This marks
1935  * the section where the console_lock owner can not sleep, because
1936  * there may be a waiter spinning (like a spinlock). Also it must be
1937  * ready to hand over the lock at the end of the section.
1938  */
1939 static void console_lock_spinning_enable(void)
1940 {
1941         raw_spin_lock(&console_owner_lock);
1942         console_owner = current;
1943         raw_spin_unlock(&console_owner_lock);
1944
1945         /* The waiter may spin on us after setting console_owner */
1946         spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1947 }
1948
1949 /**
1950  * console_lock_spinning_disable_and_check - mark end of code where another
1951  *      thread was able to busy wait and check if there is a waiter
1952  *
1953  * This is called at the end of the section where spinning is allowed.
1954  * It has two functions. First, it is a signal that it is no longer
1955  * safe to start busy waiting for the lock. Second, it checks if
1956  * there is a busy waiter and passes the lock rights to her.
1957  *
1958  * Important: Callers lose the lock if there was a busy waiter.
1959  *      They must not touch items synchronized by console_lock
1960  *      in this case.
1961  *
1962  * Return: 1 if the lock rights were passed, 0 otherwise.
1963  */
1964 static int console_lock_spinning_disable_and_check(void)
1965 {
1966         int waiter;
1967
1968         raw_spin_lock(&console_owner_lock);
1969         waiter = READ_ONCE(console_waiter);
1970         console_owner = NULL;
1971         raw_spin_unlock(&console_owner_lock);
1972
1973         if (!waiter) {
1974                 spin_release(&console_owner_dep_map, _THIS_IP_);
1975                 return 0;
1976         }
1977
1978         /* The waiter is now free to continue */
1979         WRITE_ONCE(console_waiter, false);
1980
1981         spin_release(&console_owner_dep_map, _THIS_IP_);
1982
1983         /*
1984          * Hand off console_lock to waiter. The waiter will perform
1985          * the up(). After this, the waiter is the console_lock owner.
1986          */
1987         mutex_release(&console_lock_dep_map, _THIS_IP_);
1988         return 1;
1989 }
1990
1991 /**
1992  * console_trylock_spinning - try to get console_lock by busy waiting
1993  *
1994  * This allows to busy wait for the console_lock when the current
1995  * owner is running in specially marked sections. It means that
1996  * the current owner is running and cannot reschedule until it
1997  * is ready to lose the lock.
1998  *
1999  * Return: 1 if we got the lock, 0 othrewise
2000  */
2001 static int console_trylock_spinning(void)
2002 {
2003         struct task_struct *owner = NULL;
2004         bool waiter;
2005         bool spin = false;
2006         unsigned long flags;
2007
2008         if (console_trylock())
2009                 return 1;
2010
2011         /*
2012          * It's unsafe to spin once a panic has begun. If we are the
2013          * panic CPU, we may have already halted the owner of the
2014          * console_sem. If we are not the panic CPU, then we should
2015          * avoid taking console_sem, so the panic CPU has a better
2016          * chance of cleanly acquiring it later.
2017          */
2018         if (panic_in_progress())
2019                 return 0;
2020
2021         printk_safe_enter_irqsave(flags);
2022
2023         raw_spin_lock(&console_owner_lock);
2024         owner = READ_ONCE(console_owner);
2025         waiter = READ_ONCE(console_waiter);
2026         if (!waiter && owner && owner != current) {
2027                 WRITE_ONCE(console_waiter, true);
2028                 spin = true;
2029         }
2030         raw_spin_unlock(&console_owner_lock);
2031
2032         /*
2033          * If there is an active printk() writing to the
2034          * consoles, instead of having it write our data too,
2035          * see if we can offload that load from the active
2036          * printer, and do some printing ourselves.
2037          * Go into a spin only if there isn't already a waiter
2038          * spinning, and there is an active printer, and
2039          * that active printer isn't us (recursive printk?).
2040          */
2041         if (!spin) {
2042                 printk_safe_exit_irqrestore(flags);
2043                 return 0;
2044         }
2045
2046         /* We spin waiting for the owner to release us */
2047         spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
2048         /* Owner will clear console_waiter on hand off */
2049         while (READ_ONCE(console_waiter))
2050                 cpu_relax();
2051         spin_release(&console_owner_dep_map, _THIS_IP_);
2052
2053         printk_safe_exit_irqrestore(flags);
2054         /*
2055          * The owner passed the console lock to us.
2056          * Since we did not spin on console lock, annotate
2057          * this as a trylock. Otherwise lockdep will
2058          * complain.
2059          */
2060         mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
2061
2062         return 1;
2063 }
2064
2065 /*
2066  * Call the specified console driver, asking it to write out the specified
2067  * text and length. If @dropped_text is non-NULL and any records have been
2068  * dropped, a dropped message will be written out first.
2069  */
2070 static void call_console_driver(struct console *con, const char *text, size_t len,
2071                                 char *dropped_text)
2072 {
2073         size_t dropped_len;
2074
2075         if (con->dropped && dropped_text) {
2076                 dropped_len = snprintf(dropped_text, DROPPED_TEXT_MAX,
2077                                        "** %lu printk messages dropped **\n",
2078                                        con->dropped);
2079                 con->dropped = 0;
2080                 con->write(con, dropped_text, dropped_len);
2081         }
2082
2083         con->write(con, text, len);
2084 }
2085
2086 /*
2087  * Recursion is tracked separately on each CPU. If NMIs are supported, an
2088  * additional NMI context per CPU is also separately tracked. Until per-CPU
2089  * is available, a separate "early tracking" is performed.
2090  */
2091 static DEFINE_PER_CPU(u8, printk_count);
2092 static u8 printk_count_early;
2093 #ifdef CONFIG_HAVE_NMI
2094 static DEFINE_PER_CPU(u8, printk_count_nmi);
2095 static u8 printk_count_nmi_early;
2096 #endif
2097
2098 /*
2099  * Recursion is limited to keep the output sane. printk() should not require
2100  * more than 1 level of recursion (allowing, for example, printk() to trigger
2101  * a WARN), but a higher value is used in case some printk-internal errors
2102  * exist, such as the ringbuffer validation checks failing.
2103  */
2104 #define PRINTK_MAX_RECURSION 3
2105
2106 /*
2107  * Return a pointer to the dedicated counter for the CPU+context of the
2108  * caller.
2109  */
2110 static u8 *__printk_recursion_counter(void)
2111 {
2112 #ifdef CONFIG_HAVE_NMI
2113         if (in_nmi()) {
2114                 if (printk_percpu_data_ready())
2115                         return this_cpu_ptr(&printk_count_nmi);
2116                 return &printk_count_nmi_early;
2117         }
2118 #endif
2119         if (printk_percpu_data_ready())
2120                 return this_cpu_ptr(&printk_count);
2121         return &printk_count_early;
2122 }
2123
2124 /*
2125  * Enter recursion tracking. Interrupts are disabled to simplify tracking.
2126  * The caller must check the boolean return value to see if the recursion is
2127  * allowed. On failure, interrupts are not disabled.
2128  *
2129  * @recursion_ptr must be a variable of type (u8 *) and is the same variable
2130  * that is passed to printk_exit_irqrestore().
2131  */
2132 #define printk_enter_irqsave(recursion_ptr, flags)      \
2133 ({                                                      \
2134         bool success = true;                            \
2135                                                         \
2136         typecheck(u8 *, recursion_ptr);                 \
2137         local_irq_save(flags);                          \
2138         (recursion_ptr) = __printk_recursion_counter(); \
2139         if (*(recursion_ptr) > PRINTK_MAX_RECURSION) {  \
2140                 local_irq_restore(flags);               \
2141                 success = false;                        \
2142         } else {                                        \
2143                 (*(recursion_ptr))++;                   \
2144         }                                               \
2145         success;                                        \
2146 })
2147
2148 /* Exit recursion tracking, restoring interrupts. */
2149 #define printk_exit_irqrestore(recursion_ptr, flags)    \
2150         do {                                            \
2151                 typecheck(u8 *, recursion_ptr);         \
2152                 (*(recursion_ptr))--;                   \
2153                 local_irq_restore(flags);               \
2154         } while (0)
2155
2156 int printk_delay_msec __read_mostly;
2157
2158 static inline void printk_delay(int level)
2159 {
2160         boot_delay_msec(level);
2161
2162         if (unlikely(printk_delay_msec)) {
2163                 int m = printk_delay_msec;
2164
2165                 while (m--) {
2166                         mdelay(1);
2167                         touch_nmi_watchdog();
2168                 }
2169         }
2170 }
2171
2172 static inline u32 printk_caller_id(void)
2173 {
2174         return in_task() ? task_pid_nr(current) :
2175                 0x80000000 + smp_processor_id();
2176 }
2177
2178 /**
2179  * printk_parse_prefix - Parse level and control flags.
2180  *
2181  * @text:     The terminated text message.
2182  * @level:    A pointer to the current level value, will be updated.
2183  * @flags:    A pointer to the current printk_info flags, will be updated.
2184  *
2185  * @level may be NULL if the caller is not interested in the parsed value.
2186  * Otherwise the variable pointed to by @level must be set to
2187  * LOGLEVEL_DEFAULT in order to be updated with the parsed value.
2188  *
2189  * @flags may be NULL if the caller is not interested in the parsed value.
2190  * Otherwise the variable pointed to by @flags will be OR'd with the parsed
2191  * value.
2192  *
2193  * Return: The length of the parsed level and control flags.
2194  */
2195 u16 printk_parse_prefix(const char *text, int *level,
2196                         enum printk_info_flags *flags)
2197 {
2198         u16 prefix_len = 0;
2199         int kern_level;
2200
2201         while (*text) {
2202                 kern_level = printk_get_level(text);
2203                 if (!kern_level)
2204                         break;
2205
2206                 switch (kern_level) {
2207                 case '0' ... '7':
2208                         if (level && *level == LOGLEVEL_DEFAULT)
2209                                 *level = kern_level - '0';
2210                         break;
2211                 case 'c':       /* KERN_CONT */
2212                         if (flags)
2213                                 *flags |= LOG_CONT;
2214                 }
2215
2216                 prefix_len += 2;
2217                 text += 2;
2218         }
2219
2220         return prefix_len;
2221 }
2222
2223 __printf(5, 0)
2224 static u16 printk_sprint(char *text, u16 size, int facility,
2225                          enum printk_info_flags *flags, const char *fmt,
2226                          va_list args)
2227 {
2228         u16 text_len;
2229
2230         text_len = vscnprintf(text, size, fmt, args);
2231
2232         /* Mark and strip a trailing newline. */
2233         if (text_len && text[text_len - 1] == '\n') {
2234                 text_len--;
2235                 *flags |= LOG_NEWLINE;
2236         }
2237
2238         /* Strip log level and control flags. */
2239         if (facility == 0) {
2240                 u16 prefix_len;
2241
2242                 prefix_len = printk_parse_prefix(text, NULL, NULL);
2243                 if (prefix_len) {
2244                         text_len -= prefix_len;
2245                         memmove(text, text + prefix_len, text_len);
2246                 }
2247         }
2248
2249         trace_console_rcuidle(text, text_len);
2250
2251         return text_len;
2252 }
2253
2254 __printf(4, 0)
2255 int vprintk_store(int facility, int level,
2256                   const struct dev_printk_info *dev_info,
2257                   const char *fmt, va_list args)
2258 {
2259         struct prb_reserved_entry e;
2260         enum printk_info_flags flags = 0;
2261         struct printk_record r;
2262         unsigned long irqflags;
2263         u16 trunc_msg_len = 0;
2264         char prefix_buf[8];
2265         u8 *recursion_ptr;
2266         u16 reserve_size;
2267         va_list args2;
2268         u32 caller_id;
2269         u16 text_len;
2270         int ret = 0;
2271         u64 ts_nsec;
2272
2273         if (!printk_enter_irqsave(recursion_ptr, irqflags))
2274                 return 0;
2275
2276         /*
2277          * Since the duration of printk() can vary depending on the message
2278          * and state of the ringbuffer, grab the timestamp now so that it is
2279          * close to the call of printk(). This provides a more deterministic
2280          * timestamp with respect to the caller.
2281          */
2282         ts_nsec = local_clock();
2283
2284         caller_id = printk_caller_id();
2285
2286         /*
2287          * The sprintf needs to come first since the syslog prefix might be
2288          * passed in as a parameter. An extra byte must be reserved so that
2289          * later the vscnprintf() into the reserved buffer has room for the
2290          * terminating '\0', which is not counted by vsnprintf().
2291          */
2292         va_copy(args2, args);
2293         reserve_size = vsnprintf(&prefix_buf[0], sizeof(prefix_buf), fmt, args2) + 1;
2294         va_end(args2);
2295
2296         if (reserve_size > LOG_LINE_MAX)
2297                 reserve_size = LOG_LINE_MAX;
2298
2299         /* Extract log level or control flags. */
2300         if (facility == 0)
2301                 printk_parse_prefix(&prefix_buf[0], &level, &flags);
2302
2303         if (level == LOGLEVEL_DEFAULT)
2304                 level = default_message_loglevel;
2305
2306         if (dev_info)
2307                 flags |= LOG_NEWLINE;
2308
2309         if (flags & LOG_CONT) {
2310                 prb_rec_init_wr(&r, reserve_size);
2311                 if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
2312                         text_len = printk_sprint(&r.text_buf[r.info->text_len], reserve_size,
2313                                                  facility, &flags, fmt, args);
2314                         r.info->text_len += text_len;
2315
2316                         if (flags & LOG_NEWLINE) {
2317                                 r.info->flags |= LOG_NEWLINE;
2318                                 prb_final_commit(&e);
2319                         } else {
2320                                 prb_commit(&e);
2321                         }
2322
2323                         ret = text_len;
2324                         goto out;
2325                 }
2326         }
2327
2328         /*
2329          * Explicitly initialize the record before every prb_reserve() call.
2330          * prb_reserve_in_last() and prb_reserve() purposely invalidate the
2331          * structure when they fail.
2332          */
2333         prb_rec_init_wr(&r, reserve_size);
2334         if (!prb_reserve(&e, prb, &r)) {
2335                 /* truncate the message if it is too long for empty buffer */
2336                 truncate_msg(&reserve_size, &trunc_msg_len);
2337
2338                 prb_rec_init_wr(&r, reserve_size + trunc_msg_len);
2339                 if (!prb_reserve(&e, prb, &r))
2340                         goto out;
2341         }
2342
2343         /* fill message */
2344         text_len = printk_sprint(&r.text_buf[0], reserve_size, facility, &flags, fmt, args);
2345         if (trunc_msg_len)
2346                 memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
2347         r.info->text_len = text_len + trunc_msg_len;
2348         r.info->facility = facility;
2349         r.info->level = level & 7;
2350         r.info->flags = flags & 0x1f;
2351         r.info->ts_nsec = ts_nsec;
2352         r.info->caller_id = caller_id;
2353         if (dev_info)
2354                 memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
2355
2356         /* A message without a trailing newline can be continued. */
2357         if (!(flags & LOG_NEWLINE))
2358                 prb_commit(&e);
2359         else
2360                 prb_final_commit(&e);
2361
2362         ret = text_len + trunc_msg_len;
2363 out:
2364         printk_exit_irqrestore(recursion_ptr, irqflags);
2365         return ret;
2366 }
2367
2368 asmlinkage int vprintk_emit(int facility, int level,
2369                             const struct dev_printk_info *dev_info,
2370                             const char *fmt, va_list args)
2371 {
2372         int printed_len;
2373         bool in_sched = false;
2374
2375         /* Suppress unimportant messages after panic happens */
2376         if (unlikely(suppress_printk))
2377                 return 0;
2378
2379         if (unlikely(suppress_panic_printk) &&
2380             atomic_read(&panic_cpu) != raw_smp_processor_id())
2381                 return 0;
2382
2383         if (level == LOGLEVEL_SCHED) {
2384                 level = LOGLEVEL_DEFAULT;
2385                 in_sched = true;
2386         }
2387
2388         printk_delay(level);
2389
2390         printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2391
2392         /* If called from the scheduler, we can not call up(). */
2393         if (!in_sched && allow_direct_printing()) {
2394                 /*
2395                  * The caller may be holding system-critical or
2396                  * timing-sensitive locks. Disable preemption during direct
2397                  * printing of all remaining records to all consoles so that
2398                  * this context can return as soon as possible. Hopefully
2399                  * another printk() caller will take over the printing.
2400                  */
2401                 preempt_disable();
2402                 /*
2403                  * Try to acquire and then immediately release the console
2404                  * semaphore. The release will print out buffers. With the
2405                  * spinning variant, this context tries to take over the
2406                  * printing from another printing context.
2407                  */
2408                 if (console_trylock_spinning())
2409                         console_unlock();
2410                 preempt_enable();
2411         }
2412
2413         wake_up_klogd();
2414         return printed_len;
2415 }
2416 EXPORT_SYMBOL(vprintk_emit);
2417
2418 int vprintk_default(const char *fmt, va_list args)
2419 {
2420         return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2421 }
2422 EXPORT_SYMBOL_GPL(vprintk_default);
2423
2424 asmlinkage __visible int _printk(const char *fmt, ...)
2425 {
2426         va_list args;
2427         int r;
2428
2429         va_start(args, fmt);
2430         r = vprintk(fmt, args);
2431         va_end(args);
2432
2433         return r;
2434 }
2435 EXPORT_SYMBOL(_printk);
2436
2437 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress);
2438
2439 static void printk_start_kthread(struct console *con);
2440
2441 #else /* CONFIG_PRINTK */
2442
2443 #define CONSOLE_LOG_MAX         0
2444 #define DROPPED_TEXT_MAX        0
2445 #define printk_time             false
2446
2447 #define prb_read_valid(rb, seq, r)      false
2448 #define prb_first_valid_seq(rb)         0
2449 #define prb_next_seq(rb)                0
2450
2451 static u64 syslog_seq;
2452
2453 static size_t record_print_text(const struct printk_record *r,
2454                                 bool syslog, bool time)
2455 {
2456         return 0;
2457 }
2458 static ssize_t info_print_ext_header(char *buf, size_t size,
2459                                      struct printk_info *info)
2460 {
2461         return 0;
2462 }
2463 static ssize_t msg_print_ext_body(char *buf, size_t size,
2464                                   char *text, size_t text_len,
2465                                   struct dev_printk_info *dev_info) { return 0; }
2466 static void console_lock_spinning_enable(void) { }
2467 static int console_lock_spinning_disable_and_check(void) { return 0; }
2468 static void call_console_driver(struct console *con, const char *text, size_t len,
2469                                 char *dropped_text)
2470 {
2471 }
2472 static bool suppress_message_printing(int level) { return false; }
2473 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress) { return true; }
2474 static void printk_start_kthread(struct console *con) { }
2475 static bool allow_direct_printing(void) { return true; }
2476
2477 #endif /* CONFIG_PRINTK */
2478
2479 #ifdef CONFIG_EARLY_PRINTK
2480 struct console *early_console;
2481
2482 asmlinkage __visible void early_printk(const char *fmt, ...)
2483 {
2484         va_list ap;
2485         char buf[512];
2486         int n;
2487
2488         if (!early_console)
2489                 return;
2490
2491         va_start(ap, fmt);
2492         n = vscnprintf(buf, sizeof(buf), fmt, ap);
2493         va_end(ap);
2494
2495         early_console->write(early_console, buf, n);
2496 }
2497 #endif
2498
2499 static void set_user_specified(struct console_cmdline *c, bool user_specified)
2500 {
2501         if (!user_specified)
2502                 return;
2503
2504         /*
2505          * @c console was defined by the user on the command line.
2506          * Do not clear when added twice also by SPCR or the device tree.
2507          */
2508         c->user_specified = true;
2509         /* At least one console defined by the user on the command line. */
2510         console_set_on_cmdline = 1;
2511 }
2512
2513 static int __add_preferred_console(char *name, int idx, char *options,
2514                                    char *brl_options, bool user_specified)
2515 {
2516         struct console_cmdline *c;
2517         int i;
2518
2519         /*
2520          *      See if this tty is not yet registered, and
2521          *      if we have a slot free.
2522          */
2523         for (i = 0, c = console_cmdline;
2524              i < MAX_CMDLINECONSOLES && c->name[0];
2525              i++, c++) {
2526                 if (strcmp(c->name, name) == 0 && c->index == idx) {
2527                         if (!brl_options)
2528                                 preferred_console = i;
2529                         set_user_specified(c, user_specified);
2530                         return 0;
2531                 }
2532         }
2533         if (i == MAX_CMDLINECONSOLES)
2534                 return -E2BIG;
2535         if (!brl_options)
2536                 preferred_console = i;
2537         strlcpy(c->name, name, sizeof(c->name));
2538         c->options = options;
2539         set_user_specified(c, user_specified);
2540         braille_set_options(c, brl_options);
2541
2542         c->index = idx;
2543         return 0;
2544 }
2545
2546 static int __init console_msg_format_setup(char *str)
2547 {
2548         if (!strcmp(str, "syslog"))
2549                 console_msg_format = MSG_FORMAT_SYSLOG;
2550         if (!strcmp(str, "default"))
2551                 console_msg_format = MSG_FORMAT_DEFAULT;
2552         return 1;
2553 }
2554 __setup("console_msg_format=", console_msg_format_setup);
2555
2556 /*
2557  * Set up a console.  Called via do_early_param() in init/main.c
2558  * for each "console=" parameter in the boot command line.
2559  */
2560 static int __init console_setup(char *str)
2561 {
2562         char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2563         char *s, *options, *brl_options = NULL;
2564         int idx;
2565
2566         /*
2567          * console="" or console=null have been suggested as a way to
2568          * disable console output. Use ttynull that has been created
2569          * for exactly this purpose.
2570          */
2571         if (str[0] == 0 || strcmp(str, "null") == 0) {
2572                 __add_preferred_console("ttynull", 0, NULL, NULL, true);
2573                 return 1;
2574         }
2575
2576         if (_braille_console_setup(&str, &brl_options))
2577                 return 1;
2578
2579         /*
2580          * Decode str into name, index, options.
2581          */
2582         if (str[0] >= '0' && str[0] <= '9') {
2583                 strcpy(buf, "ttyS");
2584                 strncpy(buf + 4, str, sizeof(buf) - 5);
2585         } else {
2586                 strncpy(buf, str, sizeof(buf) - 1);
2587         }
2588         buf[sizeof(buf) - 1] = 0;
2589         options = strchr(str, ',');
2590         if (options)
2591                 *(options++) = 0;
2592 #ifdef __sparc__
2593         if (!strcmp(str, "ttya"))
2594                 strcpy(buf, "ttyS0");
2595         if (!strcmp(str, "ttyb"))
2596                 strcpy(buf, "ttyS1");
2597 #endif
2598         for (s = buf; *s; s++)
2599                 if (isdigit(*s) || *s == ',')
2600                         break;
2601         idx = simple_strtoul(s, NULL, 10);
2602         *s = 0;
2603
2604         __add_preferred_console(buf, idx, options, brl_options, true);
2605         return 1;
2606 }
2607 __setup("console=", console_setup);
2608
2609 /**
2610  * add_preferred_console - add a device to the list of preferred consoles.
2611  * @name: device name
2612  * @idx: device index
2613  * @options: options for this console
2614  *
2615  * The last preferred console added will be used for kernel messages
2616  * and stdin/out/err for init.  Normally this is used by console_setup
2617  * above to handle user-supplied console arguments; however it can also
2618  * be used by arch-specific code either to override the user or more
2619  * commonly to provide a default console (ie from PROM variables) when
2620  * the user has not supplied one.
2621  */
2622 int add_preferred_console(char *name, int idx, char *options)
2623 {
2624         return __add_preferred_console(name, idx, options, NULL, false);
2625 }
2626
2627 bool console_suspend_enabled = true;
2628 EXPORT_SYMBOL(console_suspend_enabled);
2629
2630 static int __init console_suspend_disable(char *str)
2631 {
2632         console_suspend_enabled = false;
2633         return 1;
2634 }
2635 __setup("no_console_suspend", console_suspend_disable);
2636 module_param_named(console_suspend, console_suspend_enabled,
2637                 bool, S_IRUGO | S_IWUSR);
2638 MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2639         " and hibernate operations");
2640
2641 static bool printk_console_no_auto_verbose;
2642
2643 void console_verbose(void)
2644 {
2645         if (console_loglevel && !printk_console_no_auto_verbose)
2646                 console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
2647 }
2648 EXPORT_SYMBOL_GPL(console_verbose);
2649
2650 module_param_named(console_no_auto_verbose, printk_console_no_auto_verbose, bool, 0644);
2651 MODULE_PARM_DESC(console_no_auto_verbose, "Disable console loglevel raise to highest on oops/panic/etc");
2652
2653 /**
2654  * suspend_console - suspend the console subsystem
2655  *
2656  * This disables printk() while we go into suspend states
2657  */
2658 void suspend_console(void)
2659 {
2660         if (!console_suspend_enabled)
2661                 return;
2662         pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2663         pr_flush(1000, true);
2664         console_lock();
2665         console_suspended = 1;
2666         up_console_sem();
2667 }
2668
2669 void resume_console(void)
2670 {
2671         if (!console_suspend_enabled)
2672                 return;
2673         down_console_sem();
2674         console_suspended = 0;
2675         console_unlock();
2676         pr_flush(1000, true);
2677 }
2678
2679 /**
2680  * console_cpu_notify - print deferred console messages after CPU hotplug
2681  * @cpu: unused
2682  *
2683  * If printk() is called from a CPU that is not online yet, the messages
2684  * will be printed on the console only if there are CON_ANYTIME consoles.
2685  * This function is called when a new CPU comes online (or fails to come
2686  * up) or goes offline.
2687  */
2688 static int console_cpu_notify(unsigned int cpu)
2689 {
2690         if (!cpuhp_tasks_frozen) {
2691                 /* If trylock fails, someone else is doing the printing */
2692                 if (console_trylock())
2693                         console_unlock();
2694                 else {
2695                         /*
2696                          * If a new CPU comes online, the conditions for
2697                          * printer_should_wake() may have changed for some
2698                          * kthread printer with !CON_ANYTIME.
2699                          */
2700                         wake_up_klogd();
2701                 }
2702         }
2703         return 0;
2704 }
2705
2706 /**
2707  * console_lock - lock the console system for exclusive use.
2708  *
2709  * Acquires a lock which guarantees that the caller has
2710  * exclusive access to the console system and the console_drivers list.
2711  *
2712  * Can sleep, returns nothing.
2713  */
2714 void console_lock(void)
2715 {
2716         might_sleep();
2717
2718         down_console_sem();
2719         if (console_suspended)
2720                 return;
2721         console_kthreads_block();
2722         console_locked = 1;
2723         console_may_schedule = 1;
2724 }
2725 EXPORT_SYMBOL(console_lock);
2726
2727 /**
2728  * console_trylock - try to lock the console system for exclusive use.
2729  *
2730  * Try to acquire a lock which guarantees that the caller has exclusive
2731  * access to the console system and the console_drivers list.
2732  *
2733  * returns 1 on success, and 0 on failure to acquire the lock.
2734  */
2735 int console_trylock(void)
2736 {
2737         if (down_trylock_console_sem())
2738                 return 0;
2739         if (console_suspended) {
2740                 up_console_sem();
2741                 return 0;
2742         }
2743         if (!console_kthreads_atomic_tryblock()) {
2744                 up_console_sem();
2745                 return 0;
2746         }
2747         console_locked = 1;
2748         console_may_schedule = 0;
2749         return 1;
2750 }
2751 EXPORT_SYMBOL(console_trylock);
2752
2753 int is_console_locked(void)
2754 {
2755         return (console_locked || atomic_read(&console_kthreads_active));
2756 }
2757 EXPORT_SYMBOL(is_console_locked);
2758
2759 /*
2760  * Return true when this CPU should unlock console_sem without pushing all
2761  * messages to the console. This reduces the chance that the console is
2762  * locked when the panic CPU tries to use it.
2763  */
2764 static bool abandon_console_lock_in_panic(void)
2765 {
2766         if (!panic_in_progress())
2767                 return false;
2768
2769         /*
2770          * We can use raw_smp_processor_id() here because it is impossible for
2771          * the task to be migrated to the panic_cpu, or away from it. If
2772          * panic_cpu has already been set, and we're not currently executing on
2773          * that CPU, then we never will be.
2774          */
2775         return atomic_read(&panic_cpu) != raw_smp_processor_id();
2776 }
2777
2778 static inline bool __console_is_usable(short flags)
2779 {
2780         if (!(flags & CON_ENABLED))
2781                 return false;
2782
2783         /*
2784          * Console drivers may assume that per-cpu resources have been
2785          * allocated. So unless they're explicitly marked as being able to
2786          * cope (CON_ANYTIME) don't call them until this CPU is officially up.
2787          */
2788         if (!cpu_online(raw_smp_processor_id()) &&
2789             !(flags & CON_ANYTIME))
2790                 return false;
2791
2792         return true;
2793 }
2794
2795 /*
2796  * Check if the given console is currently capable and allowed to print
2797  * records.
2798  *
2799  * Requires holding the console_lock.
2800  */
2801 static inline bool console_is_usable(struct console *con)
2802 {
2803         if (!con->write)
2804                 return false;
2805
2806         return __console_is_usable(con->flags);
2807 }
2808
2809 static void __console_unlock(void)
2810 {
2811         console_locked = 0;
2812
2813         /*
2814          * Depending on whether console_lock() or console_trylock() was used,
2815          * appropriately allow the kthread printers to continue.
2816          */
2817         if (console_kthreads_blocked)
2818                 console_kthreads_unblock();
2819         else
2820                 console_kthreads_atomic_unblock();
2821
2822         /*
2823          * New records may have arrived while the console was locked.
2824          * Wake the kthread printers to print them.
2825          */
2826         wake_up_klogd();
2827
2828         up_console_sem();
2829 }
2830
2831 /*
2832  * Print one record for the given console. The record printed is whatever
2833  * record is the next available record for the given console.
2834  *
2835  * @text is a buffer of size CONSOLE_LOG_MAX.
2836  *
2837  * If extended messages should be printed, @ext_text is a buffer of size
2838  * CONSOLE_EXT_LOG_MAX. Otherwise @ext_text must be NULL.
2839  *
2840  * If dropped messages should be printed, @dropped_text is a buffer of size
2841  * DROPPED_TEXT_MAX. Otherwise @dropped_text must be NULL.
2842  *
2843  * @handover will be set to true if a printk waiter has taken over the
2844  * console_lock, in which case the caller is no longer holding the
2845  * console_lock. Otherwise it is set to false. A NULL pointer may be provided
2846  * to disable allowing the console_lock to be taken over by a printk waiter.
2847  *
2848  * Returns false if the given console has no next record to print, otherwise
2849  * true.
2850  *
2851  * Requires the console_lock if @handover is non-NULL.
2852  * Requires con->lock otherwise.
2853  */
2854 static bool __console_emit_next_record(struct console *con, char *text, char *ext_text,
2855                                        char *dropped_text, bool *handover)
2856 {
2857         static atomic_t panic_console_dropped = ATOMIC_INIT(0);
2858         struct printk_info info;
2859         struct printk_record r;
2860         unsigned long flags;
2861         char *write_text;
2862         size_t len;
2863
2864         prb_rec_init_rd(&r, &info, text, CONSOLE_LOG_MAX);
2865
2866         if (handover)
2867                 *handover = false;
2868
2869         if (!prb_read_valid(prb, con->seq, &r))
2870                 return false;
2871
2872         if (con->seq != r.info->seq) {
2873                 con->dropped += r.info->seq - con->seq;
2874                 con->seq = r.info->seq;
2875                 if (panic_in_progress() &&
2876                     atomic_fetch_inc_relaxed(&panic_console_dropped) > 10) {
2877                         suppress_panic_printk = 1;
2878                         pr_warn_once("Too many dropped messages. Suppress messages on non-panic CPUs to prevent livelock.\n");
2879                 }
2880         }
2881
2882         /* Skip record that has level above the console loglevel. */
2883         if (suppress_message_printing(r.info->level)) {
2884                 con->seq++;
2885                 goto skip;
2886         }
2887
2888         if (ext_text) {
2889                 write_text = ext_text;
2890                 len = info_print_ext_header(ext_text, CONSOLE_EXT_LOG_MAX, r.info);
2891                 len += msg_print_ext_body(ext_text + len, CONSOLE_EXT_LOG_MAX - len,
2892                                           &r.text_buf[0], r.info->text_len, &r.info->dev_info);
2893         } else {
2894                 write_text = text;
2895                 len = record_print_text(&r, console_msg_format & MSG_FORMAT_SYSLOG, printk_time);
2896         }
2897
2898         if (handover) {
2899                 /*
2900                  * While actively printing out messages, if another printk()
2901                  * were to occur on another CPU, it may wait for this one to
2902                  * finish. This task can not be preempted if there is a
2903                  * waiter waiting to take over.
2904                  *
2905                  * Interrupts are disabled because the hand over to a waiter
2906                  * must not be interrupted until the hand over is completed
2907                  * (@console_waiter is cleared).
2908                  */
2909                 printk_safe_enter_irqsave(flags);
2910                 console_lock_spinning_enable();
2911
2912                 /* don't trace irqsoff print latency */
2913                 stop_critical_timings();
2914         }
2915
2916         call_console_driver(con, write_text, len, dropped_text);
2917
2918         con->seq++;
2919
2920         if (handover) {
2921                 start_critical_timings();
2922                 *handover = console_lock_spinning_disable_and_check();
2923                 printk_safe_exit_irqrestore(flags);
2924         }
2925 skip:
2926         return true;
2927 }
2928
2929 /*
2930  * Print a record for a given console, but allow another printk() caller to
2931  * take over the console_lock and continue printing.
2932  *
2933  * Requires the console_lock, but depending on @handover after the call, the
2934  * caller may no longer have the console_lock.
2935  *
2936  * See __console_emit_next_record() for argument and return details.
2937  */
2938 static bool console_emit_next_record_transferable(struct console *con, char *text, char *ext_text,
2939                                                   char *dropped_text, bool *handover)
2940 {
2941         /*
2942          * Handovers are only supported if threaded printers are atomically
2943          * blocked. The context taking over the console_lock may be atomic.
2944          */
2945         if (!console_kthreads_atomically_blocked()) {
2946                 *handover = false;
2947                 handover = NULL;
2948         }
2949
2950         return __console_emit_next_record(con, text, ext_text, dropped_text, handover);
2951 }
2952
2953 /*
2954  * Print out all remaining records to all consoles.
2955  *
2956  * @do_cond_resched is set by the caller. It can be true only in schedulable
2957  * context.
2958  *
2959  * @next_seq is set to the sequence number after the last available record.
2960  * The value is valid only when this function returns true. It means that all
2961  * usable consoles are completely flushed.
2962  *
2963  * @handover will be set to true if a printk waiter has taken over the
2964  * console_lock, in which case the caller is no longer holding the
2965  * console_lock. Otherwise it is set to false.
2966  *
2967  * Returns true when there was at least one usable console and all messages
2968  * were flushed to all usable consoles. A returned false informs the caller
2969  * that everything was not flushed (either there were no usable consoles or
2970  * another context has taken over printing or it is a panic situation and this
2971  * is not the panic CPU or direct printing is not preferred). Regardless the
2972  * reason, the caller should assume it is not useful to immediately try again.
2973  *
2974  * Requires the console_lock.
2975  */
2976 static bool console_flush_all(bool do_cond_resched, u64 *next_seq, bool *handover)
2977 {
2978         static char dropped_text[DROPPED_TEXT_MAX];
2979         static char ext_text[CONSOLE_EXT_LOG_MAX];
2980         static char text[CONSOLE_LOG_MAX];
2981         bool any_usable = false;
2982         struct console *con;
2983         bool any_progress;
2984
2985         *next_seq = 0;
2986         *handover = false;
2987
2988         do {
2989                 /* Let the kthread printers do the work if they can. */
2990                 if (!allow_direct_printing())
2991                         return false;
2992
2993                 any_progress = false;
2994
2995                 for_each_console(con) {
2996                         bool progress;
2997
2998                         if (!console_is_usable(con))
2999                                 continue;
3000                         any_usable = true;
3001
3002                         if (con->flags & CON_EXTENDED) {
3003                                 /* Extended consoles do not print "dropped messages". */
3004                                 progress = console_emit_next_record_transferable(con, &text[0],
3005                                                                 &ext_text[0], NULL, handover);
3006                         } else {
3007                                 progress = console_emit_next_record_transferable(con, &text[0],
3008                                                                 NULL, &dropped_text[0], handover);
3009                         }
3010                         if (*handover)
3011                                 return false;
3012
3013                         /* Track the next of the highest seq flushed. */
3014                         if (con->seq > *next_seq)
3015                                 *next_seq = con->seq;
3016
3017                         if (!progress)
3018                                 continue;
3019                         any_progress = true;
3020
3021                         /* Allow panic_cpu to take over the consoles safely. */
3022                         if (abandon_console_lock_in_panic())
3023                                 return false;
3024
3025                         if (do_cond_resched)
3026                                 cond_resched();
3027                 }
3028         } while (any_progress);
3029
3030         return any_usable;
3031 }
3032
3033 /**
3034  * console_unlock - unlock the console system
3035  *
3036  * Releases the console_lock which the caller holds on the console system
3037  * and the console driver list.
3038  *
3039  * While the console_lock was held, console output may have been buffered
3040  * by printk().  If this is the case, console_unlock(); emits
3041  * the output prior to releasing the lock.
3042  *
3043  * console_unlock(); may be called from any context.
3044  */
3045 void console_unlock(void)
3046 {
3047         bool do_cond_resched;
3048         bool handover;
3049         bool flushed;
3050         u64 next_seq;
3051
3052         if (console_suspended) {
3053                 up_console_sem();
3054                 return;
3055         }
3056
3057         /*
3058          * Console drivers are called with interrupts disabled, so
3059          * @console_may_schedule should be cleared before; however, we may
3060          * end up dumping a lot of lines, for example, if called from
3061          * console registration path, and should invoke cond_resched()
3062          * between lines if allowable.  Not doing so can cause a very long
3063          * scheduling stall on a slow console leading to RCU stall and
3064          * softlockup warnings which exacerbate the issue with more
3065          * messages practically incapacitating the system. Therefore, create
3066          * a local to use for the printing loop.
3067          */
3068         do_cond_resched = console_may_schedule;
3069
3070         do {
3071                 console_may_schedule = 0;
3072
3073                 flushed = console_flush_all(do_cond_resched, &next_seq, &handover);
3074                 if (!handover)
3075                         __console_unlock();
3076
3077                 /*
3078                  * Abort if there was a failure to flush all messages to all
3079                  * usable consoles. Either it is not possible to flush (in
3080                  * which case it would be an infinite loop of retrying) or
3081                  * another context has taken over printing.
3082                  */
3083                 if (!flushed)
3084                         break;
3085
3086                 /*
3087                  * Some context may have added new records after
3088                  * console_flush_all() but before unlocking the console.
3089                  * Re-check if there is a new record to flush. If the trylock
3090                  * fails, another context is already handling the printing.
3091                  */
3092         } while (prb_read_valid(prb, next_seq, NULL) && console_trylock());
3093 }
3094 EXPORT_SYMBOL(console_unlock);
3095
3096 /**
3097  * console_conditional_schedule - yield the CPU if required
3098  *
3099  * If the console code is currently allowed to sleep, and
3100  * if this CPU should yield the CPU to another task, do
3101  * so here.
3102  *
3103  * Must be called within console_lock();.
3104  */
3105 void __sched console_conditional_schedule(void)
3106 {
3107         if (console_may_schedule)
3108                 cond_resched();
3109 }
3110 EXPORT_SYMBOL(console_conditional_schedule);
3111
3112 void console_unblank(void)
3113 {
3114         struct console *c;
3115
3116         /*
3117          * console_unblank can no longer be called in interrupt context unless
3118          * oops_in_progress is set to 1..
3119          */
3120         if (oops_in_progress) {
3121                 if (down_trylock_console_sem() != 0)
3122                         return;
3123                 if (!console_kthreads_atomic_tryblock()) {
3124                         up_console_sem();
3125                         return;
3126                 }
3127         } else
3128                 console_lock();
3129
3130         console_locked = 1;
3131         console_may_schedule = 0;
3132         for_each_console(c)
3133                 if ((c->flags & CON_ENABLED) && c->unblank)
3134                         c->unblank();
3135         console_unlock();
3136
3137         if (!oops_in_progress)
3138                 pr_flush(1000, true);
3139 }
3140
3141 /**
3142  * console_flush_on_panic - flush console content on panic
3143  * @mode: flush all messages in buffer or just the pending ones
3144  *
3145  * Immediately output all pending messages no matter what.
3146  */
3147 void console_flush_on_panic(enum con_flush_mode mode)
3148 {
3149         /*
3150          * If someone else is holding the console lock, trylock will fail
3151          * and may_schedule may be set.  Ignore and proceed to unlock so
3152          * that messages are flushed out.  As this can be called from any
3153          * context and we don't want to get preempted while flushing,
3154          * ensure may_schedule is cleared.
3155          */
3156         console_trylock();
3157         console_may_schedule = 0;
3158
3159         if (mode == CONSOLE_REPLAY_ALL) {
3160                 struct console *c;
3161                 u64 seq;
3162
3163                 seq = prb_first_valid_seq(prb);
3164                 for_each_console(c)
3165                         c->seq = seq;
3166         }
3167         console_unlock();
3168 }
3169
3170 /*
3171  * Return the console tty driver structure and its associated index
3172  */
3173 struct tty_driver *console_device(int *index)
3174 {
3175         struct console *c;
3176         struct tty_driver *driver = NULL;
3177
3178         console_lock();
3179         for_each_console(c) {
3180                 if (!c->device)
3181                         continue;
3182                 driver = c->device(c, index);
3183                 if (driver)
3184                         break;
3185         }
3186         console_unlock();
3187         return driver;
3188 }
3189
3190 /*
3191  * Prevent further output on the passed console device so that (for example)
3192  * serial drivers can disable console output before suspending a port, and can
3193  * re-enable output afterwards.
3194  */
3195 void console_stop(struct console *console)
3196 {
3197         __pr_flush(console, 1000, true);
3198         console_lock();
3199         console->flags &= ~CON_ENABLED;
3200         console_unlock();
3201 }
3202 EXPORT_SYMBOL(console_stop);
3203
3204 void console_start(struct console *console)
3205 {
3206         console_lock();
3207         console->flags |= CON_ENABLED;
3208         console_unlock();
3209         __pr_flush(console, 1000, true);
3210 }
3211 EXPORT_SYMBOL(console_start);
3212
3213 static int __read_mostly keep_bootcon;
3214
3215 static int __init keep_bootcon_setup(char *str)
3216 {
3217         keep_bootcon = 1;
3218         pr_info("debug: skip boot console de-registration.\n");
3219
3220         return 0;
3221 }
3222
3223 early_param("keep_bootcon", keep_bootcon_setup);
3224
3225 /*
3226  * This is called by register_console() to try to match
3227  * the newly registered console with any of the ones selected
3228  * by either the command line or add_preferred_console() and
3229  * setup/enable it.
3230  *
3231  * Care need to be taken with consoles that are statically
3232  * enabled such as netconsole
3233  */
3234 static int try_enable_preferred_console(struct console *newcon,
3235                                         bool user_specified)
3236 {
3237         struct console_cmdline *c;
3238         int i, err;
3239
3240         for (i = 0, c = console_cmdline;
3241              i < MAX_CMDLINECONSOLES && c->name[0];
3242              i++, c++) {
3243                 if (c->user_specified != user_specified)
3244                         continue;
3245                 if (!newcon->match ||
3246                     newcon->match(newcon, c->name, c->index, c->options) != 0) {
3247                         /* default matching */
3248                         BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
3249                         if (strcmp(c->name, newcon->name) != 0)
3250                                 continue;
3251                         if (newcon->index >= 0 &&
3252                             newcon->index != c->index)
3253                                 continue;
3254                         if (newcon->index < 0)
3255                                 newcon->index = c->index;
3256
3257                         if (_braille_register_console(newcon, c))
3258                                 return 0;
3259
3260                         if (newcon->setup &&
3261                             (err = newcon->setup(newcon, c->options)) != 0)
3262                                 return err;
3263                 }
3264                 newcon->flags |= CON_ENABLED;
3265                 if (i == preferred_console)
3266                         newcon->flags |= CON_CONSDEV;
3267                 return 0;
3268         }
3269
3270         /*
3271          * Some consoles, such as pstore and netconsole, can be enabled even
3272          * without matching. Accept the pre-enabled consoles only when match()
3273          * and setup() had a chance to be called.
3274          */
3275         if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
3276                 return 0;
3277
3278         return -ENOENT;
3279 }
3280
3281 /* Try to enable the console unconditionally */
3282 static void try_enable_default_console(struct console *newcon)
3283 {
3284         if (newcon->index < 0)
3285                 newcon->index = 0;
3286
3287         if (newcon->setup && newcon->setup(newcon, NULL) != 0)
3288                 return;
3289
3290         newcon->flags |= CON_ENABLED;
3291
3292         if (newcon->device)
3293                 newcon->flags |= CON_CONSDEV;
3294 }
3295
3296 #define con_printk(lvl, con, fmt, ...)                  \
3297         printk(lvl pr_fmt("%sconsole [%s%d] " fmt),     \
3298                (con->flags & CON_BOOT) ? "boot" : "",   \
3299                con->name, con->index, ##__VA_ARGS__)
3300
3301 /*
3302  * The console driver calls this routine during kernel initialization
3303  * to register the console printing procedure with printk() and to
3304  * print any messages that were printed by the kernel before the
3305  * console driver was initialized.
3306  *
3307  * This can happen pretty early during the boot process (because of
3308  * early_printk) - sometimes before setup_arch() completes - be careful
3309  * of what kernel features are used - they may not be initialised yet.
3310  *
3311  * There are two types of consoles - bootconsoles (early_printk) and
3312  * "real" consoles (everything which is not a bootconsole) which are
3313  * handled differently.
3314  *  - Any number of bootconsoles can be registered at any time.
3315  *  - As soon as a "real" console is registered, all bootconsoles
3316  *    will be unregistered automatically.
3317  *  - Once a "real" console is registered, any attempt to register a
3318  *    bootconsoles will be rejected
3319  */
3320 void register_console(struct console *newcon)
3321 {
3322         struct console *con;
3323         bool bootcon_enabled = false;
3324         bool realcon_enabled = false;
3325         int err;
3326
3327         for_each_console(con) {
3328                 if (WARN(con == newcon, "console '%s%d' already registered\n",
3329                                          con->name, con->index))
3330                         return;
3331         }
3332
3333         for_each_console(con) {
3334                 if (con->flags & CON_BOOT)
3335                         bootcon_enabled = true;
3336                 else
3337                         realcon_enabled = true;
3338         }
3339
3340         /* Do not register boot consoles when there already is a real one. */
3341         if (newcon->flags & CON_BOOT && realcon_enabled) {
3342                 pr_info("Too late to register bootconsole %s%d\n",
3343                         newcon->name, newcon->index);
3344                 return;
3345         }
3346
3347         /*
3348          * See if we want to enable this console driver by default.
3349          *
3350          * Nope when a console is preferred by the command line, device
3351          * tree, or SPCR.
3352          *
3353          * The first real console with tty binding (driver) wins. More
3354          * consoles might get enabled before the right one is found.
3355          *
3356          * Note that a console with tty binding will have CON_CONSDEV
3357          * flag set and will be first in the list.
3358          */
3359         if (preferred_console < 0) {
3360                 if (!console_drivers || !console_drivers->device ||
3361                     console_drivers->flags & CON_BOOT) {
3362                         try_enable_default_console(newcon);
3363                 }
3364         }
3365
3366         /* See if this console matches one we selected on the command line */
3367         err = try_enable_preferred_console(newcon, true);
3368
3369         /* If not, try to match against the platform default(s) */
3370         if (err == -ENOENT)
3371                 err = try_enable_preferred_console(newcon, false);
3372
3373         /* printk() messages are not printed to the Braille console. */
3374         if (err || newcon->flags & CON_BRL)
3375                 return;
3376
3377         /*
3378          * If we have a bootconsole, and are switching to a real console,
3379          * don't print everything out again, since when the boot console, and
3380          * the real console are the same physical device, it's annoying to
3381          * see the beginning boot messages twice
3382          */
3383         if (bootcon_enabled &&
3384             ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
3385                 newcon->flags &= ~CON_PRINTBUFFER;
3386         }
3387
3388         /*
3389          *      Put this console in the list - keep the
3390          *      preferred driver at the head of the list.
3391          */
3392         console_lock();
3393         if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
3394                 newcon->next = console_drivers;
3395                 console_drivers = newcon;
3396                 if (newcon->next)
3397                         newcon->next->flags &= ~CON_CONSDEV;
3398                 /* Ensure this flag is always set for the head of the list */
3399                 newcon->flags |= CON_CONSDEV;
3400         } else {
3401                 newcon->next = console_drivers->next;
3402                 console_drivers->next = newcon;
3403         }
3404
3405         if (newcon->flags & CON_EXTENDED)
3406                 nr_ext_console_drivers++;
3407
3408         newcon->dropped = 0;
3409         newcon->thread = NULL;
3410         newcon->blocked = true;
3411         mutex_init(&newcon->lock);
3412
3413         if (newcon->flags & CON_PRINTBUFFER) {
3414                 /* Get a consistent copy of @syslog_seq. */
3415                 mutex_lock(&syslog_lock);
3416                 newcon->seq = syslog_seq;
3417                 mutex_unlock(&syslog_lock);
3418         } else {
3419                 /* Begin with next message. */
3420                 newcon->seq = prb_next_seq(prb);
3421         }
3422
3423         if (printk_kthreads_available)
3424                 printk_start_kthread(newcon);
3425
3426         console_unlock();
3427         console_sysfs_notify();
3428
3429         /*
3430          * By unregistering the bootconsoles after we enable the real console
3431          * we get the "console xxx enabled" message on all the consoles -
3432          * boot consoles, real consoles, etc - this is to ensure that end
3433          * users know there might be something in the kernel's log buffer that
3434          * went to the bootconsole (that they do not see on the real console)
3435          */
3436         con_printk(KERN_INFO, newcon, "enabled\n");
3437         if (bootcon_enabled &&
3438             ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
3439             !keep_bootcon) {
3440                 /* We need to iterate through all boot consoles, to make
3441                  * sure we print everything out, before we unregister them.
3442                  */
3443                 for_each_console(con)
3444                         if (con->flags & CON_BOOT)
3445                                 unregister_console(con);
3446         }
3447 }
3448 EXPORT_SYMBOL(register_console);
3449
3450 int unregister_console(struct console *console)
3451 {
3452         struct task_struct *thd;
3453         struct console *con;
3454         int res;
3455
3456         con_printk(KERN_INFO, console, "disabled\n");
3457
3458         res = _braille_unregister_console(console);
3459         if (res < 0)
3460                 return res;
3461         if (res > 0)
3462                 return 0;
3463
3464         res = -ENODEV;
3465         console_lock();
3466         if (console_drivers == console) {
3467                 console_drivers=console->next;
3468                 res = 0;
3469         } else {
3470                 for_each_console(con) {
3471                         if (con->next == console) {
3472                                 con->next = console->next;
3473                                 res = 0;
3474                                 break;
3475                         }
3476                 }
3477         }
3478
3479         if (res)
3480                 goto out_disable_unlock;
3481
3482         if (console->flags & CON_EXTENDED)
3483                 nr_ext_console_drivers--;
3484
3485         /*
3486          * If this isn't the last console and it has CON_CONSDEV set, we
3487          * need to set it on the next preferred console.
3488          */
3489         if (console_drivers != NULL && console->flags & CON_CONSDEV)
3490                 console_drivers->flags |= CON_CONSDEV;
3491
3492         console->flags &= ~CON_ENABLED;
3493
3494         /*
3495          * console->thread can only be cleared under the console lock. But
3496          * stopping the thread must be done without the console lock. The
3497          * task that clears @thread is the task that stops the kthread.
3498          */
3499         thd = console->thread;
3500         console->thread = NULL;
3501
3502         console_unlock();
3503
3504         if (thd)
3505                 kthread_stop(thd);
3506
3507         console_sysfs_notify();
3508
3509         if (console->exit)
3510                 res = console->exit(console);
3511
3512         return res;
3513
3514 out_disable_unlock:
3515         console->flags &= ~CON_ENABLED;
3516         console_unlock();
3517
3518         return res;
3519 }
3520 EXPORT_SYMBOL(unregister_console);
3521
3522 /*
3523  * Initialize the console device. This is called *early*, so
3524  * we can't necessarily depend on lots of kernel help here.
3525  * Just do some early initializations, and do the complex setup
3526  * later.
3527  */
3528 void __init console_init(void)
3529 {
3530         int ret;
3531         initcall_t call;
3532         initcall_entry_t *ce;
3533
3534         /* Setup the default TTY line discipline. */
3535         n_tty_init();
3536
3537         /*
3538          * set up the console device so that later boot sequences can
3539          * inform about problems etc..
3540          */
3541         ce = __con_initcall_start;
3542         trace_initcall_level("console");
3543         while (ce < __con_initcall_end) {
3544                 call = initcall_from_entry(ce);
3545                 trace_initcall_start(call);
3546                 ret = call();
3547                 trace_initcall_finish(call, ret);
3548                 ce++;
3549         }
3550 }
3551
3552 /*
3553  * Some boot consoles access data that is in the init section and which will
3554  * be discarded after the initcalls have been run. To make sure that no code
3555  * will access this data, unregister the boot consoles in a late initcall.
3556  *
3557  * If for some reason, such as deferred probe or the driver being a loadable
3558  * module, the real console hasn't registered yet at this point, there will
3559  * be a brief interval in which no messages are logged to the console, which
3560  * makes it difficult to diagnose problems that occur during this time.
3561  *
3562  * To mitigate this problem somewhat, only unregister consoles whose memory
3563  * intersects with the init section. Note that all other boot consoles will
3564  * get unregistered when the real preferred console is registered.
3565  */
3566 static int __init printk_late_init(void)
3567 {
3568         struct console *con;
3569         int ret;
3570
3571         for_each_console(con) {
3572                 if (!(con->flags & CON_BOOT))
3573                         continue;
3574
3575                 /* Check addresses that might be used for enabled consoles. */
3576                 if (init_section_intersects(con, sizeof(*con)) ||
3577                     init_section_contains(con->write, 0) ||
3578                     init_section_contains(con->read, 0) ||
3579                     init_section_contains(con->device, 0) ||
3580                     init_section_contains(con->unblank, 0) ||
3581                     init_section_contains(con->data, 0)) {
3582                         /*
3583                          * Please, consider moving the reported consoles out
3584                          * of the init section.
3585                          */
3586                         pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3587                                 con->name, con->index);
3588                         unregister_console(con);
3589                 }
3590         }
3591         ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3592                                         console_cpu_notify);
3593         WARN_ON(ret < 0);
3594         ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3595                                         console_cpu_notify, NULL);
3596         WARN_ON(ret < 0);
3597         printk_sysctl_init();
3598         return 0;
3599 }
3600 late_initcall(printk_late_init);
3601
3602 static int __init printk_activate_kthreads(void)
3603 {
3604         struct console *con;
3605
3606         console_lock();
3607         printk_kthreads_available = true;
3608         for_each_console(con)
3609                 printk_start_kthread(con);
3610         console_unlock();
3611
3612         return 0;
3613 }
3614 early_initcall(printk_activate_kthreads);
3615
3616 #if defined CONFIG_PRINTK
3617 /* If @con is specified, only wait for that console. Otherwise wait for all. */
3618 static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress)
3619 {
3620         int remaining = timeout_ms;
3621         struct console *c;
3622         u64 last_diff = 0;
3623         u64 printk_seq;
3624         u64 diff;
3625         u64 seq;
3626
3627         might_sleep();
3628
3629         seq = prb_next_seq(prb);
3630
3631         for (;;) {
3632                 diff = 0;
3633
3634                 console_lock();
3635                 for_each_console(c) {
3636                         if (con && con != c)
3637                                 continue;
3638                         if (!console_is_usable(c))
3639                                 continue;
3640                         printk_seq = c->seq;
3641                         if (printk_seq < seq)
3642                                 diff += seq - printk_seq;
3643                 }
3644                 console_unlock();
3645
3646                 if (diff != last_diff && reset_on_progress)
3647                         remaining = timeout_ms;
3648
3649                 if (diff == 0 || remaining == 0)
3650                         break;
3651
3652                 if (remaining < 0) {
3653                         /* no timeout limit */
3654                         msleep(100);
3655                 } else if (remaining < 100) {
3656                         msleep(remaining);
3657                         remaining = 0;
3658                 } else {
3659                         msleep(100);
3660                         remaining -= 100;
3661                 }
3662
3663                 last_diff = diff;
3664         }
3665
3666         return (diff == 0);
3667 }
3668
3669 /**
3670  * pr_flush() - Wait for printing threads to catch up.
3671  *
3672  * @timeout_ms:        The maximum time (in ms) to wait.
3673  * @reset_on_progress: Reset the timeout if forward progress is seen.
3674  *
3675  * A value of 0 for @timeout_ms means no waiting will occur. A value of -1
3676  * represents infinite waiting.
3677  *
3678  * If @reset_on_progress is true, the timeout will be reset whenever any
3679  * printer has been seen to make some forward progress.
3680  *
3681  * Context: Process context. May sleep while acquiring console lock.
3682  * Return: true if all enabled printers are caught up.
3683  */
3684 bool pr_flush(int timeout_ms, bool reset_on_progress)
3685 {
3686         return __pr_flush(NULL, timeout_ms, reset_on_progress);
3687 }
3688 EXPORT_SYMBOL(pr_flush);
3689
3690 static void __printk_fallback_preferred_direct(void)
3691 {
3692         printk_prefer_direct_enter();
3693         pr_err("falling back to preferred direct printing\n");
3694         printk_kthreads_available = false;
3695 }
3696
3697 /*
3698  * Enter preferred direct printing, but never exit. Mark console threads as
3699  * unavailable. The system is then forever in preferred direct printing and
3700  * any printing threads will exit.
3701  *
3702  * Must *not* be called under console_lock. Use
3703  * __printk_fallback_preferred_direct() if already holding console_lock.
3704  */
3705 static void printk_fallback_preferred_direct(void)
3706 {
3707         console_lock();
3708         __printk_fallback_preferred_direct();
3709         console_unlock();
3710 }
3711
3712 /*
3713  * Print a record for a given console, not allowing another printk() caller
3714  * to take over. This is appropriate for contexts that do not have the
3715  * console_lock.
3716  *
3717  * See __console_emit_next_record() for argument and return details.
3718  */
3719 static bool console_emit_next_record(struct console *con, char *text, char *ext_text,
3720                                      char *dropped_text)
3721 {
3722         return __console_emit_next_record(con, text, ext_text, dropped_text, NULL);
3723 }
3724
3725 static bool printer_should_wake(struct console *con, u64 seq)
3726 {
3727         short flags;
3728
3729         if (kthread_should_stop() || !printk_kthreads_available)
3730                 return true;
3731
3732         if (con->blocked ||
3733             console_kthreads_atomically_blocked()) {
3734                 return false;
3735         }
3736
3737         /*
3738          * This is an unsafe read from con->flags, but a false positive is
3739          * not a problem. Worst case it would allow the printer to wake up
3740          * although it is disabled. But the printer will notice that when
3741          * attempting to print and instead go back to sleep.
3742          */
3743         flags = data_race(READ_ONCE(con->flags));
3744
3745         if (!__console_is_usable(flags))
3746                 return false;
3747
3748         return prb_read_valid(prb, seq, NULL);
3749 }
3750
3751 static int printk_kthread_func(void *data)
3752 {
3753         struct console *con = data;
3754         char *dropped_text = NULL;
3755         char *ext_text = NULL;
3756         u64 seq = 0;
3757         char *text;
3758         int error;
3759
3760         text = kmalloc(CONSOLE_LOG_MAX, GFP_KERNEL);
3761         if (!text) {
3762                 con_printk(KERN_ERR, con, "failed to allocate text buffer\n");
3763                 printk_fallback_preferred_direct();
3764                 goto out;
3765         }
3766
3767         if (con->flags & CON_EXTENDED) {
3768                 ext_text = kmalloc(CONSOLE_EXT_LOG_MAX, GFP_KERNEL);
3769                 if (!ext_text) {
3770                         con_printk(KERN_ERR, con, "failed to allocate ext_text buffer\n");
3771                         printk_fallback_preferred_direct();
3772                         goto out;
3773                 }
3774         } else {
3775                 dropped_text = kmalloc(DROPPED_TEXT_MAX, GFP_KERNEL);
3776                 if (!dropped_text) {
3777                         con_printk(KERN_ERR, con, "failed to allocate dropped_text buffer\n");
3778                         printk_fallback_preferred_direct();
3779                         goto out;
3780                 }
3781         }
3782
3783         con_printk(KERN_INFO, con, "printing thread started\n");
3784
3785         for (;;) {
3786                 /*
3787                  * Guarantee this task is visible on the waitqueue before
3788                  * checking the wake condition.
3789                  *
3790                  * The full memory barrier within set_current_state() of
3791                  * prepare_to_wait_event() pairs with the full memory barrier
3792                  * within wq_has_sleeper().
3793                  *
3794                  * This pairs with __wake_up_klogd:A.
3795                  */
3796                 error = wait_event_interruptible(log_wait,
3797                                 printer_should_wake(con, seq)); /* LMM(printk_kthread_func:A) */
3798
3799                 if (kthread_should_stop() || !printk_kthreads_available)
3800                         break;
3801
3802                 if (error)
3803                         continue;
3804
3805                 error = mutex_lock_interruptible(&con->lock);
3806                 if (error)
3807                         continue;
3808
3809                 if (con->blocked ||
3810                     !console_kthread_printing_tryenter()) {
3811                         /* Another context has locked the console_lock. */
3812                         mutex_unlock(&con->lock);
3813                         continue;
3814                 }
3815
3816                 /*
3817                  * Although this context has not locked the console_lock, it
3818                  * is known that the console_lock is not locked and it is not
3819                  * possible for any other context to lock the console_lock.
3820                  * Therefore it is safe to read con->flags.
3821                  */
3822
3823                 if (!__console_is_usable(con->flags)) {
3824                         console_kthread_printing_exit();
3825                         mutex_unlock(&con->lock);
3826                         continue;
3827                 }
3828
3829                 /*
3830                  * Even though the printk kthread is always preemptible, it is
3831                  * still not allowed to call cond_resched() from within
3832                  * console drivers. The task may become non-preemptible in the
3833                  * console driver call chain. For example, vt_console_print()
3834                  * takes a spinlock and then can call into fbcon_redraw(),
3835                  * which can conditionally invoke cond_resched().
3836                  */
3837                 console_may_schedule = 0;
3838                 console_emit_next_record(con, text, ext_text, dropped_text);
3839
3840                 seq = con->seq;
3841
3842                 console_kthread_printing_exit();
3843
3844                 mutex_unlock(&con->lock);
3845         }
3846
3847         con_printk(KERN_INFO, con, "printing thread stopped\n");
3848 out:
3849         kfree(dropped_text);
3850         kfree(ext_text);
3851         kfree(text);
3852
3853         console_lock();
3854         /*
3855          * If this kthread is being stopped by another task, con->thread will
3856          * already be NULL. That is fine. The important thing is that it is
3857          * NULL after the kthread exits.
3858          */
3859         con->thread = NULL;
3860         console_unlock();
3861
3862         return 0;
3863 }
3864
3865 /* Must be called under console_lock. */
3866 static void printk_start_kthread(struct console *con)
3867 {
3868         /*
3869          * Do not start a kthread if there is no write() callback. The
3870          * kthreads assume the write() callback exists.
3871          */
3872         if (!con->write)
3873                 return;
3874
3875         con->thread = kthread_run(printk_kthread_func, con,
3876                                   "pr/%s%d", con->name, con->index);
3877         if (IS_ERR(con->thread)) {
3878                 con->thread = NULL;
3879                 con_printk(KERN_ERR, con, "unable to start printing thread\n");
3880                 __printk_fallback_preferred_direct();
3881                 return;
3882         }
3883 }
3884
3885 /*
3886  * Delayed printk version, for scheduler-internal messages:
3887  */
3888 #define PRINTK_PENDING_WAKEUP           0x01
3889 #define PRINTK_PENDING_DIRECT_OUTPUT    0x02
3890
3891 static DEFINE_PER_CPU(int, printk_pending);
3892
3893 static void wake_up_klogd_work_func(struct irq_work *irq_work)
3894 {
3895         int pending = this_cpu_xchg(printk_pending, 0);
3896
3897         if (pending & PRINTK_PENDING_DIRECT_OUTPUT) {
3898                 printk_prefer_direct_enter();
3899
3900                 /* If trylock fails, someone else is doing the printing */
3901                 if (console_trylock())
3902                         console_unlock();
3903
3904                 printk_prefer_direct_exit();
3905         }
3906
3907         if (pending & PRINTK_PENDING_WAKEUP)
3908                 wake_up_interruptible(&log_wait);
3909 }
3910
3911 static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) =
3912         IRQ_WORK_INIT_LAZY(wake_up_klogd_work_func);
3913
3914 static void __wake_up_klogd(int val)
3915 {
3916         if (!printk_percpu_data_ready())
3917                 return;
3918
3919         preempt_disable();
3920         /*
3921          * Guarantee any new records can be seen by tasks preparing to wait
3922          * before this context checks if the wait queue is empty.
3923          *
3924          * The full memory barrier within wq_has_sleeper() pairs with the full
3925          * memory barrier within set_current_state() of
3926          * prepare_to_wait_event(), which is called after ___wait_event() adds
3927          * the waiter but before it has checked the wait condition.
3928          *
3929          * This pairs with devkmsg_read:A, syslog_print:A, and
3930          * printk_kthread_func:A.
3931          */
3932         if (wq_has_sleeper(&log_wait) || /* LMM(__wake_up_klogd:A) */
3933             (val & PRINTK_PENDING_DIRECT_OUTPUT)) {
3934                 this_cpu_or(printk_pending, val);
3935                 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3936         }
3937         preempt_enable();
3938 }
3939
3940 void wake_up_klogd(void)
3941 {
3942         __wake_up_klogd(PRINTK_PENDING_WAKEUP);
3943 }
3944
3945 void defer_console_output(void)
3946 {
3947         /*
3948          * New messages may have been added directly to the ringbuffer
3949          * using vprintk_store(), so wake any waiters as well.
3950          */
3951         int val = PRINTK_PENDING_WAKEUP;
3952
3953         /*
3954          * Make sure that some context will print the messages when direct
3955          * printing is allowed. This happens in situations when the kthreads
3956          * may not be as reliable or perhaps unusable.
3957          */
3958         if (allow_direct_printing())
3959                 val |= PRINTK_PENDING_DIRECT_OUTPUT;
3960
3961         __wake_up_klogd(val);
3962 }
3963
3964 void printk_trigger_flush(void)
3965 {
3966         defer_console_output();
3967 }
3968
3969 int vprintk_deferred(const char *fmt, va_list args)
3970 {
3971         int r;
3972
3973         r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
3974         defer_console_output();
3975
3976         return r;
3977 }
3978
3979 int _printk_deferred(const char *fmt, ...)
3980 {
3981         va_list args;
3982         int r;
3983
3984         va_start(args, fmt);
3985         r = vprintk_deferred(fmt, args);
3986         va_end(args);
3987
3988         return r;
3989 }
3990
3991 /*
3992  * printk rate limiting, lifted from the networking subsystem.
3993  *
3994  * This enforces a rate limit: not more than 10 kernel messages
3995  * every 5s to make a denial-of-service attack impossible.
3996  */
3997 DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3998
3999 int __printk_ratelimit(const char *func)
4000 {
4001         return ___ratelimit(&printk_ratelimit_state, func);
4002 }
4003 EXPORT_SYMBOL(__printk_ratelimit);
4004
4005 /**
4006  * printk_timed_ratelimit - caller-controlled printk ratelimiting
4007  * @caller_jiffies: pointer to caller's state
4008  * @interval_msecs: minimum interval between prints
4009  *
4010  * printk_timed_ratelimit() returns true if more than @interval_msecs
4011  * milliseconds have elapsed since the last time printk_timed_ratelimit()
4012  * returned true.
4013  */
4014 bool printk_timed_ratelimit(unsigned long *caller_jiffies,
4015                         unsigned int interval_msecs)
4016 {
4017         unsigned long elapsed = jiffies - *caller_jiffies;
4018
4019         if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
4020                 return false;
4021
4022         *caller_jiffies = jiffies;
4023         return true;
4024 }
4025 EXPORT_SYMBOL(printk_timed_ratelimit);
4026
4027 static DEFINE_SPINLOCK(dump_list_lock);
4028 static LIST_HEAD(dump_list);
4029
4030 /**
4031  * kmsg_dump_register - register a kernel log dumper.
4032  * @dumper: pointer to the kmsg_dumper structure
4033  *
4034  * Adds a kernel log dumper to the system. The dump callback in the
4035  * structure will be called when the kernel oopses or panics and must be
4036  * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
4037  */
4038 int kmsg_dump_register(struct kmsg_dumper *dumper)
4039 {
4040         unsigned long flags;
4041         int err = -EBUSY;
4042
4043         /* The dump callback needs to be set */
4044         if (!dumper->dump)
4045                 return -EINVAL;
4046
4047         spin_lock_irqsave(&dump_list_lock, flags);
4048         /* Don't allow registering multiple times */
4049         if (!dumper->registered) {
4050                 dumper->registered = 1;
4051                 list_add_tail_rcu(&dumper->list, &dump_list);
4052                 err = 0;
4053         }
4054         spin_unlock_irqrestore(&dump_list_lock, flags);
4055
4056         return err;
4057 }
4058 EXPORT_SYMBOL_GPL(kmsg_dump_register);
4059
4060 /**
4061  * kmsg_dump_unregister - unregister a kmsg dumper.
4062  * @dumper: pointer to the kmsg_dumper structure
4063  *
4064  * Removes a dump device from the system. Returns zero on success and
4065  * %-EINVAL otherwise.
4066  */
4067 int kmsg_dump_unregister(struct kmsg_dumper *dumper)
4068 {
4069         unsigned long flags;
4070         int err = -EINVAL;
4071
4072         spin_lock_irqsave(&dump_list_lock, flags);
4073         if (dumper->registered) {
4074                 dumper->registered = 0;
4075                 list_del_rcu(&dumper->list);
4076                 err = 0;
4077         }
4078         spin_unlock_irqrestore(&dump_list_lock, flags);
4079         synchronize_rcu();
4080
4081         return err;
4082 }
4083 EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
4084
4085 static bool always_kmsg_dump;
4086 module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
4087
4088 const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
4089 {
4090         switch (reason) {
4091         case KMSG_DUMP_PANIC:
4092                 return "Panic";
4093         case KMSG_DUMP_OOPS:
4094                 return "Oops";
4095         case KMSG_DUMP_EMERG:
4096                 return "Emergency";
4097         case KMSG_DUMP_SHUTDOWN:
4098                 return "Shutdown";
4099         default:
4100                 return "Unknown";
4101         }
4102 }
4103 EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
4104
4105 /**
4106  * kmsg_dump - dump kernel log to kernel message dumpers.
4107  * @reason: the reason (oops, panic etc) for dumping
4108  *
4109  * Call each of the registered dumper's dump() callback, which can
4110  * retrieve the kmsg records with kmsg_dump_get_line() or
4111  * kmsg_dump_get_buffer().
4112  */
4113 void kmsg_dump(enum kmsg_dump_reason reason)
4114 {
4115         struct kmsg_dumper *dumper;
4116
4117         rcu_read_lock();
4118         list_for_each_entry_rcu(dumper, &dump_list, list) {
4119                 enum kmsg_dump_reason max_reason = dumper->max_reason;
4120
4121                 /*
4122                  * If client has not provided a specific max_reason, default
4123                  * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
4124                  */
4125                 if (max_reason == KMSG_DUMP_UNDEF) {
4126                         max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
4127                                                         KMSG_DUMP_OOPS;
4128                 }
4129                 if (reason > max_reason)
4130                         continue;
4131
4132                 /* invoke dumper which will iterate over records */
4133                 dumper->dump(dumper, reason);
4134         }
4135         rcu_read_unlock();
4136 }
4137
4138 /**
4139  * kmsg_dump_get_line - retrieve one kmsg log line
4140  * @iter: kmsg dump iterator
4141  * @syslog: include the "<4>" prefixes
4142  * @line: buffer to copy the line to
4143  * @size: maximum size of the buffer
4144  * @len: length of line placed into buffer
4145  *
4146  * Start at the beginning of the kmsg buffer, with the oldest kmsg
4147  * record, and copy one record into the provided buffer.
4148  *
4149  * Consecutive calls will return the next available record moving
4150  * towards the end of the buffer with the youngest messages.
4151  *
4152  * A return value of FALSE indicates that there are no more records to
4153  * read.
4154  */
4155 bool kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog,
4156                         char *line, size_t size, size_t *len)
4157 {
4158         u64 min_seq = latched_seq_read_nolock(&clear_seq);
4159         struct printk_info info;
4160         unsigned int line_count;
4161         struct printk_record r;
4162         size_t l = 0;
4163         bool ret = false;
4164
4165         if (iter->cur_seq < min_seq)
4166                 iter->cur_seq = min_seq;
4167
4168         prb_rec_init_rd(&r, &info, line, size);
4169
4170         /* Read text or count text lines? */
4171         if (line) {
4172                 if (!prb_read_valid(prb, iter->cur_seq, &r))
4173                         goto out;
4174                 l = record_print_text(&r, syslog, printk_time);
4175         } else {
4176                 if (!prb_read_valid_info(prb, iter->cur_seq,
4177                                          &info, &line_count)) {
4178                         goto out;
4179                 }
4180                 l = get_record_print_text_size(&info, line_count, syslog,
4181                                                printk_time);
4182
4183         }
4184
4185         iter->cur_seq = r.info->seq + 1;
4186         ret = true;
4187 out:
4188         if (len)
4189                 *len = l;
4190         return ret;
4191 }
4192 EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
4193
4194 /**
4195  * kmsg_dump_get_buffer - copy kmsg log lines
4196  * @iter: kmsg dump iterator
4197  * @syslog: include the "<4>" prefixes
4198  * @buf: buffer to copy the line to
4199  * @size: maximum size of the buffer
4200  * @len_out: length of line placed into buffer
4201  *
4202  * Start at the end of the kmsg buffer and fill the provided buffer
4203  * with as many of the *youngest* kmsg records that fit into it.
4204  * If the buffer is large enough, all available kmsg records will be
4205  * copied with a single call.
4206  *
4207  * Consecutive calls will fill the buffer with the next block of
4208  * available older records, not including the earlier retrieved ones.
4209  *
4210  * A return value of FALSE indicates that there are no more records to
4211  * read.
4212  */
4213 bool kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog,
4214                           char *buf, size_t size, size_t *len_out)
4215 {
4216         u64 min_seq = latched_seq_read_nolock(&clear_seq);
4217         struct printk_info info;
4218         struct printk_record r;
4219         u64 seq;
4220         u64 next_seq;
4221         size_t len = 0;
4222         bool ret = false;
4223         bool time = printk_time;
4224
4225         if (!buf || !size)
4226                 goto out;
4227
4228         if (iter->cur_seq < min_seq)
4229                 iter->cur_seq = min_seq;
4230
4231         if (prb_read_valid_info(prb, iter->cur_seq, &info, NULL)) {
4232                 if (info.seq != iter->cur_seq) {
4233                         /* messages are gone, move to first available one */
4234                         iter->cur_seq = info.seq;
4235                 }
4236         }
4237
4238         /* last entry */
4239         if (iter->cur_seq >= iter->next_seq)
4240                 goto out;
4241
4242         /*
4243          * Find first record that fits, including all following records,
4244          * into the user-provided buffer for this dump. Pass in size-1
4245          * because this function (by way of record_print_text()) will
4246          * not write more than size-1 bytes of text into @buf.
4247          */
4248         seq = find_first_fitting_seq(iter->cur_seq, iter->next_seq,
4249                                      size - 1, syslog, time);
4250
4251         /*
4252          * Next kmsg_dump_get_buffer() invocation will dump block of
4253          * older records stored right before this one.
4254          */
4255         next_seq = seq;
4256
4257         prb_rec_init_rd(&r, &info, buf, size);
4258
4259         len = 0;
4260         prb_for_each_record(seq, prb, seq, &r) {
4261                 if (r.info->seq >= iter->next_seq)
4262                         break;
4263
4264                 len += record_print_text(&r, syslog, time);
4265
4266                 /* Adjust record to store to remaining buffer space. */
4267                 prb_rec_init_rd(&r, &info, buf + len, size - len);
4268         }
4269
4270         iter->next_seq = next_seq;
4271         ret = true;
4272 out:
4273         if (len_out)
4274                 *len_out = len;
4275         return ret;
4276 }
4277 EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
4278
4279 /**
4280  * kmsg_dump_rewind - reset the iterator
4281  * @iter: kmsg dump iterator
4282  *
4283  * Reset the dumper's iterator so that kmsg_dump_get_line() and
4284  * kmsg_dump_get_buffer() can be called again and used multiple
4285  * times within the same dumper.dump() callback.
4286  */
4287 void kmsg_dump_rewind(struct kmsg_dump_iter *iter)
4288 {
4289         iter->cur_seq = latched_seq_read_nolock(&clear_seq);
4290         iter->next_seq = prb_next_seq(prb);
4291 }
4292 EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
4293
4294 #endif
4295
4296 #ifdef CONFIG_SMP
4297 static atomic_t printk_cpu_sync_owner = ATOMIC_INIT(-1);
4298 static atomic_t printk_cpu_sync_nested = ATOMIC_INIT(0);
4299
4300 /**
4301  * __printk_cpu_sync_wait() - Busy wait until the printk cpu-reentrant
4302  *                            spinning lock is not owned by any CPU.
4303  *
4304  * Context: Any context.
4305  */
4306 void __printk_cpu_sync_wait(void)
4307 {
4308         do {
4309                 cpu_relax();
4310         } while (atomic_read(&printk_cpu_sync_owner) != -1);
4311 }
4312 EXPORT_SYMBOL(__printk_cpu_sync_wait);
4313
4314 /**
4315  * __printk_cpu_sync_try_get() - Try to acquire the printk cpu-reentrant
4316  *                               spinning lock.
4317  *
4318  * If no processor has the lock, the calling processor takes the lock and
4319  * becomes the owner. If the calling processor is already the owner of the
4320  * lock, this function succeeds immediately.
4321  *
4322  * Context: Any context. Expects interrupts to be disabled.
4323  * Return: 1 on success, otherwise 0.
4324  */
4325 int __printk_cpu_sync_try_get(void)
4326 {
4327         int cpu;
4328         int old;
4329
4330         cpu = smp_processor_id();
4331
4332         /*
4333          * Guarantee loads and stores from this CPU when it is the lock owner
4334          * are _not_ visible to the previous lock owner. This pairs with
4335          * __printk_cpu_sync_put:B.
4336          *
4337          * Memory barrier involvement:
4338          *
4339          * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4340          * then __printk_cpu_sync_put:A can never read from
4341          * __printk_cpu_sync_try_get:B.
4342          *
4343          * Relies on:
4344          *
4345          * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
4346          * of the previous CPU
4347          *    matching
4348          * ACQUIRE from __printk_cpu_sync_try_get:A to
4349          * __printk_cpu_sync_try_get:B of this CPU
4350          */
4351         old = atomic_cmpxchg_acquire(&printk_cpu_sync_owner, -1,
4352                                      cpu); /* LMM(__printk_cpu_sync_try_get:A) */
4353         if (old == -1) {
4354                 /*
4355                  * This CPU is now the owner and begins loading/storing
4356                  * data: LMM(__printk_cpu_sync_try_get:B)
4357                  */
4358                 return 1;
4359
4360         } else if (old == cpu) {
4361                 /* This CPU is already the owner. */
4362                 atomic_inc(&printk_cpu_sync_nested);
4363                 return 1;
4364         }
4365
4366         return 0;
4367 }
4368 EXPORT_SYMBOL(__printk_cpu_sync_try_get);
4369
4370 /**
4371  * __printk_cpu_sync_put() - Release the printk cpu-reentrant spinning lock.
4372  *
4373  * The calling processor must be the owner of the lock.
4374  *
4375  * Context: Any context. Expects interrupts to be disabled.
4376  */
4377 void __printk_cpu_sync_put(void)
4378 {
4379         if (atomic_read(&printk_cpu_sync_nested)) {
4380                 atomic_dec(&printk_cpu_sync_nested);
4381                 return;
4382         }
4383
4384         /*
4385          * This CPU is finished loading/storing data:
4386          * LMM(__printk_cpu_sync_put:A)
4387          */
4388
4389         /*
4390          * Guarantee loads and stores from this CPU when it was the
4391          * lock owner are visible to the next lock owner. This pairs
4392          * with __printk_cpu_sync_try_get:A.
4393          *
4394          * Memory barrier involvement:
4395          *
4396          * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4397          * then __printk_cpu_sync_try_get:B reads from __printk_cpu_sync_put:A.
4398          *
4399          * Relies on:
4400          *
4401          * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
4402          * of this CPU
4403          *    matching
4404          * ACQUIRE from __printk_cpu_sync_try_get:A to
4405          * __printk_cpu_sync_try_get:B of the next CPU
4406          */
4407         atomic_set_release(&printk_cpu_sync_owner,
4408                            -1); /* LMM(__printk_cpu_sync_put:B) */
4409 }
4410 EXPORT_SYMBOL(__printk_cpu_sync_put);
4411 #endif /* CONFIG_SMP */