xref: /openbmc/linux/kernel/printk/printk.c (revision 360823a09426347ea8f232b0b0b5156d0aed0302)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
2b9ee979eSJoe Perches /*
3b9ee979eSJoe Perches  *  linux/kernel/printk.c
4b9ee979eSJoe Perches  *
5b9ee979eSJoe Perches  *  Copyright (C) 1991, 1992  Linus Torvalds
6b9ee979eSJoe Perches  *
7b9ee979eSJoe Perches  * Modified to make sys_syslog() more flexible: added commands to
8b9ee979eSJoe Perches  * return the last 4k of kernel messages, regardless of whether
9b9ee979eSJoe Perches  * they've been read or not.  Added option to suppress kernel printk's
10b9ee979eSJoe Perches  * to the console.  Added hook for sending the console messages
11b9ee979eSJoe Perches  * elsewhere, in preparation for a serial line console (someday).
12b9ee979eSJoe Perches  * Ted Ts'o, 2/11/93.
13b9ee979eSJoe Perches  * Modified for sysctl support, 1/8/97, Chris Horn.
14b9ee979eSJoe Perches  * Fixed SMP synchronization, 08/08/99, Manfred Spraul
15b9ee979eSJoe Perches  *     manfred@colorfullife.com
16b9ee979eSJoe Perches  * Rewrote bits to get rid of console_lock
17b9ee979eSJoe Perches  *	01Mar01 Andrew Morton
18b9ee979eSJoe Perches  */
19b9ee979eSJoe Perches 
20dd5adbfbSHe Zhe #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21dd5adbfbSHe Zhe 
22b9ee979eSJoe Perches #include <linux/kernel.h>
23b9ee979eSJoe Perches #include <linux/mm.h>
24b9ee979eSJoe Perches #include <linux/tty.h>
25b9ee979eSJoe Perches #include <linux/tty_driver.h>
26b9ee979eSJoe Perches #include <linux/console.h>
27b9ee979eSJoe Perches #include <linux/init.h>
28b9ee979eSJoe Perches #include <linux/jiffies.h>
29b9ee979eSJoe Perches #include <linux/nmi.h>
30b9ee979eSJoe Perches #include <linux/module.h>
31b9ee979eSJoe Perches #include <linux/moduleparam.h>
32b9ee979eSJoe Perches #include <linux/delay.h>
33b9ee979eSJoe Perches #include <linux/smp.h>
34b9ee979eSJoe Perches #include <linux/security.h>
35b9ee979eSJoe Perches #include <linux/memblock.h>
36b9ee979eSJoe Perches #include <linux/syscalls.h>
37692f66f2SHari Bathini #include <linux/crash_core.h>
38b9ee979eSJoe Perches #include <linux/ratelimit.h>
39b9ee979eSJoe Perches #include <linux/kmsg_dump.h>
40b9ee979eSJoe Perches #include <linux/syslog.h>
41b9ee979eSJoe Perches #include <linux/cpu.h>
42b9ee979eSJoe Perches #include <linux/rculist.h>
43b9ee979eSJoe Perches #include <linux/poll.h>
44b9ee979eSJoe Perches #include <linux/irq_work.h>
45249771b8SAlex Elder #include <linux/ctype.h>
46e2e40f2cSChristoph Hellwig #include <linux/uio.h>
47e6017571SIngo Molnar #include <linux/sched/clock.h>
48b17b0153SIngo Molnar #include <linux/sched/debug.h>
4968db0cf1SIngo Molnar #include <linux/sched/task_stack.h>
50b9ee979eSJoe Perches 
517c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
5240a7d9f5SChristoph Hellwig #include <asm/sections.h>
53b9ee979eSJoe Perches 
5458eacfffSAbderrahmane Benbachir #include <trace/events/initcall.h>
55b9ee979eSJoe Perches #define CREATE_TRACE_POINTS
56b9ee979eSJoe Perches #include <trace/events/printk.h>
57b9ee979eSJoe Perches 
58896fbe20SJohn Ogness #include "printk_ringbuffer.h"
59d197c43dSJoe Perches #include "console_cmdline.h"
60bbeddf52SJoe Perches #include "braille.h"
6142a0bb3fSPetr Mladek #include "internal.h"
62d197c43dSJoe Perches 
63b9ee979eSJoe Perches int console_printk[4] = {
64a8fe19ebSBorislav Petkov 	CONSOLE_LOGLEVEL_DEFAULT,	/* console_loglevel */
6542a9dc0bSAlex Elder 	MESSAGE_LOGLEVEL_DEFAULT,	/* default_message_loglevel */
66a8fe19ebSBorislav Petkov 	CONSOLE_LOGLEVEL_MIN,		/* minimum_console_loglevel */
67a8fe19ebSBorislav Petkov 	CONSOLE_LOGLEVEL_DEFAULT,	/* default_console_loglevel */
68b9ee979eSJoe Perches };
69a1939185SPrarit Bhargava EXPORT_SYMBOL_GPL(console_printk);
70b9ee979eSJoe Perches 
7156e6c104SThomas Zimmermann atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
7256e6c104SThomas Zimmermann EXPORT_SYMBOL(ignore_console_lock_warning);
7356e6c104SThomas Zimmermann 
741f6ab566SPavankumar Kondeti EXPORT_TRACEPOINT_SYMBOL_GPL(console);
751f6ab566SPavankumar Kondeti 
76b9ee979eSJoe Perches /*
77b9ee979eSJoe Perches  * Low level drivers may need that to know if they can schedule in
78b9ee979eSJoe Perches  * their unblank() callback or not. So let's export it.
79b9ee979eSJoe Perches  */
80b9ee979eSJoe Perches int oops_in_progress;
81b9ee979eSJoe Perches EXPORT_SYMBOL(oops_in_progress);
82b9ee979eSJoe Perches 
83b9ee979eSJoe Perches /*
844dc64682SJohn Ogness  * console_mutex protects console_list updates and console->flags updates.
854dc64682SJohn Ogness  * The flags are synchronized only for consoles that are registered, i.e.
864dc64682SJohn Ogness  * accessible via the console list.
874dc64682SJohn Ogness  */
884dc64682SJohn Ogness static DEFINE_MUTEX(console_mutex);
894dc64682SJohn Ogness 
904dc64682SJohn Ogness /*
919e70a5e1SJohn Ogness  * console_sem protects updates to console->seq
92848a9c10SJohn Ogness  * and also provides serialization for console printing.
93b9ee979eSJoe Perches  */
9448380368SPeter Zijlstra static DEFINE_SEMAPHORE(console_sem, 1);
95d9a4af56SThomas Gleixner HLIST_HEAD(console_list);
96d9a4af56SThomas Gleixner EXPORT_SYMBOL_GPL(console_list);
976c4afa79SJohn Ogness DEFINE_STATIC_SRCU(console_srcu);
98b9ee979eSJoe Perches 
99c39ea0b9SFeng Tang /*
100c39ea0b9SFeng Tang  * System may need to suppress printk message under certain
101c39ea0b9SFeng Tang  * circumstances, like after kernel panic happens.
102c39ea0b9SFeng Tang  */
103c39ea0b9SFeng Tang int __read_mostly suppress_printk;
104c39ea0b9SFeng Tang 
10513fb0f74SStephen Brennan /*
10613fb0f74SStephen Brennan  * During panic, heavy printk by other CPUs can delay the
10713fb0f74SStephen Brennan  * panic and risk deadlock on console resources.
10813fb0f74SStephen Brennan  */
109ce06e863SJiapeng Chong static int __read_mostly suppress_panic_printk;
11013fb0f74SStephen Brennan 
111b9ee979eSJoe Perches #ifdef CONFIG_LOCKDEP
112b9ee979eSJoe Perches static struct lockdep_map console_lock_dep_map = {
113b9ee979eSJoe Perches 	.name = "console_lock"
114b9ee979eSJoe Perches };
1154dc64682SJohn Ogness 
lockdep_assert_console_list_lock_held(void)1164dc64682SJohn Ogness void lockdep_assert_console_list_lock_held(void)
1174dc64682SJohn Ogness {
1184dc64682SJohn Ogness 	lockdep_assert_held(&console_mutex);
1194dc64682SJohn Ogness }
1204dc64682SJohn Ogness EXPORT_SYMBOL(lockdep_assert_console_list_lock_held);
121b9ee979eSJoe Perches #endif
122b9ee979eSJoe Perches 
1236c4afa79SJohn Ogness #ifdef CONFIG_DEBUG_LOCK_ALLOC
console_srcu_read_lock_is_held(void)1246c4afa79SJohn Ogness bool console_srcu_read_lock_is_held(void)
1256c4afa79SJohn Ogness {
1266c4afa79SJohn Ogness 	return srcu_read_lock_held(&console_srcu);
1276c4afa79SJohn Ogness }
1283ef5abd9SJohn Ogness EXPORT_SYMBOL(console_srcu_read_lock_is_held);
129b9ee979eSJoe Perches #endif
130b9ee979eSJoe Perches 
131750afe7bSBorislav Petkov enum devkmsg_log_bits {
132750afe7bSBorislav Petkov 	__DEVKMSG_LOG_BIT_ON = 0,
133750afe7bSBorislav Petkov 	__DEVKMSG_LOG_BIT_OFF,
134750afe7bSBorislav Petkov 	__DEVKMSG_LOG_BIT_LOCK,
135750afe7bSBorislav Petkov };
136750afe7bSBorislav Petkov 
137750afe7bSBorislav Petkov enum devkmsg_log_masks {
138750afe7bSBorislav Petkov 	DEVKMSG_LOG_MASK_ON             = BIT(__DEVKMSG_LOG_BIT_ON),
139750afe7bSBorislav Petkov 	DEVKMSG_LOG_MASK_OFF            = BIT(__DEVKMSG_LOG_BIT_OFF),
140750afe7bSBorislav Petkov 	DEVKMSG_LOG_MASK_LOCK           = BIT(__DEVKMSG_LOG_BIT_LOCK),
141750afe7bSBorislav Petkov };
142750afe7bSBorislav Petkov 
143750afe7bSBorislav Petkov /* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
144750afe7bSBorislav Petkov #define DEVKMSG_LOG_MASK_DEFAULT	0
145750afe7bSBorislav Petkov 
146750afe7bSBorislav Petkov static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
147750afe7bSBorislav Petkov 
__control_devkmsg(char * str)148750afe7bSBorislav Petkov static int __control_devkmsg(char *str)
149750afe7bSBorislav Petkov {
15035c35493SChuhong Yuan 	size_t len;
15135c35493SChuhong Yuan 
152750afe7bSBorislav Petkov 	if (!str)
153750afe7bSBorislav Petkov 		return -EINVAL;
154750afe7bSBorislav Petkov 
15535c35493SChuhong Yuan 	len = str_has_prefix(str, "on");
15635c35493SChuhong Yuan 	if (len) {
157750afe7bSBorislav Petkov 		devkmsg_log = DEVKMSG_LOG_MASK_ON;
15835c35493SChuhong Yuan 		return len;
159750afe7bSBorislav Petkov 	}
16035c35493SChuhong Yuan 
16135c35493SChuhong Yuan 	len = str_has_prefix(str, "off");
16235c35493SChuhong Yuan 	if (len) {
16335c35493SChuhong Yuan 		devkmsg_log = DEVKMSG_LOG_MASK_OFF;
16435c35493SChuhong Yuan 		return len;
16535c35493SChuhong Yuan 	}
16635c35493SChuhong Yuan 
16735c35493SChuhong Yuan 	len = str_has_prefix(str, "ratelimit");
16835c35493SChuhong Yuan 	if (len) {
16935c35493SChuhong Yuan 		devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
17035c35493SChuhong Yuan 		return len;
17135c35493SChuhong Yuan 	}
17235c35493SChuhong Yuan 
173750afe7bSBorislav Petkov 	return -EINVAL;
174750afe7bSBorislav Petkov }
175750afe7bSBorislav Petkov 
control_devkmsg(char * str)176750afe7bSBorislav Petkov static int __init control_devkmsg(char *str)
177750afe7bSBorislav Petkov {
178b665eae7SRandy Dunlap 	if (__control_devkmsg(str) < 0) {
179b665eae7SRandy Dunlap 		pr_warn("printk.devkmsg: bad option string '%s'\n", str);
180750afe7bSBorislav Petkov 		return 1;
181b665eae7SRandy Dunlap 	}
182750afe7bSBorislav Petkov 
183750afe7bSBorislav Petkov 	/*
184750afe7bSBorislav Petkov 	 * Set sysctl string accordingly:
185750afe7bSBorislav Petkov 	 */
1866fd78a1aSSergey Senozhatsky 	if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
1876fd78a1aSSergey Senozhatsky 		strcpy(devkmsg_log_str, "on");
1886fd78a1aSSergey Senozhatsky 	else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
1896fd78a1aSSergey Senozhatsky 		strcpy(devkmsg_log_str, "off");
190750afe7bSBorislav Petkov 	/* else "ratelimit" which is set by default. */
191750afe7bSBorislav Petkov 
192750afe7bSBorislav Petkov 	/*
193750afe7bSBorislav Petkov 	 * Sysctl cannot change it anymore. The kernel command line setting of
194750afe7bSBorislav Petkov 	 * this parameter is to force the setting to be permanent throughout the
195750afe7bSBorislav Petkov 	 * runtime of the system. This is a precation measure against userspace
196750afe7bSBorislav Petkov 	 * trying to be a smarta** and attempting to change it up on us.
197750afe7bSBorislav Petkov 	 */
198750afe7bSBorislav Petkov 	devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
199750afe7bSBorislav Petkov 
200b665eae7SRandy Dunlap 	return 1;
201750afe7bSBorislav Petkov }
202750afe7bSBorislav Petkov __setup("printk.devkmsg=", control_devkmsg);
203750afe7bSBorislav Petkov 
204750afe7bSBorislav Petkov char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
205fdcd4073SXiaoming Ni #if defined(CONFIG_PRINTK) && defined(CONFIG_SYSCTL)
devkmsg_sysctl_set_loglvl(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)206750afe7bSBorislav Petkov int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
20732927393SChristoph Hellwig 			      void *buffer, size_t *lenp, loff_t *ppos)
208750afe7bSBorislav Petkov {
209750afe7bSBorislav Petkov 	char old_str[DEVKMSG_STR_MAX_SIZE];
210750afe7bSBorislav Petkov 	unsigned int old;
211750afe7bSBorislav Petkov 	int err;
212750afe7bSBorislav Petkov 
213750afe7bSBorislav Petkov 	if (write) {
214750afe7bSBorislav Petkov 		if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
215750afe7bSBorislav Petkov 			return -EINVAL;
216750afe7bSBorislav Petkov 
217750afe7bSBorislav Petkov 		old = devkmsg_log;
218750afe7bSBorislav Petkov 		strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
219750afe7bSBorislav Petkov 	}
220750afe7bSBorislav Petkov 
221750afe7bSBorislav Petkov 	err = proc_dostring(table, write, buffer, lenp, ppos);
222750afe7bSBorislav Petkov 	if (err)
223750afe7bSBorislav Petkov 		return err;
224750afe7bSBorislav Petkov 
225750afe7bSBorislav Petkov 	if (write) {
226750afe7bSBorislav Petkov 		err = __control_devkmsg(devkmsg_log_str);
227750afe7bSBorislav Petkov 
228750afe7bSBorislav Petkov 		/*
229750afe7bSBorislav Petkov 		 * Do not accept an unknown string OR a known string with
230750afe7bSBorislav Petkov 		 * trailing crap...
231750afe7bSBorislav Petkov 		 */
232750afe7bSBorislav Petkov 		if (err < 0 || (err + 1 != *lenp)) {
233750afe7bSBorislav Petkov 
234750afe7bSBorislav Petkov 			/* ... and restore old setting. */
235750afe7bSBorislav Petkov 			devkmsg_log = old;
236750afe7bSBorislav Petkov 			strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
237750afe7bSBorislav Petkov 
238750afe7bSBorislav Petkov 			return -EINVAL;
239750afe7bSBorislav Petkov 		}
240750afe7bSBorislav Petkov 	}
241750afe7bSBorislav Petkov 
242750afe7bSBorislav Petkov 	return 0;
243750afe7bSBorislav Petkov }
244fdcd4073SXiaoming Ni #endif /* CONFIG_PRINTK && CONFIG_SYSCTL */
245750afe7bSBorislav Petkov 
2466c4afa79SJohn Ogness /**
2474dc64682SJohn Ogness  * console_list_lock - Lock the console list
2484dc64682SJohn Ogness  *
2494dc64682SJohn Ogness  * For console list or console->flags updates
2504dc64682SJohn Ogness  */
console_list_lock(void)2514dc64682SJohn Ogness void console_list_lock(void)
2524dc64682SJohn Ogness {
2534dc64682SJohn Ogness 	/*
2546f883675SJohn Ogness 	 * In unregister_console() and console_force_preferred_locked(),
2556f883675SJohn Ogness 	 * synchronize_srcu() is called with the console_list_lock held.
2566f883675SJohn Ogness 	 * Therefore it is not allowed that the console_list_lock is taken
2576f883675SJohn Ogness 	 * with the srcu_lock held.
2584dc64682SJohn Ogness 	 *
2594dc64682SJohn Ogness 	 * Detecting if this context is really in the read-side critical
2604dc64682SJohn Ogness 	 * section is only possible if the appropriate debug options are
2614dc64682SJohn Ogness 	 * enabled.
2624dc64682SJohn Ogness 	 */
2634dc64682SJohn Ogness 	WARN_ON_ONCE(debug_lockdep_rcu_enabled() &&
2644dc64682SJohn Ogness 		     srcu_read_lock_held(&console_srcu));
2654dc64682SJohn Ogness 
2664dc64682SJohn Ogness 	mutex_lock(&console_mutex);
2674dc64682SJohn Ogness }
2684dc64682SJohn Ogness EXPORT_SYMBOL(console_list_lock);
2694dc64682SJohn Ogness 
2704dc64682SJohn Ogness /**
2714dc64682SJohn Ogness  * console_list_unlock - Unlock the console list
2724dc64682SJohn Ogness  *
2734dc64682SJohn Ogness  * Counterpart to console_list_lock()
2744dc64682SJohn Ogness  */
console_list_unlock(void)2754dc64682SJohn Ogness void console_list_unlock(void)
2764dc64682SJohn Ogness {
2774dc64682SJohn Ogness 	mutex_unlock(&console_mutex);
2784dc64682SJohn Ogness }
2794dc64682SJohn Ogness EXPORT_SYMBOL(console_list_unlock);
2804dc64682SJohn Ogness 
2814dc64682SJohn Ogness /**
2826c4afa79SJohn Ogness  * console_srcu_read_lock - Register a new reader for the
2836c4afa79SJohn Ogness  *	SRCU-protected console list
2846c4afa79SJohn Ogness  *
2856c4afa79SJohn Ogness  * Use for_each_console_srcu() to iterate the console list
2866c4afa79SJohn Ogness  *
2876c4afa79SJohn Ogness  * Context: Any context.
2885074ffbeSJohn Ogness  * Return: A cookie to pass to console_srcu_read_unlock().
2896c4afa79SJohn Ogness  */
console_srcu_read_lock(void)2906c4afa79SJohn Ogness int console_srcu_read_lock(void)
2916c4afa79SJohn Ogness {
2926c4afa79SJohn Ogness 	return srcu_read_lock_nmisafe(&console_srcu);
2936c4afa79SJohn Ogness }
2946c4afa79SJohn Ogness EXPORT_SYMBOL(console_srcu_read_lock);
2956c4afa79SJohn Ogness 
2966c4afa79SJohn Ogness /**
2976c4afa79SJohn Ogness  * console_srcu_read_unlock - Unregister an old reader from
2986c4afa79SJohn Ogness  *	the SRCU-protected console list
2995074ffbeSJohn Ogness  * @cookie: cookie returned from console_srcu_read_lock()
3006c4afa79SJohn Ogness  *
3016c4afa79SJohn Ogness  * Counterpart to console_srcu_read_lock()
3026c4afa79SJohn Ogness  */
console_srcu_read_unlock(int cookie)3036c4afa79SJohn Ogness void console_srcu_read_unlock(int cookie)
3046c4afa79SJohn Ogness {
3056c4afa79SJohn Ogness 	srcu_read_unlock_nmisafe(&console_srcu, cookie);
3066c4afa79SJohn Ogness }
3076c4afa79SJohn Ogness EXPORT_SYMBOL(console_srcu_read_unlock);
3086c4afa79SJohn Ogness 
3096fe29354STejun Heo /*
310bd8d7cf5SJan Kara  * Helper macros to handle lockdep when locking/unlocking console_sem. We use
311bd8d7cf5SJan Kara  * macros instead of functions so that _RET_IP_ contains useful information.
312bd8d7cf5SJan Kara  */
313bd8d7cf5SJan Kara #define down_console_sem() do { \
314bd8d7cf5SJan Kara 	down(&console_sem);\
315bd8d7cf5SJan Kara 	mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
316bd8d7cf5SJan Kara } while (0)
317bd8d7cf5SJan Kara 
__down_trylock_console_sem(unsigned long ip)318bd8d7cf5SJan Kara static int __down_trylock_console_sem(unsigned long ip)
319bd8d7cf5SJan Kara {
320f975237bSSergey Senozhatsky 	int lock_failed;
321f975237bSSergey Senozhatsky 	unsigned long flags;
322f975237bSSergey Senozhatsky 
323f975237bSSergey Senozhatsky 	/*
324f975237bSSergey Senozhatsky 	 * Here and in __up_console_sem() we need to be in safe mode,
325f975237bSSergey Senozhatsky 	 * because spindump/WARN/etc from under console ->lock will
326f975237bSSergey Senozhatsky 	 * deadlock in printk()->down_trylock_console_sem() otherwise.
327f975237bSSergey Senozhatsky 	 */
328f975237bSSergey Senozhatsky 	printk_safe_enter_irqsave(flags);
329f975237bSSergey Senozhatsky 	lock_failed = down_trylock(&console_sem);
330f975237bSSergey Senozhatsky 	printk_safe_exit_irqrestore(flags);
331f975237bSSergey Senozhatsky 
332f975237bSSergey Senozhatsky 	if (lock_failed)
333bd8d7cf5SJan Kara 		return 1;
334bd8d7cf5SJan Kara 	mutex_acquire(&console_lock_dep_map, 0, 1, ip);
335bd8d7cf5SJan Kara 	return 0;
336bd8d7cf5SJan Kara }
337bd8d7cf5SJan Kara #define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
338bd8d7cf5SJan Kara 
__up_console_sem(unsigned long ip)339f975237bSSergey Senozhatsky static void __up_console_sem(unsigned long ip)
340f975237bSSergey Senozhatsky {
341f975237bSSergey Senozhatsky 	unsigned long flags;
342f975237bSSergey Senozhatsky 
3435facae4fSQian Cai 	mutex_release(&console_lock_dep_map, ip);
344f975237bSSergey Senozhatsky 
345f975237bSSergey Senozhatsky 	printk_safe_enter_irqsave(flags);
346f975237bSSergey Senozhatsky 	up(&console_sem);
347f975237bSSergey Senozhatsky 	printk_safe_exit_irqrestore(flags);
348f975237bSSergey Senozhatsky }
349f975237bSSergey Senozhatsky #define up_console_sem() __up_console_sem(_RET_IP_)
350bd8d7cf5SJan Kara 
panic_in_progress(void)35177498617SStephen Brennan static bool panic_in_progress(void)
35277498617SStephen Brennan {
35377498617SStephen Brennan 	return unlikely(atomic_read(&panic_cpu) != PANIC_CPU_INVALID);
35477498617SStephen Brennan }
35577498617SStephen Brennan 
356bd8d7cf5SJan Kara /*
357007eeab7SPetr Mladek  * This is used for debugging the mess that is the VT code by
358007eeab7SPetr Mladek  * keeping track if we have the console semaphore held. It's
359007eeab7SPetr Mladek  * definitely not the perfect debug tool (we don't know if _WE_
360007eeab7SPetr Mladek  * hold it and are racing, but it helps tracking those weird code
361007eeab7SPetr Mladek  * paths in the console code where we end up in places I want
362007eeab7SPetr Mladek  * locked without the console semaphore held).
363007eeab7SPetr Mladek  */
3649e70a5e1SJohn Ogness static int console_locked;
365b9ee979eSJoe Perches 
366b9ee979eSJoe Perches /*
367b9ee979eSJoe Perches  *	Array of consoles built from command line options (console=)
368b9ee979eSJoe Perches  */
369b9ee979eSJoe Perches 
370b9ee979eSJoe Perches #define MAX_CMDLINECONSOLES 8
371b9ee979eSJoe Perches 
372b9ee979eSJoe Perches static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
373d197c43dSJoe Perches 
374b9ee979eSJoe Perches static int preferred_console = -1;
375b9ee979eSJoe Perches int console_set_on_cmdline;
376b9ee979eSJoe Perches EXPORT_SYMBOL(console_set_on_cmdline);
377b9ee979eSJoe Perches 
378b9ee979eSJoe Perches /* Flag: console code may call schedule() */
379b9ee979eSJoe Perches static int console_may_schedule;
380b9ee979eSJoe Perches 
381cca10d58SSergey Senozhatsky enum con_msg_format_flags {
382cca10d58SSergey Senozhatsky 	MSG_FORMAT_DEFAULT	= 0,
383cca10d58SSergey Senozhatsky 	MSG_FORMAT_SYSLOG	= (1 << 0),
384cca10d58SSergey Senozhatsky };
385cca10d58SSergey Senozhatsky 
386cca10d58SSergey Senozhatsky static int console_msg_format = MSG_FORMAT_DEFAULT;
387cca10d58SSergey Senozhatsky 
388b9ee979eSJoe Perches /*
389896fbe20SJohn Ogness  * The printk log buffer consists of a sequenced collection of records, each
39074caba7fSJohn Ogness  * containing variable length message text. Every record also contains its
39174caba7fSJohn Ogness  * own meta-data (@info).
392b9ee979eSJoe Perches  *
393896fbe20SJohn Ogness  * Every record meta-data carries the timestamp in microseconds, as well as
394896fbe20SJohn Ogness  * the standard userspace syslog level and syslog facility. The usual kernel
395896fbe20SJohn Ogness  * messages use LOG_KERN; userspace-injected messages always carry a matching
396896fbe20SJohn Ogness  * syslog facility, by default LOG_USER. The origin of every message can be
397896fbe20SJohn Ogness  * reliably determined that way.
398b9ee979eSJoe Perches  *
399896fbe20SJohn Ogness  * The human readable log message of a record is available in @text, the
400896fbe20SJohn Ogness  * length of the message text in @text_len. The stored message is not
401896fbe20SJohn Ogness  * terminated.
402b9ee979eSJoe Perches  *
403896fbe20SJohn Ogness  * Optionally, a record can carry a dictionary of properties (key/value
40474caba7fSJohn Ogness  * pairs), to provide userspace with a machine-readable message context.
405b9ee979eSJoe Perches  *
406b9ee979eSJoe Perches  * Examples for well-defined, commonly used property names are:
407b9ee979eSJoe Perches  *   DEVICE=b12:8               device identifier
408b9ee979eSJoe Perches  *                                b12:8         block dev_t
409b9ee979eSJoe Perches  *                                c127:3        char dev_t
410b9ee979eSJoe Perches  *                                n8            netdev ifindex
411b9ee979eSJoe Perches  *                                +sound:card0  subsystem:devname
412b9ee979eSJoe Perches  *   SUBSYSTEM=pci              driver-core subsystem name
413b9ee979eSJoe Perches  *
41474caba7fSJohn Ogness  * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
41574caba7fSJohn Ogness  * and values are terminated by a '\0' character.
416b9ee979eSJoe Perches  *
417896fbe20SJohn Ogness  * Example of record values:
418896fbe20SJohn Ogness  *   record.text_buf                = "it's a line" (unterminated)
419896fbe20SJohn Ogness  *   record.info.seq                = 56
420896fbe20SJohn Ogness  *   record.info.ts_nsec            = 36863
421896fbe20SJohn Ogness  *   record.info.text_len           = 11
422896fbe20SJohn Ogness  *   record.info.facility           = 0 (LOG_KERN)
423896fbe20SJohn Ogness  *   record.info.flags              = 0
424896fbe20SJohn Ogness  *   record.info.level              = 3 (LOG_ERR)
425896fbe20SJohn Ogness  *   record.info.caller_id          = 299 (task 299)
42674caba7fSJohn Ogness  *   record.info.dev_info.subsystem = "pci" (terminated)
42774caba7fSJohn Ogness  *   record.info.dev_info.device    = "+pci:0000:00:01.0" (terminated)
428b9ee979eSJoe Perches  *
429896fbe20SJohn Ogness  * The 'struct printk_info' buffer must never be directly exported to
430b9ee979eSJoe Perches  * userspace, it is a kernel-private implementation detail that might
431b9ee979eSJoe Perches  * need to be changed in the future, when the requirements change.
432b9ee979eSJoe Perches  *
433b9ee979eSJoe Perches  * /dev/kmsg exports the structured data in the following line format:
434b389645fSAntonio Ospite  *   "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
435b389645fSAntonio Ospite  *
436b389645fSAntonio Ospite  * Users of the export format should ignore possible additional values
437b389645fSAntonio Ospite  * separated by ',', and find the message after the ';' character.
438b9ee979eSJoe Perches  *
439b9ee979eSJoe Perches  * The optional key/value pairs are attached as continuation lines starting
440b9ee979eSJoe Perches  * with a space character and terminated by a newline. All possible
441b9ee979eSJoe Perches  * non-prinatable characters are escaped in the "\xff" notation.
442b9ee979eSJoe Perches  */
443b9ee979eSJoe Perches 
444636babdcSJohn Ogness /* syslog_lock protects syslog_* variables and write access to clear_seq. */
445b371cbb5SJohn Ogness static DEFINE_MUTEX(syslog_lock);
446636babdcSJohn Ogness 
447b9ee979eSJoe Perches #ifdef CONFIG_PRINTK
448b9ee979eSJoe Perches DECLARE_WAIT_QUEUE_HEAD(log_wait);
449636babdcSJohn Ogness /* All 3 protected by @syslog_lock. */
450b9ee979eSJoe Perches /* the next printk record to read by syslog(READ) or /proc/kmsg */
451b9ee979eSJoe Perches static u64 syslog_seq;
452b9ee979eSJoe Perches static size_t syslog_partial;
453e80c1a9dSTetsuo Handa static bool syslog_time;
454b9ee979eSJoe Perches 
4557d7a23a9SJohn Ogness struct latched_seq {
4567d7a23a9SJohn Ogness 	seqcount_latch_t	latch;
4577d7a23a9SJohn Ogness 	u64			val[2];
4587d7a23a9SJohn Ogness };
4597d7a23a9SJohn Ogness 
4607d7a23a9SJohn Ogness /*
4617d7a23a9SJohn Ogness  * The next printk record to read after the last 'clear' command. There are
4627d7a23a9SJohn Ogness  * two copies (updated with seqcount_latch) so that reads can locklessly
463636babdcSJohn Ogness  * access a valid value. Writers are synchronized by @syslog_lock.
4647d7a23a9SJohn Ogness  */
4657d7a23a9SJohn Ogness static struct latched_seq clear_seq = {
4667d7a23a9SJohn Ogness 	.latch		= SEQCNT_LATCH_ZERO(clear_seq.latch),
4677d7a23a9SJohn Ogness 	.val[0]		= 0,
4687d7a23a9SJohn Ogness 	.val[1]		= 0,
4697d7a23a9SJohn Ogness };
470b9ee979eSJoe Perches 
4713824657cSMathias Krause #define LOG_LEVEL(v)		((v) & 0x07)
4723824657cSMathias Krause #define LOG_FACILITY(v)		((v) >> 3 & 0xff)
4733824657cSMathias Krause 
474b9ee979eSJoe Perches /* record buffer */
475896fbe20SJohn Ogness #define LOG_ALIGN __alignof__(unsigned long)
476b9ee979eSJoe Perches #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
477*4acf6babSKuan-Wei Chiu #define LOG_BUF_LEN_MAX ((u32)1 << 31)
478b9ee979eSJoe Perches static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
479b9ee979eSJoe Perches static char *log_buf = __log_buf;
480b9ee979eSJoe Perches static u32 log_buf_len = __LOG_BUF_LEN;
481b9ee979eSJoe Perches 
482ab6f762fSSergey Senozhatsky /*
483896fbe20SJohn Ogness  * Define the average message size. This only affects the number of
484896fbe20SJohn Ogness  * descriptors that will be available. Underestimating is better than
485896fbe20SJohn Ogness  * overestimating (too many available descriptors is better than not enough).
486896fbe20SJohn Ogness  */
487896fbe20SJohn Ogness #define PRB_AVGBITS 5	/* 32 character average length */
488896fbe20SJohn Ogness 
489896fbe20SJohn Ogness #if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
490896fbe20SJohn Ogness #error CONFIG_LOG_BUF_SHIFT value too small.
491896fbe20SJohn Ogness #endif
492896fbe20SJohn Ogness _DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
493f35efc78SJohn Ogness 		 PRB_AVGBITS, &__log_buf[0]);
494896fbe20SJohn Ogness 
495896fbe20SJohn Ogness static struct printk_ringbuffer printk_rb_dynamic;
496896fbe20SJohn Ogness 
497896fbe20SJohn Ogness static struct printk_ringbuffer *prb = &printk_rb_static;
498896fbe20SJohn Ogness 
499896fbe20SJohn Ogness /*
500ab6f762fSSergey Senozhatsky  * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
501ab6f762fSSergey Senozhatsky  * per_cpu_areas are initialised. This variable is set to true when
502ab6f762fSSergey Senozhatsky  * it's safe to access per-CPU data.
503ab6f762fSSergey Senozhatsky  */
50478ba392cSThomas Gleixner static bool __printk_percpu_data_ready __ro_after_init;
505ab6f762fSSergey Senozhatsky 
printk_percpu_data_ready(void)506ab6f762fSSergey Senozhatsky bool printk_percpu_data_ready(void)
507ab6f762fSSergey Senozhatsky {
508ab6f762fSSergey Senozhatsky 	return __printk_percpu_data_ready;
509ab6f762fSSergey Senozhatsky }
510ab6f762fSSergey Senozhatsky 
511636babdcSJohn Ogness /* Must be called under syslog_lock. */
latched_seq_write(struct latched_seq * ls,u64 val)5127d7a23a9SJohn Ogness static void latched_seq_write(struct latched_seq *ls, u64 val)
5137d7a23a9SJohn Ogness {
5147d7a23a9SJohn Ogness 	raw_write_seqcount_latch(&ls->latch);
5157d7a23a9SJohn Ogness 	ls->val[0] = val;
5167d7a23a9SJohn Ogness 	raw_write_seqcount_latch(&ls->latch);
5177d7a23a9SJohn Ogness 	ls->val[1] = val;
5187d7a23a9SJohn Ogness }
5197d7a23a9SJohn Ogness 
5207d7a23a9SJohn Ogness /* Can be called from any context. */
latched_seq_read_nolock(struct latched_seq * ls)5217d7a23a9SJohn Ogness static u64 latched_seq_read_nolock(struct latched_seq *ls)
5227d7a23a9SJohn Ogness {
5237d7a23a9SJohn Ogness 	unsigned int seq;
5247d7a23a9SJohn Ogness 	unsigned int idx;
5257d7a23a9SJohn Ogness 	u64 val;
5267d7a23a9SJohn Ogness 
5277d7a23a9SJohn Ogness 	do {
5287d7a23a9SJohn Ogness 		seq = raw_read_seqcount_latch(&ls->latch);
5297d7a23a9SJohn Ogness 		idx = seq & 0x1;
5307d7a23a9SJohn Ogness 		val = ls->val[idx];
531d16317deSPeter Zijlstra 	} while (raw_read_seqcount_latch_retry(&ls->latch, seq));
5327d7a23a9SJohn Ogness 
5337d7a23a9SJohn Ogness 	return val;
5347d7a23a9SJohn Ogness }
5357d7a23a9SJohn Ogness 
53614c4000aSVasant Hegde /* Return log buffer address */
log_buf_addr_get(void)53714c4000aSVasant Hegde char *log_buf_addr_get(void)
53814c4000aSVasant Hegde {
53914c4000aSVasant Hegde 	return log_buf;
54014c4000aSVasant Hegde }
54114c4000aSVasant Hegde 
54214c4000aSVasant Hegde /* Return log buffer size */
log_buf_len_get(void)54314c4000aSVasant Hegde u32 log_buf_len_get(void)
54414c4000aSVasant Hegde {
54514c4000aSVasant Hegde 	return log_buf_len;
54614c4000aSVasant Hegde }
54714c4000aSVasant Hegde 
54855bd53a4SPetr Mladek /*
54955bd53a4SPetr Mladek  * Define how much of the log buffer we could take at maximum. The value
55055bd53a4SPetr Mladek  * must be greater than two. Note that only half of the buffer is available
55155bd53a4SPetr Mladek  * when the index points to the middle.
55255bd53a4SPetr Mladek  */
55355bd53a4SPetr Mladek #define MAX_LOG_TAKE_PART 4
55455bd53a4SPetr Mladek static const char trunc_msg[] = "<truncated>";
55555bd53a4SPetr Mladek 
truncate_msg(u16 * text_len,u16 * trunc_msg_len)556896fbe20SJohn Ogness static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
55755bd53a4SPetr Mladek {
55855bd53a4SPetr Mladek 	/*
55955bd53a4SPetr Mladek 	 * The message should not take the whole buffer. Otherwise, it might
56055bd53a4SPetr Mladek 	 * get removed too soon.
56155bd53a4SPetr Mladek 	 */
56255bd53a4SPetr Mladek 	u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
563896fbe20SJohn Ogness 
56455bd53a4SPetr Mladek 	if (*text_len > max_text_len)
56555bd53a4SPetr Mladek 		*text_len = max_text_len;
566896fbe20SJohn Ogness 
567896fbe20SJohn Ogness 	/* enable the warning message (if there is room) */
56855bd53a4SPetr Mladek 	*trunc_msg_len = strlen(trunc_msg);
569896fbe20SJohn Ogness 	if (*text_len >= *trunc_msg_len)
570896fbe20SJohn Ogness 		*text_len -= *trunc_msg_len;
571896fbe20SJohn Ogness 	else
572896fbe20SJohn Ogness 		*trunc_msg_len = 0;
57355bd53a4SPetr Mladek }
57455bd53a4SPetr Mladek 
575e99aa461SAlex Elder int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
576b9ee979eSJoe Perches 
syslog_action_restricted(int type)577b9ee979eSJoe Perches static int syslog_action_restricted(int type)
578b9ee979eSJoe Perches {
579b9ee979eSJoe Perches 	if (dmesg_restrict)
580b9ee979eSJoe Perches 		return 1;
581b9ee979eSJoe Perches 	/*
582b9ee979eSJoe Perches 	 * Unless restricted, we allow "read all" and "get buffer size"
583b9ee979eSJoe Perches 	 * for everybody.
584b9ee979eSJoe Perches 	 */
585b9ee979eSJoe Perches 	return type != SYSLOG_ACTION_READ_ALL &&
586b9ee979eSJoe Perches 	       type != SYSLOG_ACTION_SIZE_BUFFER;
587b9ee979eSJoe Perches }
588b9ee979eSJoe Perches 
check_syslog_permissions(int type,int source)589c71b02e4SKees Cook static int check_syslog_permissions(int type, int source)
590b9ee979eSJoe Perches {
591b9ee979eSJoe Perches 	/*
592b9ee979eSJoe Perches 	 * If this is from /proc/kmsg and we've already opened it, then we've
593b9ee979eSJoe Perches 	 * already done the capabilities checks at open time.
594b9ee979eSJoe Perches 	 */
5953ea4331cSVasily Averin 	if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
596d194e5d6SVasily Averin 		goto ok;
597b9ee979eSJoe Perches 
598b9ee979eSJoe Perches 	if (syslog_action_restricted(type)) {
599b9ee979eSJoe Perches 		if (capable(CAP_SYSLOG))
600d194e5d6SVasily Averin 			goto ok;
601b9ee979eSJoe Perches 		/*
602b9ee979eSJoe Perches 		 * For historical reasons, accept CAP_SYS_ADMIN too, with
603b9ee979eSJoe Perches 		 * a warning.
604b9ee979eSJoe Perches 		 */
605b9ee979eSJoe Perches 		if (capable(CAP_SYS_ADMIN)) {
606b9ee979eSJoe Perches 			pr_warn_once("%s (%d): Attempt to access syslog with "
607b9ee979eSJoe Perches 				     "CAP_SYS_ADMIN but no CAP_SYSLOG "
608b9ee979eSJoe Perches 				     "(deprecated).\n",
609b9ee979eSJoe Perches 				 current->comm, task_pid_nr(current));
610d194e5d6SVasily Averin 			goto ok;
611b9ee979eSJoe Perches 		}
612b9ee979eSJoe Perches 		return -EPERM;
613b9ee979eSJoe Perches 	}
614d194e5d6SVasily Averin ok:
615b9ee979eSJoe Perches 	return security_syslog(type);
616b9ee979eSJoe Perches }
617b9ee979eSJoe Perches 
append_char(char ** pp,char * e,char c)618d43ff430STejun Heo static void append_char(char **pp, char *e, char c)
619d43ff430STejun Heo {
620d43ff430STejun Heo 	if (*pp < e)
621d43ff430STejun Heo 		*(*pp)++ = c;
622d43ff430STejun Heo }
623b9ee979eSJoe Perches 
info_print_ext_header(char * buf,size_t size,struct printk_info * info)624896fbe20SJohn Ogness static ssize_t info_print_ext_header(char *buf, size_t size,
625896fbe20SJohn Ogness 				     struct printk_info *info)
6260a295e67STejun Heo {
627896fbe20SJohn Ogness 	u64 ts_usec = info->ts_nsec;
62815ff2069STetsuo Handa 	char caller[20];
62915ff2069STetsuo Handa #ifdef CONFIG_PRINTK_CALLER
630896fbe20SJohn Ogness 	u32 id = info->caller_id;
63115ff2069STetsuo Handa 
63215ff2069STetsuo Handa 	snprintf(caller, sizeof(caller), ",caller=%c%u",
63315ff2069STetsuo Handa 		 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
63415ff2069STetsuo Handa #else
63515ff2069STetsuo Handa 	caller[0] = '\0';
63615ff2069STetsuo Handa #endif
6370a295e67STejun Heo 
6380a295e67STejun Heo 	do_div(ts_usec, 1000);
6390a295e67STejun Heo 
64015ff2069STetsuo Handa 	return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
641896fbe20SJohn Ogness 			 (info->facility << 3) | info->level, info->seq,
642896fbe20SJohn Ogness 			 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
6430a295e67STejun Heo }
6440a295e67STejun Heo 
msg_add_ext_text(char * buf,size_t size,const char * text,size_t text_len,unsigned char endc)64574caba7fSJohn Ogness static ssize_t msg_add_ext_text(char *buf, size_t size,
64674caba7fSJohn Ogness 				const char *text, size_t text_len,
64774caba7fSJohn Ogness 				unsigned char endc)
6480a295e67STejun Heo {
6490a295e67STejun Heo 	char *p = buf, *e = buf + size;
6500a295e67STejun Heo 	size_t i;
6510a295e67STejun Heo 
6520a295e67STejun Heo 	/* escape non-printable characters */
6530a295e67STejun Heo 	for (i = 0; i < text_len; i++) {
6540a295e67STejun Heo 		unsigned char c = text[i];
6550a295e67STejun Heo 
6560a295e67STejun Heo 		if (c < ' ' || c >= 127 || c == '\\')
6570a295e67STejun Heo 			p += scnprintf(p, e - p, "\\x%02x", c);
6580a295e67STejun Heo 		else
6590a295e67STejun Heo 			append_char(&p, e, c);
6600a295e67STejun Heo 	}
66174caba7fSJohn Ogness 	append_char(&p, e, endc);
6620a295e67STejun Heo 
6630a295e67STejun Heo 	return p - buf;
6640a295e67STejun Heo }
6650a295e67STejun Heo 
msg_add_dict_text(char * buf,size_t size,const char * key,const char * val)66674caba7fSJohn Ogness static ssize_t msg_add_dict_text(char *buf, size_t size,
66774caba7fSJohn Ogness 				 const char *key, const char *val)
66874caba7fSJohn Ogness {
66974caba7fSJohn Ogness 	size_t val_len = strlen(val);
67074caba7fSJohn Ogness 	ssize_t len;
67174caba7fSJohn Ogness 
67274caba7fSJohn Ogness 	if (!val_len)
67374caba7fSJohn Ogness 		return 0;
67474caba7fSJohn Ogness 
67574caba7fSJohn Ogness 	len = msg_add_ext_text(buf, size, "", 0, ' ');	/* dict prefix */
67674caba7fSJohn Ogness 	len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
67774caba7fSJohn Ogness 	len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
67874caba7fSJohn Ogness 
67974caba7fSJohn Ogness 	return len;
68074caba7fSJohn Ogness }
68174caba7fSJohn Ogness 
msg_print_ext_body(char * buf,size_t size,char * text,size_t text_len,struct dev_printk_info * dev_info)68274caba7fSJohn Ogness static ssize_t msg_print_ext_body(char *buf, size_t size,
68374caba7fSJohn Ogness 				  char *text, size_t text_len,
68474caba7fSJohn Ogness 				  struct dev_printk_info *dev_info)
68574caba7fSJohn Ogness {
68674caba7fSJohn Ogness 	ssize_t len;
68774caba7fSJohn Ogness 
68874caba7fSJohn Ogness 	len = msg_add_ext_text(buf, size, text, text_len, '\n');
68974caba7fSJohn Ogness 
69074caba7fSJohn Ogness 	if (!dev_info)
69174caba7fSJohn Ogness 		goto out;
69274caba7fSJohn Ogness 
69374caba7fSJohn Ogness 	len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
69474caba7fSJohn Ogness 				 dev_info->subsystem);
69574caba7fSJohn Ogness 	len += msg_add_dict_text(buf + len, size - len, "DEVICE",
69674caba7fSJohn Ogness 				 dev_info->device);
69774caba7fSJohn Ogness out:
69874caba7fSJohn Ogness 	return len;
69974caba7fSJohn Ogness }
70074caba7fSJohn Ogness 
701ea308da1SJohn Ogness static bool printk_get_next_message(struct printk_message *pmsg, u64 seq,
702ea308da1SJohn Ogness 				    bool is_extended, bool may_supress);
703ea308da1SJohn Ogness 
704b9ee979eSJoe Perches /* /dev/kmsg - userspace message inject/listen interface */
705b9ee979eSJoe Perches struct devkmsg_user {
70635b2b163SJohn Ogness 	atomic64_t seq;
707750afe7bSBorislav Petkov 	struct ratelimit_state rs;
708b9ee979eSJoe Perches 	struct mutex lock;
709ea308da1SJohn Ogness 	struct printk_buffers pbufs;
710b9ee979eSJoe Perches };
711b9ee979eSJoe Perches 
7129adcfaffSTetsuo Handa static __printf(3, 4) __cold
devkmsg_emit(int facility,int level,const char * fmt,...)7139adcfaffSTetsuo Handa int devkmsg_emit(int facility, int level, const char *fmt, ...)
7149adcfaffSTetsuo Handa {
7159adcfaffSTetsuo Handa 	va_list args;
7169adcfaffSTetsuo Handa 	int r;
7179adcfaffSTetsuo Handa 
7189adcfaffSTetsuo Handa 	va_start(args, fmt);
71974caba7fSJohn Ogness 	r = vprintk_emit(facility, level, NULL, fmt, args);
7209adcfaffSTetsuo Handa 	va_end(args);
7219adcfaffSTetsuo Handa 
7229adcfaffSTetsuo Handa 	return r;
7239adcfaffSTetsuo Handa }
7249adcfaffSTetsuo Handa 
devkmsg_write(struct kiocb * iocb,struct iov_iter * from)725849f3127SAl Viro static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
726b9ee979eSJoe Perches {
727b9ee979eSJoe Perches 	char *buf, *line;
728b9ee979eSJoe Perches 	int level = default_message_loglevel;
729b9ee979eSJoe Perches 	int facility = 1;	/* LOG_USER */
730750afe7bSBorislav Petkov 	struct file *file = iocb->ki_filp;
731750afe7bSBorislav Petkov 	struct devkmsg_user *user = file->private_data;
73266ee59afSChristoph Hellwig 	size_t len = iov_iter_count(from);
733b9ee979eSJoe Perches 	ssize_t ret = len;
734b9ee979eSJoe Perches 
735bee43904SStanislav Kinsburskii 	if (len > PRINTKRB_RECORD_MAX)
736b9ee979eSJoe Perches 		return -EINVAL;
737750afe7bSBorislav Petkov 
738750afe7bSBorislav Petkov 	/* Ignore when user logging is disabled. */
739750afe7bSBorislav Petkov 	if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
740750afe7bSBorislav Petkov 		return len;
741750afe7bSBorislav Petkov 
742750afe7bSBorislav Petkov 	/* Ratelimit when not explicitly enabled. */
743750afe7bSBorislav Petkov 	if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
744750afe7bSBorislav Petkov 		if (!___ratelimit(&user->rs, current->comm))
745750afe7bSBorislav Petkov 			return ret;
746750afe7bSBorislav Petkov 	}
747750afe7bSBorislav Petkov 
748b9ee979eSJoe Perches 	buf = kmalloc(len+1, GFP_KERNEL);
749b9ee979eSJoe Perches 	if (buf == NULL)
750b9ee979eSJoe Perches 		return -ENOMEM;
751b9ee979eSJoe Perches 
752849f3127SAl Viro 	buf[len] = '\0';
753cbbd26b8SAl Viro 	if (!copy_from_iter_full(buf, len, from)) {
754849f3127SAl Viro 		kfree(buf);
755849f3127SAl Viro 		return -EFAULT;
756b9ee979eSJoe Perches 	}
757b9ee979eSJoe Perches 
758b9ee979eSJoe Perches 	/*
759b9ee979eSJoe Perches 	 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
760b9ee979eSJoe Perches 	 * the decimal value represents 32bit, the lower 3 bit are the log
761b9ee979eSJoe Perches 	 * level, the rest are the log facility.
762b9ee979eSJoe Perches 	 *
763b9ee979eSJoe Perches 	 * If no prefix or no userspace facility is specified, we
764b9ee979eSJoe Perches 	 * enforce LOG_USER, to be able to reliably distinguish
765b9ee979eSJoe Perches 	 * kernel-generated messages from userspace-injected ones.
766b9ee979eSJoe Perches 	 */
767b9ee979eSJoe Perches 	line = buf;
768b9ee979eSJoe Perches 	if (line[0] == '<') {
769b9ee979eSJoe Perches 		char *endp = NULL;
7703824657cSMathias Krause 		unsigned int u;
771b9ee979eSJoe Perches 
7723824657cSMathias Krause 		u = simple_strtoul(line + 1, &endp, 10);
773b9ee979eSJoe Perches 		if (endp && endp[0] == '>') {
7743824657cSMathias Krause 			level = LOG_LEVEL(u);
7753824657cSMathias Krause 			if (LOG_FACILITY(u) != 0)
7763824657cSMathias Krause 				facility = LOG_FACILITY(u);
777b9ee979eSJoe Perches 			endp++;
778b9ee979eSJoe Perches 			line = endp;
779b9ee979eSJoe Perches 		}
780b9ee979eSJoe Perches 	}
781b9ee979eSJoe Perches 
7829adcfaffSTetsuo Handa 	devkmsg_emit(facility, level, "%s", line);
783b9ee979eSJoe Perches 	kfree(buf);
784b9ee979eSJoe Perches 	return ret;
785b9ee979eSJoe Perches }
786b9ee979eSJoe Perches 
devkmsg_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)787b9ee979eSJoe Perches static ssize_t devkmsg_read(struct file *file, char __user *buf,
788b9ee979eSJoe Perches 			    size_t count, loff_t *ppos)
789b9ee979eSJoe Perches {
790b9ee979eSJoe Perches 	struct devkmsg_user *user = file->private_data;
791ea308da1SJohn Ogness 	char *outbuf = &user->pbufs.outbuf[0];
792ea308da1SJohn Ogness 	struct printk_message pmsg = {
793ea308da1SJohn Ogness 		.pbufs = &user->pbufs,
794ea308da1SJohn Ogness 	};
795b9ee979eSJoe Perches 	ssize_t ret;
796b9ee979eSJoe Perches 
797b9ee979eSJoe Perches 	ret = mutex_lock_interruptible(&user->lock);
798b9ee979eSJoe Perches 	if (ret)
799b9ee979eSJoe Perches 		return ret;
800de6fcbdbSSergey Senozhatsky 
801ea308da1SJohn Ogness 	if (!printk_get_next_message(&pmsg, atomic64_read(&user->seq), true, false)) {
802b9ee979eSJoe Perches 		if (file->f_flags & O_NONBLOCK) {
803b9ee979eSJoe Perches 			ret = -EAGAIN;
804b9ee979eSJoe Perches 			goto out;
805b9ee979eSJoe Perches 		}
806b9ee979eSJoe Perches 
8071f5d7830SJohn Ogness 		/*
8081f5d7830SJohn Ogness 		 * Guarantee this task is visible on the waitqueue before
8091f5d7830SJohn Ogness 		 * checking the wake condition.
8101f5d7830SJohn Ogness 		 *
8111f5d7830SJohn Ogness 		 * The full memory barrier within set_current_state() of
8121f5d7830SJohn Ogness 		 * prepare_to_wait_event() pairs with the full memory barrier
8131f5d7830SJohn Ogness 		 * within wq_has_sleeper().
8141f5d7830SJohn Ogness 		 *
8155341b93dSJohn Ogness 		 * This pairs with __wake_up_klogd:A.
8161f5d7830SJohn Ogness 		 */
817b9ee979eSJoe Perches 		ret = wait_event_interruptible(log_wait,
818ea308da1SJohn Ogness 				printk_get_next_message(&pmsg, atomic64_read(&user->seq), true,
819ea308da1SJohn Ogness 							false)); /* LMM(devkmsg_read:A) */
820b9ee979eSJoe Perches 		if (ret)
821b9ee979eSJoe Perches 			goto out;
822b9ee979eSJoe Perches 	}
823b9ee979eSJoe Perches 
824ea308da1SJohn Ogness 	if (pmsg.dropped) {
825b9ee979eSJoe Perches 		/* our last seen message is gone, return error and reset */
826ea308da1SJohn Ogness 		atomic64_set(&user->seq, pmsg.seq);
827b9ee979eSJoe Perches 		ret = -EPIPE;
828b9ee979eSJoe Perches 		goto out;
829b9ee979eSJoe Perches 	}
830b9ee979eSJoe Perches 
831ea308da1SJohn Ogness 	atomic64_set(&user->seq, pmsg.seq + 1);
832b9ee979eSJoe Perches 
833ea308da1SJohn Ogness 	if (pmsg.outbuf_len > count) {
834b9ee979eSJoe Perches 		ret = -EINVAL;
835b9ee979eSJoe Perches 		goto out;
836b9ee979eSJoe Perches 	}
837b9ee979eSJoe Perches 
838ea308da1SJohn Ogness 	if (copy_to_user(buf, outbuf, pmsg.outbuf_len)) {
839b9ee979eSJoe Perches 		ret = -EFAULT;
840b9ee979eSJoe Perches 		goto out;
841b9ee979eSJoe Perches 	}
842ea308da1SJohn Ogness 	ret = pmsg.outbuf_len;
843b9ee979eSJoe Perches out:
844b9ee979eSJoe Perches 	mutex_unlock(&user->lock);
845b9ee979eSJoe Perches 	return ret;
846b9ee979eSJoe Perches }
847b9ee979eSJoe Perches 
848bc885f1aSBruno Meneguele /*
849bc885f1aSBruno Meneguele  * Be careful when modifying this function!!!
850bc885f1aSBruno Meneguele  *
851bc885f1aSBruno Meneguele  * Only few operations are supported because the device works only with the
852bc885f1aSBruno Meneguele  * entire variable length messages (records). Non-standard values are
853bc885f1aSBruno Meneguele  * returned in the other cases and has been this way for quite some time.
854bc885f1aSBruno Meneguele  * User space applications might depend on this behavior.
855bc885f1aSBruno Meneguele  */
devkmsg_llseek(struct file * file,loff_t offset,int whence)856b9ee979eSJoe Perches static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
857b9ee979eSJoe Perches {
858b9ee979eSJoe Perches 	struct devkmsg_user *user = file->private_data;
859b9ee979eSJoe Perches 	loff_t ret = 0;
860b9ee979eSJoe Perches 
861b9ee979eSJoe Perches 	if (offset)
862b9ee979eSJoe Perches 		return -ESPIPE;
863b9ee979eSJoe Perches 
864b9ee979eSJoe Perches 	switch (whence) {
865b9ee979eSJoe Perches 	case SEEK_SET:
866b9ee979eSJoe Perches 		/* the first record */
86735b2b163SJohn Ogness 		atomic64_set(&user->seq, prb_first_valid_seq(prb));
868b9ee979eSJoe Perches 		break;
869b9ee979eSJoe Perches 	case SEEK_DATA:
870b9ee979eSJoe Perches 		/*
871b9ee979eSJoe Perches 		 * The first record after the last SYSLOG_ACTION_CLEAR,
872b9ee979eSJoe Perches 		 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
873b9ee979eSJoe Perches 		 * changes no global state, and does not clear anything.
874b9ee979eSJoe Perches 		 */
87535b2b163SJohn Ogness 		atomic64_set(&user->seq, latched_seq_read_nolock(&clear_seq));
876b9ee979eSJoe Perches 		break;
877b9ee979eSJoe Perches 	case SEEK_END:
878b9ee979eSJoe Perches 		/* after the last record */
87935b2b163SJohn Ogness 		atomic64_set(&user->seq, prb_next_seq(prb));
880b9ee979eSJoe Perches 		break;
881b9ee979eSJoe Perches 	default:
882b9ee979eSJoe Perches 		ret = -EINVAL;
883b9ee979eSJoe Perches 	}
884b9ee979eSJoe Perches 	return ret;
885b9ee979eSJoe Perches }
886b9ee979eSJoe Perches 
devkmsg_poll(struct file * file,poll_table * wait)8879dd95748SAl Viro static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
888b9ee979eSJoe Perches {
889b9ee979eSJoe Perches 	struct devkmsg_user *user = file->private_data;
89013791c80SJohn Ogness 	struct printk_info info;
8919dd95748SAl Viro 	__poll_t ret = 0;
892b9ee979eSJoe Perches 
893b9ee979eSJoe Perches 	poll_wait(file, &log_wait, wait);
894b9ee979eSJoe Perches 
89535b2b163SJohn Ogness 	if (prb_read_valid_info(prb, atomic64_read(&user->seq), &info, NULL)) {
896b9ee979eSJoe Perches 		/* return error when data has vanished underneath us */
89735b2b163SJohn Ogness 		if (info.seq != atomic64_read(&user->seq))
898a9a08845SLinus Torvalds 			ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
899b9ee979eSJoe Perches 		else
900a9a08845SLinus Torvalds 			ret = EPOLLIN|EPOLLRDNORM;
901b9ee979eSJoe Perches 	}
902b9ee979eSJoe Perches 
903b9ee979eSJoe Perches 	return ret;
904b9ee979eSJoe Perches }
905b9ee979eSJoe Perches 
devkmsg_open(struct inode * inode,struct file * file)906b9ee979eSJoe Perches static int devkmsg_open(struct inode *inode, struct file *file)
907b9ee979eSJoe Perches {
908b9ee979eSJoe Perches 	struct devkmsg_user *user;
909b9ee979eSJoe Perches 	int err;
910b9ee979eSJoe Perches 
911750afe7bSBorislav Petkov 	if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
912750afe7bSBorislav Petkov 		return -EPERM;
913b9ee979eSJoe Perches 
914750afe7bSBorislav Petkov 	/* write-only does not need any file context */
915750afe7bSBorislav Petkov 	if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
916b9ee979eSJoe Perches 		err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
917b9ee979eSJoe Perches 					       SYSLOG_FROM_READER);
918b9ee979eSJoe Perches 		if (err)
919b9ee979eSJoe Perches 			return err;
920750afe7bSBorislav Petkov 	}
921b9ee979eSJoe Perches 
9229980c425SYong-Taek Lee 	user = kvmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
923b9ee979eSJoe Perches 	if (!user)
924b9ee979eSJoe Perches 		return -ENOMEM;
925b9ee979eSJoe Perches 
926750afe7bSBorislav Petkov 	ratelimit_default_init(&user->rs);
927750afe7bSBorislav Petkov 	ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
928750afe7bSBorislav Petkov 
929b9ee979eSJoe Perches 	mutex_init(&user->lock);
930b9ee979eSJoe Perches 
93135b2b163SJohn Ogness 	atomic64_set(&user->seq, prb_first_valid_seq(prb));
932b9ee979eSJoe Perches 
933b9ee979eSJoe Perches 	file->private_data = user;
934b9ee979eSJoe Perches 	return 0;
935b9ee979eSJoe Perches }
936b9ee979eSJoe Perches 
devkmsg_release(struct inode * inode,struct file * file)937b9ee979eSJoe Perches static int devkmsg_release(struct inode *inode, struct file *file)
938b9ee979eSJoe Perches {
939b9ee979eSJoe Perches 	struct devkmsg_user *user = file->private_data;
940b9ee979eSJoe Perches 
941750afe7bSBorislav Petkov 	ratelimit_state_exit(&user->rs);
942750afe7bSBorislav Petkov 
943b9ee979eSJoe Perches 	mutex_destroy(&user->lock);
9449980c425SYong-Taek Lee 	kvfree(user);
945b9ee979eSJoe Perches 	return 0;
946b9ee979eSJoe Perches }
947b9ee979eSJoe Perches 
948b9ee979eSJoe Perches const struct file_operations kmsg_fops = {
949b9ee979eSJoe Perches 	.open = devkmsg_open,
950b9ee979eSJoe Perches 	.read = devkmsg_read,
951849f3127SAl Viro 	.write_iter = devkmsg_write,
952b9ee979eSJoe Perches 	.llseek = devkmsg_llseek,
953b9ee979eSJoe Perches 	.poll = devkmsg_poll,
954b9ee979eSJoe Perches 	.release = devkmsg_release,
955b9ee979eSJoe Perches };
956b9ee979eSJoe Perches 
957692f66f2SHari Bathini #ifdef CONFIG_CRASH_CORE
958b9ee979eSJoe Perches /*
9594c1ace64SDirk Gouders  * This appends the listed symbols to /proc/vmcore
960b9ee979eSJoe Perches  *
9614c1ace64SDirk Gouders  * /proc/vmcore is used by various utilities, like crash and makedumpfile to
962b9ee979eSJoe Perches  * obtain access to symbols that are otherwise very difficult to locate.  These
963b9ee979eSJoe Perches  * symbols are specifically used so that utilities can access and extract the
964b9ee979eSJoe Perches  * dmesg log from a vmcore file after a crash.
965b9ee979eSJoe Perches  */
log_buf_vmcoreinfo_setup(void)966692f66f2SHari Bathini void log_buf_vmcoreinfo_setup(void)
967b9ee979eSJoe Perches {
96874caba7fSJohn Ogness 	struct dev_printk_info *dev_info = NULL;
96974caba7fSJohn Ogness 
970896fbe20SJohn Ogness 	VMCOREINFO_SYMBOL(prb);
971896fbe20SJohn Ogness 	VMCOREINFO_SYMBOL(printk_rb_static);
972896fbe20SJohn Ogness 	VMCOREINFO_SYMBOL(clear_seq);
973896fbe20SJohn Ogness 
974b9ee979eSJoe Perches 	/*
975896fbe20SJohn Ogness 	 * Export struct size and field offsets. User space tools can
976b9ee979eSJoe Perches 	 * parse it and detect any changes to structure down the line.
977b9ee979eSJoe Perches 	 */
978896fbe20SJohn Ogness 
979896fbe20SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
980896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
981896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
982896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_ringbuffer, fail);
983896fbe20SJohn Ogness 
984896fbe20SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
985896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
986896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_desc_ring, descs);
987cfe2790bSJohn Ogness 	VMCOREINFO_OFFSET(prb_desc_ring, infos);
988896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_desc_ring, head_id);
989896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
990896fbe20SJohn Ogness 
991896fbe20SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(prb_desc);
992896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_desc, state_var);
993896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
994896fbe20SJohn Ogness 
995896fbe20SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
996896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
997896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
998896fbe20SJohn Ogness 
999896fbe20SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(printk_info);
1000896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_info, seq);
1001896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_info, ts_nsec);
1002896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_info, text_len);
1003896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(printk_info, caller_id);
100474caba7fSJohn Ogness 	VMCOREINFO_OFFSET(printk_info, dev_info);
100574caba7fSJohn Ogness 
100674caba7fSJohn Ogness 	VMCOREINFO_STRUCT_SIZE(dev_printk_info);
100774caba7fSJohn Ogness 	VMCOREINFO_OFFSET(dev_printk_info, subsystem);
100874caba7fSJohn Ogness 	VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
100974caba7fSJohn Ogness 	VMCOREINFO_OFFSET(dev_printk_info, device);
101074caba7fSJohn Ogness 	VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
1011896fbe20SJohn Ogness 
1012896fbe20SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(prb_data_ring);
1013896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1014896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_data_ring, data);
1015896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1016896fbe20SJohn Ogness 	VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1017896fbe20SJohn Ogness 
1018896fbe20SJohn Ogness 	VMCOREINFO_SIZE(atomic_long_t);
1019896fbe20SJohn Ogness 	VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
10207d7a23a9SJohn Ogness 
10217d7a23a9SJohn Ogness 	VMCOREINFO_STRUCT_SIZE(latched_seq);
10227d7a23a9SJohn Ogness 	VMCOREINFO_OFFSET(latched_seq, val);
1023b9ee979eSJoe Perches }
1024b9ee979eSJoe Perches #endif
1025b9ee979eSJoe Perches 
1026b9ee979eSJoe Perches /* requested log_buf_len from kernel cmdline */
1027b9ee979eSJoe Perches static unsigned long __initdata new_log_buf_len;
1028b9ee979eSJoe Perches 
1029c0a318a3SLuis R. Rodriguez /* we practice scaling the ring buffer by powers of 2 */
log_buf_len_update(u64 size)1030e6fe3e5bSHe Zhe static void __init log_buf_len_update(u64 size)
1031c0a318a3SLuis R. Rodriguez {
1032e6fe3e5bSHe Zhe 	if (size > (u64)LOG_BUF_LEN_MAX) {
1033e6fe3e5bSHe Zhe 		size = (u64)LOG_BUF_LEN_MAX;
1034e6fe3e5bSHe Zhe 		pr_err("log_buf over 2G is not supported.\n");
1035e6fe3e5bSHe Zhe 	}
1036e6fe3e5bSHe Zhe 
1037c0a318a3SLuis R. Rodriguez 	if (size)
1038c0a318a3SLuis R. Rodriguez 		size = roundup_pow_of_two(size);
1039c0a318a3SLuis R. Rodriguez 	if (size > log_buf_len)
1040e6fe3e5bSHe Zhe 		new_log_buf_len = (unsigned long)size;
1041c0a318a3SLuis R. Rodriguez }
1042c0a318a3SLuis R. Rodriguez 
1043b9ee979eSJoe Perches /* save requested log_buf_len since it's too early to process it */
log_buf_len_setup(char * str)1044b9ee979eSJoe Perches static int __init log_buf_len_setup(char *str)
1045b9ee979eSJoe Perches {
1046e6fe3e5bSHe Zhe 	u64 size;
1047277fcdb2SHe Zhe 
1048277fcdb2SHe Zhe 	if (!str)
1049277fcdb2SHe Zhe 		return -EINVAL;
1050277fcdb2SHe Zhe 
1051277fcdb2SHe Zhe 	size = memparse(str, &str);
1052b9ee979eSJoe Perches 
1053c0a318a3SLuis R. Rodriguez 	log_buf_len_update(size);
1054b9ee979eSJoe Perches 
1055b9ee979eSJoe Perches 	return 0;
1056b9ee979eSJoe Perches }
1057b9ee979eSJoe Perches early_param("log_buf_len", log_buf_len_setup);
1058b9ee979eSJoe Perches 
10592240a31dSGeert Uytterhoeven #ifdef CONFIG_SMP
10602240a31dSGeert Uytterhoeven #define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
10612240a31dSGeert Uytterhoeven 
log_buf_add_cpu(void)106223b2899fSLuis R. Rodriguez static void __init log_buf_add_cpu(void)
106323b2899fSLuis R. Rodriguez {
106423b2899fSLuis R. Rodriguez 	unsigned int cpu_extra;
106523b2899fSLuis R. Rodriguez 
106623b2899fSLuis R. Rodriguez 	/*
106723b2899fSLuis R. Rodriguez 	 * archs should set up cpu_possible_bits properly with
106823b2899fSLuis R. Rodriguez 	 * set_cpu_possible() after setup_arch() but just in
106923b2899fSLuis R. Rodriguez 	 * case lets ensure this is valid.
107023b2899fSLuis R. Rodriguez 	 */
107123b2899fSLuis R. Rodriguez 	if (num_possible_cpus() == 1)
107223b2899fSLuis R. Rodriguez 		return;
107323b2899fSLuis R. Rodriguez 
107423b2899fSLuis R. Rodriguez 	cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
107523b2899fSLuis R. Rodriguez 
107623b2899fSLuis R. Rodriguez 	/* by default this will only continue through for large > 64 CPUs */
107723b2899fSLuis R. Rodriguez 	if (cpu_extra <= __LOG_BUF_LEN / 2)
107823b2899fSLuis R. Rodriguez 		return;
107923b2899fSLuis R. Rodriguez 
108023b2899fSLuis R. Rodriguez 	pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
108123b2899fSLuis R. Rodriguez 		__LOG_CPU_MAX_BUF_LEN);
108223b2899fSLuis R. Rodriguez 	pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
108323b2899fSLuis R. Rodriguez 		cpu_extra);
108423b2899fSLuis R. Rodriguez 	pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
108523b2899fSLuis R. Rodriguez 
108623b2899fSLuis R. Rodriguez 	log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
108723b2899fSLuis R. Rodriguez }
10882240a31dSGeert Uytterhoeven #else /* !CONFIG_SMP */
log_buf_add_cpu(void)10892240a31dSGeert Uytterhoeven static inline void log_buf_add_cpu(void) {}
10902240a31dSGeert Uytterhoeven #endif /* CONFIG_SMP */
109123b2899fSLuis R. Rodriguez 
set_percpu_data_ready(void)1092ab6f762fSSergey Senozhatsky static void __init set_percpu_data_ready(void)
1093ab6f762fSSergey Senozhatsky {
1094ab6f762fSSergey Senozhatsky 	__printk_percpu_data_ready = true;
1095ab6f762fSSergey Senozhatsky }
1096ab6f762fSSergey Senozhatsky 
add_to_rb(struct printk_ringbuffer * rb,struct printk_record * r)1097896fbe20SJohn Ogness static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1098896fbe20SJohn Ogness 				     struct printk_record *r)
1099896fbe20SJohn Ogness {
1100896fbe20SJohn Ogness 	struct prb_reserved_entry e;
1101896fbe20SJohn Ogness 	struct printk_record dest_r;
1102896fbe20SJohn Ogness 
1103f35efc78SJohn Ogness 	prb_rec_init_wr(&dest_r, r->info->text_len);
1104896fbe20SJohn Ogness 
1105896fbe20SJohn Ogness 	if (!prb_reserve(&e, rb, &dest_r))
1106896fbe20SJohn Ogness 		return 0;
1107896fbe20SJohn Ogness 
1108cc5c7041SJohn Ogness 	memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1109cc5c7041SJohn Ogness 	dest_r.info->text_len = r->info->text_len;
1110896fbe20SJohn Ogness 	dest_r.info->facility = r->info->facility;
1111896fbe20SJohn Ogness 	dest_r.info->level = r->info->level;
1112896fbe20SJohn Ogness 	dest_r.info->flags = r->info->flags;
1113896fbe20SJohn Ogness 	dest_r.info->ts_nsec = r->info->ts_nsec;
1114896fbe20SJohn Ogness 	dest_r.info->caller_id = r->info->caller_id;
111574caba7fSJohn Ogness 	memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1116896fbe20SJohn Ogness 
1117f5f022e5SJohn Ogness 	prb_final_commit(&e);
1118896fbe20SJohn Ogness 
1119896fbe20SJohn Ogness 	return prb_record_text_space(&e);
1120896fbe20SJohn Ogness }
1121896fbe20SJohn Ogness 
1122b0975c47SJohn Ogness static char setup_text_buf[PRINTKRB_RECORD_MAX] __initdata;
1123896fbe20SJohn Ogness 
setup_log_buf(int early)1124b9ee979eSJoe Perches void __init setup_log_buf(int early)
1125b9ee979eSJoe Perches {
1126cfe2790bSJohn Ogness 	struct printk_info *new_infos;
1127896fbe20SJohn Ogness 	unsigned int new_descs_count;
1128896fbe20SJohn Ogness 	struct prb_desc *new_descs;
1129896fbe20SJohn Ogness 	struct printk_info info;
1130896fbe20SJohn Ogness 	struct printk_record r;
113193d102f0SJohn Ogness 	unsigned int text_size;
1132896fbe20SJohn Ogness 	size_t new_descs_size;
1133cfe2790bSJohn Ogness 	size_t new_infos_size;
1134b9ee979eSJoe Perches 	unsigned long flags;
1135b9ee979eSJoe Perches 	char *new_log_buf;
1136d2130e82SSergey Senozhatsky 	unsigned int free;
1137896fbe20SJohn Ogness 	u64 seq;
1138b9ee979eSJoe Perches 
1139ab6f762fSSergey Senozhatsky 	/*
1140ab6f762fSSergey Senozhatsky 	 * Some archs call setup_log_buf() multiple times - first is very
1141ab6f762fSSergey Senozhatsky 	 * early, e.g. from setup_arch(), and second - when percpu_areas
1142ab6f762fSSergey Senozhatsky 	 * are initialised.
1143ab6f762fSSergey Senozhatsky 	 */
1144ab6f762fSSergey Senozhatsky 	if (!early)
1145ab6f762fSSergey Senozhatsky 		set_percpu_data_ready();
1146ab6f762fSSergey Senozhatsky 
114723b2899fSLuis R. Rodriguez 	if (log_buf != __log_buf)
114823b2899fSLuis R. Rodriguez 		return;
114923b2899fSLuis R. Rodriguez 
115023b2899fSLuis R. Rodriguez 	if (!early && !new_log_buf_len)
115123b2899fSLuis R. Rodriguez 		log_buf_add_cpu();
115223b2899fSLuis R. Rodriguez 
1153b9ee979eSJoe Perches 	if (!new_log_buf_len)
1154b9ee979eSJoe Perches 		return;
1155b9ee979eSJoe Perches 
1156896fbe20SJohn Ogness 	new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1157896fbe20SJohn Ogness 	if (new_descs_count == 0) {
1158896fbe20SJohn Ogness 		pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
1159896fbe20SJohn Ogness 		return;
1160896fbe20SJohn Ogness 	}
1161896fbe20SJohn Ogness 
116226fb3daeSMike Rapoport 	new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1163b9ee979eSJoe Perches 	if (unlikely(!new_log_buf)) {
1164896fbe20SJohn Ogness 		pr_err("log_buf_len: %lu text bytes not available\n",
1165b9ee979eSJoe Perches 		       new_log_buf_len);
1166b9ee979eSJoe Perches 		return;
1167b9ee979eSJoe Perches 	}
1168b9ee979eSJoe Perches 
1169896fbe20SJohn Ogness 	new_descs_size = new_descs_count * sizeof(struct prb_desc);
1170896fbe20SJohn Ogness 	new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1171896fbe20SJohn Ogness 	if (unlikely(!new_descs)) {
1172896fbe20SJohn Ogness 		pr_err("log_buf_len: %zu desc bytes not available\n",
1173896fbe20SJohn Ogness 		       new_descs_size);
1174f35efc78SJohn Ogness 		goto err_free_log_buf;
1175cfe2790bSJohn Ogness 	}
1176cfe2790bSJohn Ogness 
1177cfe2790bSJohn Ogness 	new_infos_size = new_descs_count * sizeof(struct printk_info);
1178cfe2790bSJohn Ogness 	new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1179cfe2790bSJohn Ogness 	if (unlikely(!new_infos)) {
1180cfe2790bSJohn Ogness 		pr_err("log_buf_len: %zu info bytes not available\n",
1181cfe2790bSJohn Ogness 		       new_infos_size);
1182cfe2790bSJohn Ogness 		goto err_free_descs;
1183896fbe20SJohn Ogness 	}
1184896fbe20SJohn Ogness 
1185f35efc78SJohn Ogness 	prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1186896fbe20SJohn Ogness 
1187896fbe20SJohn Ogness 	prb_init(&printk_rb_dynamic,
1188896fbe20SJohn Ogness 		 new_log_buf, ilog2(new_log_buf_len),
1189cfe2790bSJohn Ogness 		 new_descs, ilog2(new_descs_count),
1190cfe2790bSJohn Ogness 		 new_infos);
1191896fbe20SJohn Ogness 
119293d102f0SJohn Ogness 	local_irq_save(flags);
1193896fbe20SJohn Ogness 
1194b9ee979eSJoe Perches 	log_buf_len = new_log_buf_len;
1195b9ee979eSJoe Perches 	log_buf = new_log_buf;
1196b9ee979eSJoe Perches 	new_log_buf_len = 0;
1197896fbe20SJohn Ogness 
1198896fbe20SJohn Ogness 	free = __LOG_BUF_LEN;
119993d102f0SJohn Ogness 	prb_for_each_record(0, &printk_rb_static, seq, &r) {
120093d102f0SJohn Ogness 		text_size = add_to_rb(&printk_rb_dynamic, &r);
120193d102f0SJohn Ogness 		if (text_size > free)
120293d102f0SJohn Ogness 			free = 0;
120393d102f0SJohn Ogness 		else
120493d102f0SJohn Ogness 			free -= text_size;
120593d102f0SJohn Ogness 	}
1206896fbe20SJohn Ogness 
1207896fbe20SJohn Ogness 	prb = &printk_rb_dynamic;
1208896fbe20SJohn Ogness 
120993d102f0SJohn Ogness 	local_irq_restore(flags);
121093d102f0SJohn Ogness 
121193d102f0SJohn Ogness 	/*
121293d102f0SJohn Ogness 	 * Copy any remaining messages that might have appeared from
121393d102f0SJohn Ogness 	 * NMI context after copying but before switching to the
121493d102f0SJohn Ogness 	 * dynamic buffer.
121593d102f0SJohn Ogness 	 */
121693d102f0SJohn Ogness 	prb_for_each_record(seq, &printk_rb_static, seq, &r) {
121793d102f0SJohn Ogness 		text_size = add_to_rb(&printk_rb_dynamic, &r);
121893d102f0SJohn Ogness 		if (text_size > free)
121993d102f0SJohn Ogness 			free = 0;
122093d102f0SJohn Ogness 		else
122193d102f0SJohn Ogness 			free -= text_size;
122293d102f0SJohn Ogness 	}
1223b9ee979eSJoe Perches 
1224896fbe20SJohn Ogness 	if (seq != prb_next_seq(&printk_rb_static)) {
1225896fbe20SJohn Ogness 		pr_err("dropped %llu messages\n",
1226896fbe20SJohn Ogness 		       prb_next_seq(&printk_rb_static) - seq);
1227896fbe20SJohn Ogness 	}
1228896fbe20SJohn Ogness 
1229e6fe3e5bSHe Zhe 	pr_info("log_buf_len: %u bytes\n", log_buf_len);
1230e6fe3e5bSHe Zhe 	pr_info("early log buf free: %u(%u%%)\n",
1231b9ee979eSJoe Perches 		free, (free * 100) / __LOG_BUF_LEN);
1232cfe2790bSJohn Ogness 	return;
1233cfe2790bSJohn Ogness 
1234cfe2790bSJohn Ogness err_free_descs:
12354421cca0SMike Rapoport 	memblock_free(new_descs, new_descs_size);
1236cfe2790bSJohn Ogness err_free_log_buf:
12374421cca0SMike Rapoport 	memblock_free(new_log_buf, new_log_buf_len);
1238b9ee979eSJoe Perches }
1239b9ee979eSJoe Perches 
1240b9ee979eSJoe Perches static bool __read_mostly ignore_loglevel;
1241b9ee979eSJoe Perches 
ignore_loglevel_setup(char * str)1242b9ee979eSJoe Perches static int __init ignore_loglevel_setup(char *str)
1243b9ee979eSJoe Perches {
1244d25d9fecSNeil Zhang 	ignore_loglevel = true;
124527083bacSAndrew Morton 	pr_info("debug: ignoring loglevel setting.\n");
1246b9ee979eSJoe Perches 
1247b9ee979eSJoe Perches 	return 0;
1248b9ee979eSJoe Perches }
1249b9ee979eSJoe Perches 
1250b9ee979eSJoe Perches early_param("ignore_loglevel", ignore_loglevel_setup);
1251b9ee979eSJoe Perches module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1252205bd3d2SJoe Perches MODULE_PARM_DESC(ignore_loglevel,
1253205bd3d2SJoe Perches 		 "ignore loglevel setting (prints all kernel messages to the console)");
1254b9ee979eSJoe Perches 
suppress_message_printing(int level)1255cf775444SSergey Senozhatsky static bool suppress_message_printing(int level)
1256cf775444SSergey Senozhatsky {
1257cf775444SSergey Senozhatsky 	return (level >= console_loglevel && !ignore_loglevel);
1258cf775444SSergey Senozhatsky }
1259cf775444SSergey Senozhatsky 
1260b9ee979eSJoe Perches #ifdef CONFIG_BOOT_PRINTK_DELAY
1261b9ee979eSJoe Perches 
1262b9ee979eSJoe Perches static int boot_delay; /* msecs delay after each printk during bootup */
1263b9ee979eSJoe Perches static unsigned long long loops_per_msec;	/* based on boot_delay */
1264b9ee979eSJoe Perches 
boot_delay_setup(char * str)1265b9ee979eSJoe Perches static int __init boot_delay_setup(char *str)
1266b9ee979eSJoe Perches {
1267b9ee979eSJoe Perches 	unsigned long lpj;
1268b9ee979eSJoe Perches 
1269b9ee979eSJoe Perches 	lpj = preset_lpj ? preset_lpj : 1000000;	/* some guess */
1270b9ee979eSJoe Perches 	loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1271b9ee979eSJoe Perches 
1272b9ee979eSJoe Perches 	get_option(&str, &boot_delay);
1273b9ee979eSJoe Perches 	if (boot_delay > 10 * 1000)
1274b9ee979eSJoe Perches 		boot_delay = 0;
1275b9ee979eSJoe Perches 
1276b9ee979eSJoe Perches 	pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1277b9ee979eSJoe Perches 		"HZ: %d, loops_per_msec: %llu\n",
1278b9ee979eSJoe Perches 		boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
127929e9d225SDave Young 	return 0;
1280b9ee979eSJoe Perches }
128129e9d225SDave Young early_param("boot_delay", boot_delay_setup);
1282b9ee979eSJoe Perches 
boot_delay_msec(int level)1283b9ee979eSJoe Perches static void boot_delay_msec(int level)
1284b9ee979eSJoe Perches {
1285b9ee979eSJoe Perches 	unsigned long long k;
1286b9ee979eSJoe Perches 	unsigned long timeout;
1287b9ee979eSJoe Perches 
1288ff48cd26SThomas Gleixner 	if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1289cf775444SSergey Senozhatsky 		|| suppress_message_printing(level)) {
1290b9ee979eSJoe Perches 		return;
1291b9ee979eSJoe Perches 	}
1292b9ee979eSJoe Perches 
1293b9ee979eSJoe Perches 	k = (unsigned long long)loops_per_msec * boot_delay;
1294b9ee979eSJoe Perches 
1295b9ee979eSJoe Perches 	timeout = jiffies + msecs_to_jiffies(boot_delay);
1296b9ee979eSJoe Perches 	while (k) {
1297b9ee979eSJoe Perches 		k--;
1298b9ee979eSJoe Perches 		cpu_relax();
1299b9ee979eSJoe Perches 		/*
1300b9ee979eSJoe Perches 		 * use (volatile) jiffies to prevent
1301b9ee979eSJoe Perches 		 * compiler reduction; loop termination via jiffies
1302b9ee979eSJoe Perches 		 * is secondary and may or may not happen.
1303b9ee979eSJoe Perches 		 */
1304b9ee979eSJoe Perches 		if (time_after(jiffies, timeout))
1305b9ee979eSJoe Perches 			break;
1306b9ee979eSJoe Perches 		touch_nmi_watchdog();
1307b9ee979eSJoe Perches 	}
1308b9ee979eSJoe Perches }
1309b9ee979eSJoe Perches #else
boot_delay_msec(int level)1310b9ee979eSJoe Perches static inline void boot_delay_msec(int level)
1311b9ee979eSJoe Perches {
1312b9ee979eSJoe Perches }
1313b9ee979eSJoe Perches #endif
1314b9ee979eSJoe Perches 
1315e99aa461SAlex Elder static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1316b9ee979eSJoe Perches module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1317b9ee979eSJoe Perches 
print_syslog(unsigned int level,char * buf)131807c17732STetsuo Handa static size_t print_syslog(unsigned int level, char *buf)
131907c17732STetsuo Handa {
132007c17732STetsuo Handa 	return sprintf(buf, "<%u>", level);
132107c17732STetsuo Handa }
132207c17732STetsuo Handa 
print_time(u64 ts,char * buf)1323b9ee979eSJoe Perches static size_t print_time(u64 ts, char *buf)
1324b9ee979eSJoe Perches {
1325e80c1a9dSTetsuo Handa 	unsigned long rem_nsec = do_div(ts, 1000000000);
1326b9ee979eSJoe Perches 
1327b9ee979eSJoe Perches 	return sprintf(buf, "[%5lu.%06lu]",
1328b9ee979eSJoe Perches 		       (unsigned long)ts, rem_nsec / 1000);
1329b9ee979eSJoe Perches }
1330b9ee979eSJoe Perches 
133115ff2069STetsuo Handa #ifdef CONFIG_PRINTK_CALLER
print_caller(u32 id,char * buf)133215ff2069STetsuo Handa static size_t print_caller(u32 id, char *buf)
133315ff2069STetsuo Handa {
133415ff2069STetsuo Handa 	char caller[12];
133515ff2069STetsuo Handa 
133615ff2069STetsuo Handa 	snprintf(caller, sizeof(caller), "%c%u",
133715ff2069STetsuo Handa 		 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
133815ff2069STetsuo Handa 	return sprintf(buf, "[%6s]", caller);
133915ff2069STetsuo Handa }
134015ff2069STetsuo Handa #else
134115ff2069STetsuo Handa #define print_caller(id, buf) 0
134215ff2069STetsuo Handa #endif
134315ff2069STetsuo Handa 
info_print_prefix(const struct printk_info * info,bool syslog,bool time,char * buf)1344896fbe20SJohn Ogness static size_t info_print_prefix(const struct printk_info  *info, bool syslog,
1345e80c1a9dSTetsuo Handa 				bool time, char *buf)
1346b9ee979eSJoe Perches {
1347b9ee979eSJoe Perches 	size_t len = 0;
1348b9ee979eSJoe Perches 
134907c17732STetsuo Handa 	if (syslog)
1350896fbe20SJohn Ogness 		len = print_syslog((info->facility << 3) | info->level, buf);
135115ff2069STetsuo Handa 
1352e80c1a9dSTetsuo Handa 	if (time)
1353896fbe20SJohn Ogness 		len += print_time(info->ts_nsec, buf + len);
135415ff2069STetsuo Handa 
1355896fbe20SJohn Ogness 	len += print_caller(info->caller_id, buf + len);
135615ff2069STetsuo Handa 
135715ff2069STetsuo Handa 	if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
135815ff2069STetsuo Handa 		buf[len++] = ' ';
135915ff2069STetsuo Handa 		buf[len] = '\0';
136015ff2069STetsuo Handa 	}
136115ff2069STetsuo Handa 
1362b9ee979eSJoe Perches 	return len;
1363b9ee979eSJoe Perches }
1364b9ee979eSJoe Perches 
1365896fbe20SJohn Ogness /*
1366896fbe20SJohn Ogness  * Prepare the record for printing. The text is shifted within the given
1367896fbe20SJohn Ogness  * buffer to avoid a need for another one. The following operations are
1368896fbe20SJohn Ogness  * done:
1369896fbe20SJohn Ogness  *
1370896fbe20SJohn Ogness  *   - Add prefix for each line.
1371f0e386eeSJohn Ogness  *   - Drop truncated lines that no longer fit into the buffer.
1372896fbe20SJohn Ogness  *   - Add the trailing newline that has been removed in vprintk_store().
1373f0e386eeSJohn Ogness  *   - Add a string terminator.
1374f0e386eeSJohn Ogness  *
1375f0e386eeSJohn Ogness  * Since the produced string is always terminated, the maximum possible
1376f0e386eeSJohn Ogness  * return value is @r->text_buf_size - 1;
1377896fbe20SJohn Ogness  *
1378896fbe20SJohn Ogness  * Return: The length of the updated/prepared text, including the added
1379f0e386eeSJohn Ogness  * prefixes and the newline. The terminator is not counted. The dropped
1380f0e386eeSJohn Ogness  * line(s) are not counted.
1381896fbe20SJohn Ogness  */
record_print_text(struct printk_record * r,bool syslog,bool time)1382896fbe20SJohn Ogness static size_t record_print_text(struct printk_record *r, bool syslog,
1383896fbe20SJohn Ogness 				bool time)
1384b9ee979eSJoe Perches {
1385896fbe20SJohn Ogness 	size_t text_len = r->info->text_len;
1386896fbe20SJohn Ogness 	size_t buf_size = r->text_buf_size;
1387896fbe20SJohn Ogness 	char *text = r->text_buf;
1388b0975c47SJohn Ogness 	char prefix[PRINTK_PREFIX_MAX];
1389896fbe20SJohn Ogness 	bool truncated = false;
1390896fbe20SJohn Ogness 	size_t prefix_len;
1391896fbe20SJohn Ogness 	size_t line_len;
1392896fbe20SJohn Ogness 	size_t len = 0;
1393896fbe20SJohn Ogness 	char *next;
1394b9ee979eSJoe Perches 
139559f8bccaSJohn Ogness 	/*
139659f8bccaSJohn Ogness 	 * If the message was truncated because the buffer was not large
139759f8bccaSJohn Ogness 	 * enough, treat the available text as if it were the full text.
139859f8bccaSJohn Ogness 	 */
139959f8bccaSJohn Ogness 	if (text_len > buf_size)
140059f8bccaSJohn Ogness 		text_len = buf_size;
1401b9ee979eSJoe Perches 
1402896fbe20SJohn Ogness 	prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1403b9ee979eSJoe Perches 
1404896fbe20SJohn Ogness 	/*
1405896fbe20SJohn Ogness 	 * @text_len: bytes of unprocessed text
1406896fbe20SJohn Ogness 	 * @line_len: bytes of current line _without_ newline
1407896fbe20SJohn Ogness 	 * @text:     pointer to beginning of current line
1408896fbe20SJohn Ogness 	 * @len:      number of bytes prepared in r->text_buf
1409896fbe20SJohn Ogness 	 */
1410896fbe20SJohn Ogness 	for (;;) {
1411896fbe20SJohn Ogness 		next = memchr(text, '\n', text_len);
1412b9ee979eSJoe Perches 		if (next) {
1413896fbe20SJohn Ogness 			line_len = next - text;
1414b9ee979eSJoe Perches 		} else {
1415896fbe20SJohn Ogness 			/* Drop truncated line(s). */
1416896fbe20SJohn Ogness 			if (truncated)
1417896fbe20SJohn Ogness 				break;
1418896fbe20SJohn Ogness 			line_len = text_len;
1419b9ee979eSJoe Perches 		}
1420b9ee979eSJoe Perches 
1421896fbe20SJohn Ogness 		/*
1422896fbe20SJohn Ogness 		 * Truncate the text if there is not enough space to add the
1423f0e386eeSJohn Ogness 		 * prefix and a trailing newline and a terminator.
1424896fbe20SJohn Ogness 		 */
1425f0e386eeSJohn Ogness 		if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1426896fbe20SJohn Ogness 			/* Drop even the current line if no space. */
1427f0e386eeSJohn Ogness 			if (len + prefix_len + line_len + 1 + 1 > buf_size)
1428b9ee979eSJoe Perches 				break;
1429b9ee979eSJoe Perches 
1430f0e386eeSJohn Ogness 			text_len = buf_size - len - prefix_len - 1 - 1;
1431896fbe20SJohn Ogness 			truncated = true;
1432b9ee979eSJoe Perches 		}
1433b9ee979eSJoe Perches 
1434896fbe20SJohn Ogness 		memmove(text + prefix_len, text, text_len);
1435896fbe20SJohn Ogness 		memcpy(text, prefix, prefix_len);
1436896fbe20SJohn Ogness 
1437f0e386eeSJohn Ogness 		/*
1438f0e386eeSJohn Ogness 		 * Increment the prepared length to include the text and
1439f0e386eeSJohn Ogness 		 * prefix that were just moved+copied. Also increment for the
1440f0e386eeSJohn Ogness 		 * newline at the end of this line. If this is the last line,
1441f0e386eeSJohn Ogness 		 * there is no newline, but it will be added immediately below.
1442f0e386eeSJohn Ogness 		 */
1443896fbe20SJohn Ogness 		len += prefix_len + line_len + 1;
1444896fbe20SJohn Ogness 		if (text_len == line_len) {
1445896fbe20SJohn Ogness 			/*
1446f0e386eeSJohn Ogness 			 * This is the last line. Add the trailing newline
1447f0e386eeSJohn Ogness 			 * removed in vprintk_store().
1448896fbe20SJohn Ogness 			 */
1449896fbe20SJohn Ogness 			text[prefix_len + line_len] = '\n';
1450896fbe20SJohn Ogness 			break;
1451896fbe20SJohn Ogness 		}
1452896fbe20SJohn Ogness 
1453896fbe20SJohn Ogness 		/*
1454896fbe20SJohn Ogness 		 * Advance beyond the added prefix and the related line with
1455896fbe20SJohn Ogness 		 * its newline.
1456896fbe20SJohn Ogness 		 */
1457896fbe20SJohn Ogness 		text += prefix_len + line_len + 1;
1458896fbe20SJohn Ogness 
1459896fbe20SJohn Ogness 		/*
1460896fbe20SJohn Ogness 		 * The remaining text has only decreased by the line with its
1461896fbe20SJohn Ogness 		 * newline.
1462896fbe20SJohn Ogness 		 *
1463896fbe20SJohn Ogness 		 * Note that @text_len can become zero. It happens when @text
1464896fbe20SJohn Ogness 		 * ended with a newline (either due to truncation or the
1465896fbe20SJohn Ogness 		 * original string ending with "\n\n"). The loop is correctly
1466896fbe20SJohn Ogness 		 * repeated and (if not truncated) an empty line with a prefix
1467896fbe20SJohn Ogness 		 * will be prepared.
1468896fbe20SJohn Ogness 		 */
1469896fbe20SJohn Ogness 		text_len -= line_len + 1;
1470896fbe20SJohn Ogness 	}
1471b9ee979eSJoe Perches 
1472f0e386eeSJohn Ogness 	/*
1473f0e386eeSJohn Ogness 	 * If a buffer was provided, it will be terminated. Space for the
1474f0e386eeSJohn Ogness 	 * string terminator is guaranteed to be available. The terminator is
1475f0e386eeSJohn Ogness 	 * not counted in the return value.
1476f0e386eeSJohn Ogness 	 */
1477f0e386eeSJohn Ogness 	if (buf_size > 0)
147808d60e59SJohn Ogness 		r->text_buf[len] = 0;
1479f0e386eeSJohn Ogness 
1480b9ee979eSJoe Perches 	return len;
1481b9ee979eSJoe Perches }
1482b9ee979eSJoe Perches 
get_record_print_text_size(struct printk_info * info,unsigned int line_count,bool syslog,bool time)1483896fbe20SJohn Ogness static size_t get_record_print_text_size(struct printk_info *info,
1484896fbe20SJohn Ogness 					 unsigned int line_count,
1485896fbe20SJohn Ogness 					 bool syslog, bool time)
1486896fbe20SJohn Ogness {
1487b0975c47SJohn Ogness 	char prefix[PRINTK_PREFIX_MAX];
1488896fbe20SJohn Ogness 	size_t prefix_len;
1489896fbe20SJohn Ogness 
1490896fbe20SJohn Ogness 	prefix_len = info_print_prefix(info, syslog, time, prefix);
1491896fbe20SJohn Ogness 
1492896fbe20SJohn Ogness 	/*
1493896fbe20SJohn Ogness 	 * Each line will be preceded with a prefix. The intermediate
1494896fbe20SJohn Ogness 	 * newlines are already within the text, but a final trailing
1495896fbe20SJohn Ogness 	 * newline will be added.
1496896fbe20SJohn Ogness 	 */
1497896fbe20SJohn Ogness 	return ((prefix_len * line_count) + info->text_len + 1);
1498896fbe20SJohn Ogness }
1499896fbe20SJohn Ogness 
15004260e0e5SJohn Ogness /*
15014260e0e5SJohn Ogness  * Beginning with @start_seq, find the first record where it and all following
15024260e0e5SJohn Ogness  * records up to (but not including) @max_seq fit into @size.
15034260e0e5SJohn Ogness  *
15044260e0e5SJohn Ogness  * @max_seq is simply an upper bound and does not need to exist. If the caller
15054260e0e5SJohn Ogness  * does not require an upper bound, -1 can be used for @max_seq.
15064260e0e5SJohn Ogness  */
find_first_fitting_seq(u64 start_seq,u64 max_seq,size_t size,bool syslog,bool time)15074260e0e5SJohn Ogness static u64 find_first_fitting_seq(u64 start_seq, u64 max_seq, size_t size,
15084260e0e5SJohn Ogness 				  bool syslog, bool time)
15094260e0e5SJohn Ogness {
15104260e0e5SJohn Ogness 	struct printk_info info;
15114260e0e5SJohn Ogness 	unsigned int line_count;
15124260e0e5SJohn Ogness 	size_t len = 0;
15134260e0e5SJohn Ogness 	u64 seq;
15144260e0e5SJohn Ogness 
15154260e0e5SJohn Ogness 	/* Determine the size of the records up to @max_seq. */
15164260e0e5SJohn Ogness 	prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
15174260e0e5SJohn Ogness 		if (info.seq >= max_seq)
15184260e0e5SJohn Ogness 			break;
15194260e0e5SJohn Ogness 		len += get_record_print_text_size(&info, line_count, syslog, time);
15204260e0e5SJohn Ogness 	}
15214260e0e5SJohn Ogness 
15224260e0e5SJohn Ogness 	/*
15234260e0e5SJohn Ogness 	 * Adjust the upper bound for the next loop to avoid subtracting
15244260e0e5SJohn Ogness 	 * lengths that were never added.
15254260e0e5SJohn Ogness 	 */
15264260e0e5SJohn Ogness 	if (seq < max_seq)
15274260e0e5SJohn Ogness 		max_seq = seq;
15284260e0e5SJohn Ogness 
15294260e0e5SJohn Ogness 	/*
15304260e0e5SJohn Ogness 	 * Move first record forward until length fits into the buffer. Ignore
15314260e0e5SJohn Ogness 	 * newest messages that were not counted in the above cycle. Messages
15324260e0e5SJohn Ogness 	 * might appear and get lost in the meantime. This is a best effort
15334260e0e5SJohn Ogness 	 * that prevents an infinite loop that could occur with a retry.
15344260e0e5SJohn Ogness 	 */
15354260e0e5SJohn Ogness 	prb_for_each_info(start_seq, prb, seq, &info, &line_count) {
15364260e0e5SJohn Ogness 		if (len <= size || info.seq >= max_seq)
15374260e0e5SJohn Ogness 			break;
15384260e0e5SJohn Ogness 		len -= get_record_print_text_size(&info, line_count, syslog, time);
15394260e0e5SJohn Ogness 	}
15404260e0e5SJohn Ogness 
15414260e0e5SJohn Ogness 	return seq;
15424260e0e5SJohn Ogness }
15434260e0e5SJohn Ogness 
15448d909b23SJohn Ogness /* The caller is responsible for making sure @size is greater than 0. */
syslog_print(char __user * buf,int size)1545b9ee979eSJoe Perches static int syslog_print(char __user *buf, int size)
1546b9ee979eSJoe Perches {
1547896fbe20SJohn Ogness 	struct printk_info info;
1548896fbe20SJohn Ogness 	struct printk_record r;
1549b9ee979eSJoe Perches 	char *text;
1550b9ee979eSJoe Perches 	int len = 0;
15518d909b23SJohn Ogness 	u64 seq;
1552b9ee979eSJoe Perches 
1553b0975c47SJohn Ogness 	text = kmalloc(PRINTK_MESSAGE_MAX, GFP_KERNEL);
1554b9ee979eSJoe Perches 	if (!text)
1555b9ee979eSJoe Perches 		return -ENOMEM;
1556b9ee979eSJoe Perches 
1557b0975c47SJohn Ogness 	prb_rec_init_rd(&r, &info, text, PRINTK_MESSAGE_MAX);
1558896fbe20SJohn Ogness 
15598d909b23SJohn Ogness 	mutex_lock(&syslog_lock);
15608d909b23SJohn Ogness 
15618d909b23SJohn Ogness 	/*
15628d909b23SJohn Ogness 	 * Wait for the @syslog_seq record to be available. @syslog_seq may
15638d909b23SJohn Ogness 	 * change while waiting.
15648d909b23SJohn Ogness 	 */
15658d909b23SJohn Ogness 	do {
15668d909b23SJohn Ogness 		seq = syslog_seq;
15678d909b23SJohn Ogness 
15688d909b23SJohn Ogness 		mutex_unlock(&syslog_lock);
15691f5d7830SJohn Ogness 		/*
15701f5d7830SJohn Ogness 		 * Guarantee this task is visible on the waitqueue before
15711f5d7830SJohn Ogness 		 * checking the wake condition.
15721f5d7830SJohn Ogness 		 *
15731f5d7830SJohn Ogness 		 * The full memory barrier within set_current_state() of
15741f5d7830SJohn Ogness 		 * prepare_to_wait_event() pairs with the full memory barrier
15751f5d7830SJohn Ogness 		 * within wq_has_sleeper().
15761f5d7830SJohn Ogness 		 *
15775341b93dSJohn Ogness 		 * This pairs with __wake_up_klogd:A.
15781f5d7830SJohn Ogness 		 */
15791f5d7830SJohn Ogness 		len = wait_event_interruptible(log_wait,
15801f5d7830SJohn Ogness 				prb_read_valid(prb, seq, NULL)); /* LMM(syslog_print:A) */
15818d909b23SJohn Ogness 		mutex_lock(&syslog_lock);
15828d909b23SJohn Ogness 
15838d909b23SJohn Ogness 		if (len)
15848d909b23SJohn Ogness 			goto out;
15858d909b23SJohn Ogness 	} while (syslog_seq != seq);
15868d909b23SJohn Ogness 
15878d909b23SJohn Ogness 	/*
15888d909b23SJohn Ogness 	 * Copy records that fit into the buffer. The above cycle makes sure
15898d909b23SJohn Ogness 	 * that the first record is always available.
15908d909b23SJohn Ogness 	 */
15918d909b23SJohn Ogness 	do {
1592b9ee979eSJoe Perches 		size_t n;
1593b9ee979eSJoe Perches 		size_t skip;
15948d909b23SJohn Ogness 		int err;
1595b9ee979eSJoe Perches 
15968d909b23SJohn Ogness 		if (!prb_read_valid(prb, syslog_seq, &r))
1597b9ee979eSJoe Perches 			break;
15988d909b23SJohn Ogness 
1599896fbe20SJohn Ogness 		if (r.info->seq != syslog_seq) {
1600896fbe20SJohn Ogness 			/* message is gone, move to next valid one */
1601896fbe20SJohn Ogness 			syslog_seq = r.info->seq;
1602896fbe20SJohn Ogness 			syslog_partial = 0;
1603896fbe20SJohn Ogness 		}
1604b9ee979eSJoe Perches 
1605e80c1a9dSTetsuo Handa 		/*
1606e80c1a9dSTetsuo Handa 		 * To keep reading/counting partial line consistent,
1607e80c1a9dSTetsuo Handa 		 * use printk_time value as of the beginning of a line.
1608e80c1a9dSTetsuo Handa 		 */
1609e80c1a9dSTetsuo Handa 		if (!syslog_partial)
1610e80c1a9dSTetsuo Handa 			syslog_time = printk_time;
1611e80c1a9dSTetsuo Handa 
1612b9ee979eSJoe Perches 		skip = syslog_partial;
1613896fbe20SJohn Ogness 		n = record_print_text(&r, true, syslog_time);
1614b9ee979eSJoe Perches 		if (n - syslog_partial <= size) {
1615b9ee979eSJoe Perches 			/* message fits into buffer, move forward */
1616896fbe20SJohn Ogness 			syslog_seq = r.info->seq + 1;
1617b9ee979eSJoe Perches 			n -= syslog_partial;
1618b9ee979eSJoe Perches 			syslog_partial = 0;
1619b9ee979eSJoe Perches 		} else if (!len){
1620b9ee979eSJoe Perches 			/* partial read(), remember position */
1621b9ee979eSJoe Perches 			n = size;
1622b9ee979eSJoe Perches 			syslog_partial += n;
1623b9ee979eSJoe Perches 		} else
1624b9ee979eSJoe Perches 			n = 0;
1625b9ee979eSJoe Perches 
1626b9ee979eSJoe Perches 		if (!n)
1627b9ee979eSJoe Perches 			break;
1628b9ee979eSJoe Perches 
16298d909b23SJohn Ogness 		mutex_unlock(&syslog_lock);
16308d909b23SJohn Ogness 		err = copy_to_user(buf, text + skip, n);
16318d909b23SJohn Ogness 		mutex_lock(&syslog_lock);
16328d909b23SJohn Ogness 
16338d909b23SJohn Ogness 		if (err) {
1634b9ee979eSJoe Perches 			if (!len)
1635b9ee979eSJoe Perches 				len = -EFAULT;
1636b9ee979eSJoe Perches 			break;
1637b9ee979eSJoe Perches 		}
1638b9ee979eSJoe Perches 
1639b9ee979eSJoe Perches 		len += n;
1640b9ee979eSJoe Perches 		size -= n;
1641b9ee979eSJoe Perches 		buf += n;
16428d909b23SJohn Ogness 	} while (size);
16438d909b23SJohn Ogness out:
16448d909b23SJohn Ogness 	mutex_unlock(&syslog_lock);
1645b9ee979eSJoe Perches 	kfree(text);
1646b9ee979eSJoe Perches 	return len;
1647b9ee979eSJoe Perches }
1648b9ee979eSJoe Perches 
syslog_print_all(char __user * buf,int size,bool clear)1649b9ee979eSJoe Perches static int syslog_print_all(char __user *buf, int size, bool clear)
1650b9ee979eSJoe Perches {
1651896fbe20SJohn Ogness 	struct printk_info info;
1652896fbe20SJohn Ogness 	struct printk_record r;
1653b9ee979eSJoe Perches 	char *text;
1654b9ee979eSJoe Perches 	int len = 0;
165563842c21SNamit Gupta 	u64 seq;
1656e80c1a9dSTetsuo Handa 	bool time;
165763842c21SNamit Gupta 
1658b0975c47SJohn Ogness 	text = kmalloc(PRINTK_MESSAGE_MAX, GFP_KERNEL);
1659b9ee979eSJoe Perches 	if (!text)
1660b9ee979eSJoe Perches 		return -ENOMEM;
1661b9ee979eSJoe Perches 
1662e80c1a9dSTetsuo Handa 	time = printk_time;
1663b9ee979eSJoe Perches 	/*
1664b9ee979eSJoe Perches 	 * Find first record that fits, including all following records,
1665b9ee979eSJoe Perches 	 * into the user-provided buffer for this dump.
1666b9ee979eSJoe Perches 	 */
16677d7a23a9SJohn Ogness 	seq = find_first_fitting_seq(latched_seq_read_nolock(&clear_seq), -1,
16687d7a23a9SJohn Ogness 				     size, true, time);
1669b9ee979eSJoe Perches 
1670b0975c47SJohn Ogness 	prb_rec_init_rd(&r, &info, text, PRINTK_MESSAGE_MAX);
1671b9ee979eSJoe Perches 
1672b9ee979eSJoe Perches 	len = 0;
1673896fbe20SJohn Ogness 	prb_for_each_record(seq, prb, seq, &r) {
1674896fbe20SJohn Ogness 		int textlen;
1675e80c1a9dSTetsuo Handa 
1676896fbe20SJohn Ogness 		textlen = record_print_text(&r, true, time);
1677896fbe20SJohn Ogness 
1678896fbe20SJohn Ogness 		if (len + textlen > size) {
1679896fbe20SJohn Ogness 			seq--;
1680896fbe20SJohn Ogness 			break;
1681896fbe20SJohn Ogness 		}
1682b9ee979eSJoe Perches 
1683b9ee979eSJoe Perches 		if (copy_to_user(buf + len, text, textlen))
1684b9ee979eSJoe Perches 			len = -EFAULT;
1685b9ee979eSJoe Perches 		else
1686b9ee979eSJoe Perches 			len += textlen;
1687b9ee979eSJoe Perches 
1688896fbe20SJohn Ogness 		if (len < 0)
1689896fbe20SJohn Ogness 			break;
1690b9ee979eSJoe Perches 	}
1691b9ee979eSJoe Perches 
1692636babdcSJohn Ogness 	if (clear) {
1693b371cbb5SJohn Ogness 		mutex_lock(&syslog_lock);
16947d7a23a9SJohn Ogness 		latched_seq_write(&clear_seq, seq);
1695b371cbb5SJohn Ogness 		mutex_unlock(&syslog_lock);
1696636babdcSJohn Ogness 	}
1697b9ee979eSJoe Perches 
1698b9ee979eSJoe Perches 	kfree(text);
1699b9ee979eSJoe Perches 	return len;
1700b9ee979eSJoe Perches }
1701b9ee979eSJoe Perches 
syslog_clear(void)17028599dc7dSPetr Mladek static void syslog_clear(void)
17038599dc7dSPetr Mladek {
1704b371cbb5SJohn Ogness 	mutex_lock(&syslog_lock);
17057d7a23a9SJohn Ogness 	latched_seq_write(&clear_seq, prb_next_seq(prb));
1706b371cbb5SJohn Ogness 	mutex_unlock(&syslog_lock);
1707636babdcSJohn Ogness }
1708636babdcSJohn Ogness 
do_syslog(int type,char __user * buf,int len,int source)17093ea4331cSVasily Averin int do_syslog(int type, char __user *buf, int len, int source)
1710b9ee979eSJoe Perches {
171113791c80SJohn Ogness 	struct printk_info info;
1712b9ee979eSJoe Perches 	bool clear = false;
1713a39d4a85SJoe Perches 	static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1714b9ee979eSJoe Perches 	int error;
1715b9ee979eSJoe Perches 
17163ea4331cSVasily Averin 	error = check_syslog_permissions(type, source);
1717b9ee979eSJoe Perches 	if (error)
1718077a1cc0SNikitas Angelinas 		return error;
1719b9ee979eSJoe Perches 
1720b9ee979eSJoe Perches 	switch (type) {
1721b9ee979eSJoe Perches 	case SYSLOG_ACTION_CLOSE:	/* Close log */
1722b9ee979eSJoe Perches 		break;
1723b9ee979eSJoe Perches 	case SYSLOG_ACTION_OPEN:	/* Open log */
1724b9ee979eSJoe Perches 		break;
1725b9ee979eSJoe Perches 	case SYSLOG_ACTION_READ:	/* Read from log */
1726b9ee979eSJoe Perches 		if (!buf || len < 0)
1727077a1cc0SNikitas Angelinas 			return -EINVAL;
1728b9ee979eSJoe Perches 		if (!len)
1729077a1cc0SNikitas Angelinas 			return 0;
173096d4f267SLinus Torvalds 		if (!access_ok(buf, len))
1731077a1cc0SNikitas Angelinas 			return -EFAULT;
1732b9ee979eSJoe Perches 		error = syslog_print(buf, len);
1733b9ee979eSJoe Perches 		break;
1734b9ee979eSJoe Perches 	/* Read/clear last kernel messages */
1735b9ee979eSJoe Perches 	case SYSLOG_ACTION_READ_CLEAR:
1736b9ee979eSJoe Perches 		clear = true;
17374e797e6eSGustavo A. R. Silva 		fallthrough;
1738b9ee979eSJoe Perches 	/* Read last kernel messages */
1739b9ee979eSJoe Perches 	case SYSLOG_ACTION_READ_ALL:
1740b9ee979eSJoe Perches 		if (!buf || len < 0)
1741077a1cc0SNikitas Angelinas 			return -EINVAL;
1742b9ee979eSJoe Perches 		if (!len)
1743077a1cc0SNikitas Angelinas 			return 0;
174496d4f267SLinus Torvalds 		if (!access_ok(buf, len))
1745077a1cc0SNikitas Angelinas 			return -EFAULT;
1746b9ee979eSJoe Perches 		error = syslog_print_all(buf, len, clear);
1747b9ee979eSJoe Perches 		break;
1748b9ee979eSJoe Perches 	/* Clear ring buffer */
1749b9ee979eSJoe Perches 	case SYSLOG_ACTION_CLEAR:
17508599dc7dSPetr Mladek 		syslog_clear();
1751b9ee979eSJoe Perches 		break;
1752b9ee979eSJoe Perches 	/* Disable logging to console */
1753b9ee979eSJoe Perches 	case SYSLOG_ACTION_CONSOLE_OFF:
1754a39d4a85SJoe Perches 		if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1755b9ee979eSJoe Perches 			saved_console_loglevel = console_loglevel;
1756b9ee979eSJoe Perches 		console_loglevel = minimum_console_loglevel;
1757b9ee979eSJoe Perches 		break;
1758b9ee979eSJoe Perches 	/* Enable logging to console */
1759b9ee979eSJoe Perches 	case SYSLOG_ACTION_CONSOLE_ON:
1760a39d4a85SJoe Perches 		if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1761b9ee979eSJoe Perches 			console_loglevel = saved_console_loglevel;
1762a39d4a85SJoe Perches 			saved_console_loglevel = LOGLEVEL_DEFAULT;
1763b9ee979eSJoe Perches 		}
1764b9ee979eSJoe Perches 		break;
1765b9ee979eSJoe Perches 	/* Set level of messages printed to console */
1766b9ee979eSJoe Perches 	case SYSLOG_ACTION_CONSOLE_LEVEL:
1767b9ee979eSJoe Perches 		if (len < 1 || len > 8)
1768077a1cc0SNikitas Angelinas 			return -EINVAL;
1769b9ee979eSJoe Perches 		if (len < minimum_console_loglevel)
1770b9ee979eSJoe Perches 			len = minimum_console_loglevel;
1771b9ee979eSJoe Perches 		console_loglevel = len;
1772b9ee979eSJoe Perches 		/* Implicitly re-enable logging to console */
1773a39d4a85SJoe Perches 		saved_console_loglevel = LOGLEVEL_DEFAULT;
1774b9ee979eSJoe Perches 		break;
1775b9ee979eSJoe Perches 	/* Number of chars in the log buffer */
1776b9ee979eSJoe Perches 	case SYSLOG_ACTION_SIZE_UNREAD:
1777b371cbb5SJohn Ogness 		mutex_lock(&syslog_lock);
177813791c80SJohn Ogness 		if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
177913791c80SJohn Ogness 			/* No unread messages. */
1780b371cbb5SJohn Ogness 			mutex_unlock(&syslog_lock);
178113791c80SJohn Ogness 			return 0;
178213791c80SJohn Ogness 		}
178313791c80SJohn Ogness 		if (info.seq != syslog_seq) {
1784b9ee979eSJoe Perches 			/* messages are gone, move to first one */
178513791c80SJohn Ogness 			syslog_seq = info.seq;
1786b9ee979eSJoe Perches 			syslog_partial = 0;
1787b9ee979eSJoe Perches 		}
17883ea4331cSVasily Averin 		if (source == SYSLOG_FROM_PROC) {
1789b9ee979eSJoe Perches 			/*
1790b9ee979eSJoe Perches 			 * Short-cut for poll(/"proc/kmsg") which simply checks
1791b9ee979eSJoe Perches 			 * for pending data, not the size; return the count of
1792b9ee979eSJoe Perches 			 * records, not the length.
1793b9ee979eSJoe Perches 			 */
1794896fbe20SJohn Ogness 			error = prb_next_seq(prb) - syslog_seq;
1795b9ee979eSJoe Perches 		} else {
1796e80c1a9dSTetsuo Handa 			bool time = syslog_partial ? syslog_time : printk_time;
1797896fbe20SJohn Ogness 			unsigned int line_count;
1798896fbe20SJohn Ogness 			u64 seq;
1799b9ee979eSJoe Perches 
1800896fbe20SJohn Ogness 			prb_for_each_info(syslog_seq, prb, seq, &info,
1801896fbe20SJohn Ogness 					  &line_count) {
1802896fbe20SJohn Ogness 				error += get_record_print_text_size(&info, line_count,
1803896fbe20SJohn Ogness 								    true, time);
1804e80c1a9dSTetsuo Handa 				time = printk_time;
1805b9ee979eSJoe Perches 			}
1806b9ee979eSJoe Perches 			error -= syslog_partial;
1807b9ee979eSJoe Perches 		}
1808b371cbb5SJohn Ogness 		mutex_unlock(&syslog_lock);
1809b9ee979eSJoe Perches 		break;
1810b9ee979eSJoe Perches 	/* Size of the log buffer */
1811b9ee979eSJoe Perches 	case SYSLOG_ACTION_SIZE_BUFFER:
1812b9ee979eSJoe Perches 		error = log_buf_len;
1813b9ee979eSJoe Perches 		break;
1814b9ee979eSJoe Perches 	default:
1815b9ee979eSJoe Perches 		error = -EINVAL;
1816b9ee979eSJoe Perches 		break;
1817b9ee979eSJoe Perches 	}
1818077a1cc0SNikitas Angelinas 
1819b9ee979eSJoe Perches 	return error;
1820b9ee979eSJoe Perches }
1821b9ee979eSJoe Perches 
SYSCALL_DEFINE3(syslog,int,type,char __user *,buf,int,len)1822b9ee979eSJoe Perches SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1823b9ee979eSJoe Perches {
1824b9ee979eSJoe Perches 	return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1825b9ee979eSJoe Perches }
1826b9ee979eSJoe Perches 
1827b9ee979eSJoe Perches /*
1828c162d5b4SPetr Mladek  * Special console_lock variants that help to reduce the risk of soft-lockups.
1829c162d5b4SPetr Mladek  * They allow to pass console_lock to another printk() call using a busy wait.
1830c162d5b4SPetr Mladek  */
1831c162d5b4SPetr Mladek 
1832c162d5b4SPetr Mladek #ifdef CONFIG_LOCKDEP
1833c162d5b4SPetr Mladek static struct lockdep_map console_owner_dep_map = {
1834c162d5b4SPetr Mladek 	.name = "console_owner"
1835c162d5b4SPetr Mladek };
1836c162d5b4SPetr Mladek #endif
1837c162d5b4SPetr Mladek 
1838c162d5b4SPetr Mladek static DEFINE_RAW_SPINLOCK(console_owner_lock);
1839c162d5b4SPetr Mladek static struct task_struct *console_owner;
1840c162d5b4SPetr Mladek static bool console_waiter;
1841c162d5b4SPetr Mladek 
1842c162d5b4SPetr Mladek /**
1843c162d5b4SPetr Mladek  * console_lock_spinning_enable - mark beginning of code where another
1844c162d5b4SPetr Mladek  *	thread might safely busy wait
1845c162d5b4SPetr Mladek  *
1846c162d5b4SPetr Mladek  * This basically converts console_lock into a spinlock. This marks
1847c162d5b4SPetr Mladek  * the section where the console_lock owner can not sleep, because
1848c162d5b4SPetr Mladek  * there may be a waiter spinning (like a spinlock). Also it must be
1849c162d5b4SPetr Mladek  * ready to hand over the lock at the end of the section.
1850c162d5b4SPetr Mladek  */
console_lock_spinning_enable(void)1851c162d5b4SPetr Mladek static void console_lock_spinning_enable(void)
1852c162d5b4SPetr Mladek {
1853a3b17859SPetr Mladek 	/*
1854a3b17859SPetr Mladek 	 * Do not use spinning in panic(). The panic CPU wants to keep the lock.
1855a3b17859SPetr Mladek 	 * Non-panic CPUs abandon the flush anyway.
1856a3b17859SPetr Mladek 	 *
1857a3b17859SPetr Mladek 	 * Just keep the lockdep annotation. The panic-CPU should avoid
1858a3b17859SPetr Mladek 	 * taking console_owner_lock because it might cause a deadlock.
1859a3b17859SPetr Mladek 	 * This looks like the easiest way how to prevent false lockdep
1860a3b17859SPetr Mladek 	 * reports without handling races a lockless way.
1861a3b17859SPetr Mladek 	 */
1862a3b17859SPetr Mladek 	if (panic_in_progress())
1863a3b17859SPetr Mladek 		goto lockdep;
1864a3b17859SPetr Mladek 
1865c162d5b4SPetr Mladek 	raw_spin_lock(&console_owner_lock);
1866c162d5b4SPetr Mladek 	console_owner = current;
1867c162d5b4SPetr Mladek 	raw_spin_unlock(&console_owner_lock);
1868c162d5b4SPetr Mladek 
1869a3b17859SPetr Mladek lockdep:
1870c162d5b4SPetr Mladek 	/* The waiter may spin on us after setting console_owner */
1871c162d5b4SPetr Mladek 	spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1872c162d5b4SPetr Mladek }
1873c162d5b4SPetr Mladek 
1874c162d5b4SPetr Mladek /**
1875c162d5b4SPetr Mladek  * console_lock_spinning_disable_and_check - mark end of code where another
1876c162d5b4SPetr Mladek  *	thread was able to busy wait and check if there is a waiter
18774fe59a13SAnuradha Weeraman  * @cookie: cookie returned from console_srcu_read_lock()
1878c162d5b4SPetr Mladek  *
1879c162d5b4SPetr Mladek  * This is called at the end of the section where spinning is allowed.
1880c162d5b4SPetr Mladek  * It has two functions. First, it is a signal that it is no longer
1881c162d5b4SPetr Mladek  * safe to start busy waiting for the lock. Second, it checks if
1882c162d5b4SPetr Mladek  * there is a busy waiter and passes the lock rights to her.
1883c162d5b4SPetr Mladek  *
1884fc956ae0SJohn Ogness  * Important: Callers lose both the console_lock and the SRCU read lock if
1885fc956ae0SJohn Ogness  *	there was a busy waiter. They must not touch items synchronized by
1886fc956ae0SJohn Ogness  *	console_lock or SRCU read lock in this case.
1887c162d5b4SPetr Mladek  *
1888c162d5b4SPetr Mladek  * Return: 1 if the lock rights were passed, 0 otherwise.
1889c162d5b4SPetr Mladek  */
console_lock_spinning_disable_and_check(int cookie)1890fc956ae0SJohn Ogness static int console_lock_spinning_disable_and_check(int cookie)
1891c162d5b4SPetr Mladek {
1892c162d5b4SPetr Mladek 	int waiter;
1893c162d5b4SPetr Mladek 
1894a3b17859SPetr Mladek 	/*
1895a3b17859SPetr Mladek 	 * Ignore spinning waiters during panic() because they might get stopped
1896a3b17859SPetr Mladek 	 * or blocked at any time,
1897a3b17859SPetr Mladek 	 *
1898a3b17859SPetr Mladek 	 * It is safe because nobody is allowed to start spinning during panic
1899a3b17859SPetr Mladek 	 * in the first place. If there has been a waiter then non panic CPUs
1900a3b17859SPetr Mladek 	 * might stay spinning. They would get stopped anyway. The panic context
1901a3b17859SPetr Mladek 	 * will never start spinning and an interrupted spin on panic CPU will
1902a3b17859SPetr Mladek 	 * never continue.
1903a3b17859SPetr Mladek 	 */
1904a3b17859SPetr Mladek 	if (panic_in_progress()) {
1905a3b17859SPetr Mladek 		/* Keep lockdep happy. */
1906a3b17859SPetr Mladek 		spin_release(&console_owner_dep_map, _THIS_IP_);
1907a3b17859SPetr Mladek 		return 0;
1908a3b17859SPetr Mladek 	}
1909a3b17859SPetr Mladek 
1910c162d5b4SPetr Mladek 	raw_spin_lock(&console_owner_lock);
1911c162d5b4SPetr Mladek 	waiter = READ_ONCE(console_waiter);
1912c162d5b4SPetr Mladek 	console_owner = NULL;
1913c162d5b4SPetr Mladek 	raw_spin_unlock(&console_owner_lock);
1914c162d5b4SPetr Mladek 
1915c162d5b4SPetr Mladek 	if (!waiter) {
19165facae4fSQian Cai 		spin_release(&console_owner_dep_map, _THIS_IP_);
1917c162d5b4SPetr Mladek 		return 0;
1918c162d5b4SPetr Mladek 	}
1919c162d5b4SPetr Mladek 
1920c162d5b4SPetr Mladek 	/* The waiter is now free to continue */
1921c162d5b4SPetr Mladek 	WRITE_ONCE(console_waiter, false);
1922c162d5b4SPetr Mladek 
19235facae4fSQian Cai 	spin_release(&console_owner_dep_map, _THIS_IP_);
1924c162d5b4SPetr Mladek 
1925c162d5b4SPetr Mladek 	/*
1926fc956ae0SJohn Ogness 	 * Preserve lockdep lock ordering. Release the SRCU read lock before
1927fc956ae0SJohn Ogness 	 * releasing the console_lock.
1928fc956ae0SJohn Ogness 	 */
1929fc956ae0SJohn Ogness 	console_srcu_read_unlock(cookie);
1930fc956ae0SJohn Ogness 
1931fc956ae0SJohn Ogness 	/*
1932c162d5b4SPetr Mladek 	 * Hand off console_lock to waiter. The waiter will perform
1933c162d5b4SPetr Mladek 	 * the up(). After this, the waiter is the console_lock owner.
1934c162d5b4SPetr Mladek 	 */
19355facae4fSQian Cai 	mutex_release(&console_lock_dep_map, _THIS_IP_);
1936c162d5b4SPetr Mladek 	return 1;
1937c162d5b4SPetr Mladek }
1938c162d5b4SPetr Mladek 
1939c162d5b4SPetr Mladek /**
1940c162d5b4SPetr Mladek  * console_trylock_spinning - try to get console_lock by busy waiting
1941c162d5b4SPetr Mladek  *
1942c162d5b4SPetr Mladek  * This allows to busy wait for the console_lock when the current
1943c162d5b4SPetr Mladek  * owner is running in specially marked sections. It means that
1944c162d5b4SPetr Mladek  * the current owner is running and cannot reschedule until it
1945c162d5b4SPetr Mladek  * is ready to lose the lock.
1946c162d5b4SPetr Mladek  *
1947c162d5b4SPetr Mladek  * Return: 1 if we got the lock, 0 othrewise
1948c162d5b4SPetr Mladek  */
console_trylock_spinning(void)1949c162d5b4SPetr Mladek static int console_trylock_spinning(void)
1950c162d5b4SPetr Mladek {
1951c162d5b4SPetr Mladek 	struct task_struct *owner = NULL;
1952c162d5b4SPetr Mladek 	bool waiter;
1953c162d5b4SPetr Mladek 	bool spin = false;
1954c162d5b4SPetr Mladek 	unsigned long flags;
1955c162d5b4SPetr Mladek 
1956c162d5b4SPetr Mladek 	if (console_trylock())
1957c162d5b4SPetr Mladek 		return 1;
1958c162d5b4SPetr Mladek 
1959d5150709SStephen Brennan 	/*
1960d5150709SStephen Brennan 	 * It's unsafe to spin once a panic has begun. If we are the
1961d5150709SStephen Brennan 	 * panic CPU, we may have already halted the owner of the
1962d5150709SStephen Brennan 	 * console_sem. If we are not the panic CPU, then we should
1963d5150709SStephen Brennan 	 * avoid taking console_sem, so the panic CPU has a better
1964d5150709SStephen Brennan 	 * chance of cleanly acquiring it later.
1965d5150709SStephen Brennan 	 */
1966d5150709SStephen Brennan 	if (panic_in_progress())
1967d5150709SStephen Brennan 		return 0;
1968d5150709SStephen Brennan 
1969c162d5b4SPetr Mladek 	printk_safe_enter_irqsave(flags);
1970c162d5b4SPetr Mladek 
1971c162d5b4SPetr Mladek 	raw_spin_lock(&console_owner_lock);
1972c162d5b4SPetr Mladek 	owner = READ_ONCE(console_owner);
1973c162d5b4SPetr Mladek 	waiter = READ_ONCE(console_waiter);
1974c162d5b4SPetr Mladek 	if (!waiter && owner && owner != current) {
1975c162d5b4SPetr Mladek 		WRITE_ONCE(console_waiter, true);
1976c162d5b4SPetr Mladek 		spin = true;
1977c162d5b4SPetr Mladek 	}
1978c162d5b4SPetr Mladek 	raw_spin_unlock(&console_owner_lock);
1979c162d5b4SPetr Mladek 
1980c162d5b4SPetr Mladek 	/*
1981c162d5b4SPetr Mladek 	 * If there is an active printk() writing to the
1982c162d5b4SPetr Mladek 	 * consoles, instead of having it write our data too,
1983c162d5b4SPetr Mladek 	 * see if we can offload that load from the active
1984c162d5b4SPetr Mladek 	 * printer, and do some printing ourselves.
1985c162d5b4SPetr Mladek 	 * Go into a spin only if there isn't already a waiter
1986c162d5b4SPetr Mladek 	 * spinning, and there is an active printer, and
1987c162d5b4SPetr Mladek 	 * that active printer isn't us (recursive printk?).
1988c162d5b4SPetr Mladek 	 */
1989c162d5b4SPetr Mladek 	if (!spin) {
1990c162d5b4SPetr Mladek 		printk_safe_exit_irqrestore(flags);
1991c162d5b4SPetr Mladek 		return 0;
1992c162d5b4SPetr Mladek 	}
1993c162d5b4SPetr Mladek 
1994c162d5b4SPetr Mladek 	/* We spin waiting for the owner to release us */
1995c162d5b4SPetr Mladek 	spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1996c162d5b4SPetr Mladek 	/* Owner will clear console_waiter on hand off */
1997c162d5b4SPetr Mladek 	while (READ_ONCE(console_waiter))
1998c162d5b4SPetr Mladek 		cpu_relax();
19995facae4fSQian Cai 	spin_release(&console_owner_dep_map, _THIS_IP_);
2000c162d5b4SPetr Mladek 
2001c162d5b4SPetr Mladek 	printk_safe_exit_irqrestore(flags);
2002c162d5b4SPetr Mladek 	/*
2003c162d5b4SPetr Mladek 	 * The owner passed the console lock to us.
2004c162d5b4SPetr Mladek 	 * Since we did not spin on console lock, annotate
2005c162d5b4SPetr Mladek 	 * this as a trylock. Otherwise lockdep will
2006c162d5b4SPetr Mladek 	 * complain.
2007c162d5b4SPetr Mladek 	 */
2008c162d5b4SPetr Mladek 	mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
2009c162d5b4SPetr Mladek 
2010ea4c338cSJohn Ogness 	/*
2011ea4c338cSJohn Ogness 	 * Update @console_may_schedule for trylock because the previous
2012ea4c338cSJohn Ogness 	 * owner may have been schedulable.
2013ea4c338cSJohn Ogness 	 */
2014ea4c338cSJohn Ogness 	console_may_schedule = 0;
2015ea4c338cSJohn Ogness 
2016c162d5b4SPetr Mladek 	return 1;
2017c162d5b4SPetr Mladek }
2018c162d5b4SPetr Mladek 
2019c162d5b4SPetr Mladek /*
2020002eb6adSJohn Ogness  * Recursion is tracked separately on each CPU. If NMIs are supported, an
2021002eb6adSJohn Ogness  * additional NMI context per CPU is also separately tracked. Until per-CPU
2022002eb6adSJohn Ogness  * is available, a separate "early tracking" is performed.
2023002eb6adSJohn Ogness  */
2024002eb6adSJohn Ogness static DEFINE_PER_CPU(u8, printk_count);
2025002eb6adSJohn Ogness static u8 printk_count_early;
2026002eb6adSJohn Ogness #ifdef CONFIG_HAVE_NMI
2027002eb6adSJohn Ogness static DEFINE_PER_CPU(u8, printk_count_nmi);
2028002eb6adSJohn Ogness static u8 printk_count_nmi_early;
2029002eb6adSJohn Ogness #endif
2030002eb6adSJohn Ogness 
2031002eb6adSJohn Ogness /*
2032002eb6adSJohn Ogness  * Recursion is limited to keep the output sane. printk() should not require
2033002eb6adSJohn Ogness  * more than 1 level of recursion (allowing, for example, printk() to trigger
2034002eb6adSJohn Ogness  * a WARN), but a higher value is used in case some printk-internal errors
2035002eb6adSJohn Ogness  * exist, such as the ringbuffer validation checks failing.
2036002eb6adSJohn Ogness  */
2037002eb6adSJohn Ogness #define PRINTK_MAX_RECURSION 3
2038002eb6adSJohn Ogness 
2039002eb6adSJohn Ogness /*
2040002eb6adSJohn Ogness  * Return a pointer to the dedicated counter for the CPU+context of the
2041002eb6adSJohn Ogness  * caller.
2042002eb6adSJohn Ogness  */
__printk_recursion_counter(void)2043002eb6adSJohn Ogness static u8 *__printk_recursion_counter(void)
2044002eb6adSJohn Ogness {
2045002eb6adSJohn Ogness #ifdef CONFIG_HAVE_NMI
2046002eb6adSJohn Ogness 	if (in_nmi()) {
2047002eb6adSJohn Ogness 		if (printk_percpu_data_ready())
2048002eb6adSJohn Ogness 			return this_cpu_ptr(&printk_count_nmi);
2049002eb6adSJohn Ogness 		return &printk_count_nmi_early;
2050002eb6adSJohn Ogness 	}
2051002eb6adSJohn Ogness #endif
2052002eb6adSJohn Ogness 	if (printk_percpu_data_ready())
2053002eb6adSJohn Ogness 		return this_cpu_ptr(&printk_count);
2054002eb6adSJohn Ogness 	return &printk_count_early;
2055002eb6adSJohn Ogness }
2056002eb6adSJohn Ogness 
2057002eb6adSJohn Ogness /*
2058002eb6adSJohn Ogness  * Enter recursion tracking. Interrupts are disabled to simplify tracking.
2059002eb6adSJohn Ogness  * The caller must check the boolean return value to see if the recursion is
2060002eb6adSJohn Ogness  * allowed. On failure, interrupts are not disabled.
2061002eb6adSJohn Ogness  *
2062002eb6adSJohn Ogness  * @recursion_ptr must be a variable of type (u8 *) and is the same variable
2063002eb6adSJohn Ogness  * that is passed to printk_exit_irqrestore().
2064002eb6adSJohn Ogness  */
2065002eb6adSJohn Ogness #define printk_enter_irqsave(recursion_ptr, flags)	\
2066002eb6adSJohn Ogness ({							\
2067002eb6adSJohn Ogness 	bool success = true;				\
2068002eb6adSJohn Ogness 							\
2069002eb6adSJohn Ogness 	typecheck(u8 *, recursion_ptr);			\
2070002eb6adSJohn Ogness 	local_irq_save(flags);				\
2071002eb6adSJohn Ogness 	(recursion_ptr) = __printk_recursion_counter();	\
2072002eb6adSJohn Ogness 	if (*(recursion_ptr) > PRINTK_MAX_RECURSION) {	\
2073002eb6adSJohn Ogness 		local_irq_restore(flags);		\
2074002eb6adSJohn Ogness 		success = false;			\
2075002eb6adSJohn Ogness 	} else {					\
2076002eb6adSJohn Ogness 		(*(recursion_ptr))++;			\
2077002eb6adSJohn Ogness 	}						\
2078002eb6adSJohn Ogness 	success;					\
2079002eb6adSJohn Ogness })
2080002eb6adSJohn Ogness 
2081002eb6adSJohn Ogness /* Exit recursion tracking, restoring interrupts. */
2082002eb6adSJohn Ogness #define printk_exit_irqrestore(recursion_ptr, flags)	\
2083002eb6adSJohn Ogness 	do {						\
2084002eb6adSJohn Ogness 		typecheck(u8 *, recursion_ptr);		\
2085002eb6adSJohn Ogness 		(*(recursion_ptr))--;			\
2086002eb6adSJohn Ogness 		local_irq_restore(flags);		\
2087002eb6adSJohn Ogness 	} while (0)
2088002eb6adSJohn Ogness 
2089b9ee979eSJoe Perches int printk_delay_msec __read_mostly;
2090b9ee979eSJoe Perches 
printk_delay(int level)20911f47e8afSJohn Ogness static inline void printk_delay(int level)
2092b9ee979eSJoe Perches {
20931f47e8afSJohn Ogness 	boot_delay_msec(level);
20941f47e8afSJohn Ogness 
2095b9ee979eSJoe Perches 	if (unlikely(printk_delay_msec)) {
2096b9ee979eSJoe Perches 		int m = printk_delay_msec;
2097b9ee979eSJoe Perches 
2098b9ee979eSJoe Perches 		while (m--) {
2099b9ee979eSJoe Perches 			mdelay(1);
2100b9ee979eSJoe Perches 			touch_nmi_watchdog();
2101b9ee979eSJoe Perches 		}
2102b9ee979eSJoe Perches 	}
2103b9ee979eSJoe Perches }
2104b9ee979eSJoe Perches 
printk_caller_id(void)2105cbae05d3STetsuo Handa static inline u32 printk_caller_id(void)
2106cbae05d3STetsuo Handa {
2107cbae05d3STetsuo Handa 	return in_task() ? task_pid_nr(current) :
21089f0844deSJohn Ogness 		0x80000000 + smp_processor_id();
2109cbae05d3STetsuo Handa }
2110cbae05d3STetsuo Handa 
2111b031a684SJohn Ogness /**
2112f3d75cf5SChris Down  * printk_parse_prefix - Parse level and control flags.
2113b031a684SJohn Ogness  *
2114b031a684SJohn Ogness  * @text:     The terminated text message.
2115b031a684SJohn Ogness  * @level:    A pointer to the current level value, will be updated.
2116a1ad4b8aSChris Down  * @flags:    A pointer to the current printk_info flags, will be updated.
2117b031a684SJohn Ogness  *
2118b031a684SJohn Ogness  * @level may be NULL if the caller is not interested in the parsed value.
2119b031a684SJohn Ogness  * Otherwise the variable pointed to by @level must be set to
2120b031a684SJohn Ogness  * LOGLEVEL_DEFAULT in order to be updated with the parsed value.
2121b031a684SJohn Ogness  *
2122a1ad4b8aSChris Down  * @flags may be NULL if the caller is not interested in the parsed value.
2123a1ad4b8aSChris Down  * Otherwise the variable pointed to by @flags will be OR'd with the parsed
2124b031a684SJohn Ogness  * value.
2125b031a684SJohn Ogness  *
2126b031a684SJohn Ogness  * Return: The length of the parsed level and control flags.
2127b031a684SJohn Ogness  */
printk_parse_prefix(const char * text,int * level,enum printk_info_flags * flags)2128f3d75cf5SChris Down u16 printk_parse_prefix(const char *text, int *level,
2129a1ad4b8aSChris Down 			enum printk_info_flags *flags)
2130c362c7ffSLinus Torvalds {
2131b031a684SJohn Ogness 	u16 prefix_len = 0;
2132b031a684SJohn Ogness 	int kern_level;
2133cbae05d3STetsuo Handa 
2134b031a684SJohn Ogness 	while (*text) {
2135b031a684SJohn Ogness 		kern_level = printk_get_level(text);
2136b031a684SJohn Ogness 		if (!kern_level)
2137b031a684SJohn Ogness 			break;
2138f5f022e5SJohn Ogness 
2139b031a684SJohn Ogness 		switch (kern_level) {
2140b031a684SJohn Ogness 		case '0' ... '7':
2141b031a684SJohn Ogness 			if (level && *level == LOGLEVEL_DEFAULT)
2142b031a684SJohn Ogness 				*level = kern_level - '0';
2143b031a684SJohn Ogness 			break;
2144b031a684SJohn Ogness 		case 'c':	/* KERN_CONT */
2145a1ad4b8aSChris Down 			if (flags)
2146a1ad4b8aSChris Down 				*flags |= LOG_CONT;
2147f5f022e5SJohn Ogness 		}
2148b031a684SJohn Ogness 
2149b031a684SJohn Ogness 		prefix_len += 2;
2150b031a684SJohn Ogness 		text += 2;
2151b031a684SJohn Ogness 	}
2152b031a684SJohn Ogness 
2153b031a684SJohn Ogness 	return prefix_len;
2154b031a684SJohn Ogness }
2155b031a684SJohn Ogness 
2156264a7504SJohn Ogness __printf(5, 0)
printk_sprint(char * text,u16 size,int facility,enum printk_info_flags * flags,const char * fmt,va_list args)2157a1ad4b8aSChris Down static u16 printk_sprint(char *text, u16 size, int facility,
2158a1ad4b8aSChris Down 			 enum printk_info_flags *flags, const char *fmt,
2159a1ad4b8aSChris Down 			 va_list args)
2160b031a684SJohn Ogness {
2161b031a684SJohn Ogness 	u16 text_len;
2162b031a684SJohn Ogness 
2163b031a684SJohn Ogness 	text_len = vscnprintf(text, size, fmt, args);
2164b031a684SJohn Ogness 
2165b031a684SJohn Ogness 	/* Mark and strip a trailing newline. */
2166b031a684SJohn Ogness 	if (text_len && text[text_len - 1] == '\n') {
2167b031a684SJohn Ogness 		text_len--;
2168a1ad4b8aSChris Down 		*flags |= LOG_NEWLINE;
2169b031a684SJohn Ogness 	}
2170b031a684SJohn Ogness 
2171b031a684SJohn Ogness 	/* Strip log level and control flags. */
2172b031a684SJohn Ogness 	if (facility == 0) {
2173b031a684SJohn Ogness 		u16 prefix_len;
2174b031a684SJohn Ogness 
2175f3d75cf5SChris Down 		prefix_len = printk_parse_prefix(text, NULL, NULL);
2176b031a684SJohn Ogness 		if (prefix_len) {
2177b031a684SJohn Ogness 			text_len -= prefix_len;
2178b031a684SJohn Ogness 			memmove(text, text + prefix_len, text_len);
2179b031a684SJohn Ogness 		}
2180b031a684SJohn Ogness 	}
2181b031a684SJohn Ogness 
2182880970b5SPeter Zijlstra 	trace_console(text, text_len);
2183701850dcSMarco Elver 
21845e467652SLinus Torvalds 	return text_len;
21855e467652SLinus Torvalds }
2186c362c7ffSLinus Torvalds 
2187b031a684SJohn Ogness __printf(4, 0)
vprintk_store(int facility,int level,const struct dev_printk_info * dev_info,const char * fmt,va_list args)2188ba552399SPetr Mladek int vprintk_store(int facility, int level,
218974caba7fSJohn Ogness 		  const struct dev_printk_info *dev_info,
2190b9ee979eSJoe Perches 		  const char *fmt, va_list args)
2191b9ee979eSJoe Perches {
21926b916706SJohn Ogness 	struct prb_reserved_entry e;
2193a1ad4b8aSChris Down 	enum printk_info_flags flags = 0;
21946b916706SJohn Ogness 	struct printk_record r;
2195002eb6adSJohn Ogness 	unsigned long irqflags;
21966b916706SJohn Ogness 	u16 trunc_msg_len = 0;
2197b031a684SJohn Ogness 	char prefix_buf[8];
2198002eb6adSJohn Ogness 	u8 *recursion_ptr;
2199b031a684SJohn Ogness 	u16 reserve_size;
2200b031a684SJohn Ogness 	va_list args2;
22019f0844deSJohn Ogness 	u32 caller_id;
22026b916706SJohn Ogness 	u16 text_len;
2203002eb6adSJohn Ogness 	int ret = 0;
22046b916706SJohn Ogness 	u64 ts_nsec;
2205608873caSJan Kara 
22069f0844deSJohn Ogness 	if (!printk_enter_irqsave(recursion_ptr, irqflags))
22079f0844deSJohn Ogness 		return 0;
22089f0844deSJohn Ogness 
2209b9ee979eSJoe Perches 	/*
22106b916706SJohn Ogness 	 * Since the duration of printk() can vary depending on the message
22116b916706SJohn Ogness 	 * and state of the ringbuffer, grab the timestamp now so that it is
22126b916706SJohn Ogness 	 * close to the call of printk(). This provides a more deterministic
22136b916706SJohn Ogness 	 * timestamp with respect to the caller.
2214b9ee979eSJoe Perches 	 */
22156b916706SJohn Ogness 	ts_nsec = local_clock();
2216b9ee979eSJoe Perches 
22179f0844deSJohn Ogness 	caller_id = printk_caller_id();
2218002eb6adSJohn Ogness 
2219b9ee979eSJoe Perches 	/*
2220b031a684SJohn Ogness 	 * The sprintf needs to come first since the syslog prefix might be
2221b031a684SJohn Ogness 	 * passed in as a parameter. An extra byte must be reserved so that
2222b031a684SJohn Ogness 	 * later the vscnprintf() into the reserved buffer has room for the
2223b031a684SJohn Ogness 	 * terminating '\0', which is not counted by vsnprintf().
2224b9ee979eSJoe Perches 	 */
2225b031a684SJohn Ogness 	va_copy(args2, args);
2226b031a684SJohn Ogness 	reserve_size = vsnprintf(&prefix_buf[0], sizeof(prefix_buf), fmt, args2) + 1;
2227b031a684SJohn Ogness 	va_end(args2);
2228b9ee979eSJoe Perches 
2229b0975c47SJohn Ogness 	if (reserve_size > PRINTKRB_RECORD_MAX)
2230b0975c47SJohn Ogness 		reserve_size = PRINTKRB_RECORD_MAX;
2231b9ee979eSJoe Perches 
2232b031a684SJohn Ogness 	/* Extract log level or control flags. */
2233b031a684SJohn Ogness 	if (facility == 0)
2234f3d75cf5SChris Down 		printk_parse_prefix(&prefix_buf[0], &level, &flags);
2235b9ee979eSJoe Perches 
2236a39d4a85SJoe Perches 	if (level == LOGLEVEL_DEFAULT)
2237b9ee979eSJoe Perches 		level = default_message_loglevel;
2238b9ee979eSJoe Perches 
223974caba7fSJohn Ogness 	if (dev_info)
2240a1ad4b8aSChris Down 		flags |= LOG_NEWLINE;
2241b9ee979eSJoe Perches 
2242a1ad4b8aSChris Down 	if (flags & LOG_CONT) {
2243b031a684SJohn Ogness 		prb_rec_init_wr(&r, reserve_size);
2244b0975c47SJohn Ogness 		if (prb_reserve_in_last(&e, prb, &r, caller_id, PRINTKRB_RECORD_MAX)) {
2245b031a684SJohn Ogness 			text_len = printk_sprint(&r.text_buf[r.info->text_len], reserve_size,
2246a1ad4b8aSChris Down 						 facility, &flags, fmt, args);
22476b916706SJohn Ogness 			r.info->text_len += text_len;
22486b916706SJohn Ogness 
2249a1ad4b8aSChris Down 			if (flags & LOG_NEWLINE) {
22506b916706SJohn Ogness 				r.info->flags |= LOG_NEWLINE;
22516b916706SJohn Ogness 				prb_final_commit(&e);
22526b916706SJohn Ogness 			} else {
22536b916706SJohn Ogness 				prb_commit(&e);
22546b916706SJohn Ogness 			}
22556b916706SJohn Ogness 
2256002eb6adSJohn Ogness 			ret = text_len;
2257002eb6adSJohn Ogness 			goto out;
22586b916706SJohn Ogness 		}
22596b916706SJohn Ogness 	}
22606b916706SJohn Ogness 
22616b916706SJohn Ogness 	/*
22626b916706SJohn Ogness 	 * Explicitly initialize the record before every prb_reserve() call.
22636b916706SJohn Ogness 	 * prb_reserve_in_last() and prb_reserve() purposely invalidate the
22646b916706SJohn Ogness 	 * structure when they fail.
22656b916706SJohn Ogness 	 */
2266b031a684SJohn Ogness 	prb_rec_init_wr(&r, reserve_size);
22676b916706SJohn Ogness 	if (!prb_reserve(&e, prb, &r)) {
22686b916706SJohn Ogness 		/* truncate the message if it is too long for empty buffer */
2269b031a684SJohn Ogness 		truncate_msg(&reserve_size, &trunc_msg_len);
22706b916706SJohn Ogness 
2271b031a684SJohn Ogness 		prb_rec_init_wr(&r, reserve_size + trunc_msg_len);
22726b916706SJohn Ogness 		if (!prb_reserve(&e, prb, &r))
2273002eb6adSJohn Ogness 			goto out;
22746b916706SJohn Ogness 	}
22756b916706SJohn Ogness 
22766b916706SJohn Ogness 	/* fill message */
2277a1ad4b8aSChris Down 	text_len = printk_sprint(&r.text_buf[0], reserve_size, facility, &flags, fmt, args);
22786b916706SJohn Ogness 	if (trunc_msg_len)
22796b916706SJohn Ogness 		memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
22806b916706SJohn Ogness 	r.info->text_len = text_len + trunc_msg_len;
22816b916706SJohn Ogness 	r.info->facility = facility;
22826b916706SJohn Ogness 	r.info->level = level & 7;
2283a1ad4b8aSChris Down 	r.info->flags = flags & 0x1f;
22846b916706SJohn Ogness 	r.info->ts_nsec = ts_nsec;
22856b916706SJohn Ogness 	r.info->caller_id = caller_id;
22866b916706SJohn Ogness 	if (dev_info)
22876b916706SJohn Ogness 		memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
22886b916706SJohn Ogness 
22896b916706SJohn Ogness 	/* A message without a trailing newline can be continued. */
2290a1ad4b8aSChris Down 	if (!(flags & LOG_NEWLINE))
22916b916706SJohn Ogness 		prb_commit(&e);
22926b916706SJohn Ogness 	else
22936b916706SJohn Ogness 		prb_final_commit(&e);
22946b916706SJohn Ogness 
2295002eb6adSJohn Ogness 	ret = text_len + trunc_msg_len;
2296002eb6adSJohn Ogness out:
2297002eb6adSJohn Ogness 	printk_exit_irqrestore(recursion_ptr, irqflags);
2298002eb6adSJohn Ogness 	return ret;
2299ba552399SPetr Mladek }
2300b9ee979eSJoe Perches 
vprintk_emit(int facility,int level,const struct dev_printk_info * dev_info,const char * fmt,va_list args)2301ba552399SPetr Mladek asmlinkage int vprintk_emit(int facility, int level,
230274caba7fSJohn Ogness 			    const struct dev_printk_info *dev_info,
2303ba552399SPetr Mladek 			    const char *fmt, va_list args)
2304ba552399SPetr Mladek {
2305ba552399SPetr Mladek 	int printed_len;
23068749efc0SJohn Ogness 	bool in_sched = false;
2307ba552399SPetr Mladek 
2308c39ea0b9SFeng Tang 	/* Suppress unimportant messages after panic happens */
2309c39ea0b9SFeng Tang 	if (unlikely(suppress_printk))
2310c39ea0b9SFeng Tang 		return 0;
2311c39ea0b9SFeng Tang 
2312a2e14cc2SJohn Ogness 	if (unlikely(suppress_panic_printk) && other_cpu_in_panic())
231313fb0f74SStephen Brennan 		return 0;
231413fb0f74SStephen Brennan 
2315ba552399SPetr Mladek 	if (level == LOGLEVEL_SCHED) {
2316ba552399SPetr Mladek 		level = LOGLEVEL_DEFAULT;
2317ba552399SPetr Mladek 		in_sched = true;
2318ba552399SPetr Mladek 	}
2319ba552399SPetr Mladek 
23201f47e8afSJohn Ogness 	printk_delay(level);
2321ba552399SPetr Mladek 
232274caba7fSJohn Ogness 	printed_len = vprintk_store(facility, level, dev_info, fmt, args);
2323939f04beSJan Kara 
2324458df9fdSSteven Rostedt 	/* If called from the scheduler, we can not call up(). */
23255831788aSPetr Mladek 	if (!in_sched) {
23265874af20SJan Kara 		/*
2327a699449bSJohn Ogness 		 * The caller may be holding system-critical or
23285831788aSPetr Mladek 		 * timing-sensitive locks. Disable preemption during
2329a699449bSJohn Ogness 		 * printing of all remaining records to all consoles so that
2330a699449bSJohn Ogness 		 * this context can return as soon as possible. Hopefully
2331a699449bSJohn Ogness 		 * another printk() caller will take over the printing.
2332fd5f7cdeSSergey Senozhatsky 		 */
2333fd5f7cdeSSergey Senozhatsky 		preempt_disable();
2334fd5f7cdeSSergey Senozhatsky 		/*
2335d18bbc21SAndrew Morton 		 * Try to acquire and then immediately release the console
2336a699449bSJohn Ogness 		 * semaphore. The release will print out buffers. With the
2337a699449bSJohn Ogness 		 * spinning variant, this context tries to take over the
2338a699449bSJohn Ogness 		 * printing from another printing context.
2339939f04beSJan Kara 		 */
2340c162d5b4SPetr Mladek 		if (console_trylock_spinning())
2341b9ee979eSJoe Perches 			console_unlock();
2342fd5f7cdeSSergey Senozhatsky 		preempt_enable();
2343d18bbc21SAndrew Morton 	}
2344b9ee979eSJoe Perches 
2345696ffaf5SJohn Ogness 	if (in_sched)
2346696ffaf5SJohn Ogness 		defer_console_output();
2347696ffaf5SJohn Ogness 	else
234843a17111SSergey Senozhatsky 		wake_up_klogd();
2349696ffaf5SJohn Ogness 
2350b9ee979eSJoe Perches 	return printed_len;
2351b9ee979eSJoe Perches }
2352b9ee979eSJoe Perches EXPORT_SYMBOL(vprintk_emit);
2353b9ee979eSJoe Perches 
vprintk_default(const char * fmt,va_list args)2354a0cba217SLinus Torvalds int vprintk_default(const char *fmt, va_list args)
2355afdc34a3SSteven Rostedt (Red Hat) {
235674caba7fSJohn Ogness 	return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
2357afdc34a3SSteven Rostedt (Red Hat) }
2358afdc34a3SSteven Rostedt (Red Hat) EXPORT_SYMBOL_GPL(vprintk_default);
2359afdc34a3SSteven Rostedt (Red Hat) 
_printk(const char * fmt,...)236033701557SChris Down asmlinkage __visible int _printk(const char *fmt, ...)
2361b9ee979eSJoe Perches {
2362b9ee979eSJoe Perches 	va_list args;
2363b9ee979eSJoe Perches 	int r;
2364b9ee979eSJoe Perches 
2365b9ee979eSJoe Perches 	va_start(args, fmt);
236628e1745bSRasmus Villemoes 	r = vprintk(fmt, args);
2367b9ee979eSJoe Perches 	va_end(args);
2368b9ee979eSJoe Perches 
2369b9ee979eSJoe Perches 	return r;
2370b9ee979eSJoe Perches }
237133701557SChris Down EXPORT_SYMBOL(_printk);
2372b9ee979eSJoe Perches 
2373c60ba2d3SThomas Gleixner static bool pr_flush(int timeout_ms, bool reset_on_progress);
23743b604ca8SJohn Ogness static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress);
23753b604ca8SJohn Ogness 
2376b9ee979eSJoe Perches #else /* CONFIG_PRINTK */
2377b9ee979eSJoe Perches 
2378e80c1a9dSTetsuo Handa #define printk_time		false
2379249771b8SAlex Elder 
2380896fbe20SJohn Ogness #define prb_read_valid(rb, seq, r)	false
2381896fbe20SJohn Ogness #define prb_first_valid_seq(rb)		0
2382a699449bSJohn Ogness #define prb_next_seq(rb)		0
2383896fbe20SJohn Ogness 
2384b9ee979eSJoe Perches static u64 syslog_seq;
2385896fbe20SJohn Ogness 
record_print_text(const struct printk_record * r,bool syslog,bool time)2386896fbe20SJohn Ogness static size_t record_print_text(const struct printk_record *r,
2387896fbe20SJohn Ogness 				bool syslog, bool time)
2388896fbe20SJohn Ogness {
2389896fbe20SJohn Ogness 	return 0;
2390896fbe20SJohn Ogness }
info_print_ext_header(char * buf,size_t size,struct printk_info * info)2391896fbe20SJohn Ogness static ssize_t info_print_ext_header(char *buf, size_t size,
2392896fbe20SJohn Ogness 				     struct printk_info *info)
2393896fbe20SJohn Ogness {
2394896fbe20SJohn Ogness 	return 0;
2395896fbe20SJohn Ogness }
msg_print_ext_body(char * buf,size_t size,char * text,size_t text_len,struct dev_printk_info * dev_info)23966fe29354STejun Heo static ssize_t msg_print_ext_body(char *buf, size_t size,
239774caba7fSJohn Ogness 				  char *text, size_t text_len,
239874caba7fSJohn Ogness 				  struct dev_printk_info *dev_info) { return 0; }
console_lock_spinning_enable(void)2399c162d5b4SPetr Mladek static void console_lock_spinning_enable(void) { }
console_lock_spinning_disable_and_check(int cookie)2400fc956ae0SJohn Ogness static int console_lock_spinning_disable_and_check(int cookie) { return 0; }
suppress_message_printing(int level)2401a6ae928cSPetr Mladek static bool suppress_message_printing(int level) { return false; }
pr_flush(int timeout_ms,bool reset_on_progress)2402c60ba2d3SThomas Gleixner static bool pr_flush(int timeout_ms, bool reset_on_progress) { return true; }
__pr_flush(struct console * con,int timeout_ms,bool reset_on_progress)24033b604ca8SJohn Ogness static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress) { return true; }
2404b9ee979eSJoe Perches 
2405b9ee979eSJoe Perches #endif /* CONFIG_PRINTK */
2406b9ee979eSJoe Perches 
2407b9ee979eSJoe Perches #ifdef CONFIG_EARLY_PRINTK
2408b9ee979eSJoe Perches struct console *early_console;
2409b9ee979eSJoe Perches 
early_printk(const char * fmt,...)2410722a9f92SAndi Kleen asmlinkage __visible void early_printk(const char *fmt, ...)
2411b9ee979eSJoe Perches {
2412b9ee979eSJoe Perches 	va_list ap;
24131dc6244bSJoe Perches 	char buf[512];
24141dc6244bSJoe Perches 	int n;
24151dc6244bSJoe Perches 
24161dc6244bSJoe Perches 	if (!early_console)
24171dc6244bSJoe Perches 		return;
2418b9ee979eSJoe Perches 
2419b9ee979eSJoe Perches 	va_start(ap, fmt);
24201dc6244bSJoe Perches 	n = vscnprintf(buf, sizeof(buf), fmt, ap);
2421b9ee979eSJoe Perches 	va_end(ap);
24221dc6244bSJoe Perches 
24231dc6244bSJoe Perches 	early_console->write(early_console, buf, n);
2424b9ee979eSJoe Perches }
2425b9ee979eSJoe Perches #endif
2426b9ee979eSJoe Perches 
set_user_specified(struct console_cmdline * c,bool user_specified)2427a5a763b2SAndre Kalb static void set_user_specified(struct console_cmdline *c, bool user_specified)
2428a5a763b2SAndre Kalb {
2429a5a763b2SAndre Kalb 	if (!user_specified)
2430a5a763b2SAndre Kalb 		return;
2431a5a763b2SAndre Kalb 
2432a5a763b2SAndre Kalb 	/*
2433a5a763b2SAndre Kalb 	 * @c console was defined by the user on the command line.
2434a5a763b2SAndre Kalb 	 * Do not clear when added twice also by SPCR or the device tree.
2435a5a763b2SAndre Kalb 	 */
2436a5a763b2SAndre Kalb 	c->user_specified = true;
2437a5a763b2SAndre Kalb 	/* At least one console defined by the user on the command line. */
2438a5a763b2SAndre Kalb 	console_set_on_cmdline = 1;
2439a5a763b2SAndre Kalb }
2440a5a763b2SAndre Kalb 
__add_preferred_console(char * name,int idx,char * options,char * brl_options,bool user_specified)2441b9ee979eSJoe Perches static int __add_preferred_console(char *name, int idx, char *options,
2442e369d822SBenjamin Herrenschmidt 				   char *brl_options, bool user_specified)
2443b9ee979eSJoe Perches {
2444b9ee979eSJoe Perches 	struct console_cmdline *c;
2445b9ee979eSJoe Perches 	int i;
2446b9ee979eSJoe Perches 
2447b9ee979eSJoe Perches 	/*
2448b9ee979eSJoe Perches 	 *	See if this tty is not yet registered, and
2449b9ee979eSJoe Perches 	 *	if we have a slot free.
2450b9ee979eSJoe Perches 	 */
2451dac8bbbaSPetr Mladek 	for (i = 0, c = console_cmdline;
2452dac8bbbaSPetr Mladek 	     i < MAX_CMDLINECONSOLES && c->name[0];
2453dac8bbbaSPetr Mladek 	     i++, c++) {
245423475408SJoe Perches 		if (strcmp(c->name, name) == 0 && c->index == idx) {
2455dac8bbbaSPetr Mladek 			if (!brl_options)
2456dac8bbbaSPetr Mladek 				preferred_console = i;
2457a5a763b2SAndre Kalb 			set_user_specified(c, user_specified);
2458b9ee979eSJoe Perches 			return 0;
2459b9ee979eSJoe Perches 		}
246023475408SJoe Perches 	}
2461b9ee979eSJoe Perches 	if (i == MAX_CMDLINECONSOLES)
2462b9ee979eSJoe Perches 		return -E2BIG;
2463b9ee979eSJoe Perches 	if (!brl_options)
2464ad86ee2bSAleksey Makarov 		preferred_console = i;
24657365df19SXu Panda 	strscpy(c->name, name, sizeof(c->name));
2466b9ee979eSJoe Perches 	c->options = options;
2467a5a763b2SAndre Kalb 	set_user_specified(c, user_specified);
2468bbeddf52SJoe Perches 	braille_set_options(c, brl_options);
2469bbeddf52SJoe Perches 
2470b9ee979eSJoe Perches 	c->index = idx;
2471b9ee979eSJoe Perches 	return 0;
2472b9ee979eSJoe Perches }
2473cca10d58SSergey Senozhatsky 
console_msg_format_setup(char * str)2474cca10d58SSergey Senozhatsky static int __init console_msg_format_setup(char *str)
2475cca10d58SSergey Senozhatsky {
2476cca10d58SSergey Senozhatsky 	if (!strcmp(str, "syslog"))
2477cca10d58SSergey Senozhatsky 		console_msg_format = MSG_FORMAT_SYSLOG;
2478cca10d58SSergey Senozhatsky 	if (!strcmp(str, "default"))
2479cca10d58SSergey Senozhatsky 		console_msg_format = MSG_FORMAT_DEFAULT;
2480cca10d58SSergey Senozhatsky 	return 1;
2481cca10d58SSergey Senozhatsky }
2482cca10d58SSergey Senozhatsky __setup("console_msg_format=", console_msg_format_setup);
2483cca10d58SSergey Senozhatsky 
2484b9ee979eSJoe Perches /*
24850b90fec3SAlex Elder  * Set up a console.  Called via do_early_param() in init/main.c
24860b90fec3SAlex Elder  * for each "console=" parameter in the boot command line.
2487b9ee979eSJoe Perches  */
console_setup(char * str)2488b9ee979eSJoe Perches static int __init console_setup(char *str)
2489b9ee979eSJoe Perches {
24900b90fec3SAlex Elder 	char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2491b9ee979eSJoe Perches 	char *s, *options, *brl_options = NULL;
2492b9ee979eSJoe Perches 	int idx;
2493b9ee979eSJoe Perches 
24943cffa06aSPetr Mladek 	/*
24953cffa06aSPetr Mladek 	 * console="" or console=null have been suggested as a way to
24963cffa06aSPetr Mladek 	 * disable console output. Use ttynull that has been created
2497acebb559SBhaskar Chowdhury 	 * for exactly this purpose.
24983cffa06aSPetr Mladek 	 */
24993cffa06aSPetr Mladek 	if (str[0] == 0 || strcmp(str, "null") == 0) {
25003cffa06aSPetr Mladek 		__add_preferred_console("ttynull", 0, NULL, NULL, true);
250148021f98SShreyas Joshi 		return 1;
25023cffa06aSPetr Mladek 	}
250348021f98SShreyas Joshi 
2504bbeddf52SJoe Perches 	if (_braille_console_setup(&str, &brl_options))
2505b9ee979eSJoe Perches 		return 1;
2506b9ee979eSJoe Perches 
2507b9ee979eSJoe Perches 	/*
2508b9ee979eSJoe Perches 	 * Decode str into name, index, options.
2509b9ee979eSJoe Perches 	 */
2510b9ee979eSJoe Perches 	if (str[0] >= '0' && str[0] <= '9') {
2511b9ee979eSJoe Perches 		strcpy(buf, "ttyS");
2512b9ee979eSJoe Perches 		strncpy(buf + 4, str, sizeof(buf) - 5);
2513b9ee979eSJoe Perches 	} else {
2514b9ee979eSJoe Perches 		strncpy(buf, str, sizeof(buf) - 1);
2515b9ee979eSJoe Perches 	}
2516b9ee979eSJoe Perches 	buf[sizeof(buf) - 1] = 0;
2517249771b8SAlex Elder 	options = strchr(str, ',');
2518249771b8SAlex Elder 	if (options)
2519b9ee979eSJoe Perches 		*(options++) = 0;
2520b9ee979eSJoe Perches #ifdef __sparc__
2521b9ee979eSJoe Perches 	if (!strcmp(str, "ttya"))
2522b9ee979eSJoe Perches 		strcpy(buf, "ttyS0");
2523b9ee979eSJoe Perches 	if (!strcmp(str, "ttyb"))
2524b9ee979eSJoe Perches 		strcpy(buf, "ttyS1");
2525b9ee979eSJoe Perches #endif
2526b9ee979eSJoe Perches 	for (s = buf; *s; s++)
2527249771b8SAlex Elder 		if (isdigit(*s) || *s == ',')
2528b9ee979eSJoe Perches 			break;
2529b9ee979eSJoe Perches 	idx = simple_strtoul(s, NULL, 10);
2530b9ee979eSJoe Perches 	*s = 0;
2531b9ee979eSJoe Perches 
2532e369d822SBenjamin Herrenschmidt 	__add_preferred_console(buf, idx, options, brl_options, true);
2533b9ee979eSJoe Perches 	return 1;
2534b9ee979eSJoe Perches }
2535b9ee979eSJoe Perches __setup("console=", console_setup);
2536b9ee979eSJoe Perches 
2537b9ee979eSJoe Perches /**
2538b9ee979eSJoe Perches  * add_preferred_console - add a device to the list of preferred consoles.
2539b9ee979eSJoe Perches  * @name: device name
2540b9ee979eSJoe Perches  * @idx: device index
2541b9ee979eSJoe Perches  * @options: options for this console
2542b9ee979eSJoe Perches  *
2543b9ee979eSJoe Perches  * The last preferred console added will be used for kernel messages
2544b9ee979eSJoe Perches  * and stdin/out/err for init.  Normally this is used by console_setup
2545b9ee979eSJoe Perches  * above to handle user-supplied console arguments; however it can also
2546b9ee979eSJoe Perches  * be used by arch-specific code either to override the user or more
2547b9ee979eSJoe Perches  * commonly to provide a default console (ie from PROM variables) when
2548b9ee979eSJoe Perches  * the user has not supplied one.
2549b9ee979eSJoe Perches  */
add_preferred_console(char * name,int idx,char * options)2550b9ee979eSJoe Perches int add_preferred_console(char *name, int idx, char *options)
2551b9ee979eSJoe Perches {
2552e369d822SBenjamin Herrenschmidt 	return __add_preferred_console(name, idx, options, NULL, false);
2553b9ee979eSJoe Perches }
2554b9ee979eSJoe Perches 
2555d25d9fecSNeil Zhang bool console_suspend_enabled = true;
2556b9ee979eSJoe Perches EXPORT_SYMBOL(console_suspend_enabled);
2557b9ee979eSJoe Perches 
console_suspend_disable(char * str)2558b9ee979eSJoe Perches static int __init console_suspend_disable(char *str)
2559b9ee979eSJoe Perches {
2560d25d9fecSNeil Zhang 	console_suspend_enabled = false;
2561b9ee979eSJoe Perches 	return 1;
2562b9ee979eSJoe Perches }
2563b9ee979eSJoe Perches __setup("no_console_suspend", console_suspend_disable);
2564b9ee979eSJoe Perches module_param_named(console_suspend, console_suspend_enabled,
2565b9ee979eSJoe Perches 		bool, S_IRUGO | S_IWUSR);
2566b9ee979eSJoe Perches MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2567b9ee979eSJoe Perches 	" and hibernate operations");
2568b9ee979eSJoe Perches 
256910102a89SDmitry Safonov static bool printk_console_no_auto_verbose;
257010102a89SDmitry Safonov 
console_verbose(void)257110102a89SDmitry Safonov void console_verbose(void)
257210102a89SDmitry Safonov {
257310102a89SDmitry Safonov 	if (console_loglevel && !printk_console_no_auto_verbose)
257410102a89SDmitry Safonov 		console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
257510102a89SDmitry Safonov }
257610102a89SDmitry Safonov EXPORT_SYMBOL_GPL(console_verbose);
257710102a89SDmitry Safonov 
257810102a89SDmitry Safonov module_param_named(console_no_auto_verbose, printk_console_no_auto_verbose, bool, 0644);
257910102a89SDmitry Safonov MODULE_PARM_DESC(console_no_auto_verbose, "Disable console loglevel raise to highest on oops/panic/etc");
258010102a89SDmitry Safonov 
2581b9ee979eSJoe Perches /**
2582b9ee979eSJoe Perches  * suspend_console - suspend the console subsystem
2583b9ee979eSJoe Perches  *
2584b9ee979eSJoe Perches  * This disables printk() while we go into suspend states
2585b9ee979eSJoe Perches  */
suspend_console(void)2586b9ee979eSJoe Perches void suspend_console(void)
2587b9ee979eSJoe Perches {
25889e70a5e1SJohn Ogness 	struct console *con;
25899e70a5e1SJohn Ogness 
2590b9ee979eSJoe Perches 	if (!console_suspend_enabled)
2591b9ee979eSJoe Perches 		return;
259247319f71STomeu Vizoso 	pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
25933b604ca8SJohn Ogness 	pr_flush(1000, true);
25949e70a5e1SJohn Ogness 
25959e70a5e1SJohn Ogness 	console_list_lock();
25969e70a5e1SJohn Ogness 	for_each_console(con)
25979e70a5e1SJohn Ogness 		console_srcu_write_flags(con, con->flags | CON_SUSPENDED);
25989e70a5e1SJohn Ogness 	console_list_unlock();
25999e70a5e1SJohn Ogness 
26009e70a5e1SJohn Ogness 	/*
26019e70a5e1SJohn Ogness 	 * Ensure that all SRCU list walks have completed. All printing
26029e70a5e1SJohn Ogness 	 * contexts must be able to see that they are suspended so that it
26039e70a5e1SJohn Ogness 	 * is guaranteed that all printing has stopped when this function
26049e70a5e1SJohn Ogness 	 * completes.
26059e70a5e1SJohn Ogness 	 */
26069e70a5e1SJohn Ogness 	synchronize_srcu(&console_srcu);
2607b9ee979eSJoe Perches }
2608b9ee979eSJoe Perches 
resume_console(void)2609b9ee979eSJoe Perches void resume_console(void)
2610b9ee979eSJoe Perches {
26119e70a5e1SJohn Ogness 	struct console *con;
26129e70a5e1SJohn Ogness 
2613b9ee979eSJoe Perches 	if (!console_suspend_enabled)
2614b9ee979eSJoe Perches 		return;
26159e70a5e1SJohn Ogness 
26169e70a5e1SJohn Ogness 	console_list_lock();
26179e70a5e1SJohn Ogness 	for_each_console(con)
26189e70a5e1SJohn Ogness 		console_srcu_write_flags(con, con->flags & ~CON_SUSPENDED);
26199e70a5e1SJohn Ogness 	console_list_unlock();
26209e70a5e1SJohn Ogness 
26219e70a5e1SJohn Ogness 	/*
26229e70a5e1SJohn Ogness 	 * Ensure that all SRCU list walks have completed. All printing
26239e70a5e1SJohn Ogness 	 * contexts must be able to see they are no longer suspended so
26249e70a5e1SJohn Ogness 	 * that they are guaranteed to wake up and resume printing.
26259e70a5e1SJohn Ogness 	 */
26269e70a5e1SJohn Ogness 	synchronize_srcu(&console_srcu);
26279e70a5e1SJohn Ogness 
26283b604ca8SJohn Ogness 	pr_flush(1000, true);
2629b9ee979eSJoe Perches }
2630b9ee979eSJoe Perches 
2631b9ee979eSJoe Perches /**
2632b9ee979eSJoe Perches  * console_cpu_notify - print deferred console messages after CPU hotplug
263390b14889SSebastian Andrzej Siewior  * @cpu: unused
2634b9ee979eSJoe Perches  *
2635b9ee979eSJoe Perches  * If printk() is called from a CPU that is not online yet, the messages
263664ca752dSSergey Senozhatsky  * will be printed on the console only if there are CON_ANYTIME consoles.
263764ca752dSSergey Senozhatsky  * This function is called when a new CPU comes online (or fails to come
263864ca752dSSergey Senozhatsky  * up) or goes offline.
2639b9ee979eSJoe Perches  */
console_cpu_notify(unsigned int cpu)264090b14889SSebastian Andrzej Siewior static int console_cpu_notify(unsigned int cpu)
2641b9ee979eSJoe Perches {
2642f97960fbSThomas Gleixner 	if (!cpuhp_tasks_frozen) {
264364ca752dSSergey Senozhatsky 		/* If trylock fails, someone else is doing the printing */
264464ca752dSSergey Senozhatsky 		if (console_trylock())
2645b9ee979eSJoe Perches 			console_unlock();
2646b9ee979eSJoe Perches 	}
264790b14889SSebastian Andrzej Siewior 	return 0;
2648b9ee979eSJoe Perches }
2649b9ee979eSJoe Perches 
265051a1d258SJohn Ogness /*
2651132a90d1SJohn Ogness  * Return true if a panic is in progress on a remote CPU.
2652132a90d1SJohn Ogness  *
2653132a90d1SJohn Ogness  * On true, the local CPU should immediately release any printing resources
2654132a90d1SJohn Ogness  * that may be needed by the panic CPU.
265551a1d258SJohn Ogness  */
other_cpu_in_panic(void)2656132a90d1SJohn Ogness bool other_cpu_in_panic(void)
265751a1d258SJohn Ogness {
265851a1d258SJohn Ogness 	if (!panic_in_progress())
265951a1d258SJohn Ogness 		return false;
266051a1d258SJohn Ogness 
266151a1d258SJohn Ogness 	/*
266251a1d258SJohn Ogness 	 * We can use raw_smp_processor_id() here because it is impossible for
266351a1d258SJohn Ogness 	 * the task to be migrated to the panic_cpu, or away from it. If
266451a1d258SJohn Ogness 	 * panic_cpu has already been set, and we're not currently executing on
266551a1d258SJohn Ogness 	 * that CPU, then we never will be.
266651a1d258SJohn Ogness 	 */
266751a1d258SJohn Ogness 	return atomic_read(&panic_cpu) != raw_smp_processor_id();
266851a1d258SJohn Ogness }
266951a1d258SJohn Ogness 
2670b9ee979eSJoe Perches /**
2671848a9c10SJohn Ogness  * console_lock - block the console subsystem from printing
2672b9ee979eSJoe Perches  *
2673848a9c10SJohn Ogness  * Acquires a lock which guarantees that no consoles will
2674848a9c10SJohn Ogness  * be in or enter their write() callback.
2675b9ee979eSJoe Perches  *
2676b9ee979eSJoe Perches  * Can sleep, returns nothing.
2677b9ee979eSJoe Perches  */
console_lock(void)2678b9ee979eSJoe Perches void console_lock(void)
2679b9ee979eSJoe Perches {
2680b9ee979eSJoe Perches 	might_sleep();
2681b9ee979eSJoe Perches 
268251a1d258SJohn Ogness 	/* On panic, the console_lock must be left to the panic cpu. */
2683132a90d1SJohn Ogness 	while (other_cpu_in_panic())
268451a1d258SJohn Ogness 		msleep(1000);
268551a1d258SJohn Ogness 
2686bd8d7cf5SJan Kara 	down_console_sem();
2687007eeab7SPetr Mladek 	console_locked = 1;
2688b9ee979eSJoe Perches 	console_may_schedule = 1;
2689b9ee979eSJoe Perches }
2690b9ee979eSJoe Perches EXPORT_SYMBOL(console_lock);
2691b9ee979eSJoe Perches 
2692b9ee979eSJoe Perches /**
2693848a9c10SJohn Ogness  * console_trylock - try to block the console subsystem from printing
2694b9ee979eSJoe Perches  *
2695848a9c10SJohn Ogness  * Try to acquire a lock which guarantees that no consoles will
2696848a9c10SJohn Ogness  * be in or enter their write() callback.
2697b9ee979eSJoe Perches  *
2698b9ee979eSJoe Perches  * returns 1 on success, and 0 on failure to acquire the lock.
2699b9ee979eSJoe Perches  */
console_trylock(void)2700b9ee979eSJoe Perches int console_trylock(void)
2701b9ee979eSJoe Perches {
270251a1d258SJohn Ogness 	/* On panic, the console_lock must be left to the panic cpu. */
2703132a90d1SJohn Ogness 	if (other_cpu_in_panic())
270451a1d258SJohn Ogness 		return 0;
2705bd8d7cf5SJan Kara 	if (down_trylock_console_sem())
2706b9ee979eSJoe Perches 		return 0;
2707007eeab7SPetr Mladek 	console_locked = 1;
2708fd5f7cdeSSergey Senozhatsky 	console_may_schedule = 0;
2709b9ee979eSJoe Perches 	return 1;
2710b9ee979eSJoe Perches }
2711b9ee979eSJoe Perches EXPORT_SYMBOL(console_trylock);
2712b9ee979eSJoe Perches 
is_console_locked(void)2713b9ee979eSJoe Perches int is_console_locked(void)
2714b9ee979eSJoe Perches {
27152d9ef940SPetr Mladek 	return console_locked;
2716b9ee979eSJoe Perches }
2717d48de54aSHans de Goede EXPORT_SYMBOL(is_console_locked);
2718b9ee979eSJoe Perches 
2719a8199371SSergey Senozhatsky /*
272009c5ba0aSJohn Ogness  * Check if the given console is currently capable and allowed to print
272109c5ba0aSJohn Ogness  * records.
272209c5ba0aSJohn Ogness  *
272312f1da5fSJohn Ogness  * Requires the console_srcu_read_lock.
272409c5ba0aSJohn Ogness  */
console_is_usable(struct console * con)272509c5ba0aSJohn Ogness static inline bool console_is_usable(struct console *con)
272609c5ba0aSJohn Ogness {
272712f1da5fSJohn Ogness 	short flags = console_srcu_read_flags(con);
272812f1da5fSJohn Ogness 
272912f1da5fSJohn Ogness 	if (!(flags & CON_ENABLED))
27305831788aSPetr Mladek 		return false;
27315831788aSPetr Mladek 
27329e70a5e1SJohn Ogness 	if ((flags & CON_SUSPENDED))
27339e70a5e1SJohn Ogness 		return false;
27349e70a5e1SJohn Ogness 
273509c5ba0aSJohn Ogness 	if (!con->write)
273609c5ba0aSJohn Ogness 		return false;
273709c5ba0aSJohn Ogness 
27385831788aSPetr Mladek 	/*
27395831788aSPetr Mladek 	 * Console drivers may assume that per-cpu resources have been
27405831788aSPetr Mladek 	 * allocated. So unless they're explicitly marked as being able to
27415831788aSPetr Mladek 	 * cope (CON_ANYTIME) don't call them until this CPU is officially up.
27425831788aSPetr Mladek 	 */
274312f1da5fSJohn Ogness 	if (!cpu_online(raw_smp_processor_id()) && !(flags & CON_ANYTIME))
27445831788aSPetr Mladek 		return false;
27455831788aSPetr Mladek 
27465831788aSPetr Mladek 	return true;
274709c5ba0aSJohn Ogness }
274809c5ba0aSJohn Ogness 
__console_unlock(void)2749a699449bSJohn Ogness static void __console_unlock(void)
2750a699449bSJohn Ogness {
2751007eeab7SPetr Mladek 	console_locked = 0;
2752a699449bSJohn Ogness 	up_console_sem();
2753a699449bSJohn Ogness }
2754a699449bSJohn Ogness 
2755a699449bSJohn Ogness /*
2756c4fcc617SJohn Ogness  * Prepend the message in @pmsg->pbufs->outbuf with a "dropped message". This
2757c4fcc617SJohn Ogness  * is achieved by shifting the existing message over and inserting the dropped
2758c4fcc617SJohn Ogness  * message.
2759c4fcc617SJohn Ogness  *
2760c4fcc617SJohn Ogness  * @pmsg is the printk message to prepend.
2761c4fcc617SJohn Ogness  *
2762c4fcc617SJohn Ogness  * @dropped is the dropped count to report in the dropped message.
2763c4fcc617SJohn Ogness  *
2764c4fcc617SJohn Ogness  * If the message text in @pmsg->pbufs->outbuf does not have enough space for
2765c4fcc617SJohn Ogness  * the dropped message, the message text will be sufficiently truncated.
2766c4fcc617SJohn Ogness  *
2767c4fcc617SJohn Ogness  * If @pmsg->pbufs->outbuf is modified, @pmsg->outbuf_len is updated.
2768c4fcc617SJohn Ogness  */
2769c4fcc617SJohn Ogness #ifdef CONFIG_PRINTK
console_prepend_dropped(struct printk_message * pmsg,unsigned long dropped)2770c4fcc617SJohn Ogness static void console_prepend_dropped(struct printk_message *pmsg, unsigned long dropped)
2771c4fcc617SJohn Ogness {
2772c4fcc617SJohn Ogness 	struct printk_buffers *pbufs = pmsg->pbufs;
2773c4fcc617SJohn Ogness 	const size_t scratchbuf_sz = sizeof(pbufs->scratchbuf);
2774c4fcc617SJohn Ogness 	const size_t outbuf_sz = sizeof(pbufs->outbuf);
2775c4fcc617SJohn Ogness 	char *scratchbuf = &pbufs->scratchbuf[0];
2776c4fcc617SJohn Ogness 	char *outbuf = &pbufs->outbuf[0];
2777c4fcc617SJohn Ogness 	size_t len;
2778c4fcc617SJohn Ogness 
2779d551afc2SPetr Mladek 	len = scnprintf(scratchbuf, scratchbuf_sz,
2780c4fcc617SJohn Ogness 		       "** %lu printk messages dropped **\n", dropped);
2781c4fcc617SJohn Ogness 
2782c4fcc617SJohn Ogness 	/*
2783c4fcc617SJohn Ogness 	 * Make sure outbuf is sufficiently large before prepending.
2784c4fcc617SJohn Ogness 	 * Keep at least the prefix when the message must be truncated.
2785c4fcc617SJohn Ogness 	 * It is a rather theoretical problem when someone tries to
2786c4fcc617SJohn Ogness 	 * use a minimalist buffer.
2787c4fcc617SJohn Ogness 	 */
2788b0975c47SJohn Ogness 	if (WARN_ON_ONCE(len + PRINTK_PREFIX_MAX >= outbuf_sz))
2789c4fcc617SJohn Ogness 		return;
2790c4fcc617SJohn Ogness 
2791c4fcc617SJohn Ogness 	if (pmsg->outbuf_len + len >= outbuf_sz) {
2792c4fcc617SJohn Ogness 		/* Truncate the message, but keep it terminated. */
2793c4fcc617SJohn Ogness 		pmsg->outbuf_len = outbuf_sz - (len + 1);
2794c4fcc617SJohn Ogness 		outbuf[pmsg->outbuf_len] = 0;
2795c4fcc617SJohn Ogness 	}
2796c4fcc617SJohn Ogness 
2797c4fcc617SJohn Ogness 	memmove(outbuf + len, outbuf, pmsg->outbuf_len + 1);
2798c4fcc617SJohn Ogness 	memcpy(outbuf, scratchbuf, len);
2799c4fcc617SJohn Ogness 	pmsg->outbuf_len += len;
2800c4fcc617SJohn Ogness }
2801c4fcc617SJohn Ogness #else
2802c4fcc617SJohn Ogness #define console_prepend_dropped(pmsg, dropped)
2803c4fcc617SJohn Ogness #endif /* CONFIG_PRINTK */
2804c4fcc617SJohn Ogness 
2805c4fcc617SJohn Ogness /*
28062830eec1SJohn Ogness  * Read and format the specified record (or a later record if the specified
28072830eec1SJohn Ogness  * record is not available).
28082830eec1SJohn Ogness  *
28092830eec1SJohn Ogness  * @pmsg will contain the formatted result. @pmsg->pbufs must point to a
28102830eec1SJohn Ogness  * struct printk_buffers.
28112830eec1SJohn Ogness  *
28122830eec1SJohn Ogness  * @seq is the record to read and format. If it is not available, the next
28132830eec1SJohn Ogness  * valid record is read.
28142830eec1SJohn Ogness  *
28152830eec1SJohn Ogness  * @is_extended specifies if the message should be formatted for extended
28162830eec1SJohn Ogness  * console output.
28172830eec1SJohn Ogness  *
2818ea308da1SJohn Ogness  * @may_supress specifies if records may be skipped based on loglevel.
2819ea308da1SJohn Ogness  *
28202830eec1SJohn Ogness  * Returns false if no record is available. Otherwise true and all fields
28212830eec1SJohn Ogness  * of @pmsg are valid. (See the documentation of struct printk_message
28222830eec1SJohn Ogness  * for information about the @pmsg fields.)
28232830eec1SJohn Ogness  */
printk_get_next_message(struct printk_message * pmsg,u64 seq,bool is_extended,bool may_suppress)28242830eec1SJohn Ogness static bool printk_get_next_message(struct printk_message *pmsg, u64 seq,
2825ea308da1SJohn Ogness 				    bool is_extended, bool may_suppress)
28262830eec1SJohn Ogness {
28272830eec1SJohn Ogness 	static int panic_console_dropped;
28282830eec1SJohn Ogness 
28292830eec1SJohn Ogness 	struct printk_buffers *pbufs = pmsg->pbufs;
28302830eec1SJohn Ogness 	const size_t scratchbuf_sz = sizeof(pbufs->scratchbuf);
28312830eec1SJohn Ogness 	const size_t outbuf_sz = sizeof(pbufs->outbuf);
28322830eec1SJohn Ogness 	char *scratchbuf = &pbufs->scratchbuf[0];
28332830eec1SJohn Ogness 	char *outbuf = &pbufs->outbuf[0];
28342830eec1SJohn Ogness 	struct printk_info info;
28352830eec1SJohn Ogness 	struct printk_record r;
28362830eec1SJohn Ogness 	size_t len = 0;
28372830eec1SJohn Ogness 
28382830eec1SJohn Ogness 	/*
28392830eec1SJohn Ogness 	 * Formatting extended messages requires a separate buffer, so use the
28402830eec1SJohn Ogness 	 * scratch buffer to read in the ringbuffer text.
28412830eec1SJohn Ogness 	 *
28422830eec1SJohn Ogness 	 * Formatting normal messages is done in-place, so read the ringbuffer
28432830eec1SJohn Ogness 	 * text directly into the output buffer.
28442830eec1SJohn Ogness 	 */
28452830eec1SJohn Ogness 	if (is_extended)
28462830eec1SJohn Ogness 		prb_rec_init_rd(&r, &info, scratchbuf, scratchbuf_sz);
28472830eec1SJohn Ogness 	else
28482830eec1SJohn Ogness 		prb_rec_init_rd(&r, &info, outbuf, outbuf_sz);
28492830eec1SJohn Ogness 
28502830eec1SJohn Ogness 	if (!prb_read_valid(prb, seq, &r))
28512830eec1SJohn Ogness 		return false;
28522830eec1SJohn Ogness 
28532830eec1SJohn Ogness 	pmsg->seq = r.info->seq;
28542830eec1SJohn Ogness 	pmsg->dropped = r.info->seq - seq;
28552830eec1SJohn Ogness 
28562830eec1SJohn Ogness 	/*
28572830eec1SJohn Ogness 	 * Check for dropped messages in panic here so that printk
28582830eec1SJohn Ogness 	 * suppression can occur as early as possible if necessary.
28592830eec1SJohn Ogness 	 */
28602830eec1SJohn Ogness 	if (pmsg->dropped &&
28612830eec1SJohn Ogness 	    panic_in_progress() &&
28622830eec1SJohn Ogness 	    panic_console_dropped++ > 10) {
28632830eec1SJohn Ogness 		suppress_panic_printk = 1;
28642830eec1SJohn Ogness 		pr_warn_once("Too many dropped messages. Suppress messages on non-panic CPUs to prevent livelock.\n");
28652830eec1SJohn Ogness 	}
28662830eec1SJohn Ogness 
28672830eec1SJohn Ogness 	/* Skip record that has level above the console loglevel. */
2868ea308da1SJohn Ogness 	if (may_suppress && suppress_message_printing(r.info->level))
28692830eec1SJohn Ogness 		goto out;
28702830eec1SJohn Ogness 
28712830eec1SJohn Ogness 	if (is_extended) {
28722830eec1SJohn Ogness 		len = info_print_ext_header(outbuf, outbuf_sz, r.info);
28732830eec1SJohn Ogness 		len += msg_print_ext_body(outbuf + len, outbuf_sz - len,
28742830eec1SJohn Ogness 					  &r.text_buf[0], r.info->text_len, &r.info->dev_info);
28752830eec1SJohn Ogness 	} else {
28762830eec1SJohn Ogness 		len = record_print_text(&r, console_msg_format & MSG_FORMAT_SYSLOG, printk_time);
28772830eec1SJohn Ogness 	}
28782830eec1SJohn Ogness out:
28792830eec1SJohn Ogness 	pmsg->outbuf_len = len;
28802830eec1SJohn Ogness 	return true;
28812830eec1SJohn Ogness }
28822830eec1SJohn Ogness 
28832830eec1SJohn Ogness /*
2884a699449bSJohn Ogness  * Print one record for the given console. The record printed is whatever
2885a699449bSJohn Ogness  * record is the next available record for the given console.
2886b9ee979eSJoe Perches  *
2887a699449bSJohn Ogness  * @handover will be set to true if a printk waiter has taken over the
2888fc956ae0SJohn Ogness  * console_lock, in which case the caller is no longer holding both the
2889fc956ae0SJohn Ogness  * console_lock and the SRCU read lock. Otherwise it is set to false.
2890fc956ae0SJohn Ogness  *
2891fc956ae0SJohn Ogness  * @cookie is the cookie from the SRCU read lock.
2892b9ee979eSJoe Perches  *
2893a699449bSJohn Ogness  * Returns false if the given console has no next record to print, otherwise
2894a699449bSJohn Ogness  * true.
2895b9ee979eSJoe Perches  *
2896fc956ae0SJohn Ogness  * Requires the console_lock and the SRCU read lock.
2897b9ee979eSJoe Perches  */
console_emit_next_record(struct console * con,bool * handover,int cookie)2898daaab5b5SJohn Ogness static bool console_emit_next_record(struct console *con, bool *handover, int cookie)
2899b9ee979eSJoe Perches {
2900daaab5b5SJohn Ogness 	static struct printk_buffers pbufs;
2901b9ee979eSJoe Perches 
2902daaab5b5SJohn Ogness 	bool is_extended = console_srcu_read_flags(con) & CON_EXTENDED;
2903daaab5b5SJohn Ogness 	char *outbuf = &pbufs.outbuf[0];
29042830eec1SJohn Ogness 	struct printk_message pmsg = {
29052830eec1SJohn Ogness 		.pbufs = &pbufs,
29062830eec1SJohn Ogness 	};
2907b9ee979eSJoe Perches 	unsigned long flags;
2908896fbe20SJohn Ogness 
2909a699449bSJohn Ogness 	*handover = false;
2910b9ee979eSJoe Perches 
2911ea308da1SJohn Ogness 	if (!printk_get_next_message(&pmsg, con->seq, is_extended, true))
2912a699449bSJohn Ogness 		return false;
2913a8199371SSergey Senozhatsky 
29142830eec1SJohn Ogness 	con->dropped += pmsg.dropped;
2915896fbe20SJohn Ogness 
29162830eec1SJohn Ogness 	/* Skip messages of formatted length 0. */
29172830eec1SJohn Ogness 	if (pmsg.outbuf_len == 0) {
29182830eec1SJohn Ogness 		con->seq = pmsg.seq + 1;
2919b9ee979eSJoe Perches 		goto skip;
2920b9ee979eSJoe Perches 	}
2921b9ee979eSJoe Perches 
2922c4fcc617SJohn Ogness 	if (con->dropped && !is_extended) {
2923c4fcc617SJohn Ogness 		console_prepend_dropped(&pmsg, con->dropped);
2924c4fcc617SJohn Ogness 		con->dropped = 0;
2925f92b070fSPetr Mladek 	}
2926f92b070fSPetr Mladek 
2927896fbe20SJohn Ogness 	/*
2928dbdda842SSteven Rostedt (VMware) 	 * While actively printing out messages, if another printk()
2929dbdda842SSteven Rostedt (VMware) 	 * were to occur on another CPU, it may wait for this one to
2930dbdda842SSteven Rostedt (VMware) 	 * finish. This task can not be preempted if there is a
2931dbdda842SSteven Rostedt (VMware) 	 * waiter waiting to take over.
293293d102f0SJohn Ogness 	 *
293393d102f0SJohn Ogness 	 * Interrupts are disabled because the hand over to a waiter
293493d102f0SJohn Ogness 	 * must not be interrupted until the hand over is completed
293593d102f0SJohn Ogness 	 * (@console_waiter is cleared).
2936dbdda842SSteven Rostedt (VMware) 	 */
293793d102f0SJohn Ogness 	printk_safe_enter_irqsave(flags);
2938c162d5b4SPetr Mladek 	console_lock_spinning_enable();
2939dbdda842SSteven Rostedt (VMware) 
2940c4fcc617SJohn Ogness 	/* Do not trace print latency. */
2941c4fcc617SJohn Ogness 	stop_critical_timings();
2942c4fcc617SJohn Ogness 
2943c4fcc617SJohn Ogness 	/* Write everything out to the hardware. */
2944c4fcc617SJohn Ogness 	con->write(con, outbuf, pmsg.outbuf_len);
2945c4fcc617SJohn Ogness 
29462d9ef940SPetr Mladek 	start_critical_timings();
2947dbdda842SSteven Rostedt (VMware) 
29482830eec1SJohn Ogness 	con->seq = pmsg.seq + 1;
29498d91f8b1STejun Heo 
2950fc956ae0SJohn Ogness 	*handover = console_lock_spinning_disable_and_check(cookie);
2951a699449bSJohn Ogness 	printk_safe_exit_irqrestore(flags);
2952a699449bSJohn Ogness skip:
2953a699449bSJohn Ogness 	return true;
2954a699449bSJohn Ogness }
2955a699449bSJohn Ogness 
2956a699449bSJohn Ogness /*
2957a699449bSJohn Ogness  * Print out all remaining records to all consoles.
2958a699449bSJohn Ogness  *
2959a699449bSJohn Ogness  * @do_cond_resched is set by the caller. It can be true only in schedulable
2960a699449bSJohn Ogness  * context.
2961a699449bSJohn Ogness  *
2962a699449bSJohn Ogness  * @next_seq is set to the sequence number after the last available record.
2963a699449bSJohn Ogness  * The value is valid only when this function returns true. It means that all
2964a699449bSJohn Ogness  * usable consoles are completely flushed.
2965a699449bSJohn Ogness  *
2966a699449bSJohn Ogness  * @handover will be set to true if a printk waiter has taken over the
2967a699449bSJohn Ogness  * console_lock, in which case the caller is no longer holding the
2968a699449bSJohn Ogness  * console_lock. Otherwise it is set to false.
2969a699449bSJohn Ogness  *
2970a699449bSJohn Ogness  * Returns true when there was at least one usable console and all messages
2971a699449bSJohn Ogness  * were flushed to all usable consoles. A returned false informs the caller
2972a699449bSJohn Ogness  * that everything was not flushed (either there were no usable consoles or
2973a699449bSJohn Ogness  * another context has taken over printing or it is a panic situation and this
29745831788aSPetr Mladek  * is not the panic CPU). Regardless the reason, the caller should assume it
29755831788aSPetr Mladek  * is not useful to immediately try again.
2976a699449bSJohn Ogness  *
2977a699449bSJohn Ogness  * Requires the console_lock.
2978a699449bSJohn Ogness  */
console_flush_all(bool do_cond_resched,u64 * next_seq,bool * handover)2979a699449bSJohn Ogness static bool console_flush_all(bool do_cond_resched, u64 *next_seq, bool *handover)
2980a699449bSJohn Ogness {
2981a699449bSJohn Ogness 	bool any_usable = false;
2982a699449bSJohn Ogness 	struct console *con;
2983a699449bSJohn Ogness 	bool any_progress;
2984fc956ae0SJohn Ogness 	int cookie;
2985a699449bSJohn Ogness 
2986a699449bSJohn Ogness 	*next_seq = 0;
2987a699449bSJohn Ogness 	*handover = false;
2988a699449bSJohn Ogness 
2989a699449bSJohn Ogness 	do {
2990a699449bSJohn Ogness 		any_progress = false;
2991a699449bSJohn Ogness 
2992fc956ae0SJohn Ogness 		cookie = console_srcu_read_lock();
2993fc956ae0SJohn Ogness 		for_each_console_srcu(con) {
2994a699449bSJohn Ogness 			bool progress;
2995a699449bSJohn Ogness 
2996a699449bSJohn Ogness 			if (!console_is_usable(con))
2997a699449bSJohn Ogness 				continue;
2998a699449bSJohn Ogness 			any_usable = true;
2999a699449bSJohn Ogness 
3000daaab5b5SJohn Ogness 			progress = console_emit_next_record(con, handover, cookie);
3001fc956ae0SJohn Ogness 
3002fc956ae0SJohn Ogness 			/*
3003fc956ae0SJohn Ogness 			 * If a handover has occurred, the SRCU read lock
3004fc956ae0SJohn Ogness 			 * is already released.
3005fc956ae0SJohn Ogness 			 */
3006a699449bSJohn Ogness 			if (*handover)
3007a699449bSJohn Ogness 				return false;
3008a699449bSJohn Ogness 
3009a699449bSJohn Ogness 			/* Track the next of the highest seq flushed. */
3010a699449bSJohn Ogness 			if (con->seq > *next_seq)
3011a699449bSJohn Ogness 				*next_seq = con->seq;
3012a699449bSJohn Ogness 
3013a699449bSJohn Ogness 			if (!progress)
3014a699449bSJohn Ogness 				continue;
3015a699449bSJohn Ogness 			any_progress = true;
3016a699449bSJohn Ogness 
3017a699449bSJohn Ogness 			/* Allow panic_cpu to take over the consoles safely. */
3018132a90d1SJohn Ogness 			if (other_cpu_in_panic())
3019fc956ae0SJohn Ogness 				goto abandon;
30208ebc476fSStephen Brennan 
30218d91f8b1STejun Heo 			if (do_cond_resched)
30228d91f8b1STejun Heo 				cond_resched();
3023b9ee979eSJoe Perches 		}
3024fc956ae0SJohn Ogness 		console_srcu_read_unlock(cookie);
3025a699449bSJohn Ogness 	} while (any_progress);
3026dbdda842SSteven Rostedt (VMware) 
3027a699449bSJohn Ogness 	return any_usable;
3028fc956ae0SJohn Ogness 
3029fc956ae0SJohn Ogness abandon:
3030fc956ae0SJohn Ogness 	console_srcu_read_unlock(cookie);
3031fc956ae0SJohn Ogness 	return false;
3032a699449bSJohn Ogness }
3033b9ee979eSJoe Perches 
3034a699449bSJohn Ogness /**
3035848a9c10SJohn Ogness  * console_unlock - unblock the console subsystem from printing
3036a699449bSJohn Ogness  *
3037848a9c10SJohn Ogness  * Releases the console_lock which the caller holds to block printing of
3038848a9c10SJohn Ogness  * the console subsystem.
3039a699449bSJohn Ogness  *
3040a699449bSJohn Ogness  * While the console_lock was held, console output may have been buffered
3041a699449bSJohn Ogness  * by printk().  If this is the case, console_unlock(); emits
3042a699449bSJohn Ogness  * the output prior to releasing the lock.
3043a699449bSJohn Ogness  *
3044a699449bSJohn Ogness  * console_unlock(); may be called from any context.
3045a699449bSJohn Ogness  */
console_unlock(void)3046a699449bSJohn Ogness void console_unlock(void)
3047a699449bSJohn Ogness {
3048a699449bSJohn Ogness 	bool do_cond_resched;
3049a699449bSJohn Ogness 	bool handover;
3050a699449bSJohn Ogness 	bool flushed;
3051a699449bSJohn Ogness 	u64 next_seq;
3052a699449bSJohn Ogness 
3053b9ee979eSJoe Perches 	/*
3054a699449bSJohn Ogness 	 * Console drivers are called with interrupts disabled, so
3055a699449bSJohn Ogness 	 * @console_may_schedule should be cleared before; however, we may
3056a699449bSJohn Ogness 	 * end up dumping a lot of lines, for example, if called from
3057a699449bSJohn Ogness 	 * console registration path, and should invoke cond_resched()
3058a699449bSJohn Ogness 	 * between lines if allowable.  Not doing so can cause a very long
3059a699449bSJohn Ogness 	 * scheduling stall on a slow console leading to RCU stall and
3060a699449bSJohn Ogness 	 * softlockup warnings which exacerbate the issue with more
3061a699449bSJohn Ogness 	 * messages practically incapacitating the system. Therefore, create
3062a699449bSJohn Ogness 	 * a local to use for the printing loop.
3063b9ee979eSJoe Perches 	 */
3064a699449bSJohn Ogness 	do_cond_resched = console_may_schedule;
3065a699449bSJohn Ogness 
3066a699449bSJohn Ogness 	do {
3067a699449bSJohn Ogness 		console_may_schedule = 0;
3068a699449bSJohn Ogness 
3069a699449bSJohn Ogness 		flushed = console_flush_all(do_cond_resched, &next_seq, &handover);
3070a699449bSJohn Ogness 		if (!handover)
3071a699449bSJohn Ogness 			__console_unlock();
3072a699449bSJohn Ogness 
3073a699449bSJohn Ogness 		/*
3074a699449bSJohn Ogness 		 * Abort if there was a failure to flush all messages to all
3075a699449bSJohn Ogness 		 * usable consoles. Either it is not possible to flush (in
3076a699449bSJohn Ogness 		 * which case it would be an infinite loop of retrying) or
3077a699449bSJohn Ogness 		 * another context has taken over printing.
3078a699449bSJohn Ogness 		 */
3079a699449bSJohn Ogness 		if (!flushed)
3080a699449bSJohn Ogness 			break;
3081a699449bSJohn Ogness 
3082a699449bSJohn Ogness 		/*
3083a699449bSJohn Ogness 		 * Some context may have added new records after
3084a699449bSJohn Ogness 		 * console_flush_all() but before unlocking the console.
3085a699449bSJohn Ogness 		 * Re-check if there is a new record to flush. If the trylock
3086a699449bSJohn Ogness 		 * fails, another context is already handling the printing.
3087a699449bSJohn Ogness 		 */
3088a699449bSJohn Ogness 	} while (prb_read_valid(prb, next_seq, NULL) && console_trylock());
3089b9ee979eSJoe Perches }
3090b9ee979eSJoe Perches EXPORT_SYMBOL(console_unlock);
3091b9ee979eSJoe Perches 
3092b9ee979eSJoe Perches /**
3093b9ee979eSJoe Perches  * console_conditional_schedule - yield the CPU if required
3094b9ee979eSJoe Perches  *
3095b9ee979eSJoe Perches  * If the console code is currently allowed to sleep, and
3096b9ee979eSJoe Perches  * if this CPU should yield the CPU to another task, do
3097b9ee979eSJoe Perches  * so here.
3098b9ee979eSJoe Perches  *
3099b9ee979eSJoe Perches  * Must be called within console_lock();.
3100b9ee979eSJoe Perches  */
console_conditional_schedule(void)3101b9ee979eSJoe Perches void __sched console_conditional_schedule(void)
3102b9ee979eSJoe Perches {
3103b9ee979eSJoe Perches 	if (console_may_schedule)
3104b9ee979eSJoe Perches 		cond_resched();
3105b9ee979eSJoe Perches }
3106b9ee979eSJoe Perches EXPORT_SYMBOL(console_conditional_schedule);
3107b9ee979eSJoe Perches 
console_unblank(void)3108b9ee979eSJoe Perches void console_unblank(void)
3109b9ee979eSJoe Perches {
31107b23a66dSJohn Ogness 	bool found_unblank = false;
3111b9ee979eSJoe Perches 	struct console *c;
3112d792db6fSJohn Ogness 	int cookie;
3113b9ee979eSJoe Perches 
3114b9ee979eSJoe Perches 	/*
31157b23a66dSJohn Ogness 	 * First check if there are any consoles implementing the unblank()
31167b23a66dSJohn Ogness 	 * callback. If not, there is no reason to continue and take the
31177b23a66dSJohn Ogness 	 * console lock, which in particular can be dangerous if
31187b23a66dSJohn Ogness 	 * @oops_in_progress is set.
31197b23a66dSJohn Ogness 	 */
31207b23a66dSJohn Ogness 	cookie = console_srcu_read_lock();
31217b23a66dSJohn Ogness 	for_each_console_srcu(c) {
31227b23a66dSJohn Ogness 		if ((console_srcu_read_flags(c) & CON_ENABLED) && c->unblank) {
31237b23a66dSJohn Ogness 			found_unblank = true;
31247b23a66dSJohn Ogness 			break;
31257b23a66dSJohn Ogness 		}
31267b23a66dSJohn Ogness 	}
31277b23a66dSJohn Ogness 	console_srcu_read_unlock(cookie);
31287b23a66dSJohn Ogness 	if (!found_unblank)
31297b23a66dSJohn Ogness 		return;
31307b23a66dSJohn Ogness 
31317b23a66dSJohn Ogness 	/*
3132d792db6fSJohn Ogness 	 * Stop console printing because the unblank() callback may
3133d792db6fSJohn Ogness 	 * assume the console is not within its write() callback.
3134d792db6fSJohn Ogness 	 *
3135d792db6fSJohn Ogness 	 * If @oops_in_progress is set, this may be an atomic context.
3136d792db6fSJohn Ogness 	 * In that case, attempt a trylock as best-effort.
3137b9ee979eSJoe Perches 	 */
3138b9ee979eSJoe Perches 	if (oops_in_progress) {
31397b23a66dSJohn Ogness 		/* Semaphores are not NMI-safe. */
31407b23a66dSJohn Ogness 		if (in_nmi())
31417b23a66dSJohn Ogness 			return;
31427b23a66dSJohn Ogness 
31437b23a66dSJohn Ogness 		/*
31447b23a66dSJohn Ogness 		 * Attempting to trylock the console lock can deadlock
31457b23a66dSJohn Ogness 		 * if another CPU was stopped while modifying the
31467b23a66dSJohn Ogness 		 * semaphore. "Hope and pray" that this is not the
31477b23a66dSJohn Ogness 		 * current situation.
31487b23a66dSJohn Ogness 		 */
3149bd8d7cf5SJan Kara 		if (down_trylock_console_sem() != 0)
3150b9ee979eSJoe Perches 			return;
3151b9ee979eSJoe Perches 	} else
3152b9ee979eSJoe Perches 		console_lock();
3153b9ee979eSJoe Perches 
3154007eeab7SPetr Mladek 	console_locked = 1;
3155b9ee979eSJoe Perches 	console_may_schedule = 0;
3156d792db6fSJohn Ogness 
3157d792db6fSJohn Ogness 	cookie = console_srcu_read_lock();
3158d792db6fSJohn Ogness 	for_each_console_srcu(c) {
3159d792db6fSJohn Ogness 		if ((console_srcu_read_flags(c) & CON_ENABLED) && c->unblank)
3160b9ee979eSJoe Perches 			c->unblank();
3161d792db6fSJohn Ogness 	}
3162d792db6fSJohn Ogness 	console_srcu_read_unlock(cookie);
3163d792db6fSJohn Ogness 
3164b9ee979eSJoe Perches 	console_unlock();
31653b604ca8SJohn Ogness 
31663b604ca8SJohn Ogness 	if (!oops_in_progress)
31673b604ca8SJohn Ogness 		pr_flush(1000, true);
3168b9ee979eSJoe Perches }
3169b9ee979eSJoe Perches 
31708d91f8b1STejun Heo /**
31718d91f8b1STejun Heo  * console_flush_on_panic - flush console content on panic
3172de6da1e8SFeng Tang  * @mode: flush all messages in buffer or just the pending ones
31738d91f8b1STejun Heo  *
31748d91f8b1STejun Heo  * Immediately output all pending messages no matter what.
31758d91f8b1STejun Heo  */
console_flush_on_panic(enum con_flush_mode mode)3176de6da1e8SFeng Tang void console_flush_on_panic(enum con_flush_mode mode)
31778d91f8b1STejun Heo {
3178eacb04ffSJohn Ogness 	bool handover;
3179eacb04ffSJohn Ogness 	u64 next_seq;
3180eacb04ffSJohn Ogness 
31818d91f8b1STejun Heo 	/*
3182eacb04ffSJohn Ogness 	 * Ignore the console lock and flush out the messages. Attempting a
3183eacb04ffSJohn Ogness 	 * trylock would not be useful because:
3184eacb04ffSJohn Ogness 	 *
3185eacb04ffSJohn Ogness 	 *   - if it is contended, it must be ignored anyway
3186eacb04ffSJohn Ogness 	 *   - console_lock() and console_trylock() block and fail
3187eacb04ffSJohn Ogness 	 *     respectively in panic for non-panic CPUs
3188eacb04ffSJohn Ogness 	 *   - semaphores are not NMI-safe
31898d91f8b1STejun Heo 	 */
3190eacb04ffSJohn Ogness 
3191eacb04ffSJohn Ogness 	/*
3192eacb04ffSJohn Ogness 	 * If another context is holding the console lock,
3193eacb04ffSJohn Ogness 	 * @console_may_schedule might be set. Clear it so that
3194eacb04ffSJohn Ogness 	 * this context does not call cond_resched() while flushing.
3195eacb04ffSJohn Ogness 	 */
31968d91f8b1STejun Heo 	console_may_schedule = 0;
3197de6da1e8SFeng Tang 
3198a699449bSJohn Ogness 	if (mode == CONSOLE_REPLAY_ALL) {
3199a699449bSJohn Ogness 		struct console *c;
320087f2e4b7SJohn Ogness 		int cookie;
3201a699449bSJohn Ogness 		u64 seq;
3202a699449bSJohn Ogness 
3203a699449bSJohn Ogness 		seq = prb_first_valid_seq(prb);
320487f2e4b7SJohn Ogness 
320587f2e4b7SJohn Ogness 		cookie = console_srcu_read_lock();
320687f2e4b7SJohn Ogness 		for_each_console_srcu(c) {
3207d9a4af56SThomas Gleixner 			/*
3208eacb04ffSJohn Ogness 			 * This is an unsynchronized assignment, but the
320987f2e4b7SJohn Ogness 			 * kernel is in "hope and pray" mode anyway.
3210d9a4af56SThomas Gleixner 			 */
3211a699449bSJohn Ogness 			c->seq = seq;
3212a699449bSJohn Ogness 		}
321387f2e4b7SJohn Ogness 		console_srcu_read_unlock(cookie);
321487f2e4b7SJohn Ogness 	}
3215eacb04ffSJohn Ogness 
3216eacb04ffSJohn Ogness 	console_flush_all(false, &next_seq, &handover);
32178d91f8b1STejun Heo }
32188d91f8b1STejun Heo 
3219b9ee979eSJoe Perches /*
3220b9ee979eSJoe Perches  * Return the console tty driver structure and its associated index
3221b9ee979eSJoe Perches  */
console_device(int * index)3222b9ee979eSJoe Perches struct tty_driver *console_device(int *index)
3223b9ee979eSJoe Perches {
3224b9ee979eSJoe Perches 	struct console *c;
3225b9ee979eSJoe Perches 	struct tty_driver *driver = NULL;
32268cb15f7fSJohn Ogness 	int cookie;
3227b9ee979eSJoe Perches 
32288cb15f7fSJohn Ogness 	/*
32298cb15f7fSJohn Ogness 	 * Take console_lock to serialize device() callback with
32308cb15f7fSJohn Ogness 	 * other console operations. For example, fg_console is
32318cb15f7fSJohn Ogness 	 * modified under console_lock when switching vt.
32328cb15f7fSJohn Ogness 	 */
3233b9ee979eSJoe Perches 	console_lock();
32348cb15f7fSJohn Ogness 
32358cb15f7fSJohn Ogness 	cookie = console_srcu_read_lock();
32368cb15f7fSJohn Ogness 	for_each_console_srcu(c) {
3237b9ee979eSJoe Perches 		if (!c->device)
3238b9ee979eSJoe Perches 			continue;
3239b9ee979eSJoe Perches 		driver = c->device(c, index);
3240b9ee979eSJoe Perches 		if (driver)
3241b9ee979eSJoe Perches 			break;
3242b9ee979eSJoe Perches 	}
32438cb15f7fSJohn Ogness 	console_srcu_read_unlock(cookie);
32448cb15f7fSJohn Ogness 
3245b9ee979eSJoe Perches 	console_unlock();
3246b9ee979eSJoe Perches 	return driver;
3247b9ee979eSJoe Perches }
3248b9ee979eSJoe Perches 
3249b9ee979eSJoe Perches /*
3250b9ee979eSJoe Perches  * Prevent further output on the passed console device so that (for example)
3251b9ee979eSJoe Perches  * serial drivers can disable console output before suspending a port, and can
3252b9ee979eSJoe Perches  * re-enable output afterwards.
3253b9ee979eSJoe Perches  */
console_stop(struct console * console)3254b9ee979eSJoe Perches void console_stop(struct console *console)
3255b9ee979eSJoe Perches {
32563b604ca8SJohn Ogness 	__pr_flush(console, 1000, true);
32574dc64682SJohn Ogness 	console_list_lock();
3258100bdef2SJohn Ogness 	console_srcu_write_flags(console, console->flags & ~CON_ENABLED);
32594dc64682SJohn Ogness 	console_list_unlock();
32606c4afa79SJohn Ogness 
32616c4afa79SJohn Ogness 	/*
32626c4afa79SJohn Ogness 	 * Ensure that all SRCU list walks have completed. All contexts must
32636c4afa79SJohn Ogness 	 * be able to see that this console is disabled so that (for example)
32646c4afa79SJohn Ogness 	 * the caller can suspend the port without risk of another context
32656c4afa79SJohn Ogness 	 * using the port.
32666c4afa79SJohn Ogness 	 */
32676c4afa79SJohn Ogness 	synchronize_srcu(&console_srcu);
3268b9ee979eSJoe Perches }
3269b9ee979eSJoe Perches EXPORT_SYMBOL(console_stop);
3270b9ee979eSJoe Perches 
console_start(struct console * console)3271b9ee979eSJoe Perches void console_start(struct console *console)
3272b9ee979eSJoe Perches {
32734dc64682SJohn Ogness 	console_list_lock();
3274100bdef2SJohn Ogness 	console_srcu_write_flags(console, console->flags | CON_ENABLED);
32754dc64682SJohn Ogness 	console_list_unlock();
32763b604ca8SJohn Ogness 	__pr_flush(console, 1000, true);
3277b9ee979eSJoe Perches }
3278b9ee979eSJoe Perches EXPORT_SYMBOL(console_start);
3279b9ee979eSJoe Perches 
3280b9ee979eSJoe Perches static int __read_mostly keep_bootcon;
3281b9ee979eSJoe Perches 
keep_bootcon_setup(char * str)3282b9ee979eSJoe Perches static int __init keep_bootcon_setup(char *str)
3283b9ee979eSJoe Perches {
3284b9ee979eSJoe Perches 	keep_bootcon = 1;
328527083bacSAndrew Morton 	pr_info("debug: skip boot console de-registration.\n");
3286b9ee979eSJoe Perches 
3287b9ee979eSJoe Perches 	return 0;
3288b9ee979eSJoe Perches }
3289b9ee979eSJoe Perches 
3290b9ee979eSJoe Perches early_param("keep_bootcon", keep_bootcon_setup);
3291b9ee979eSJoe Perches 
console_call_setup(struct console * newcon,char * options)32924cc3e2edSPeter Collingbourne static int console_call_setup(struct console *newcon, char *options)
32934cc3e2edSPeter Collingbourne {
32944cc3e2edSPeter Collingbourne 	int err;
32954cc3e2edSPeter Collingbourne 
32964cc3e2edSPeter Collingbourne 	if (!newcon->setup)
32974cc3e2edSPeter Collingbourne 		return 0;
32984cc3e2edSPeter Collingbourne 
32994cc3e2edSPeter Collingbourne 	/* Synchronize with possible boot console. */
33004cc3e2edSPeter Collingbourne 	console_lock();
33014cc3e2edSPeter Collingbourne 	err = newcon->setup(newcon, options);
33024cc3e2edSPeter Collingbourne 	console_unlock();
33034cc3e2edSPeter Collingbourne 
33044cc3e2edSPeter Collingbourne 	return err;
33054cc3e2edSPeter Collingbourne }
33064cc3e2edSPeter Collingbourne 
3307b9ee979eSJoe Perches /*
3308ad8cd1dbSBenjamin Herrenschmidt  * This is called by register_console() to try to match
3309ad8cd1dbSBenjamin Herrenschmidt  * the newly registered console with any of the ones selected
3310ad8cd1dbSBenjamin Herrenschmidt  * by either the command line or add_preferred_console() and
3311ad8cd1dbSBenjamin Herrenschmidt  * setup/enable it.
3312ad8cd1dbSBenjamin Herrenschmidt  *
3313ad8cd1dbSBenjamin Herrenschmidt  * Care need to be taken with consoles that are statically
3314ad8cd1dbSBenjamin Herrenschmidt  * enabled such as netconsole
3315ad8cd1dbSBenjamin Herrenschmidt  */
try_enable_preferred_console(struct console * newcon,bool user_specified)3316ed758b30SPetr Mladek static int try_enable_preferred_console(struct console *newcon,
3317ed758b30SPetr Mladek 					bool user_specified)
3318ad8cd1dbSBenjamin Herrenschmidt {
3319ad8cd1dbSBenjamin Herrenschmidt 	struct console_cmdline *c;
3320bba18a1aSAndy Shevchenko 	int i, err;
3321ad8cd1dbSBenjamin Herrenschmidt 
3322ad8cd1dbSBenjamin Herrenschmidt 	for (i = 0, c = console_cmdline;
3323ad8cd1dbSBenjamin Herrenschmidt 	     i < MAX_CMDLINECONSOLES && c->name[0];
3324ad8cd1dbSBenjamin Herrenschmidt 	     i++, c++) {
3325e369d822SBenjamin Herrenschmidt 		if (c->user_specified != user_specified)
3326e369d822SBenjamin Herrenschmidt 			continue;
3327ad8cd1dbSBenjamin Herrenschmidt 		if (!newcon->match ||
3328ad8cd1dbSBenjamin Herrenschmidt 		    newcon->match(newcon, c->name, c->index, c->options) != 0) {
3329ad8cd1dbSBenjamin Herrenschmidt 			/* default matching */
3330ad8cd1dbSBenjamin Herrenschmidt 			BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
3331ad8cd1dbSBenjamin Herrenschmidt 			if (strcmp(c->name, newcon->name) != 0)
3332ad8cd1dbSBenjamin Herrenschmidt 				continue;
3333ad8cd1dbSBenjamin Herrenschmidt 			if (newcon->index >= 0 &&
3334ad8cd1dbSBenjamin Herrenschmidt 			    newcon->index != c->index)
3335ad8cd1dbSBenjamin Herrenschmidt 				continue;
3336ad8cd1dbSBenjamin Herrenschmidt 			if (newcon->index < 0)
3337ad8cd1dbSBenjamin Herrenschmidt 				newcon->index = c->index;
3338ad8cd1dbSBenjamin Herrenschmidt 
3339ad8cd1dbSBenjamin Herrenschmidt 			if (_braille_register_console(newcon, c))
3340ad8cd1dbSBenjamin Herrenschmidt 				return 0;
3341ad8cd1dbSBenjamin Herrenschmidt 
33424cc3e2edSPeter Collingbourne 			err = console_call_setup(newcon, c->options);
33434cc3e2edSPeter Collingbourne 			if (err)
3344bba18a1aSAndy Shevchenko 				return err;
3345ad8cd1dbSBenjamin Herrenschmidt 		}
3346ad8cd1dbSBenjamin Herrenschmidt 		newcon->flags |= CON_ENABLED;
3347f873efe8SPetr Mladek 		if (i == preferred_console)
3348ad8cd1dbSBenjamin Herrenschmidt 			newcon->flags |= CON_CONSDEV;
3349ad8cd1dbSBenjamin Herrenschmidt 		return 0;
3350ad8cd1dbSBenjamin Herrenschmidt 	}
3351ad8cd1dbSBenjamin Herrenschmidt 
3352ad8cd1dbSBenjamin Herrenschmidt 	/*
3353ad8cd1dbSBenjamin Herrenschmidt 	 * Some consoles, such as pstore and netconsole, can be enabled even
3354e369d822SBenjamin Herrenschmidt 	 * without matching. Accept the pre-enabled consoles only when match()
335550460376SAndy Shevchenko 	 * and setup() had a chance to be called.
3356ad8cd1dbSBenjamin Herrenschmidt 	 */
3357e369d822SBenjamin Herrenschmidt 	if (newcon->flags & CON_ENABLED && c->user_specified ==	user_specified)
3358ad8cd1dbSBenjamin Herrenschmidt 		return 0;
3359ad8cd1dbSBenjamin Herrenschmidt 
3360ad8cd1dbSBenjamin Herrenschmidt 	return -ENOENT;
3361ad8cd1dbSBenjamin Herrenschmidt }
3362ad8cd1dbSBenjamin Herrenschmidt 
3363ed758b30SPetr Mladek /* Try to enable the console unconditionally */
try_enable_default_console(struct console * newcon)3364ed758b30SPetr Mladek static void try_enable_default_console(struct console *newcon)
3365ed758b30SPetr Mladek {
3366ed758b30SPetr Mladek 	if (newcon->index < 0)
3367ed758b30SPetr Mladek 		newcon->index = 0;
3368ed758b30SPetr Mladek 
33694cc3e2edSPeter Collingbourne 	if (console_call_setup(newcon, NULL) != 0)
3370ed758b30SPetr Mladek 		return;
3371ed758b30SPetr Mladek 
3372ed758b30SPetr Mladek 	newcon->flags |= CON_ENABLED;
3373ed758b30SPetr Mladek 
33744f546939SPetr Mladek 	if (newcon->device)
3375ed758b30SPetr Mladek 		newcon->flags |= CON_CONSDEV;
3376ed758b30SPetr Mladek }
3377ed758b30SPetr Mladek 
33781fc0ca9eSJohn Ogness #define con_printk(lvl, con, fmt, ...)			\
33791fc0ca9eSJohn Ogness 	printk(lvl pr_fmt("%sconsole [%s%d] " fmt),	\
33801fc0ca9eSJohn Ogness 	       (con->flags & CON_BOOT) ? "boot" : "",	\
33811fc0ca9eSJohn Ogness 	       con->name, con->index, ##__VA_ARGS__)
33821fc0ca9eSJohn Ogness 
console_init_seq(struct console * newcon,bool bootcon_registered)3383a4242760SJohn Ogness static void console_init_seq(struct console *newcon, bool bootcon_registered)
3384b80ea0e8SJohn Ogness {
3385a4242760SJohn Ogness 	struct console *con;
3386a4242760SJohn Ogness 	bool handover;
3387a4242760SJohn Ogness 
3388a4242760SJohn Ogness 	if (newcon->flags & (CON_PRINTBUFFER | CON_BOOT)) {
3389b80ea0e8SJohn Ogness 		/* Get a consistent copy of @syslog_seq. */
3390b80ea0e8SJohn Ogness 		mutex_lock(&syslog_lock);
3391b80ea0e8SJohn Ogness 		newcon->seq = syslog_seq;
3392b80ea0e8SJohn Ogness 		mutex_unlock(&syslog_lock);
3393b80ea0e8SJohn Ogness 	} else {
3394a4242760SJohn Ogness 		/* Begin with next message added to ringbuffer. */
3395b80ea0e8SJohn Ogness 		newcon->seq = prb_next_seq(prb);
3396a4242760SJohn Ogness 
3397a4242760SJohn Ogness 		/*
3398a4242760SJohn Ogness 		 * If any enabled boot consoles are due to be unregistered
3399a4242760SJohn Ogness 		 * shortly, some may not be caught up and may be the same
3400a4242760SJohn Ogness 		 * device as @newcon. Since it is not known which boot console
3401a4242760SJohn Ogness 		 * is the same device, flush all consoles and, if necessary,
3402a4242760SJohn Ogness 		 * start with the message of the enabled boot console that is
3403a4242760SJohn Ogness 		 * the furthest behind.
3404a4242760SJohn Ogness 		 */
3405a4242760SJohn Ogness 		if (bootcon_registered && !keep_bootcon) {
3406a4242760SJohn Ogness 			/*
3407848a9c10SJohn Ogness 			 * Hold the console_lock to stop console printing and
3408848a9c10SJohn Ogness 			 * guarantee safe access to console->seq.
3409848a9c10SJohn Ogness 			 */
3410848a9c10SJohn Ogness 			console_lock();
3411848a9c10SJohn Ogness 
3412848a9c10SJohn Ogness 			/*
3413a4242760SJohn Ogness 			 * Flush all consoles and set the console to start at
3414a4242760SJohn Ogness 			 * the next unprinted sequence number.
3415a4242760SJohn Ogness 			 */
3416a4242760SJohn Ogness 			if (!console_flush_all(true, &newcon->seq, &handover)) {
3417a4242760SJohn Ogness 				/*
3418a4242760SJohn Ogness 				 * Flushing failed. Just choose the lowest
3419a4242760SJohn Ogness 				 * sequence of the enabled boot consoles.
3420a4242760SJohn Ogness 				 */
3421a4242760SJohn Ogness 
3422a4242760SJohn Ogness 				/*
3423a4242760SJohn Ogness 				 * If there was a handover, this context no
3424a4242760SJohn Ogness 				 * longer holds the console_lock.
3425a4242760SJohn Ogness 				 */
3426a4242760SJohn Ogness 				if (handover)
3427a4242760SJohn Ogness 					console_lock();
3428a4242760SJohn Ogness 
3429a4242760SJohn Ogness 				newcon->seq = prb_next_seq(prb);
3430a4242760SJohn Ogness 				for_each_console(con) {
3431a4242760SJohn Ogness 					if ((con->flags & CON_BOOT) &&
3432a4242760SJohn Ogness 					    (con->flags & CON_ENABLED) &&
3433a4242760SJohn Ogness 					    con->seq < newcon->seq) {
3434a4242760SJohn Ogness 						newcon->seq = con->seq;
3435a4242760SJohn Ogness 					}
3436a4242760SJohn Ogness 				}
3437a4242760SJohn Ogness 			}
3438848a9c10SJohn Ogness 
3439848a9c10SJohn Ogness 			console_unlock();
3440a4242760SJohn Ogness 		}
3441b80ea0e8SJohn Ogness 	}
3442b80ea0e8SJohn Ogness }
3443b80ea0e8SJohn Ogness 
3444d9a4af56SThomas Gleixner #define console_first()				\
3445d9a4af56SThomas Gleixner 	hlist_entry(console_list.first, struct console, node)
3446d9a4af56SThomas Gleixner 
34474dc64682SJohn Ogness static int unregister_console_locked(struct console *console);
34484dc64682SJohn Ogness 
3449ad8cd1dbSBenjamin Herrenschmidt /*
3450b9ee979eSJoe Perches  * The console driver calls this routine during kernel initialization
3451b9ee979eSJoe Perches  * to register the console printing procedure with printk() and to
3452b9ee979eSJoe Perches  * print any messages that were printed by the kernel before the
3453b9ee979eSJoe Perches  * console driver was initialized.
3454b9ee979eSJoe Perches  *
3455b9ee979eSJoe Perches  * This can happen pretty early during the boot process (because of
3456b9ee979eSJoe Perches  * early_printk) - sometimes before setup_arch() completes - be careful
3457b9ee979eSJoe Perches  * of what kernel features are used - they may not be initialised yet.
3458b9ee979eSJoe Perches  *
3459b9ee979eSJoe Perches  * There are two types of consoles - bootconsoles (early_printk) and
3460b9ee979eSJoe Perches  * "real" consoles (everything which is not a bootconsole) which are
3461b9ee979eSJoe Perches  * handled differently.
3462b9ee979eSJoe Perches  *  - Any number of bootconsoles can be registered at any time.
3463b9ee979eSJoe Perches  *  - As soon as a "real" console is registered, all bootconsoles
3464b9ee979eSJoe Perches  *    will be unregistered automatically.
3465b9ee979eSJoe Perches  *  - Once a "real" console is registered, any attempt to register a
3466b9ee979eSJoe Perches  *    bootconsoles will be rejected
3467b9ee979eSJoe Perches  */
register_console(struct console * newcon)3468b9ee979eSJoe Perches void register_console(struct console *newcon)
3469b9ee979eSJoe Perches {
34705e8ba485SPetr Mladek 	struct console *con;
347111457036SJohn Ogness 	bool bootcon_registered = false;
347211457036SJohn Ogness 	bool realcon_registered = false;
3473ad8cd1dbSBenjamin Herrenschmidt 	int err;
3474b9ee979eSJoe Perches 
34754dc64682SJohn Ogness 	console_list_lock();
347616cf48a6SAndreas Bießmann 
3477b9ee979eSJoe Perches 	for_each_console(con) {
3478b9ee979eSJoe Perches 		if (WARN(con == newcon, "console '%s%d' already registered\n",
34794dc64682SJohn Ogness 					 con->name, con->index)) {
34804dc64682SJohn Ogness 			goto unlock;
3481b9ee979eSJoe Perches 		}
3482b9ee979eSJoe Perches 
34835e8ba485SPetr Mladek 		if (con->flags & CON_BOOT)
348411457036SJohn Ogness 			bootcon_registered = true;
34855e8ba485SPetr Mladek 		else
348611457036SJohn Ogness 			realcon_registered = true;
34875e8ba485SPetr Mladek 	}
34885e8ba485SPetr Mladek 
34895e8ba485SPetr Mladek 	/* Do not register boot consoles when there already is a real one. */
349011457036SJohn Ogness 	if ((newcon->flags & CON_BOOT) && realcon_registered) {
349127083bacSAndrew Morton 		pr_info("Too late to register bootconsole %s%d\n",
3492b9ee979eSJoe Perches 			newcon->name, newcon->index);
34934dc64682SJohn Ogness 		goto unlock;
3494b9ee979eSJoe Perches 	}
3495b9ee979eSJoe Perches 
3496b9ee979eSJoe Perches 	/*
34974f546939SPetr Mladek 	 * See if we want to enable this console driver by default.
34984f546939SPetr Mladek 	 *
34994f546939SPetr Mladek 	 * Nope when a console is preferred by the command line, device
35004f546939SPetr Mladek 	 * tree, or SPCR.
35014f546939SPetr Mladek 	 *
35024f546939SPetr Mladek 	 * The first real console with tty binding (driver) wins. More
35034f546939SPetr Mladek 	 * consoles might get enabled before the right one is found.
35044f546939SPetr Mladek 	 *
35054f546939SPetr Mladek 	 * Note that a console with tty binding will have CON_CONSDEV
35064f546939SPetr Mladek 	 * flag set and will be first in the list.
3507b9ee979eSJoe Perches 	 */
35084f546939SPetr Mladek 	if (preferred_console < 0) {
3509d9a4af56SThomas Gleixner 		if (hlist_empty(&console_list) || !console_first()->device ||
3510d9a4af56SThomas Gleixner 		    console_first()->flags & CON_BOOT) {
3511ed758b30SPetr Mladek 			try_enable_default_console(newcon);
35124f546939SPetr Mladek 		}
35134f546939SPetr Mladek 	}
3514b9ee979eSJoe Perches 
3515e369d822SBenjamin Herrenschmidt 	/* See if this console matches one we selected on the command line */
3516ed758b30SPetr Mladek 	err = try_enable_preferred_console(newcon, true);
3517bbeddf52SJoe Perches 
3518e369d822SBenjamin Herrenschmidt 	/* If not, try to match against the platform default(s) */
3519e369d822SBenjamin Herrenschmidt 	if (err == -ENOENT)
3520ed758b30SPetr Mladek 		err = try_enable_preferred_console(newcon, false);
3521bbeddf52SJoe Perches 
3522ad8cd1dbSBenjamin Herrenschmidt 	/* printk() messages are not printed to the Braille console. */
3523ad8cd1dbSBenjamin Herrenschmidt 	if (err || newcon->flags & CON_BRL)
35244dc64682SJohn Ogness 		goto unlock;
3525b9ee979eSJoe Perches 
3526b9ee979eSJoe Perches 	/*
3527b9ee979eSJoe Perches 	 * If we have a bootconsole, and are switching to a real console,
3528b9ee979eSJoe Perches 	 * don't print everything out again, since when the boot console, and
3529b9ee979eSJoe Perches 	 * the real console are the same physical device, it's annoying to
3530b9ee979eSJoe Perches 	 * see the beginning boot messages twice
3531b9ee979eSJoe Perches 	 */
353211457036SJohn Ogness 	if (bootcon_registered &&
35335e8ba485SPetr Mladek 	    ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV)) {
3534b9ee979eSJoe Perches 		newcon->flags &= ~CON_PRINTBUFFER;
35355e8ba485SPetr Mladek 	}
3536b9ee979eSJoe Perches 
3537a699449bSJohn Ogness 	newcon->dropped = 0;
3538a4242760SJohn Ogness 	console_init_seq(newcon, bootcon_registered);
35396c4afa79SJohn Ogness 
3540b9ee979eSJoe Perches 	/*
3541b9ee979eSJoe Perches 	 * Put this console in the list - keep the
3542b9ee979eSJoe Perches 	 * preferred driver at the head of the list.
3543b9ee979eSJoe Perches 	 */
35446c4afa79SJohn Ogness 	if (hlist_empty(&console_list)) {
35456c4afa79SJohn Ogness 		/* Ensure CON_CONSDEV is always set for the head. */
3546b9ee979eSJoe Perches 		newcon->flags |= CON_CONSDEV;
35476c4afa79SJohn Ogness 		hlist_add_head_rcu(&newcon->node, &console_list);
35486c4afa79SJohn Ogness 
35496c4afa79SJohn Ogness 	} else if (newcon->flags & CON_CONSDEV) {
35506c4afa79SJohn Ogness 		/* Only the new head can have CON_CONSDEV set. */
3551100bdef2SJohn Ogness 		console_srcu_write_flags(console_first(), console_first()->flags & ~CON_CONSDEV);
35526c4afa79SJohn Ogness 		hlist_add_head_rcu(&newcon->node, &console_list);
35536c4afa79SJohn Ogness 
3554b9ee979eSJoe Perches 	} else {
35556c4afa79SJohn Ogness 		hlist_add_behind_rcu(&newcon->node, console_list.first);
35566fe29354STejun Heo 	}
35579627808dSSergey Senozhatsky 
35586c4afa79SJohn Ogness 	/*
35596c4afa79SJohn Ogness 	 * No need to synchronize SRCU here! The caller does not rely
35606c4afa79SJohn Ogness 	 * on all contexts being able to see the new console before
35616c4afa79SJohn Ogness 	 * register_console() completes.
35626c4afa79SJohn Ogness 	 */
35636c4afa79SJohn Ogness 
3564b9ee979eSJoe Perches 	console_sysfs_notify();
3565b9ee979eSJoe Perches 
3566b9ee979eSJoe Perches 	/*
3567b9ee979eSJoe Perches 	 * By unregistering the bootconsoles after we enable the real console
3568b9ee979eSJoe Perches 	 * we get the "console xxx enabled" message on all the consoles -
3569b9ee979eSJoe Perches 	 * boot consoles, real consoles, etc - this is to ensure that end
3570b9ee979eSJoe Perches 	 * users know there might be something in the kernel's log buffer that
3571b9ee979eSJoe Perches 	 * went to the bootconsole (that they do not see on the real console)
3572b9ee979eSJoe Perches 	 */
35731fc0ca9eSJohn Ogness 	con_printk(KERN_INFO, newcon, "enabled\n");
357411457036SJohn Ogness 	if (bootcon_registered &&
35756b802394SKees Cook 	    ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
35766b802394SKees Cook 	    !keep_bootcon) {
3577d9a4af56SThomas Gleixner 		struct hlist_node *tmp;
3578d9a4af56SThomas Gleixner 
3579d9a4af56SThomas Gleixner 		hlist_for_each_entry_safe(con, tmp, &console_list, node) {
35805e8ba485SPetr Mladek 			if (con->flags & CON_BOOT)
35814dc64682SJohn Ogness 				unregister_console_locked(con);
3582b9ee979eSJoe Perches 		}
3583b9ee979eSJoe Perches 	}
35844dc64682SJohn Ogness unlock:
35854dc64682SJohn Ogness 	console_list_unlock();
3586d9a4af56SThomas Gleixner }
3587b9ee979eSJoe Perches EXPORT_SYMBOL(register_console);
3588b9ee979eSJoe Perches 
35894dc64682SJohn Ogness /* Must be called under console_list_lock(). */
unregister_console_locked(struct console * console)35904dc64682SJohn Ogness static int unregister_console_locked(struct console *console)
3591b9ee979eSJoe Perches {
3592bbeddf52SJoe Perches 	int res;
3593b9ee979eSJoe Perches 
35944dc64682SJohn Ogness 	lockdep_assert_console_list_lock_held();
35954dc64682SJohn Ogness 
35961fc0ca9eSJohn Ogness 	con_printk(KERN_INFO, console, "disabled\n");
35976b802394SKees Cook 
3598bbeddf52SJoe Perches 	res = _braille_unregister_console(console);
3599bb72e398SAndy Shevchenko 	if (res < 0)
3600bbeddf52SJoe Perches 		return res;
3601bb72e398SAndy Shevchenko 	if (res > 0)
3602bb72e398SAndy Shevchenko 		return 0;
3603b9ee979eSJoe Perches 
3604d9a4af56SThomas Gleixner 	/* Disable it unconditionally */
3605100bdef2SJohn Ogness 	console_srcu_write_flags(console, console->flags & ~CON_ENABLED);
3606b9ee979eSJoe Perches 
3607848a9c10SJohn Ogness 	if (!console_is_registered_locked(console))
3608d9a4af56SThomas Gleixner 		return -ENODEV;
3609b9ee979eSJoe Perches 
36106c4afa79SJohn Ogness 	hlist_del_init_rcu(&console->node);
3611e78bedbdSAndy Shevchenko 
3612b9ee979eSJoe Perches 	/*
3613d9a4af56SThomas Gleixner 	 * <HISTORICAL>
3614b9ee979eSJoe Perches 	 * If this isn't the last console and it has CON_CONSDEV set, we
3615b9ee979eSJoe Perches 	 * need to set it on the next preferred console.
3616d9a4af56SThomas Gleixner 	 * </HISTORICAL>
3617d9a4af56SThomas Gleixner 	 *
3618d9a4af56SThomas Gleixner 	 * The above makes no sense as there is no guarantee that the next
3619d9a4af56SThomas Gleixner 	 * console has any device attached. Oh well....
3620b9ee979eSJoe Perches 	 */
3621d9a4af56SThomas Gleixner 	if (!hlist_empty(&console_list) && console->flags & CON_CONSDEV)
3622100bdef2SJohn Ogness 		console_srcu_write_flags(console_first(), console_first()->flags | CON_CONSDEV);
3623b9ee979eSJoe Perches 
36246c4afa79SJohn Ogness 	/*
36256c4afa79SJohn Ogness 	 * Ensure that all SRCU list walks have completed. All contexts
36266c4afa79SJohn Ogness 	 * must not be able to see this console in the list so that any
36276c4afa79SJohn Ogness 	 * exit/cleanup routines can be performed safely.
36286c4afa79SJohn Ogness 	 */
36296c4afa79SJohn Ogness 	synchronize_srcu(&console_srcu);
36306c4afa79SJohn Ogness 
3631b9ee979eSJoe Perches 	console_sysfs_notify();
3632e78bedbdSAndy Shevchenko 
3633ed31685cSAndy Shevchenko 	if (console->exit)
3634ed31685cSAndy Shevchenko 		res = console->exit(console);
3635ed31685cSAndy Shevchenko 
3636e78bedbdSAndy Shevchenko 	return res;
3637b9ee979eSJoe Perches }
36380c688614SNicolas Pitre 
unregister_console(struct console * console)36394dc64682SJohn Ogness int unregister_console(struct console *console)
36404dc64682SJohn Ogness {
36414dc64682SJohn Ogness 	int res;
36420c688614SNicolas Pitre 
36434dc64682SJohn Ogness 	console_list_lock();
36444dc64682SJohn Ogness 	res = unregister_console_locked(console);
36454dc64682SJohn Ogness 	console_list_unlock();
3646b9ee979eSJoe Perches 	return res;
3647b9ee979eSJoe Perches }
3648b9ee979eSJoe Perches EXPORT_SYMBOL(unregister_console);
3649b9ee979eSJoe Perches 
36506f883675SJohn Ogness /**
36516f883675SJohn Ogness  * console_force_preferred_locked - force a registered console preferred
36526f883675SJohn Ogness  * @con: The registered console to force preferred.
36536f883675SJohn Ogness  *
36546f883675SJohn Ogness  * Must be called under console_list_lock().
36556f883675SJohn Ogness  */
console_force_preferred_locked(struct console * con)36566f883675SJohn Ogness void console_force_preferred_locked(struct console *con)
36576f883675SJohn Ogness {
36586f883675SJohn Ogness 	struct console *cur_pref_con;
36596f883675SJohn Ogness 
36606f883675SJohn Ogness 	if (!console_is_registered_locked(con))
36616f883675SJohn Ogness 		return;
36626f883675SJohn Ogness 
36636f883675SJohn Ogness 	cur_pref_con = console_first();
36646f883675SJohn Ogness 
36656f883675SJohn Ogness 	/* Already preferred? */
36666f883675SJohn Ogness 	if (cur_pref_con == con)
36676f883675SJohn Ogness 		return;
36686f883675SJohn Ogness 
36696f883675SJohn Ogness 	/*
36706f883675SJohn Ogness 	 * Delete, but do not re-initialize the entry. This allows the console
36716f883675SJohn Ogness 	 * to continue to appear registered (via any hlist_unhashed_lockless()
36726f883675SJohn Ogness 	 * checks), even though it was briefly removed from the console list.
36736f883675SJohn Ogness 	 */
36746f883675SJohn Ogness 	hlist_del_rcu(&con->node);
36756f883675SJohn Ogness 
36766f883675SJohn Ogness 	/*
36776f883675SJohn Ogness 	 * Ensure that all SRCU list walks have completed so that the console
36786f883675SJohn Ogness 	 * can be added to the beginning of the console list and its forward
36796f883675SJohn Ogness 	 * list pointer can be re-initialized.
36806f883675SJohn Ogness 	 */
36816f883675SJohn Ogness 	synchronize_srcu(&console_srcu);
36826f883675SJohn Ogness 
36836f883675SJohn Ogness 	con->flags |= CON_CONSDEV;
36846f883675SJohn Ogness 	WARN_ON(!con->device);
36856f883675SJohn Ogness 
36866f883675SJohn Ogness 	/* Only the new head can have CON_CONSDEV set. */
36876f883675SJohn Ogness 	console_srcu_write_flags(cur_pref_con, cur_pref_con->flags & ~CON_CONSDEV);
36886f883675SJohn Ogness 	hlist_add_head_rcu(&con->node, &console_list);
36896f883675SJohn Ogness }
36906f883675SJohn Ogness EXPORT_SYMBOL(console_force_preferred_locked);
36916f883675SJohn Ogness 
369281cc26f2SThierry Reding /*
36930c688614SNicolas Pitre  * Initialize the console device. This is called *early*, so
36940c688614SNicolas Pitre  * we can't necessarily depend on lots of kernel help here.
36950c688614SNicolas Pitre  * Just do some early initializations, and do the complex setup
36960c688614SNicolas Pitre  * later.
36970c688614SNicolas Pitre  */
console_init(void)36980c688614SNicolas Pitre void __init console_init(void)
36990c688614SNicolas Pitre {
370058eacfffSAbderrahmane Benbachir 	int ret;
37011b1eeca7SArd Biesheuvel 	initcall_t call;
37021b1eeca7SArd Biesheuvel 	initcall_entry_t *ce;
37030c688614SNicolas Pitre 
37040c688614SNicolas Pitre 	/* Setup the default TTY line discipline. */
37050c688614SNicolas Pitre 	n_tty_init();
37060c688614SNicolas Pitre 
37070c688614SNicolas Pitre 	/*
37080c688614SNicolas Pitre 	 * set up the console device so that later boot sequences can
37090c688614SNicolas Pitre 	 * inform about problems etc..
37100c688614SNicolas Pitre 	 */
37111b1eeca7SArd Biesheuvel 	ce = __con_initcall_start;
371258eacfffSAbderrahmane Benbachir 	trace_initcall_level("console");
37131b1eeca7SArd Biesheuvel 	while (ce < __con_initcall_end) {
37141b1eeca7SArd Biesheuvel 		call = initcall_from_entry(ce);
37151b1eeca7SArd Biesheuvel 		trace_initcall_start(call);
37161b1eeca7SArd Biesheuvel 		ret = call();
37171b1eeca7SArd Biesheuvel 		trace_initcall_finish(call, ret);
37181b1eeca7SArd Biesheuvel 		ce++;
37190c688614SNicolas Pitre 	}
37200c688614SNicolas Pitre }
37210c688614SNicolas Pitre 
37220c688614SNicolas Pitre /*
372381cc26f2SThierry Reding  * Some boot consoles access data that is in the init section and which will
372481cc26f2SThierry Reding  * be discarded after the initcalls have been run. To make sure that no code
372581cc26f2SThierry Reding  * will access this data, unregister the boot consoles in a late initcall.
372681cc26f2SThierry Reding  *
372781cc26f2SThierry Reding  * If for some reason, such as deferred probe or the driver being a loadable
372881cc26f2SThierry Reding  * module, the real console hasn't registered yet at this point, there will
372981cc26f2SThierry Reding  * be a brief interval in which no messages are logged to the console, which
373081cc26f2SThierry Reding  * makes it difficult to diagnose problems that occur during this time.
373181cc26f2SThierry Reding  *
373281cc26f2SThierry Reding  * To mitigate this problem somewhat, only unregister consoles whose memory
37332b1be689SMatt Redfearn  * intersects with the init section. Note that all other boot consoles will
3734acebb559SBhaskar Chowdhury  * get unregistered when the real preferred console is registered.
373581cc26f2SThierry Reding  */
printk_late_init(void)3736b9ee979eSJoe Perches static int __init printk_late_init(void)
3737b9ee979eSJoe Perches {
3738d9a4af56SThomas Gleixner 	struct hlist_node *tmp;
3739b9ee979eSJoe Perches 	struct console *con;
374090b14889SSebastian Andrzej Siewior 	int ret;
3741b9ee979eSJoe Perches 
37424dc64682SJohn Ogness 	console_list_lock();
3743d9a4af56SThomas Gleixner 	hlist_for_each_entry_safe(con, tmp, &console_list, node) {
37445a814231SPetr Mladek 		if (!(con->flags & CON_BOOT))
37455a814231SPetr Mladek 			continue;
37465a814231SPetr Mladek 
37475a814231SPetr Mladek 		/* Check addresses that might be used for enabled consoles. */
37485a814231SPetr Mladek 		if (init_section_intersects(con, sizeof(*con)) ||
37495a814231SPetr Mladek 		    init_section_contains(con->write, 0) ||
37505a814231SPetr Mladek 		    init_section_contains(con->read, 0) ||
37515a814231SPetr Mladek 		    init_section_contains(con->device, 0) ||
37525a814231SPetr Mladek 		    init_section_contains(con->unblank, 0) ||
37535a814231SPetr Mladek 		    init_section_contains(con->data, 0)) {
375481cc26f2SThierry Reding 			/*
37552b1be689SMatt Redfearn 			 * Please, consider moving the reported consoles out
37562b1be689SMatt Redfearn 			 * of the init section.
375781cc26f2SThierry Reding 			 */
37582b1be689SMatt Redfearn 			pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
37592b1be689SMatt Redfearn 				con->name, con->index);
37604dc64682SJohn Ogness 			unregister_console_locked(con);
3761b9ee979eSJoe Perches 		}
3762b9ee979eSJoe Perches 	}
37634dc64682SJohn Ogness 	console_list_unlock();
3764d9a4af56SThomas Gleixner 
376590b14889SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
376690b14889SSebastian Andrzej Siewior 					console_cpu_notify);
376790b14889SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
376890b14889SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
376990b14889SSebastian Andrzej Siewior 					console_cpu_notify, NULL);
377090b14889SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
3771faaa357aSXiaoming Ni 	printk_sysctl_init();
3772b9ee979eSJoe Perches 	return 0;
3773b9ee979eSJoe Perches }
3774b9ee979eSJoe Perches late_initcall(printk_late_init);
3775b9ee979eSJoe Perches 
3776b9ee979eSJoe Perches #if defined CONFIG_PRINTK
37773b604ca8SJohn Ogness /* If @con is specified, only wait for that console. Otherwise wait for all. */
__pr_flush(struct console * con,int timeout_ms,bool reset_on_progress)37783b604ca8SJohn Ogness static bool __pr_flush(struct console *con, int timeout_ms, bool reset_on_progress)
37793b604ca8SJohn Ogness {
37803b604ca8SJohn Ogness 	int remaining = timeout_ms;
37813b604ca8SJohn Ogness 	struct console *c;
37823b604ca8SJohn Ogness 	u64 last_diff = 0;
37833b604ca8SJohn Ogness 	u64 printk_seq;
3784eb7f1ed2SJohn Ogness 	int cookie;
37853b604ca8SJohn Ogness 	u64 diff;
37863b604ca8SJohn Ogness 	u64 seq;
37873b604ca8SJohn Ogness 
37883b604ca8SJohn Ogness 	might_sleep();
37893b604ca8SJohn Ogness 
37903b604ca8SJohn Ogness 	seq = prb_next_seq(prb);
37913b604ca8SJohn Ogness 
3792054c22bdSJohn Ogness 	/* Flush the consoles so that records up to @seq are printed. */
3793054c22bdSJohn Ogness 	console_lock();
3794054c22bdSJohn Ogness 	console_unlock();
3795054c22bdSJohn Ogness 
37963b604ca8SJohn Ogness 	for (;;) {
37973b604ca8SJohn Ogness 		diff = 0;
37983b604ca8SJohn Ogness 
3799eb7f1ed2SJohn Ogness 		/*
3800eb7f1ed2SJohn Ogness 		 * Hold the console_lock to guarantee safe access to
3801054c22bdSJohn Ogness 		 * console->seq. Releasing console_lock flushes more
3802054c22bdSJohn Ogness 		 * records in case @seq is still not printed on all
3803054c22bdSJohn Ogness 		 * usable consoles.
3804eb7f1ed2SJohn Ogness 		 */
38053b604ca8SJohn Ogness 		console_lock();
38069023ca08SJohn Ogness 
3807eb7f1ed2SJohn Ogness 		cookie = console_srcu_read_lock();
3808eb7f1ed2SJohn Ogness 		for_each_console_srcu(c) {
38093b604ca8SJohn Ogness 			if (con && con != c)
38103b604ca8SJohn Ogness 				continue;
38119e70a5e1SJohn Ogness 			/*
38129e70a5e1SJohn Ogness 			 * If consoles are not usable, it cannot be expected
38139e70a5e1SJohn Ogness 			 * that they make forward progress, so only increment
38149e70a5e1SJohn Ogness 			 * @diff for usable consoles.
38159e70a5e1SJohn Ogness 			 */
38163b604ca8SJohn Ogness 			if (!console_is_usable(c))
38173b604ca8SJohn Ogness 				continue;
38183b604ca8SJohn Ogness 			printk_seq = c->seq;
38193b604ca8SJohn Ogness 			if (printk_seq < seq)
38203b604ca8SJohn Ogness 				diff += seq - printk_seq;
38213b604ca8SJohn Ogness 		}
3822eb7f1ed2SJohn Ogness 		console_srcu_read_unlock(cookie);
38233b604ca8SJohn Ogness 
38249e70a5e1SJohn Ogness 		if (diff != last_diff && reset_on_progress)
38253b604ca8SJohn Ogness 			remaining = timeout_ms;
38263b604ca8SJohn Ogness 
38279023ca08SJohn Ogness 		console_unlock();
38289023ca08SJohn Ogness 
38299e70a5e1SJohn Ogness 		/* Note: @diff is 0 if there are no usable consoles. */
38303b604ca8SJohn Ogness 		if (diff == 0 || remaining == 0)
38313b604ca8SJohn Ogness 			break;
38323b604ca8SJohn Ogness 
38333b604ca8SJohn Ogness 		if (remaining < 0) {
38343b604ca8SJohn Ogness 			/* no timeout limit */
38353b604ca8SJohn Ogness 			msleep(100);
38363b604ca8SJohn Ogness 		} else if (remaining < 100) {
38373b604ca8SJohn Ogness 			msleep(remaining);
38383b604ca8SJohn Ogness 			remaining = 0;
38393b604ca8SJohn Ogness 		} else {
38403b604ca8SJohn Ogness 			msleep(100);
38413b604ca8SJohn Ogness 			remaining -= 100;
38423b604ca8SJohn Ogness 		}
38433b604ca8SJohn Ogness 
38443b604ca8SJohn Ogness 		last_diff = diff;
38453b604ca8SJohn Ogness 	}
38463b604ca8SJohn Ogness 
38473b604ca8SJohn Ogness 	return (diff == 0);
38483b604ca8SJohn Ogness }
38493b604ca8SJohn Ogness 
38503b604ca8SJohn Ogness /**
38513b604ca8SJohn Ogness  * pr_flush() - Wait for printing threads to catch up.
38523b604ca8SJohn Ogness  *
38533b604ca8SJohn Ogness  * @timeout_ms:        The maximum time (in ms) to wait.
38543b604ca8SJohn Ogness  * @reset_on_progress: Reset the timeout if forward progress is seen.
38553b604ca8SJohn Ogness  *
38563b604ca8SJohn Ogness  * A value of 0 for @timeout_ms means no waiting will occur. A value of -1
38573b604ca8SJohn Ogness  * represents infinite waiting.
38583b604ca8SJohn Ogness  *
38593b604ca8SJohn Ogness  * If @reset_on_progress is true, the timeout will be reset whenever any
38603b604ca8SJohn Ogness  * printer has been seen to make some forward progress.
38613b604ca8SJohn Ogness  *
38623b604ca8SJohn Ogness  * Context: Process context. May sleep while acquiring console lock.
38639e70a5e1SJohn Ogness  * Return: true if all usable printers are caught up.
38643b604ca8SJohn Ogness  */
pr_flush(int timeout_ms,bool reset_on_progress)3865c60ba2d3SThomas Gleixner static bool pr_flush(int timeout_ms, bool reset_on_progress)
38663b604ca8SJohn Ogness {
38673b604ca8SJohn Ogness 	return __pr_flush(NULL, timeout_ms, reset_on_progress);
38683b604ca8SJohn Ogness }
38693b604ca8SJohn Ogness 
3870b9ee979eSJoe Perches /*
3871b9ee979eSJoe Perches  * Delayed printk version, for scheduler-internal messages:
3872b9ee979eSJoe Perches  */
3873b9ee979eSJoe Perches #define PRINTK_PENDING_WAKEUP	0x01
38745831788aSPetr Mladek #define PRINTK_PENDING_OUTPUT	0x02
3875b9ee979eSJoe Perches 
3876b9ee979eSJoe Perches static DEFINE_PER_CPU(int, printk_pending);
3877b9ee979eSJoe Perches 
wake_up_klogd_work_func(struct irq_work * irq_work)3878b9ee979eSJoe Perches static void wake_up_klogd_work_func(struct irq_work *irq_work)
3879b9ee979eSJoe Perches {
38802ba3673dSJohn Ogness 	int pending = this_cpu_xchg(printk_pending, 0);
3881b9ee979eSJoe Perches 
38825831788aSPetr Mladek 	if (pending & PRINTK_PENDING_OUTPUT) {
3883458df9fdSSteven Rostedt 		/* If trylock fails, someone else is doing the printing */
3884458df9fdSSteven Rostedt 		if (console_trylock())
3885458df9fdSSteven Rostedt 			console_unlock();
3886b9ee979eSJoe Perches 	}
3887b9ee979eSJoe Perches 
3888b9ee979eSJoe Perches 	if (pending & PRINTK_PENDING_WAKEUP)
3889809631e2SJohn Ogness 		wake_up_interruptible(&log_wait);
3890b9ee979eSJoe Perches }
3891b9ee979eSJoe Perches 
38927a9f50a0SPeter Zijlstra static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) =
38937a9f50a0SPeter Zijlstra 	IRQ_WORK_INIT_LAZY(wake_up_klogd_work_func);
3894b9ee979eSJoe Perches 
__wake_up_klogd(int val)38955341b93dSJohn Ogness static void __wake_up_klogd(int val)
3896b9ee979eSJoe Perches {
3897ab6f762fSSergey Senozhatsky 	if (!printk_percpu_data_ready())
3898ab6f762fSSergey Senozhatsky 		return;
3899ab6f762fSSergey Senozhatsky 
3900b9ee979eSJoe Perches 	preempt_disable();
39011f5d7830SJohn Ogness 	/*
39021f5d7830SJohn Ogness 	 * Guarantee any new records can be seen by tasks preparing to wait
39031f5d7830SJohn Ogness 	 * before this context checks if the wait queue is empty.
39041f5d7830SJohn Ogness 	 *
39051f5d7830SJohn Ogness 	 * The full memory barrier within wq_has_sleeper() pairs with the full
39061f5d7830SJohn Ogness 	 * memory barrier within set_current_state() of
39071f5d7830SJohn Ogness 	 * prepare_to_wait_event(), which is called after ___wait_event() adds
39081f5d7830SJohn Ogness 	 * the waiter but before it has checked the wait condition.
39091f5d7830SJohn Ogness 	 *
39105831788aSPetr Mladek 	 * This pairs with devkmsg_read:A and syslog_print:A.
39111f5d7830SJohn Ogness 	 */
39125341b93dSJohn Ogness 	if (wq_has_sleeper(&log_wait) || /* LMM(__wake_up_klogd:A) */
39135831788aSPetr Mladek 	    (val & PRINTK_PENDING_OUTPUT)) {
39145341b93dSJohn Ogness 		this_cpu_or(printk_pending, val);
3915bb964a92SChristoph Lameter 		irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3916b9ee979eSJoe Perches 	}
3917b9ee979eSJoe Perches 	preempt_enable();
3918b9ee979eSJoe Perches }
3919b9ee979eSJoe Perches 
3920696ffaf5SJohn Ogness /**
3921696ffaf5SJohn Ogness  * wake_up_klogd - Wake kernel logging daemon
3922696ffaf5SJohn Ogness  *
3923696ffaf5SJohn Ogness  * Use this function when new records have been added to the ringbuffer
3924696ffaf5SJohn Ogness  * and the console printing of those records has already occurred or is
3925696ffaf5SJohn Ogness  * known to be handled by some other context. This function will only
3926696ffaf5SJohn Ogness  * wake the logging daemon.
3927696ffaf5SJohn Ogness  *
3928696ffaf5SJohn Ogness  * Context: Any context.
3929696ffaf5SJohn Ogness  */
wake_up_klogd(void)39305341b93dSJohn Ogness void wake_up_klogd(void)
39315341b93dSJohn Ogness {
39325341b93dSJohn Ogness 	__wake_up_klogd(PRINTK_PENDING_WAKEUP);
39335341b93dSJohn Ogness }
39345341b93dSJohn Ogness 
3935696ffaf5SJohn Ogness /**
3936696ffaf5SJohn Ogness  * defer_console_output - Wake kernel logging daemon and trigger
3937696ffaf5SJohn Ogness  *	console printing in a deferred context
3938696ffaf5SJohn Ogness  *
3939696ffaf5SJohn Ogness  * Use this function when new records have been added to the ringbuffer,
3940696ffaf5SJohn Ogness  * this context is responsible for console printing those records, but
3941696ffaf5SJohn Ogness  * the current context is not allowed to perform the console printing.
3942696ffaf5SJohn Ogness  * Trigger an irq_work context to perform the console printing. This
3943696ffaf5SJohn Ogness  * function also wakes the logging daemon.
3944696ffaf5SJohn Ogness  *
3945696ffaf5SJohn Ogness  * Context: Any context.
3946696ffaf5SJohn Ogness  */
defer_console_output(void)3947a338f84dSPetr Mladek void defer_console_output(void)
3948a338f84dSPetr Mladek {
39495341b93dSJohn Ogness 	/*
39505341b93dSJohn Ogness 	 * New messages may have been added directly to the ringbuffer
39515341b93dSJohn Ogness 	 * using vprintk_store(), so wake any waiters as well.
39525341b93dSJohn Ogness 	 */
39535831788aSPetr Mladek 	__wake_up_klogd(PRINTK_PENDING_WAKEUP | PRINTK_PENDING_OUTPUT);
3954a338f84dSPetr Mladek }
3955a338f84dSPetr Mladek 
printk_trigger_flush(void)39565d5e4522SNicholas Piggin void printk_trigger_flush(void)
39575d5e4522SNicholas Piggin {
39585d5e4522SNicholas Piggin 	defer_console_output();
39595d5e4522SNicholas Piggin }
39605d5e4522SNicholas Piggin 
vprintk_deferred(const char * fmt,va_list args)3961719f6a70SPetr Mladek int vprintk_deferred(const char *fmt, va_list args)
3962719f6a70SPetr Mladek {
3963696ffaf5SJohn Ogness 	return vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
3964719f6a70SPetr Mladek }
3965719f6a70SPetr Mladek 
_printk_deferred(const char * fmt,...)396633701557SChris Down int _printk_deferred(const char *fmt, ...)
3967b9ee979eSJoe Perches {
3968b9ee979eSJoe Perches 	va_list args;
3969b9ee979eSJoe Perches 	int r;
3970b9ee979eSJoe Perches 
3971b9ee979eSJoe Perches 	va_start(args, fmt);
3972719f6a70SPetr Mladek 	r = vprintk_deferred(fmt, args);
3973b9ee979eSJoe Perches 	va_end(args);
3974b9ee979eSJoe Perches 
3975b9ee979eSJoe Perches 	return r;
3976b9ee979eSJoe Perches }
3977b9ee979eSJoe Perches 
3978b9ee979eSJoe Perches /*
3979b9ee979eSJoe Perches  * printk rate limiting, lifted from the networking subsystem.
3980b9ee979eSJoe Perches  *
3981b9ee979eSJoe Perches  * This enforces a rate limit: not more than 10 kernel messages
3982b9ee979eSJoe Perches  * every 5s to make a denial-of-service attack impossible.
3983b9ee979eSJoe Perches  */
3984b9ee979eSJoe Perches DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3985b9ee979eSJoe Perches 
__printk_ratelimit(const char * func)3986b9ee979eSJoe Perches int __printk_ratelimit(const char *func)
3987b9ee979eSJoe Perches {
3988b9ee979eSJoe Perches 	return ___ratelimit(&printk_ratelimit_state, func);
3989b9ee979eSJoe Perches }
3990b9ee979eSJoe Perches EXPORT_SYMBOL(__printk_ratelimit);
3991b9ee979eSJoe Perches 
3992b9ee979eSJoe Perches /**
3993b9ee979eSJoe Perches  * printk_timed_ratelimit - caller-controlled printk ratelimiting
3994b9ee979eSJoe Perches  * @caller_jiffies: pointer to caller's state
3995b9ee979eSJoe Perches  * @interval_msecs: minimum interval between prints
3996b9ee979eSJoe Perches  *
3997b9ee979eSJoe Perches  * printk_timed_ratelimit() returns true if more than @interval_msecs
3998b9ee979eSJoe Perches  * milliseconds have elapsed since the last time printk_timed_ratelimit()
3999b9ee979eSJoe Perches  * returned true.
4000b9ee979eSJoe Perches  */
printk_timed_ratelimit(unsigned long * caller_jiffies,unsigned int interval_msecs)4001b9ee979eSJoe Perches bool printk_timed_ratelimit(unsigned long *caller_jiffies,
4002b9ee979eSJoe Perches 			unsigned int interval_msecs)
4003b9ee979eSJoe Perches {
4004249771b8SAlex Elder 	unsigned long elapsed = jiffies - *caller_jiffies;
4005249771b8SAlex Elder 
4006249771b8SAlex Elder 	if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
4007249771b8SAlex Elder 		return false;
4008249771b8SAlex Elder 
4009b9ee979eSJoe Perches 	*caller_jiffies = jiffies;
4010b9ee979eSJoe Perches 	return true;
4011b9ee979eSJoe Perches }
4012b9ee979eSJoe Perches EXPORT_SYMBOL(printk_timed_ratelimit);
4013b9ee979eSJoe Perches 
4014b9ee979eSJoe Perches static DEFINE_SPINLOCK(dump_list_lock);
4015b9ee979eSJoe Perches static LIST_HEAD(dump_list);
4016b9ee979eSJoe Perches 
4017b9ee979eSJoe Perches /**
4018b9ee979eSJoe Perches  * kmsg_dump_register - register a kernel log dumper.
4019b9ee979eSJoe Perches  * @dumper: pointer to the kmsg_dumper structure
4020b9ee979eSJoe Perches  *
4021b9ee979eSJoe Perches  * Adds a kernel log dumper to the system. The dump callback in the
4022b9ee979eSJoe Perches  * structure will be called when the kernel oopses or panics and must be
4023b9ee979eSJoe Perches  * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
4024b9ee979eSJoe Perches  */
kmsg_dump_register(struct kmsg_dumper * dumper)4025b9ee979eSJoe Perches int kmsg_dump_register(struct kmsg_dumper *dumper)
4026b9ee979eSJoe Perches {
4027b9ee979eSJoe Perches 	unsigned long flags;
4028b9ee979eSJoe Perches 	int err = -EBUSY;
4029b9ee979eSJoe Perches 
4030b9ee979eSJoe Perches 	/* The dump callback needs to be set */
4031b9ee979eSJoe Perches 	if (!dumper->dump)
4032b9ee979eSJoe Perches 		return -EINVAL;
4033b9ee979eSJoe Perches 
4034b9ee979eSJoe Perches 	spin_lock_irqsave(&dump_list_lock, flags);
4035b9ee979eSJoe Perches 	/* Don't allow registering multiple times */
4036b9ee979eSJoe Perches 	if (!dumper->registered) {
4037b9ee979eSJoe Perches 		dumper->registered = 1;
4038b9ee979eSJoe Perches 		list_add_tail_rcu(&dumper->list, &dump_list);
4039b9ee979eSJoe Perches 		err = 0;
4040b9ee979eSJoe Perches 	}
4041b9ee979eSJoe Perches 	spin_unlock_irqrestore(&dump_list_lock, flags);
4042b9ee979eSJoe Perches 
4043b9ee979eSJoe Perches 	return err;
4044b9ee979eSJoe Perches }
4045b9ee979eSJoe Perches EXPORT_SYMBOL_GPL(kmsg_dump_register);
4046b9ee979eSJoe Perches 
4047b9ee979eSJoe Perches /**
4048b9ee979eSJoe Perches  * kmsg_dump_unregister - unregister a kmsg dumper.
4049b9ee979eSJoe Perches  * @dumper: pointer to the kmsg_dumper structure
4050b9ee979eSJoe Perches  *
4051b9ee979eSJoe Perches  * Removes a dump device from the system. Returns zero on success and
4052b9ee979eSJoe Perches  * %-EINVAL otherwise.
4053b9ee979eSJoe Perches  */
kmsg_dump_unregister(struct kmsg_dumper * dumper)4054b9ee979eSJoe Perches int kmsg_dump_unregister(struct kmsg_dumper *dumper)
4055b9ee979eSJoe Perches {
4056b9ee979eSJoe Perches 	unsigned long flags;
4057b9ee979eSJoe Perches 	int err = -EINVAL;
4058b9ee979eSJoe Perches 
4059b9ee979eSJoe Perches 	spin_lock_irqsave(&dump_list_lock, flags);
4060b9ee979eSJoe Perches 	if (dumper->registered) {
4061b9ee979eSJoe Perches 		dumper->registered = 0;
4062b9ee979eSJoe Perches 		list_del_rcu(&dumper->list);
4063b9ee979eSJoe Perches 		err = 0;
4064b9ee979eSJoe Perches 	}
4065b9ee979eSJoe Perches 	spin_unlock_irqrestore(&dump_list_lock, flags);
4066b9ee979eSJoe Perches 	synchronize_rcu();
4067b9ee979eSJoe Perches 
4068b9ee979eSJoe Perches 	return err;
4069b9ee979eSJoe Perches }
4070b9ee979eSJoe Perches EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
4071b9ee979eSJoe Perches 
4072b9ee979eSJoe Perches static bool always_kmsg_dump;
4073b9ee979eSJoe Perches module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
4074b9ee979eSJoe Perches 
kmsg_dump_reason_str(enum kmsg_dump_reason reason)4075fb13cb8aSKees Cook const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
4076fb13cb8aSKees Cook {
4077fb13cb8aSKees Cook 	switch (reason) {
4078fb13cb8aSKees Cook 	case KMSG_DUMP_PANIC:
4079fb13cb8aSKees Cook 		return "Panic";
4080fb13cb8aSKees Cook 	case KMSG_DUMP_OOPS:
4081fb13cb8aSKees Cook 		return "Oops";
4082fb13cb8aSKees Cook 	case KMSG_DUMP_EMERG:
4083fb13cb8aSKees Cook 		return "Emergency";
4084fb13cb8aSKees Cook 	case KMSG_DUMP_SHUTDOWN:
4085fb13cb8aSKees Cook 		return "Shutdown";
4086fb13cb8aSKees Cook 	default:
4087fb13cb8aSKees Cook 		return "Unknown";
4088fb13cb8aSKees Cook 	}
4089fb13cb8aSKees Cook }
4090fb13cb8aSKees Cook EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
4091fb13cb8aSKees Cook 
4092b9ee979eSJoe Perches /**
4093b9ee979eSJoe Perches  * kmsg_dump - dump kernel log to kernel message dumpers.
4094b9ee979eSJoe Perches  * @reason: the reason (oops, panic etc) for dumping
4095b9ee979eSJoe Perches  *
4096b9ee979eSJoe Perches  * Call each of the registered dumper's dump() callback, which can
4097b9ee979eSJoe Perches  * retrieve the kmsg records with kmsg_dump_get_line() or
4098b9ee979eSJoe Perches  * kmsg_dump_get_buffer().
4099b9ee979eSJoe Perches  */
kmsg_dump(enum kmsg_dump_reason reason)4100b9ee979eSJoe Perches void kmsg_dump(enum kmsg_dump_reason reason)
4101b9ee979eSJoe Perches {
4102b9ee979eSJoe Perches 	struct kmsg_dumper *dumper;
4103b9ee979eSJoe Perches 
4104b9ee979eSJoe Perches 	rcu_read_lock();
4105b9ee979eSJoe Perches 	list_for_each_entry_rcu(dumper, &dump_list, list) {
4106b1f6f161SPavel Tatashin 		enum kmsg_dump_reason max_reason = dumper->max_reason;
4107b1f6f161SPavel Tatashin 
4108b1f6f161SPavel Tatashin 		/*
4109b1f6f161SPavel Tatashin 		 * If client has not provided a specific max_reason, default
4110b1f6f161SPavel Tatashin 		 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
4111b1f6f161SPavel Tatashin 		 */
4112b1f6f161SPavel Tatashin 		if (max_reason == KMSG_DUMP_UNDEF) {
4113b1f6f161SPavel Tatashin 			max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
4114b1f6f161SPavel Tatashin 							KMSG_DUMP_OOPS;
4115b1f6f161SPavel Tatashin 		}
4116b1f6f161SPavel Tatashin 		if (reason > max_reason)
4117b9ee979eSJoe Perches 			continue;
4118b9ee979eSJoe Perches 
4119b9ee979eSJoe Perches 		/* invoke dumper which will iterate over records */
4120b9ee979eSJoe Perches 		dumper->dump(dumper, reason);
4121b9ee979eSJoe Perches 	}
4122b9ee979eSJoe Perches 	rcu_read_unlock();
4123b9ee979eSJoe Perches }
4124b9ee979eSJoe Perches 
4125b9ee979eSJoe Perches /**
4126a4f98765SJohn Ogness  * kmsg_dump_get_line - retrieve one kmsg log line
4127f9f3f02dSJohn Ogness  * @iter: kmsg dump iterator
4128b9ee979eSJoe Perches  * @syslog: include the "<4>" prefixes
4129b9ee979eSJoe Perches  * @line: buffer to copy the line to
4130b9ee979eSJoe Perches  * @size: maximum size of the buffer
4131b9ee979eSJoe Perches  * @len: length of line placed into buffer
4132b9ee979eSJoe Perches  *
4133b9ee979eSJoe Perches  * Start at the beginning of the kmsg buffer, with the oldest kmsg
4134b9ee979eSJoe Perches  * record, and copy one record into the provided buffer.
4135b9ee979eSJoe Perches  *
4136b9ee979eSJoe Perches  * Consecutive calls will return the next available record moving
4137b9ee979eSJoe Perches  * towards the end of the buffer with the youngest messages.
4138b9ee979eSJoe Perches  *
4139b9ee979eSJoe Perches  * A return value of FALSE indicates that there are no more records to
4140b9ee979eSJoe Perches  * read.
4141b9ee979eSJoe Perches  */
kmsg_dump_get_line(struct kmsg_dump_iter * iter,bool syslog,char * line,size_t size,size_t * len)4142a4f98765SJohn Ogness bool kmsg_dump_get_line(struct kmsg_dump_iter *iter, bool syslog,
4143b9ee979eSJoe Perches 			char *line, size_t size, size_t *len)
4144b9ee979eSJoe Perches {
4145f9f3f02dSJohn Ogness 	u64 min_seq = latched_seq_read_nolock(&clear_seq);
4146896fbe20SJohn Ogness 	struct printk_info info;
4147896fbe20SJohn Ogness 	unsigned int line_count;
4148896fbe20SJohn Ogness 	struct printk_record r;
4149b9ee979eSJoe Perches 	size_t l = 0;
4150b9ee979eSJoe Perches 	bool ret = false;
4151b9ee979eSJoe Perches 
4152f9f3f02dSJohn Ogness 	if (iter->cur_seq < min_seq)
4153f9f3f02dSJohn Ogness 		iter->cur_seq = min_seq;
4154f9f3f02dSJohn Ogness 
4155f35efc78SJohn Ogness 	prb_rec_init_rd(&r, &info, line, size);
4156896fbe20SJohn Ogness 
4157896fbe20SJohn Ogness 	/* Read text or count text lines? */
4158896fbe20SJohn Ogness 	if (line) {
4159f9f3f02dSJohn Ogness 		if (!prb_read_valid(prb, iter->cur_seq, &r))
4160896fbe20SJohn Ogness 			goto out;
4161896fbe20SJohn Ogness 		l = record_print_text(&r, syslog, printk_time);
4162896fbe20SJohn Ogness 	} else {
4163f9f3f02dSJohn Ogness 		if (!prb_read_valid_info(prb, iter->cur_seq,
4164896fbe20SJohn Ogness 					 &info, &line_count)) {
4165896fbe20SJohn Ogness 			goto out;
4166896fbe20SJohn Ogness 		}
4167896fbe20SJohn Ogness 		l = get_record_print_text_size(&info, line_count, syslog,
4168896fbe20SJohn Ogness 					       printk_time);
4169896fbe20SJohn Ogness 
4170b9ee979eSJoe Perches 	}
4171b9ee979eSJoe Perches 
4172f9f3f02dSJohn Ogness 	iter->cur_seq = r.info->seq + 1;
4173b9ee979eSJoe Perches 	ret = true;
4174b9ee979eSJoe Perches out:
4175b9ee979eSJoe Perches 	if (len)
4176b9ee979eSJoe Perches 		*len = l;
4177b9ee979eSJoe Perches 	return ret;
4178b9ee979eSJoe Perches }
4179b9ee979eSJoe Perches EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
4180b9ee979eSJoe Perches 
4181b9ee979eSJoe Perches /**
4182b9ee979eSJoe Perches  * kmsg_dump_get_buffer - copy kmsg log lines
4183f9f3f02dSJohn Ogness  * @iter: kmsg dump iterator
4184b9ee979eSJoe Perches  * @syslog: include the "<4>" prefixes
4185b9ee979eSJoe Perches  * @buf: buffer to copy the line to
4186b9ee979eSJoe Perches  * @size: maximum size of the buffer
4187726b5097SJohn Ogness  * @len_out: length of line placed into buffer
4188b9ee979eSJoe Perches  *
4189b9ee979eSJoe Perches  * Start at the end of the kmsg buffer and fill the provided buffer
4190547bbf7dSRandy Dunlap  * with as many of the *youngest* kmsg records that fit into it.
4191b9ee979eSJoe Perches  * If the buffer is large enough, all available kmsg records will be
4192b9ee979eSJoe Perches  * copied with a single call.
4193b9ee979eSJoe Perches  *
4194b9ee979eSJoe Perches  * Consecutive calls will fill the buffer with the next block of
4195b9ee979eSJoe Perches  * available older records, not including the earlier retrieved ones.
4196b9ee979eSJoe Perches  *
4197b9ee979eSJoe Perches  * A return value of FALSE indicates that there are no more records to
4198b9ee979eSJoe Perches  * read.
4199b9ee979eSJoe Perches  */
kmsg_dump_get_buffer(struct kmsg_dump_iter * iter,bool syslog,char * buf,size_t size,size_t * len_out)4200f9f3f02dSJohn Ogness bool kmsg_dump_get_buffer(struct kmsg_dump_iter *iter, bool syslog,
4201726b5097SJohn Ogness 			  char *buf, size_t size, size_t *len_out)
4202b9ee979eSJoe Perches {
4203f9f3f02dSJohn Ogness 	u64 min_seq = latched_seq_read_nolock(&clear_seq);
4204896fbe20SJohn Ogness 	struct printk_info info;
4205896fbe20SJohn Ogness 	struct printk_record r;
4206b9ee979eSJoe Perches 	u64 seq;
4207b9ee979eSJoe Perches 	u64 next_seq;
4208726b5097SJohn Ogness 	size_t len = 0;
4209b9ee979eSJoe Perches 	bool ret = false;
4210e80c1a9dSTetsuo Handa 	bool time = printk_time;
4211b9ee979eSJoe Perches 
42125f6c7648SJohn Ogness 	if (!buf || !size)
4213b9ee979eSJoe Perches 		goto out;
4214b9ee979eSJoe Perches 
4215f9f3f02dSJohn Ogness 	if (iter->cur_seq < min_seq)
4216f9f3f02dSJohn Ogness 		iter->cur_seq = min_seq;
4217f9f3f02dSJohn Ogness 
4218f9f3f02dSJohn Ogness 	if (prb_read_valid_info(prb, iter->cur_seq, &info, NULL)) {
4219f9f3f02dSJohn Ogness 		if (info.seq != iter->cur_seq) {
4220b9ee979eSJoe Perches 			/* messages are gone, move to first available one */
4221f9f3f02dSJohn Ogness 			iter->cur_seq = info.seq;
422213791c80SJohn Ogness 		}
4223b9ee979eSJoe Perches 	}
4224b9ee979eSJoe Perches 
4225b9ee979eSJoe Perches 	/* last entry */
422693d102f0SJohn Ogness 	if (iter->cur_seq >= iter->next_seq)
4227b9ee979eSJoe Perches 		goto out;
4228b9ee979eSJoe Perches 
4229726b5097SJohn Ogness 	/*
4230726b5097SJohn Ogness 	 * Find first record that fits, including all following records,
42314260e0e5SJohn Ogness 	 * into the user-provided buffer for this dump. Pass in size-1
42324260e0e5SJohn Ogness 	 * because this function (by way of record_print_text()) will
42334260e0e5SJohn Ogness 	 * not write more than size-1 bytes of text into @buf.
4234726b5097SJohn Ogness 	 */
4235f9f3f02dSJohn Ogness 	seq = find_first_fitting_seq(iter->cur_seq, iter->next_seq,
42364260e0e5SJohn Ogness 				     size - 1, syslog, time);
4237b9ee979eSJoe Perches 
4238726b5097SJohn Ogness 	/*
4239726b5097SJohn Ogness 	 * Next kmsg_dump_get_buffer() invocation will dump block of
4240726b5097SJohn Ogness 	 * older records stored right before this one.
4241726b5097SJohn Ogness 	 */
4242b9ee979eSJoe Perches 	next_seq = seq;
4243b9ee979eSJoe Perches 
4244726b5097SJohn Ogness 	prb_rec_init_rd(&r, &info, buf, size);
4245726b5097SJohn Ogness 
4246726b5097SJohn Ogness 	len = 0;
4247726b5097SJohn Ogness 	prb_for_each_record(seq, prb, seq, &r) {
4248f9f3f02dSJohn Ogness 		if (r.info->seq >= iter->next_seq)
4249896fbe20SJohn Ogness 			break;
4250b9ee979eSJoe Perches 
4251726b5097SJohn Ogness 		len += record_print_text(&r, syslog, time);
4252896fbe20SJohn Ogness 
4253726b5097SJohn Ogness 		/* Adjust record to store to remaining buffer space. */
4254726b5097SJohn Ogness 		prb_rec_init_rd(&r, &info, buf + len, size - len);
4255b9ee979eSJoe Perches 	}
4256b9ee979eSJoe Perches 
4257f9f3f02dSJohn Ogness 	iter->next_seq = next_seq;
4258b9ee979eSJoe Perches 	ret = true;
4259b9ee979eSJoe Perches out:
4260726b5097SJohn Ogness 	if (len_out)
4261726b5097SJohn Ogness 		*len_out = len;
4262b9ee979eSJoe Perches 	return ret;
4263b9ee979eSJoe Perches }
4264b9ee979eSJoe Perches EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
4265b9ee979eSJoe Perches 
4266b9ee979eSJoe Perches /**
4267325606afSEthon Paul  * kmsg_dump_rewind - reset the iterator
4268f9f3f02dSJohn Ogness  * @iter: kmsg dump iterator
4269b9ee979eSJoe Perches  *
4270b9ee979eSJoe Perches  * Reset the dumper's iterator so that kmsg_dump_get_line() and
4271b9ee979eSJoe Perches  * kmsg_dump_get_buffer() can be called again and used multiple
4272b9ee979eSJoe Perches  * times within the same dumper.dump() callback.
4273b9ee979eSJoe Perches  */
kmsg_dump_rewind(struct kmsg_dump_iter * iter)4274f9f3f02dSJohn Ogness void kmsg_dump_rewind(struct kmsg_dump_iter *iter)
4275b9ee979eSJoe Perches {
4276a4f98765SJohn Ogness 	iter->cur_seq = latched_seq_read_nolock(&clear_seq);
4277a4f98765SJohn Ogness 	iter->next_seq = prb_next_seq(prb);
4278b9ee979eSJoe Perches }
4279b9ee979eSJoe Perches EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
4280b9ee979eSJoe Perches 
4281b9ee979eSJoe Perches #endif
4282766c268bSJohn Ogness 
4283766c268bSJohn Ogness #ifdef CONFIG_SMP
4284faebd693SJohn Ogness static atomic_t printk_cpu_sync_owner = ATOMIC_INIT(-1);
4285faebd693SJohn Ogness static atomic_t printk_cpu_sync_nested = ATOMIC_INIT(0);
4286766c268bSJohn Ogness 
4287766c268bSJohn Ogness /**
4288faebd693SJohn Ogness  * __printk_cpu_sync_wait() - Busy wait until the printk cpu-reentrant
4289766c268bSJohn Ogness  *                            spinning lock is not owned by any CPU.
4290766c268bSJohn Ogness  *
4291766c268bSJohn Ogness  * Context: Any context.
4292766c268bSJohn Ogness  */
__printk_cpu_sync_wait(void)4293faebd693SJohn Ogness void __printk_cpu_sync_wait(void)
4294766c268bSJohn Ogness {
4295766c268bSJohn Ogness 	do {
4296766c268bSJohn Ogness 		cpu_relax();
4297faebd693SJohn Ogness 	} while (atomic_read(&printk_cpu_sync_owner) != -1);
4298766c268bSJohn Ogness }
4299faebd693SJohn Ogness EXPORT_SYMBOL(__printk_cpu_sync_wait);
4300766c268bSJohn Ogness 
4301766c268bSJohn Ogness /**
4302faebd693SJohn Ogness  * __printk_cpu_sync_try_get() - Try to acquire the printk cpu-reentrant
4303766c268bSJohn Ogness  *                               spinning lock.
4304766c268bSJohn Ogness  *
4305766c268bSJohn Ogness  * If no processor has the lock, the calling processor takes the lock and
4306766c268bSJohn Ogness  * becomes the owner. If the calling processor is already the owner of the
4307766c268bSJohn Ogness  * lock, this function succeeds immediately.
4308766c268bSJohn Ogness  *
4309766c268bSJohn Ogness  * Context: Any context. Expects interrupts to be disabled.
4310766c268bSJohn Ogness  * Return: 1 on success, otherwise 0.
4311766c268bSJohn Ogness  */
__printk_cpu_sync_try_get(void)4312faebd693SJohn Ogness int __printk_cpu_sync_try_get(void)
4313766c268bSJohn Ogness {
4314766c268bSJohn Ogness 	int cpu;
4315766c268bSJohn Ogness 	int old;
4316766c268bSJohn Ogness 
4317766c268bSJohn Ogness 	cpu = smp_processor_id();
4318766c268bSJohn Ogness 
43193342aa8eSJohn Ogness 	/*
43203342aa8eSJohn Ogness 	 * Guarantee loads and stores from this CPU when it is the lock owner
43213342aa8eSJohn Ogness 	 * are _not_ visible to the previous lock owner. This pairs with
4322faebd693SJohn Ogness 	 * __printk_cpu_sync_put:B.
43233342aa8eSJohn Ogness 	 *
43243342aa8eSJohn Ogness 	 * Memory barrier involvement:
43253342aa8eSJohn Ogness 	 *
4326faebd693SJohn Ogness 	 * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4327faebd693SJohn Ogness 	 * then __printk_cpu_sync_put:A can never read from
4328faebd693SJohn Ogness 	 * __printk_cpu_sync_try_get:B.
43293342aa8eSJohn Ogness 	 *
43303342aa8eSJohn Ogness 	 * Relies on:
43313342aa8eSJohn Ogness 	 *
4332faebd693SJohn Ogness 	 * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
43333342aa8eSJohn Ogness 	 * of the previous CPU
43343342aa8eSJohn Ogness 	 *    matching
4335faebd693SJohn Ogness 	 * ACQUIRE from __printk_cpu_sync_try_get:A to
4336faebd693SJohn Ogness 	 * __printk_cpu_sync_try_get:B of this CPU
43373342aa8eSJohn Ogness 	 */
4338faebd693SJohn Ogness 	old = atomic_cmpxchg_acquire(&printk_cpu_sync_owner, -1,
4339faebd693SJohn Ogness 				     cpu); /* LMM(__printk_cpu_sync_try_get:A) */
4340766c268bSJohn Ogness 	if (old == -1) {
43413342aa8eSJohn Ogness 		/*
43423342aa8eSJohn Ogness 		 * This CPU is now the owner and begins loading/storing
4343faebd693SJohn Ogness 		 * data: LMM(__printk_cpu_sync_try_get:B)
43443342aa8eSJohn Ogness 		 */
4345766c268bSJohn Ogness 		return 1;
43463342aa8eSJohn Ogness 
4347766c268bSJohn Ogness 	} else if (old == cpu) {
4348766c268bSJohn Ogness 		/* This CPU is already the owner. */
4349faebd693SJohn Ogness 		atomic_inc(&printk_cpu_sync_nested);
4350766c268bSJohn Ogness 		return 1;
4351766c268bSJohn Ogness 	}
4352766c268bSJohn Ogness 
4353766c268bSJohn Ogness 	return 0;
4354766c268bSJohn Ogness }
4355faebd693SJohn Ogness EXPORT_SYMBOL(__printk_cpu_sync_try_get);
4356766c268bSJohn Ogness 
4357766c268bSJohn Ogness /**
4358faebd693SJohn Ogness  * __printk_cpu_sync_put() - Release the printk cpu-reentrant spinning lock.
4359766c268bSJohn Ogness  *
4360766c268bSJohn Ogness  * The calling processor must be the owner of the lock.
4361766c268bSJohn Ogness  *
4362766c268bSJohn Ogness  * Context: Any context. Expects interrupts to be disabled.
4363766c268bSJohn Ogness  */
__printk_cpu_sync_put(void)4364faebd693SJohn Ogness void __printk_cpu_sync_put(void)
4365766c268bSJohn Ogness {
4366faebd693SJohn Ogness 	if (atomic_read(&printk_cpu_sync_nested)) {
4367faebd693SJohn Ogness 		atomic_dec(&printk_cpu_sync_nested);
4368766c268bSJohn Ogness 		return;
4369766c268bSJohn Ogness 	}
4370766c268bSJohn Ogness 
43713342aa8eSJohn Ogness 	/*
43723342aa8eSJohn Ogness 	 * This CPU is finished loading/storing data:
4373faebd693SJohn Ogness 	 * LMM(__printk_cpu_sync_put:A)
43743342aa8eSJohn Ogness 	 */
43753342aa8eSJohn Ogness 
43763342aa8eSJohn Ogness 	/*
43773342aa8eSJohn Ogness 	 * Guarantee loads and stores from this CPU when it was the
43783342aa8eSJohn Ogness 	 * lock owner are visible to the next lock owner. This pairs
4379faebd693SJohn Ogness 	 * with __printk_cpu_sync_try_get:A.
43803342aa8eSJohn Ogness 	 *
43813342aa8eSJohn Ogness 	 * Memory barrier involvement:
43823342aa8eSJohn Ogness 	 *
4383faebd693SJohn Ogness 	 * If __printk_cpu_sync_try_get:A reads from __printk_cpu_sync_put:B,
4384faebd693SJohn Ogness 	 * then __printk_cpu_sync_try_get:B reads from __printk_cpu_sync_put:A.
43853342aa8eSJohn Ogness 	 *
43863342aa8eSJohn Ogness 	 * Relies on:
43873342aa8eSJohn Ogness 	 *
4388faebd693SJohn Ogness 	 * RELEASE from __printk_cpu_sync_put:A to __printk_cpu_sync_put:B
43893342aa8eSJohn Ogness 	 * of this CPU
43903342aa8eSJohn Ogness 	 *    matching
4391faebd693SJohn Ogness 	 * ACQUIRE from __printk_cpu_sync_try_get:A to
4392faebd693SJohn Ogness 	 * __printk_cpu_sync_try_get:B of the next CPU
43933342aa8eSJohn Ogness 	 */
4394faebd693SJohn Ogness 	atomic_set_release(&printk_cpu_sync_owner,
4395faebd693SJohn Ogness 			   -1); /* LMM(__printk_cpu_sync_put:B) */
4396766c268bSJohn Ogness }
4397faebd693SJohn Ogness EXPORT_SYMBOL(__printk_cpu_sync_put);
4398766c268bSJohn Ogness #endif /* CONFIG_SMP */
4399