blob: 17a310dcb6d962ac71fb124c0773b72e6d088847 [file] [log] [blame]
David Brazdil0f672f62019-12-10 10:32:29 +00001// SPDX-License-Identifier: GPL-2.0-only
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002/*
3 * linux/kernel/printk.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 *
7 * Modified to make sys_syslog() more flexible: added commands to
8 * return the last 4k of kernel messages, regardless of whether
9 * they've been read or not. Added option to suppress kernel printk's
10 * to the console. Added hook for sending the console messages
11 * elsewhere, in preparation for a serial line console (someday).
12 * Ted Ts'o, 2/11/93.
13 * Modified for sysctl support, 1/8/97, Chris Horn.
14 * Fixed SMP synchronization, 08/08/99, Manfred Spraul
15 * manfred@colorfullife.com
16 * Rewrote bits to get rid of console_lock
17 * 01Mar01 Andrew Morton
18 */
19
David Brazdil0f672f62019-12-10 10:32:29 +000020#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000022#include <linux/kernel.h>
23#include <linux/mm.h>
24#include <linux/tty.h>
25#include <linux/tty_driver.h>
26#include <linux/console.h>
27#include <linux/init.h>
28#include <linux/jiffies.h>
29#include <linux/nmi.h>
30#include <linux/module.h>
31#include <linux/moduleparam.h>
32#include <linux/delay.h>
33#include <linux/smp.h>
34#include <linux/security.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000035#include <linux/memblock.h>
36#include <linux/syscalls.h>
37#include <linux/crash_core.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000038#include <linux/ratelimit.h>
39#include <linux/kmsg_dump.h>
40#include <linux/syslog.h>
41#include <linux/cpu.h>
42#include <linux/rculist.h>
43#include <linux/poll.h>
44#include <linux/irq_work.h>
45#include <linux/ctype.h>
46#include <linux/uio.h>
47#include <linux/sched/clock.h>
48#include <linux/sched/debug.h>
49#include <linux/sched/task_stack.h>
50
51#include <linux/uaccess.h>
52#include <asm/sections.h>
53
54#include <trace/events/initcall.h>
55#define CREATE_TRACE_POINTS
56#include <trace/events/printk.h>
57
Olivier Deprez157378f2022-04-04 15:47:50 +020058#include "printk_ringbuffer.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000059#include "console_cmdline.h"
60#include "braille.h"
61#include "internal.h"
62
63int console_printk[4] = {
64 CONSOLE_LOGLEVEL_DEFAULT, /* console_loglevel */
65 MESSAGE_LOGLEVEL_DEFAULT, /* default_message_loglevel */
66 CONSOLE_LOGLEVEL_MIN, /* minimum_console_loglevel */
67 CONSOLE_LOGLEVEL_DEFAULT, /* default_console_loglevel */
68};
David Brazdil0f672f62019-12-10 10:32:29 +000069EXPORT_SYMBOL_GPL(console_printk);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000070
71atomic_t ignore_console_lock_warning __read_mostly = ATOMIC_INIT(0);
72EXPORT_SYMBOL(ignore_console_lock_warning);
73
74/*
75 * Low level drivers may need that to know if they can schedule in
76 * their unblank() callback or not. So let's export it.
77 */
78int oops_in_progress;
79EXPORT_SYMBOL(oops_in_progress);
80
81/*
82 * console_sem protects the console_drivers list, and also
83 * provides serialisation for access to the entire console
84 * driver system.
85 */
86static DEFINE_SEMAPHORE(console_sem);
87struct console *console_drivers;
88EXPORT_SYMBOL_GPL(console_drivers);
89
David Brazdil0f672f62019-12-10 10:32:29 +000090/*
91 * System may need to suppress printk message under certain
92 * circumstances, like after kernel panic happens.
93 */
94int __read_mostly suppress_printk;
95
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000096#ifdef CONFIG_LOCKDEP
97static struct lockdep_map console_lock_dep_map = {
98 .name = "console_lock"
99};
100#endif
101
102enum devkmsg_log_bits {
103 __DEVKMSG_LOG_BIT_ON = 0,
104 __DEVKMSG_LOG_BIT_OFF,
105 __DEVKMSG_LOG_BIT_LOCK,
106};
107
108enum devkmsg_log_masks {
109 DEVKMSG_LOG_MASK_ON = BIT(__DEVKMSG_LOG_BIT_ON),
110 DEVKMSG_LOG_MASK_OFF = BIT(__DEVKMSG_LOG_BIT_OFF),
111 DEVKMSG_LOG_MASK_LOCK = BIT(__DEVKMSG_LOG_BIT_LOCK),
112};
113
114/* Keep both the 'on' and 'off' bits clear, i.e. ratelimit by default: */
115#define DEVKMSG_LOG_MASK_DEFAULT 0
116
117static unsigned int __read_mostly devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
118
119static int __control_devkmsg(char *str)
120{
David Brazdil0f672f62019-12-10 10:32:29 +0000121 size_t len;
122
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000123 if (!str)
124 return -EINVAL;
125
David Brazdil0f672f62019-12-10 10:32:29 +0000126 len = str_has_prefix(str, "on");
127 if (len) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000128 devkmsg_log = DEVKMSG_LOG_MASK_ON;
David Brazdil0f672f62019-12-10 10:32:29 +0000129 return len;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000130 }
David Brazdil0f672f62019-12-10 10:32:29 +0000131
132 len = str_has_prefix(str, "off");
133 if (len) {
134 devkmsg_log = DEVKMSG_LOG_MASK_OFF;
135 return len;
136 }
137
138 len = str_has_prefix(str, "ratelimit");
139 if (len) {
140 devkmsg_log = DEVKMSG_LOG_MASK_DEFAULT;
141 return len;
142 }
143
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000144 return -EINVAL;
145}
146
147static int __init control_devkmsg(char *str)
148{
Olivier Deprez92d4c212022-12-06 15:05:30 +0100149 if (__control_devkmsg(str) < 0) {
150 pr_warn("printk.devkmsg: bad option string '%s'\n", str);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000151 return 1;
Olivier Deprez92d4c212022-12-06 15:05:30 +0100152 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000153
154 /*
155 * Set sysctl string accordingly:
156 */
157 if (devkmsg_log == DEVKMSG_LOG_MASK_ON)
158 strcpy(devkmsg_log_str, "on");
159 else if (devkmsg_log == DEVKMSG_LOG_MASK_OFF)
160 strcpy(devkmsg_log_str, "off");
161 /* else "ratelimit" which is set by default. */
162
163 /*
164 * Sysctl cannot change it anymore. The kernel command line setting of
165 * this parameter is to force the setting to be permanent throughout the
166 * runtime of the system. This is a precation measure against userspace
167 * trying to be a smarta** and attempting to change it up on us.
168 */
169 devkmsg_log |= DEVKMSG_LOG_MASK_LOCK;
170
Olivier Deprez92d4c212022-12-06 15:05:30 +0100171 return 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000172}
173__setup("printk.devkmsg=", control_devkmsg);
174
175char devkmsg_log_str[DEVKMSG_STR_MAX_SIZE] = "ratelimit";
176
177int devkmsg_sysctl_set_loglvl(struct ctl_table *table, int write,
Olivier Deprez157378f2022-04-04 15:47:50 +0200178 void *buffer, size_t *lenp, loff_t *ppos)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000179{
180 char old_str[DEVKMSG_STR_MAX_SIZE];
181 unsigned int old;
182 int err;
183
184 if (write) {
185 if (devkmsg_log & DEVKMSG_LOG_MASK_LOCK)
186 return -EINVAL;
187
188 old = devkmsg_log;
189 strncpy(old_str, devkmsg_log_str, DEVKMSG_STR_MAX_SIZE);
190 }
191
192 err = proc_dostring(table, write, buffer, lenp, ppos);
193 if (err)
194 return err;
195
196 if (write) {
197 err = __control_devkmsg(devkmsg_log_str);
198
199 /*
200 * Do not accept an unknown string OR a known string with
201 * trailing crap...
202 */
203 if (err < 0 || (err + 1 != *lenp)) {
204
205 /* ... and restore old setting. */
206 devkmsg_log = old;
207 strncpy(devkmsg_log_str, old_str, DEVKMSG_STR_MAX_SIZE);
208
209 return -EINVAL;
210 }
211 }
212
213 return 0;
214}
215
David Brazdil0f672f62019-12-10 10:32:29 +0000216/* Number of registered extended console drivers. */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000217static int nr_ext_console_drivers;
218
219/*
220 * Helper macros to handle lockdep when locking/unlocking console_sem. We use
221 * macros instead of functions so that _RET_IP_ contains useful information.
222 */
223#define down_console_sem() do { \
224 down(&console_sem);\
225 mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);\
226} while (0)
227
228static int __down_trylock_console_sem(unsigned long ip)
229{
230 int lock_failed;
231 unsigned long flags;
232
233 /*
234 * Here and in __up_console_sem() we need to be in safe mode,
235 * because spindump/WARN/etc from under console ->lock will
236 * deadlock in printk()->down_trylock_console_sem() otherwise.
237 */
238 printk_safe_enter_irqsave(flags);
239 lock_failed = down_trylock(&console_sem);
240 printk_safe_exit_irqrestore(flags);
241
242 if (lock_failed)
243 return 1;
244 mutex_acquire(&console_lock_dep_map, 0, 1, ip);
245 return 0;
246}
247#define down_trylock_console_sem() __down_trylock_console_sem(_RET_IP_)
248
249static void __up_console_sem(unsigned long ip)
250{
251 unsigned long flags;
252
Olivier Deprez157378f2022-04-04 15:47:50 +0200253 mutex_release(&console_lock_dep_map, ip);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000254
255 printk_safe_enter_irqsave(flags);
256 up(&console_sem);
257 printk_safe_exit_irqrestore(flags);
258}
259#define up_console_sem() __up_console_sem(_RET_IP_)
260
261/*
262 * This is used for debugging the mess that is the VT code by
263 * keeping track if we have the console semaphore held. It's
264 * definitely not the perfect debug tool (we don't know if _WE_
265 * hold it and are racing, but it helps tracking those weird code
266 * paths in the console code where we end up in places I want
267 * locked without the console sempahore held).
268 */
269static int console_locked, console_suspended;
270
271/*
272 * If exclusive_console is non-NULL then only this console is to be printed to.
273 */
274static struct console *exclusive_console;
275
276/*
277 * Array of consoles built from command line options (console=)
278 */
279
280#define MAX_CMDLINECONSOLES 8
281
282static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
283
284static int preferred_console = -1;
Olivier Deprez157378f2022-04-04 15:47:50 +0200285static bool has_preferred_console;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000286int console_set_on_cmdline;
287EXPORT_SYMBOL(console_set_on_cmdline);
288
289/* Flag: console code may call schedule() */
290static int console_may_schedule;
291
292enum con_msg_format_flags {
293 MSG_FORMAT_DEFAULT = 0,
294 MSG_FORMAT_SYSLOG = (1 << 0),
295};
296
297static int console_msg_format = MSG_FORMAT_DEFAULT;
298
299/*
Olivier Deprez157378f2022-04-04 15:47:50 +0200300 * The printk log buffer consists of a sequenced collection of records, each
301 * containing variable length message text. Every record also contains its
302 * own meta-data (@info).
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000303 *
Olivier Deprez157378f2022-04-04 15:47:50 +0200304 * Every record meta-data carries the timestamp in microseconds, as well as
305 * the standard userspace syslog level and syslog facility. The usual kernel
306 * messages use LOG_KERN; userspace-injected messages always carry a matching
307 * syslog facility, by default LOG_USER. The origin of every message can be
308 * reliably determined that way.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000309 *
Olivier Deprez157378f2022-04-04 15:47:50 +0200310 * The human readable log message of a record is available in @text, the
311 * length of the message text in @text_len. The stored message is not
312 * terminated.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000313 *
Olivier Deprez157378f2022-04-04 15:47:50 +0200314 * Optionally, a record can carry a dictionary of properties (key/value
315 * pairs), to provide userspace with a machine-readable message context.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000316 *
317 * Examples for well-defined, commonly used property names are:
318 * DEVICE=b12:8 device identifier
319 * b12:8 block dev_t
320 * c127:3 char dev_t
321 * n8 netdev ifindex
322 * +sound:card0 subsystem:devname
323 * SUBSYSTEM=pci driver-core subsystem name
324 *
Olivier Deprez157378f2022-04-04 15:47:50 +0200325 * Valid characters in property names are [a-zA-Z0-9.-_]. Property names
326 * and values are terminated by a '\0' character.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000327 *
Olivier Deprez157378f2022-04-04 15:47:50 +0200328 * Example of record values:
329 * record.text_buf = "it's a line" (unterminated)
330 * record.info.seq = 56
331 * record.info.ts_nsec = 36863
332 * record.info.text_len = 11
333 * record.info.facility = 0 (LOG_KERN)
334 * record.info.flags = 0
335 * record.info.level = 3 (LOG_ERR)
336 * record.info.caller_id = 299 (task 299)
337 * record.info.dev_info.subsystem = "pci" (terminated)
338 * record.info.dev_info.device = "+pci:0000:00:01.0" (terminated)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000339 *
Olivier Deprez157378f2022-04-04 15:47:50 +0200340 * The 'struct printk_info' buffer must never be directly exported to
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000341 * userspace, it is a kernel-private implementation detail that might
342 * need to be changed in the future, when the requirements change.
343 *
344 * /dev/kmsg exports the structured data in the following line format:
345 * "<level>,<sequnum>,<timestamp>,<contflag>[,additional_values, ... ];<message text>\n"
346 *
347 * Users of the export format should ignore possible additional values
348 * separated by ',', and find the message after the ';' character.
349 *
350 * The optional key/value pairs are attached as continuation lines starting
351 * with a space character and terminated by a newline. All possible
352 * non-prinatable characters are escaped in the "\xff" notation.
353 */
354
355enum log_flags {
356 LOG_NEWLINE = 2, /* text ended with a newline */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000357 LOG_CONT = 8, /* text is a fragment of a continuation line */
358};
359
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000360/*
361 * The logbuf_lock protects kmsg buffer, indices, counters. This can be taken
362 * within the scheduler's rq lock. It must be released before calling
363 * console_unlock() or anything else that might wake up a process.
364 */
365DEFINE_RAW_SPINLOCK(logbuf_lock);
366
367/*
368 * Helper macros to lock/unlock logbuf_lock and switch between
369 * printk-safe/unsafe modes.
370 */
371#define logbuf_lock_irq() \
372 do { \
373 printk_safe_enter_irq(); \
374 raw_spin_lock(&logbuf_lock); \
375 } while (0)
376
377#define logbuf_unlock_irq() \
378 do { \
379 raw_spin_unlock(&logbuf_lock); \
380 printk_safe_exit_irq(); \
381 } while (0)
382
383#define logbuf_lock_irqsave(flags) \
384 do { \
385 printk_safe_enter_irqsave(flags); \
386 raw_spin_lock(&logbuf_lock); \
387 } while (0)
388
389#define logbuf_unlock_irqrestore(flags) \
390 do { \
391 raw_spin_unlock(&logbuf_lock); \
392 printk_safe_exit_irqrestore(flags); \
393 } while (0)
394
395#ifdef CONFIG_PRINTK
396DECLARE_WAIT_QUEUE_HEAD(log_wait);
397/* the next printk record to read by syslog(READ) or /proc/kmsg */
398static u64 syslog_seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000399static size_t syslog_partial;
David Brazdil0f672f62019-12-10 10:32:29 +0000400static bool syslog_time;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000401
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000402/* the next printk record to write to the console */
403static u64 console_seq;
David Brazdil0f672f62019-12-10 10:32:29 +0000404static u64 exclusive_console_stop_seq;
Olivier Deprez157378f2022-04-04 15:47:50 +0200405static unsigned long console_dropped;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000406
407/* the next printk record to read after the last 'clear' command */
408static u64 clear_seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000409
David Brazdil0f672f62019-12-10 10:32:29 +0000410#ifdef CONFIG_PRINTK_CALLER
411#define PREFIX_MAX 48
412#else
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000413#define PREFIX_MAX 32
David Brazdil0f672f62019-12-10 10:32:29 +0000414#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000415#define LOG_LINE_MAX (1024 - PREFIX_MAX)
416
417#define LOG_LEVEL(v) ((v) & 0x07)
418#define LOG_FACILITY(v) ((v) >> 3 & 0xff)
419
420/* record buffer */
Olivier Deprez157378f2022-04-04 15:47:50 +0200421#define LOG_ALIGN __alignof__(unsigned long)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000422#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
David Brazdil0f672f62019-12-10 10:32:29 +0000423#define LOG_BUF_LEN_MAX (u32)(1 << 31)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000424static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
425static char *log_buf = __log_buf;
426static u32 log_buf_len = __LOG_BUF_LEN;
427
Olivier Deprez0e641232021-09-23 10:07:05 +0200428/*
Olivier Deprez157378f2022-04-04 15:47:50 +0200429 * Define the average message size. This only affects the number of
430 * descriptors that will be available. Underestimating is better than
431 * overestimating (too many available descriptors is better than not enough).
432 */
433#define PRB_AVGBITS 5 /* 32 character average length */
434
435#if CONFIG_LOG_BUF_SHIFT <= PRB_AVGBITS
436#error CONFIG_LOG_BUF_SHIFT value too small.
437#endif
438_DEFINE_PRINTKRB(printk_rb_static, CONFIG_LOG_BUF_SHIFT - PRB_AVGBITS,
439 PRB_AVGBITS, &__log_buf[0]);
440
441static struct printk_ringbuffer printk_rb_dynamic;
442
443static struct printk_ringbuffer *prb = &printk_rb_static;
444
445/*
Olivier Deprez0e641232021-09-23 10:07:05 +0200446 * We cannot access per-CPU data (e.g. per-CPU flush irq_work) before
447 * per_cpu_areas are initialised. This variable is set to true when
448 * it's safe to access per-CPU data.
449 */
450static bool __printk_percpu_data_ready __read_mostly;
451
452bool printk_percpu_data_ready(void)
453{
454 return __printk_percpu_data_ready;
455}
456
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000457/* Return log buffer address */
458char *log_buf_addr_get(void)
459{
460 return log_buf;
461}
462
463/* Return log buffer size */
464u32 log_buf_len_get(void)
465{
466 return log_buf_len;
467}
468
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000469/*
470 * Define how much of the log buffer we could take at maximum. The value
471 * must be greater than two. Note that only half of the buffer is available
472 * when the index points to the middle.
473 */
474#define MAX_LOG_TAKE_PART 4
475static const char trunc_msg[] = "<truncated>";
476
Olivier Deprez157378f2022-04-04 15:47:50 +0200477static void truncate_msg(u16 *text_len, u16 *trunc_msg_len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000478{
479 /*
480 * The message should not take the whole buffer. Otherwise, it might
481 * get removed too soon.
482 */
483 u32 max_text_len = log_buf_len / MAX_LOG_TAKE_PART;
Olivier Deprez157378f2022-04-04 15:47:50 +0200484
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000485 if (*text_len > max_text_len)
486 *text_len = max_text_len;
Olivier Deprez157378f2022-04-04 15:47:50 +0200487
488 /* enable the warning message (if there is room) */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000489 *trunc_msg_len = strlen(trunc_msg);
Olivier Deprez157378f2022-04-04 15:47:50 +0200490 if (*text_len >= *trunc_msg_len)
491 *text_len -= *trunc_msg_len;
492 else
493 *trunc_msg_len = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000494}
495
496/* insert record into the buffer, discard old ones, update heads */
David Brazdil0f672f62019-12-10 10:32:29 +0000497static int log_store(u32 caller_id, int facility, int level,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000498 enum log_flags flags, u64 ts_nsec,
Olivier Deprez157378f2022-04-04 15:47:50 +0200499 const struct dev_printk_info *dev_info,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000500 const char *text, u16 text_len)
501{
Olivier Deprez157378f2022-04-04 15:47:50 +0200502 struct prb_reserved_entry e;
503 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000504 u16 trunc_msg_len = 0;
505
Olivier Deprez157378f2022-04-04 15:47:50 +0200506 prb_rec_init_wr(&r, text_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000507
Olivier Deprez157378f2022-04-04 15:47:50 +0200508 if (!prb_reserve(&e, prb, &r)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000509 /* truncate the message if it is too long for empty buffer */
Olivier Deprez157378f2022-04-04 15:47:50 +0200510 truncate_msg(&text_len, &trunc_msg_len);
511 prb_rec_init_wr(&r, text_len + trunc_msg_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000512 /* survive when the log buffer is too small for trunc_msg */
Olivier Deprez157378f2022-04-04 15:47:50 +0200513 if (!prb_reserve(&e, prb, &r))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000514 return 0;
515 }
516
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000517 /* fill message */
Olivier Deprez157378f2022-04-04 15:47:50 +0200518 memcpy(&r.text_buf[0], text, text_len);
519 if (trunc_msg_len)
520 memcpy(&r.text_buf[text_len], trunc_msg, trunc_msg_len);
521 r.info->text_len = text_len + trunc_msg_len;
522 r.info->facility = facility;
523 r.info->level = level & 7;
524 r.info->flags = flags & 0x1f;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000525 if (ts_nsec > 0)
Olivier Deprez157378f2022-04-04 15:47:50 +0200526 r.info->ts_nsec = ts_nsec;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000527 else
Olivier Deprez157378f2022-04-04 15:47:50 +0200528 r.info->ts_nsec = local_clock();
529 r.info->caller_id = caller_id;
530 if (dev_info)
531 memcpy(&r.info->dev_info, dev_info, sizeof(r.info->dev_info));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000532
Olivier Deprez157378f2022-04-04 15:47:50 +0200533 /* A message without a trailing newline can be continued. */
534 if (!(flags & LOG_NEWLINE))
535 prb_commit(&e);
536 else
537 prb_final_commit(&e);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000538
Olivier Deprez157378f2022-04-04 15:47:50 +0200539 return (text_len + trunc_msg_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000540}
541
542int dmesg_restrict = IS_ENABLED(CONFIG_SECURITY_DMESG_RESTRICT);
543
544static int syslog_action_restricted(int type)
545{
546 if (dmesg_restrict)
547 return 1;
548 /*
549 * Unless restricted, we allow "read all" and "get buffer size"
550 * for everybody.
551 */
552 return type != SYSLOG_ACTION_READ_ALL &&
553 type != SYSLOG_ACTION_SIZE_BUFFER;
554}
555
556static int check_syslog_permissions(int type, int source)
557{
558 /*
559 * If this is from /proc/kmsg and we've already opened it, then we've
560 * already done the capabilities checks at open time.
561 */
562 if (source == SYSLOG_FROM_PROC && type != SYSLOG_ACTION_OPEN)
563 goto ok;
564
565 if (syslog_action_restricted(type)) {
566 if (capable(CAP_SYSLOG))
567 goto ok;
568 /*
569 * For historical reasons, accept CAP_SYS_ADMIN too, with
570 * a warning.
571 */
572 if (capable(CAP_SYS_ADMIN)) {
573 pr_warn_once("%s (%d): Attempt to access syslog with "
574 "CAP_SYS_ADMIN but no CAP_SYSLOG "
575 "(deprecated).\n",
576 current->comm, task_pid_nr(current));
577 goto ok;
578 }
579 return -EPERM;
580 }
581ok:
582 return security_syslog(type);
583}
584
585static void append_char(char **pp, char *e, char c)
586{
587 if (*pp < e)
588 *(*pp)++ = c;
589}
590
Olivier Deprez157378f2022-04-04 15:47:50 +0200591static ssize_t info_print_ext_header(char *buf, size_t size,
592 struct printk_info *info)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000593{
Olivier Deprez157378f2022-04-04 15:47:50 +0200594 u64 ts_usec = info->ts_nsec;
David Brazdil0f672f62019-12-10 10:32:29 +0000595 char caller[20];
596#ifdef CONFIG_PRINTK_CALLER
Olivier Deprez157378f2022-04-04 15:47:50 +0200597 u32 id = info->caller_id;
David Brazdil0f672f62019-12-10 10:32:29 +0000598
599 snprintf(caller, sizeof(caller), ",caller=%c%u",
600 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
601#else
602 caller[0] = '\0';
603#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000604
605 do_div(ts_usec, 1000);
606
David Brazdil0f672f62019-12-10 10:32:29 +0000607 return scnprintf(buf, size, "%u,%llu,%llu,%c%s;",
Olivier Deprez157378f2022-04-04 15:47:50 +0200608 (info->facility << 3) | info->level, info->seq,
609 ts_usec, info->flags & LOG_CONT ? 'c' : '-', caller);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000610}
611
Olivier Deprez157378f2022-04-04 15:47:50 +0200612static ssize_t msg_add_ext_text(char *buf, size_t size,
613 const char *text, size_t text_len,
614 unsigned char endc)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000615{
616 char *p = buf, *e = buf + size;
617 size_t i;
618
619 /* escape non-printable characters */
620 for (i = 0; i < text_len; i++) {
621 unsigned char c = text[i];
622
623 if (c < ' ' || c >= 127 || c == '\\')
624 p += scnprintf(p, e - p, "\\x%02x", c);
625 else
626 append_char(&p, e, c);
627 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200628 append_char(&p, e, endc);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000629
630 return p - buf;
631}
632
Olivier Deprez157378f2022-04-04 15:47:50 +0200633static ssize_t msg_add_dict_text(char *buf, size_t size,
634 const char *key, const char *val)
635{
636 size_t val_len = strlen(val);
637 ssize_t len;
638
639 if (!val_len)
640 return 0;
641
642 len = msg_add_ext_text(buf, size, "", 0, ' '); /* dict prefix */
643 len += msg_add_ext_text(buf + len, size - len, key, strlen(key), '=');
644 len += msg_add_ext_text(buf + len, size - len, val, val_len, '\n');
645
646 return len;
647}
648
649static ssize_t msg_print_ext_body(char *buf, size_t size,
650 char *text, size_t text_len,
651 struct dev_printk_info *dev_info)
652{
653 ssize_t len;
654
655 len = msg_add_ext_text(buf, size, text, text_len, '\n');
656
657 if (!dev_info)
658 goto out;
659
660 len += msg_add_dict_text(buf + len, size - len, "SUBSYSTEM",
661 dev_info->subsystem);
662 len += msg_add_dict_text(buf + len, size - len, "DEVICE",
663 dev_info->device);
664out:
665 return len;
666}
667
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000668/* /dev/kmsg - userspace message inject/listen interface */
669struct devkmsg_user {
670 u64 seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000671 struct ratelimit_state rs;
672 struct mutex lock;
673 char buf[CONSOLE_EXT_LOG_MAX];
Olivier Deprez157378f2022-04-04 15:47:50 +0200674
675 struct printk_info info;
676 char text_buf[CONSOLE_EXT_LOG_MAX];
677 struct printk_record record;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000678};
679
David Brazdil0f672f62019-12-10 10:32:29 +0000680static __printf(3, 4) __cold
681int devkmsg_emit(int facility, int level, const char *fmt, ...)
682{
683 va_list args;
684 int r;
685
686 va_start(args, fmt);
Olivier Deprez157378f2022-04-04 15:47:50 +0200687 r = vprintk_emit(facility, level, NULL, fmt, args);
David Brazdil0f672f62019-12-10 10:32:29 +0000688 va_end(args);
689
690 return r;
691}
692
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000693static ssize_t devkmsg_write(struct kiocb *iocb, struct iov_iter *from)
694{
695 char *buf, *line;
696 int level = default_message_loglevel;
697 int facility = 1; /* LOG_USER */
698 struct file *file = iocb->ki_filp;
699 struct devkmsg_user *user = file->private_data;
700 size_t len = iov_iter_count(from);
701 ssize_t ret = len;
702
703 if (!user || len > LOG_LINE_MAX)
704 return -EINVAL;
705
706 /* Ignore when user logging is disabled. */
707 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
708 return len;
709
710 /* Ratelimit when not explicitly enabled. */
711 if (!(devkmsg_log & DEVKMSG_LOG_MASK_ON)) {
712 if (!___ratelimit(&user->rs, current->comm))
713 return ret;
714 }
715
716 buf = kmalloc(len+1, GFP_KERNEL);
717 if (buf == NULL)
718 return -ENOMEM;
719
720 buf[len] = '\0';
721 if (!copy_from_iter_full(buf, len, from)) {
722 kfree(buf);
723 return -EFAULT;
724 }
725
726 /*
727 * Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
728 * the decimal value represents 32bit, the lower 3 bit are the log
729 * level, the rest are the log facility.
730 *
731 * If no prefix or no userspace facility is specified, we
732 * enforce LOG_USER, to be able to reliably distinguish
733 * kernel-generated messages from userspace-injected ones.
734 */
735 line = buf;
736 if (line[0] == '<') {
737 char *endp = NULL;
738 unsigned int u;
739
740 u = simple_strtoul(line + 1, &endp, 10);
741 if (endp && endp[0] == '>') {
742 level = LOG_LEVEL(u);
743 if (LOG_FACILITY(u) != 0)
744 facility = LOG_FACILITY(u);
745 endp++;
746 len -= endp - line;
747 line = endp;
748 }
749 }
750
David Brazdil0f672f62019-12-10 10:32:29 +0000751 devkmsg_emit(facility, level, "%s", line);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000752 kfree(buf);
753 return ret;
754}
755
756static ssize_t devkmsg_read(struct file *file, char __user *buf,
757 size_t count, loff_t *ppos)
758{
759 struct devkmsg_user *user = file->private_data;
Olivier Deprez157378f2022-04-04 15:47:50 +0200760 struct printk_record *r = &user->record;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000761 size_t len;
762 ssize_t ret;
763
764 if (!user)
765 return -EBADF;
766
767 ret = mutex_lock_interruptible(&user->lock);
768 if (ret)
769 return ret;
770
771 logbuf_lock_irq();
Olivier Deprez157378f2022-04-04 15:47:50 +0200772 if (!prb_read_valid(prb, user->seq, r)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000773 if (file->f_flags & O_NONBLOCK) {
774 ret = -EAGAIN;
775 logbuf_unlock_irq();
776 goto out;
777 }
778
779 logbuf_unlock_irq();
780 ret = wait_event_interruptible(log_wait,
Olivier Deprez157378f2022-04-04 15:47:50 +0200781 prb_read_valid(prb, user->seq, r));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000782 if (ret)
783 goto out;
784 logbuf_lock_irq();
785 }
786
Olivier Deprez157378f2022-04-04 15:47:50 +0200787 if (r->info->seq != user->seq) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000788 /* our last seen message is gone, return error and reset */
Olivier Deprez157378f2022-04-04 15:47:50 +0200789 user->seq = r->info->seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000790 ret = -EPIPE;
791 logbuf_unlock_irq();
792 goto out;
793 }
794
Olivier Deprez157378f2022-04-04 15:47:50 +0200795 len = info_print_ext_header(user->buf, sizeof(user->buf), r->info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000796 len += msg_print_ext_body(user->buf + len, sizeof(user->buf) - len,
Olivier Deprez157378f2022-04-04 15:47:50 +0200797 &r->text_buf[0], r->info->text_len,
798 &r->info->dev_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000799
Olivier Deprez157378f2022-04-04 15:47:50 +0200800 user->seq = r->info->seq + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000801 logbuf_unlock_irq();
802
803 if (len > count) {
804 ret = -EINVAL;
805 goto out;
806 }
807
808 if (copy_to_user(buf, user->buf, len)) {
809 ret = -EFAULT;
810 goto out;
811 }
812 ret = len;
813out:
814 mutex_unlock(&user->lock);
815 return ret;
816}
817
Olivier Deprez157378f2022-04-04 15:47:50 +0200818/*
819 * Be careful when modifying this function!!!
820 *
821 * Only few operations are supported because the device works only with the
822 * entire variable length messages (records). Non-standard values are
823 * returned in the other cases and has been this way for quite some time.
824 * User space applications might depend on this behavior.
825 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000826static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
827{
828 struct devkmsg_user *user = file->private_data;
829 loff_t ret = 0;
830
831 if (!user)
832 return -EBADF;
833 if (offset)
834 return -ESPIPE;
835
836 logbuf_lock_irq();
837 switch (whence) {
838 case SEEK_SET:
839 /* the first record */
Olivier Deprez157378f2022-04-04 15:47:50 +0200840 user->seq = prb_first_valid_seq(prb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000841 break;
842 case SEEK_DATA:
843 /*
844 * The first record after the last SYSLOG_ACTION_CLEAR,
845 * like issued by 'dmesg -c'. Reading /dev/kmsg itself
846 * changes no global state, and does not clear anything.
847 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000848 user->seq = clear_seq;
849 break;
850 case SEEK_END:
851 /* after the last record */
Olivier Deprez157378f2022-04-04 15:47:50 +0200852 user->seq = prb_next_seq(prb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000853 break;
854 default:
855 ret = -EINVAL;
856 }
857 logbuf_unlock_irq();
858 return ret;
859}
860
861static __poll_t devkmsg_poll(struct file *file, poll_table *wait)
862{
863 struct devkmsg_user *user = file->private_data;
Olivier Deprez157378f2022-04-04 15:47:50 +0200864 struct printk_info info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000865 __poll_t ret = 0;
866
867 if (!user)
868 return EPOLLERR|EPOLLNVAL;
869
870 poll_wait(file, &log_wait, wait);
871
872 logbuf_lock_irq();
Olivier Deprez157378f2022-04-04 15:47:50 +0200873 if (prb_read_valid_info(prb, user->seq, &info, NULL)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000874 /* return error when data has vanished underneath us */
Olivier Deprez157378f2022-04-04 15:47:50 +0200875 if (info.seq != user->seq)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000876 ret = EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
877 else
878 ret = EPOLLIN|EPOLLRDNORM;
879 }
880 logbuf_unlock_irq();
881
882 return ret;
883}
884
885static int devkmsg_open(struct inode *inode, struct file *file)
886{
887 struct devkmsg_user *user;
888 int err;
889
890 if (devkmsg_log & DEVKMSG_LOG_MASK_OFF)
891 return -EPERM;
892
893 /* write-only does not need any file context */
894 if ((file->f_flags & O_ACCMODE) != O_WRONLY) {
895 err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
896 SYSLOG_FROM_READER);
897 if (err)
898 return err;
899 }
900
901 user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
902 if (!user)
903 return -ENOMEM;
904
905 ratelimit_default_init(&user->rs);
906 ratelimit_set_flags(&user->rs, RATELIMIT_MSG_ON_RELEASE);
907
908 mutex_init(&user->lock);
909
Olivier Deprez157378f2022-04-04 15:47:50 +0200910 prb_rec_init_rd(&user->record, &user->info,
911 &user->text_buf[0], sizeof(user->text_buf));
912
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000913 logbuf_lock_irq();
Olivier Deprez157378f2022-04-04 15:47:50 +0200914 user->seq = prb_first_valid_seq(prb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000915 logbuf_unlock_irq();
916
917 file->private_data = user;
918 return 0;
919}
920
921static int devkmsg_release(struct inode *inode, struct file *file)
922{
923 struct devkmsg_user *user = file->private_data;
924
925 if (!user)
926 return 0;
927
928 ratelimit_state_exit(&user->rs);
929
930 mutex_destroy(&user->lock);
931 kfree(user);
932 return 0;
933}
934
935const struct file_operations kmsg_fops = {
936 .open = devkmsg_open,
937 .read = devkmsg_read,
938 .write_iter = devkmsg_write,
939 .llseek = devkmsg_llseek,
940 .poll = devkmsg_poll,
941 .release = devkmsg_release,
942};
943
944#ifdef CONFIG_CRASH_CORE
945/*
946 * This appends the listed symbols to /proc/vmcore
947 *
948 * /proc/vmcore is used by various utilities, like crash and makedumpfile to
949 * obtain access to symbols that are otherwise very difficult to locate. These
950 * symbols are specifically used so that utilities can access and extract the
951 * dmesg log from a vmcore file after a crash.
952 */
953void log_buf_vmcoreinfo_setup(void)
954{
Olivier Deprez157378f2022-04-04 15:47:50 +0200955 struct dev_printk_info *dev_info = NULL;
956
957 VMCOREINFO_SYMBOL(prb);
958 VMCOREINFO_SYMBOL(printk_rb_static);
959 VMCOREINFO_SYMBOL(clear_seq);
960
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000961 /*
Olivier Deprez157378f2022-04-04 15:47:50 +0200962 * Export struct size and field offsets. User space tools can
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000963 * parse it and detect any changes to structure down the line.
964 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200965
966 VMCOREINFO_STRUCT_SIZE(printk_ringbuffer);
967 VMCOREINFO_OFFSET(printk_ringbuffer, desc_ring);
968 VMCOREINFO_OFFSET(printk_ringbuffer, text_data_ring);
969 VMCOREINFO_OFFSET(printk_ringbuffer, fail);
970
971 VMCOREINFO_STRUCT_SIZE(prb_desc_ring);
972 VMCOREINFO_OFFSET(prb_desc_ring, count_bits);
973 VMCOREINFO_OFFSET(prb_desc_ring, descs);
974 VMCOREINFO_OFFSET(prb_desc_ring, infos);
975 VMCOREINFO_OFFSET(prb_desc_ring, head_id);
976 VMCOREINFO_OFFSET(prb_desc_ring, tail_id);
977
978 VMCOREINFO_STRUCT_SIZE(prb_desc);
979 VMCOREINFO_OFFSET(prb_desc, state_var);
980 VMCOREINFO_OFFSET(prb_desc, text_blk_lpos);
981
982 VMCOREINFO_STRUCT_SIZE(prb_data_blk_lpos);
983 VMCOREINFO_OFFSET(prb_data_blk_lpos, begin);
984 VMCOREINFO_OFFSET(prb_data_blk_lpos, next);
985
986 VMCOREINFO_STRUCT_SIZE(printk_info);
987 VMCOREINFO_OFFSET(printk_info, seq);
988 VMCOREINFO_OFFSET(printk_info, ts_nsec);
989 VMCOREINFO_OFFSET(printk_info, text_len);
990 VMCOREINFO_OFFSET(printk_info, caller_id);
991 VMCOREINFO_OFFSET(printk_info, dev_info);
992
993 VMCOREINFO_STRUCT_SIZE(dev_printk_info);
994 VMCOREINFO_OFFSET(dev_printk_info, subsystem);
995 VMCOREINFO_LENGTH(printk_info_subsystem, sizeof(dev_info->subsystem));
996 VMCOREINFO_OFFSET(dev_printk_info, device);
997 VMCOREINFO_LENGTH(printk_info_device, sizeof(dev_info->device));
998
999 VMCOREINFO_STRUCT_SIZE(prb_data_ring);
1000 VMCOREINFO_OFFSET(prb_data_ring, size_bits);
1001 VMCOREINFO_OFFSET(prb_data_ring, data);
1002 VMCOREINFO_OFFSET(prb_data_ring, head_lpos);
1003 VMCOREINFO_OFFSET(prb_data_ring, tail_lpos);
1004
1005 VMCOREINFO_SIZE(atomic_long_t);
1006 VMCOREINFO_TYPE_OFFSET(atomic_long_t, counter);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001007}
1008#endif
1009
1010/* requested log_buf_len from kernel cmdline */
1011static unsigned long __initdata new_log_buf_len;
1012
1013/* we practice scaling the ring buffer by powers of 2 */
David Brazdil0f672f62019-12-10 10:32:29 +00001014static void __init log_buf_len_update(u64 size)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001015{
David Brazdil0f672f62019-12-10 10:32:29 +00001016 if (size > (u64)LOG_BUF_LEN_MAX) {
1017 size = (u64)LOG_BUF_LEN_MAX;
1018 pr_err("log_buf over 2G is not supported.\n");
1019 }
1020
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001021 if (size)
1022 size = roundup_pow_of_two(size);
1023 if (size > log_buf_len)
David Brazdil0f672f62019-12-10 10:32:29 +00001024 new_log_buf_len = (unsigned long)size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001025}
1026
1027/* save requested log_buf_len since it's too early to process it */
1028static int __init log_buf_len_setup(char *str)
1029{
David Brazdil0f672f62019-12-10 10:32:29 +00001030 u64 size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001031
1032 if (!str)
1033 return -EINVAL;
1034
1035 size = memparse(str, &str);
1036
1037 log_buf_len_update(size);
1038
1039 return 0;
1040}
1041early_param("log_buf_len", log_buf_len_setup);
1042
1043#ifdef CONFIG_SMP
1044#define __LOG_CPU_MAX_BUF_LEN (1 << CONFIG_LOG_CPU_MAX_BUF_SHIFT)
1045
1046static void __init log_buf_add_cpu(void)
1047{
1048 unsigned int cpu_extra;
1049
1050 /*
1051 * archs should set up cpu_possible_bits properly with
1052 * set_cpu_possible() after setup_arch() but just in
1053 * case lets ensure this is valid.
1054 */
1055 if (num_possible_cpus() == 1)
1056 return;
1057
1058 cpu_extra = (num_possible_cpus() - 1) * __LOG_CPU_MAX_BUF_LEN;
1059
1060 /* by default this will only continue through for large > 64 CPUs */
1061 if (cpu_extra <= __LOG_BUF_LEN / 2)
1062 return;
1063
1064 pr_info("log_buf_len individual max cpu contribution: %d bytes\n",
1065 __LOG_CPU_MAX_BUF_LEN);
1066 pr_info("log_buf_len total cpu_extra contributions: %d bytes\n",
1067 cpu_extra);
1068 pr_info("log_buf_len min size: %d bytes\n", __LOG_BUF_LEN);
1069
1070 log_buf_len_update(cpu_extra + __LOG_BUF_LEN);
1071}
1072#else /* !CONFIG_SMP */
1073static inline void log_buf_add_cpu(void) {}
1074#endif /* CONFIG_SMP */
1075
Olivier Deprez0e641232021-09-23 10:07:05 +02001076static void __init set_percpu_data_ready(void)
1077{
1078 printk_safe_init();
1079 /* Make sure we set this flag only after printk_safe() init is done */
1080 barrier();
1081 __printk_percpu_data_ready = true;
1082}
1083
Olivier Deprez157378f2022-04-04 15:47:50 +02001084static unsigned int __init add_to_rb(struct printk_ringbuffer *rb,
1085 struct printk_record *r)
1086{
1087 struct prb_reserved_entry e;
1088 struct printk_record dest_r;
1089
1090 prb_rec_init_wr(&dest_r, r->info->text_len);
1091
1092 if (!prb_reserve(&e, rb, &dest_r))
1093 return 0;
1094
1095 memcpy(&dest_r.text_buf[0], &r->text_buf[0], r->info->text_len);
1096 dest_r.info->text_len = r->info->text_len;
1097 dest_r.info->facility = r->info->facility;
1098 dest_r.info->level = r->info->level;
1099 dest_r.info->flags = r->info->flags;
1100 dest_r.info->ts_nsec = r->info->ts_nsec;
1101 dest_r.info->caller_id = r->info->caller_id;
1102 memcpy(&dest_r.info->dev_info, &r->info->dev_info, sizeof(dest_r.info->dev_info));
1103
1104 prb_final_commit(&e);
1105
1106 return prb_record_text_space(&e);
1107}
1108
1109static char setup_text_buf[LOG_LINE_MAX] __initdata;
1110
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001111void __init setup_log_buf(int early)
1112{
Olivier Deprez157378f2022-04-04 15:47:50 +02001113 struct printk_info *new_infos;
1114 unsigned int new_descs_count;
1115 struct prb_desc *new_descs;
1116 struct printk_info info;
1117 struct printk_record r;
1118 size_t new_descs_size;
1119 size_t new_infos_size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001120 unsigned long flags;
1121 char *new_log_buf;
David Brazdil0f672f62019-12-10 10:32:29 +00001122 unsigned int free;
Olivier Deprez157378f2022-04-04 15:47:50 +02001123 u64 seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001124
Olivier Deprez0e641232021-09-23 10:07:05 +02001125 /*
1126 * Some archs call setup_log_buf() multiple times - first is very
1127 * early, e.g. from setup_arch(), and second - when percpu_areas
1128 * are initialised.
1129 */
1130 if (!early)
1131 set_percpu_data_ready();
1132
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001133 if (log_buf != __log_buf)
1134 return;
1135
1136 if (!early && !new_log_buf_len)
1137 log_buf_add_cpu();
1138
1139 if (!new_log_buf_len)
1140 return;
1141
Olivier Deprez157378f2022-04-04 15:47:50 +02001142 new_descs_count = new_log_buf_len >> PRB_AVGBITS;
1143 if (new_descs_count == 0) {
1144 pr_err("new_log_buf_len: %lu too small\n", new_log_buf_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001145 return;
1146 }
1147
Olivier Deprez157378f2022-04-04 15:47:50 +02001148 new_log_buf = memblock_alloc(new_log_buf_len, LOG_ALIGN);
1149 if (unlikely(!new_log_buf)) {
1150 pr_err("log_buf_len: %lu text bytes not available\n",
1151 new_log_buf_len);
1152 return;
1153 }
1154
1155 new_descs_size = new_descs_count * sizeof(struct prb_desc);
1156 new_descs = memblock_alloc(new_descs_size, LOG_ALIGN);
1157 if (unlikely(!new_descs)) {
1158 pr_err("log_buf_len: %zu desc bytes not available\n",
1159 new_descs_size);
1160 goto err_free_log_buf;
1161 }
1162
1163 new_infos_size = new_descs_count * sizeof(struct printk_info);
1164 new_infos = memblock_alloc(new_infos_size, LOG_ALIGN);
1165 if (unlikely(!new_infos)) {
1166 pr_err("log_buf_len: %zu info bytes not available\n",
1167 new_infos_size);
1168 goto err_free_descs;
1169 }
1170
1171 prb_rec_init_rd(&r, &info, &setup_text_buf[0], sizeof(setup_text_buf));
1172
1173 prb_init(&printk_rb_dynamic,
1174 new_log_buf, ilog2(new_log_buf_len),
1175 new_descs, ilog2(new_descs_count),
1176 new_infos);
1177
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001178 logbuf_lock_irqsave(flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02001179
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001180 log_buf_len = new_log_buf_len;
1181 log_buf = new_log_buf;
1182 new_log_buf_len = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02001183
1184 free = __LOG_BUF_LEN;
1185 prb_for_each_record(0, &printk_rb_static, seq, &r)
1186 free -= add_to_rb(&printk_rb_dynamic, &r);
1187
1188 /*
1189 * This is early enough that everything is still running on the
1190 * boot CPU and interrupts are disabled. So no new messages will
1191 * appear during the transition to the dynamic buffer.
1192 */
1193 prb = &printk_rb_dynamic;
1194
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001195 logbuf_unlock_irqrestore(flags);
1196
Olivier Deprez157378f2022-04-04 15:47:50 +02001197 if (seq != prb_next_seq(&printk_rb_static)) {
1198 pr_err("dropped %llu messages\n",
1199 prb_next_seq(&printk_rb_static) - seq);
1200 }
1201
David Brazdil0f672f62019-12-10 10:32:29 +00001202 pr_info("log_buf_len: %u bytes\n", log_buf_len);
1203 pr_info("early log buf free: %u(%u%%)\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001204 free, (free * 100) / __LOG_BUF_LEN);
Olivier Deprez157378f2022-04-04 15:47:50 +02001205 return;
1206
1207err_free_descs:
1208 memblock_free(__pa(new_descs), new_descs_size);
1209err_free_log_buf:
1210 memblock_free(__pa(new_log_buf), new_log_buf_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001211}
1212
1213static bool __read_mostly ignore_loglevel;
1214
1215static int __init ignore_loglevel_setup(char *str)
1216{
1217 ignore_loglevel = true;
1218 pr_info("debug: ignoring loglevel setting.\n");
1219
1220 return 0;
1221}
1222
1223early_param("ignore_loglevel", ignore_loglevel_setup);
1224module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
1225MODULE_PARM_DESC(ignore_loglevel,
1226 "ignore loglevel setting (prints all kernel messages to the console)");
1227
1228static bool suppress_message_printing(int level)
1229{
1230 return (level >= console_loglevel && !ignore_loglevel);
1231}
1232
1233#ifdef CONFIG_BOOT_PRINTK_DELAY
1234
1235static int boot_delay; /* msecs delay after each printk during bootup */
1236static unsigned long long loops_per_msec; /* based on boot_delay */
1237
1238static int __init boot_delay_setup(char *str)
1239{
1240 unsigned long lpj;
1241
1242 lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
1243 loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
1244
1245 get_option(&str, &boot_delay);
1246 if (boot_delay > 10 * 1000)
1247 boot_delay = 0;
1248
1249 pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
1250 "HZ: %d, loops_per_msec: %llu\n",
1251 boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
1252 return 0;
1253}
1254early_param("boot_delay", boot_delay_setup);
1255
1256static void boot_delay_msec(int level)
1257{
1258 unsigned long long k;
1259 unsigned long timeout;
1260
1261 if ((boot_delay == 0 || system_state >= SYSTEM_RUNNING)
1262 || suppress_message_printing(level)) {
1263 return;
1264 }
1265
1266 k = (unsigned long long)loops_per_msec * boot_delay;
1267
1268 timeout = jiffies + msecs_to_jiffies(boot_delay);
1269 while (k) {
1270 k--;
1271 cpu_relax();
1272 /*
1273 * use (volatile) jiffies to prevent
1274 * compiler reduction; loop termination via jiffies
1275 * is secondary and may or may not happen.
1276 */
1277 if (time_after(jiffies, timeout))
1278 break;
1279 touch_nmi_watchdog();
1280 }
1281}
1282#else
1283static inline void boot_delay_msec(int level)
1284{
1285}
1286#endif
1287
1288static bool printk_time = IS_ENABLED(CONFIG_PRINTK_TIME);
1289module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
1290
David Brazdil0f672f62019-12-10 10:32:29 +00001291static size_t print_syslog(unsigned int level, char *buf)
1292{
1293 return sprintf(buf, "<%u>", level);
1294}
1295
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001296static size_t print_time(u64 ts, char *buf)
1297{
David Brazdil0f672f62019-12-10 10:32:29 +00001298 unsigned long rem_nsec = do_div(ts, 1000000000);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001299
David Brazdil0f672f62019-12-10 10:32:29 +00001300 return sprintf(buf, "[%5lu.%06lu]",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001301 (unsigned long)ts, rem_nsec / 1000);
1302}
1303
David Brazdil0f672f62019-12-10 10:32:29 +00001304#ifdef CONFIG_PRINTK_CALLER
1305static size_t print_caller(u32 id, char *buf)
1306{
1307 char caller[12];
1308
1309 snprintf(caller, sizeof(caller), "%c%u",
1310 id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
1311 return sprintf(buf, "[%6s]", caller);
1312}
1313#else
1314#define print_caller(id, buf) 0
1315#endif
1316
Olivier Deprez157378f2022-04-04 15:47:50 +02001317static size_t info_print_prefix(const struct printk_info *info, bool syslog,
1318 bool time, char *buf)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001319{
1320 size_t len = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001321
David Brazdil0f672f62019-12-10 10:32:29 +00001322 if (syslog)
Olivier Deprez157378f2022-04-04 15:47:50 +02001323 len = print_syslog((info->facility << 3) | info->level, buf);
David Brazdil0f672f62019-12-10 10:32:29 +00001324
1325 if (time)
Olivier Deprez157378f2022-04-04 15:47:50 +02001326 len += print_time(info->ts_nsec, buf + len);
David Brazdil0f672f62019-12-10 10:32:29 +00001327
Olivier Deprez157378f2022-04-04 15:47:50 +02001328 len += print_caller(info->caller_id, buf + len);
David Brazdil0f672f62019-12-10 10:32:29 +00001329
1330 if (IS_ENABLED(CONFIG_PRINTK_CALLER) || time) {
1331 buf[len++] = ' ';
1332 buf[len] = '\0';
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001333 }
1334
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001335 return len;
1336}
1337
Olivier Deprez157378f2022-04-04 15:47:50 +02001338/*
1339 * Prepare the record for printing. The text is shifted within the given
1340 * buffer to avoid a need for another one. The following operations are
1341 * done:
1342 *
1343 * - Add prefix for each line.
1344 * - Drop truncated lines that no longer fit into the buffer.
1345 * - Add the trailing newline that has been removed in vprintk_store().
1346 * - Add a string terminator.
1347 *
1348 * Since the produced string is always terminated, the maximum possible
1349 * return value is @r->text_buf_size - 1;
1350 *
1351 * Return: The length of the updated/prepared text, including the added
1352 * prefixes and the newline. The terminator is not counted. The dropped
1353 * line(s) are not counted.
1354 */
1355static size_t record_print_text(struct printk_record *r, bool syslog,
1356 bool time)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001357{
Olivier Deprez157378f2022-04-04 15:47:50 +02001358 size_t text_len = r->info->text_len;
1359 size_t buf_size = r->text_buf_size;
1360 char *text = r->text_buf;
David Brazdil0f672f62019-12-10 10:32:29 +00001361 char prefix[PREFIX_MAX];
Olivier Deprez157378f2022-04-04 15:47:50 +02001362 bool truncated = false;
1363 size_t prefix_len;
1364 size_t line_len;
1365 size_t len = 0;
1366 char *next;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001367
Olivier Deprez157378f2022-04-04 15:47:50 +02001368 /*
1369 * If the message was truncated because the buffer was not large
1370 * enough, treat the available text as if it were the full text.
1371 */
1372 if (text_len > buf_size)
1373 text_len = buf_size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001374
Olivier Deprez157378f2022-04-04 15:47:50 +02001375 prefix_len = info_print_prefix(r->info, syslog, time, prefix);
1376
1377 /*
1378 * @text_len: bytes of unprocessed text
1379 * @line_len: bytes of current line _without_ newline
1380 * @text: pointer to beginning of current line
1381 * @len: number of bytes prepared in r->text_buf
1382 */
1383 for (;;) {
1384 next = memchr(text, '\n', text_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001385 if (next) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001386 line_len = next - text;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001387 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02001388 /* Drop truncated line(s). */
1389 if (truncated)
1390 break;
1391 line_len = text_len;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001392 }
1393
Olivier Deprez157378f2022-04-04 15:47:50 +02001394 /*
1395 * Truncate the text if there is not enough space to add the
1396 * prefix and a trailing newline and a terminator.
1397 */
1398 if (len + prefix_len + text_len + 1 + 1 > buf_size) {
1399 /* Drop even the current line if no space. */
1400 if (len + prefix_len + line_len + 1 + 1 > buf_size)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001401 break;
1402
Olivier Deprez157378f2022-04-04 15:47:50 +02001403 text_len = buf_size - len - prefix_len - 1 - 1;
1404 truncated = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001405 }
1406
Olivier Deprez157378f2022-04-04 15:47:50 +02001407 memmove(text + prefix_len, text, text_len);
1408 memcpy(text, prefix, prefix_len);
1409
1410 /*
1411 * Increment the prepared length to include the text and
1412 * prefix that were just moved+copied. Also increment for the
1413 * newline at the end of this line. If this is the last line,
1414 * there is no newline, but it will be added immediately below.
1415 */
1416 len += prefix_len + line_len + 1;
1417 if (text_len == line_len) {
1418 /*
1419 * This is the last line. Add the trailing newline
1420 * removed in vprintk_store().
1421 */
1422 text[prefix_len + line_len] = '\n';
1423 break;
1424 }
1425
1426 /*
1427 * Advance beyond the added prefix and the related line with
1428 * its newline.
1429 */
1430 text += prefix_len + line_len + 1;
1431
1432 /*
1433 * The remaining text has only decreased by the line with its
1434 * newline.
1435 *
1436 * Note that @text_len can become zero. It happens when @text
1437 * ended with a newline (either due to truncation or the
1438 * original string ending with "\n\n"). The loop is correctly
1439 * repeated and (if not truncated) an empty line with a prefix
1440 * will be prepared.
1441 */
1442 text_len -= line_len + 1;
1443 }
1444
1445 /*
1446 * If a buffer was provided, it will be terminated. Space for the
1447 * string terminator is guaranteed to be available. The terminator is
1448 * not counted in the return value.
1449 */
1450 if (buf_size > 0)
1451 r->text_buf[len] = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001452
1453 return len;
1454}
1455
Olivier Deprez157378f2022-04-04 15:47:50 +02001456static size_t get_record_print_text_size(struct printk_info *info,
1457 unsigned int line_count,
1458 bool syslog, bool time)
1459{
1460 char prefix[PREFIX_MAX];
1461 size_t prefix_len;
1462
1463 prefix_len = info_print_prefix(info, syslog, time, prefix);
1464
1465 /*
1466 * Each line will be preceded with a prefix. The intermediate
1467 * newlines are already within the text, but a final trailing
1468 * newline will be added.
1469 */
1470 return ((prefix_len * line_count) + info->text_len + 1);
1471}
1472
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001473static int syslog_print(char __user *buf, int size)
1474{
Olivier Deprez157378f2022-04-04 15:47:50 +02001475 struct printk_info info;
1476 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001477 char *text;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001478 int len = 0;
1479
1480 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1481 if (!text)
1482 return -ENOMEM;
1483
Olivier Deprez157378f2022-04-04 15:47:50 +02001484 prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
1485
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001486 while (size > 0) {
1487 size_t n;
1488 size_t skip;
1489
1490 logbuf_lock_irq();
Olivier Deprez157378f2022-04-04 15:47:50 +02001491 if (!prb_read_valid(prb, syslog_seq, &r)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001492 logbuf_unlock_irq();
1493 break;
1494 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001495 if (r.info->seq != syslog_seq) {
1496 /* message is gone, move to next valid one */
1497 syslog_seq = r.info->seq;
1498 syslog_partial = 0;
1499 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001500
David Brazdil0f672f62019-12-10 10:32:29 +00001501 /*
1502 * To keep reading/counting partial line consistent,
1503 * use printk_time value as of the beginning of a line.
1504 */
1505 if (!syslog_partial)
1506 syslog_time = printk_time;
1507
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001508 skip = syslog_partial;
Olivier Deprez157378f2022-04-04 15:47:50 +02001509 n = record_print_text(&r, true, syslog_time);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001510 if (n - syslog_partial <= size) {
1511 /* message fits into buffer, move forward */
Olivier Deprez157378f2022-04-04 15:47:50 +02001512 syslog_seq = r.info->seq + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001513 n -= syslog_partial;
1514 syslog_partial = 0;
1515 } else if (!len){
1516 /* partial read(), remember position */
1517 n = size;
1518 syslog_partial += n;
1519 } else
1520 n = 0;
1521 logbuf_unlock_irq();
1522
1523 if (!n)
1524 break;
1525
1526 if (copy_to_user(buf, text + skip, n)) {
1527 if (!len)
1528 len = -EFAULT;
1529 break;
1530 }
1531
1532 len += n;
1533 size -= n;
1534 buf += n;
1535 }
1536
1537 kfree(text);
1538 return len;
1539}
1540
1541static int syslog_print_all(char __user *buf, int size, bool clear)
1542{
Olivier Deprez157378f2022-04-04 15:47:50 +02001543 struct printk_info info;
1544 unsigned int line_count;
1545 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001546 char *text;
1547 int len = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001548 u64 seq;
David Brazdil0f672f62019-12-10 10:32:29 +00001549 bool time;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001550
1551 text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
1552 if (!text)
1553 return -ENOMEM;
1554
David Brazdil0f672f62019-12-10 10:32:29 +00001555 time = printk_time;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001556 logbuf_lock_irq();
1557 /*
1558 * Find first record that fits, including all following records,
1559 * into the user-provided buffer for this dump.
1560 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001561 prb_for_each_info(clear_seq, prb, seq, &info, &line_count)
1562 len += get_record_print_text_size(&info, line_count, true, time);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001563
1564 /* move first record forward until length fits into the buffer */
Olivier Deprez157378f2022-04-04 15:47:50 +02001565 prb_for_each_info(clear_seq, prb, seq, &info, &line_count) {
1566 if (len <= size)
1567 break;
1568 len -= get_record_print_text_size(&info, line_count, true, time);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001569 }
1570
Olivier Deprez157378f2022-04-04 15:47:50 +02001571 prb_rec_init_rd(&r, &info, text, LOG_LINE_MAX + PREFIX_MAX);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001572
1573 len = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02001574 prb_for_each_record(seq, prb, seq, &r) {
1575 int textlen;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001576
Olivier Deprez157378f2022-04-04 15:47:50 +02001577 textlen = record_print_text(&r, true, time);
1578
1579 if (len + textlen > size) {
1580 seq--;
1581 break;
1582 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001583
1584 logbuf_unlock_irq();
1585 if (copy_to_user(buf + len, text, textlen))
1586 len = -EFAULT;
1587 else
1588 len += textlen;
1589 logbuf_lock_irq();
1590
Olivier Deprez157378f2022-04-04 15:47:50 +02001591 if (len < 0)
1592 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001593 }
1594
Olivier Deprez157378f2022-04-04 15:47:50 +02001595 if (clear)
1596 clear_seq = seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001597 logbuf_unlock_irq();
1598
1599 kfree(text);
1600 return len;
1601}
1602
1603static void syslog_clear(void)
1604{
1605 logbuf_lock_irq();
Olivier Deprez157378f2022-04-04 15:47:50 +02001606 clear_seq = prb_next_seq(prb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001607 logbuf_unlock_irq();
1608}
1609
1610int do_syslog(int type, char __user *buf, int len, int source)
1611{
Olivier Deprez157378f2022-04-04 15:47:50 +02001612 struct printk_info info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001613 bool clear = false;
1614 static int saved_console_loglevel = LOGLEVEL_DEFAULT;
1615 int error;
1616
1617 error = check_syslog_permissions(type, source);
1618 if (error)
1619 return error;
1620
1621 switch (type) {
1622 case SYSLOG_ACTION_CLOSE: /* Close log */
1623 break;
1624 case SYSLOG_ACTION_OPEN: /* Open log */
1625 break;
1626 case SYSLOG_ACTION_READ: /* Read from log */
1627 if (!buf || len < 0)
1628 return -EINVAL;
1629 if (!len)
1630 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00001631 if (!access_ok(buf, len))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001632 return -EFAULT;
1633 error = wait_event_interruptible(log_wait,
Olivier Deprez157378f2022-04-04 15:47:50 +02001634 prb_read_valid(prb, syslog_seq, NULL));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001635 if (error)
1636 return error;
1637 error = syslog_print(buf, len);
1638 break;
1639 /* Read/clear last kernel messages */
1640 case SYSLOG_ACTION_READ_CLEAR:
1641 clear = true;
Olivier Deprez157378f2022-04-04 15:47:50 +02001642 fallthrough;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001643 /* Read last kernel messages */
1644 case SYSLOG_ACTION_READ_ALL:
1645 if (!buf || len < 0)
1646 return -EINVAL;
1647 if (!len)
1648 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00001649 if (!access_ok(buf, len))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001650 return -EFAULT;
1651 error = syslog_print_all(buf, len, clear);
1652 break;
1653 /* Clear ring buffer */
1654 case SYSLOG_ACTION_CLEAR:
1655 syslog_clear();
1656 break;
1657 /* Disable logging to console */
1658 case SYSLOG_ACTION_CONSOLE_OFF:
1659 if (saved_console_loglevel == LOGLEVEL_DEFAULT)
1660 saved_console_loglevel = console_loglevel;
1661 console_loglevel = minimum_console_loglevel;
1662 break;
1663 /* Enable logging to console */
1664 case SYSLOG_ACTION_CONSOLE_ON:
1665 if (saved_console_loglevel != LOGLEVEL_DEFAULT) {
1666 console_loglevel = saved_console_loglevel;
1667 saved_console_loglevel = LOGLEVEL_DEFAULT;
1668 }
1669 break;
1670 /* Set level of messages printed to console */
1671 case SYSLOG_ACTION_CONSOLE_LEVEL:
1672 if (len < 1 || len > 8)
1673 return -EINVAL;
1674 if (len < minimum_console_loglevel)
1675 len = minimum_console_loglevel;
1676 console_loglevel = len;
1677 /* Implicitly re-enable logging to console */
1678 saved_console_loglevel = LOGLEVEL_DEFAULT;
1679 break;
1680 /* Number of chars in the log buffer */
1681 case SYSLOG_ACTION_SIZE_UNREAD:
1682 logbuf_lock_irq();
Olivier Deprez157378f2022-04-04 15:47:50 +02001683 if (!prb_read_valid_info(prb, syslog_seq, &info, NULL)) {
1684 /* No unread messages. */
1685 logbuf_unlock_irq();
1686 return 0;
1687 }
1688 if (info.seq != syslog_seq) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001689 /* messages are gone, move to first one */
Olivier Deprez157378f2022-04-04 15:47:50 +02001690 syslog_seq = info.seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001691 syslog_partial = 0;
1692 }
1693 if (source == SYSLOG_FROM_PROC) {
1694 /*
1695 * Short-cut for poll(/"proc/kmsg") which simply checks
1696 * for pending data, not the size; return the count of
1697 * records, not the length.
1698 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001699 error = prb_next_seq(prb) - syslog_seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001700 } else {
David Brazdil0f672f62019-12-10 10:32:29 +00001701 bool time = syslog_partial ? syslog_time : printk_time;
Olivier Deprez157378f2022-04-04 15:47:50 +02001702 unsigned int line_count;
1703 u64 seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001704
Olivier Deprez157378f2022-04-04 15:47:50 +02001705 prb_for_each_info(syslog_seq, prb, seq, &info,
1706 &line_count) {
1707 error += get_record_print_text_size(&info, line_count,
1708 true, time);
David Brazdil0f672f62019-12-10 10:32:29 +00001709 time = printk_time;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001710 }
1711 error -= syslog_partial;
1712 }
1713 logbuf_unlock_irq();
1714 break;
1715 /* Size of the log buffer */
1716 case SYSLOG_ACTION_SIZE_BUFFER:
1717 error = log_buf_len;
1718 break;
1719 default:
1720 error = -EINVAL;
1721 break;
1722 }
1723
1724 return error;
1725}
1726
1727SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
1728{
1729 return do_syslog(type, buf, len, SYSLOG_FROM_READER);
1730}
1731
1732/*
1733 * Special console_lock variants that help to reduce the risk of soft-lockups.
1734 * They allow to pass console_lock to another printk() call using a busy wait.
1735 */
1736
1737#ifdef CONFIG_LOCKDEP
1738static struct lockdep_map console_owner_dep_map = {
1739 .name = "console_owner"
1740};
1741#endif
1742
1743static DEFINE_RAW_SPINLOCK(console_owner_lock);
1744static struct task_struct *console_owner;
1745static bool console_waiter;
1746
1747/**
1748 * console_lock_spinning_enable - mark beginning of code where another
1749 * thread might safely busy wait
1750 *
1751 * This basically converts console_lock into a spinlock. This marks
1752 * the section where the console_lock owner can not sleep, because
1753 * there may be a waiter spinning (like a spinlock). Also it must be
1754 * ready to hand over the lock at the end of the section.
1755 */
1756static void console_lock_spinning_enable(void)
1757{
1758 raw_spin_lock(&console_owner_lock);
1759 console_owner = current;
1760 raw_spin_unlock(&console_owner_lock);
1761
1762 /* The waiter may spin on us after setting console_owner */
1763 spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1764}
1765
1766/**
1767 * console_lock_spinning_disable_and_check - mark end of code where another
1768 * thread was able to busy wait and check if there is a waiter
1769 *
1770 * This is called at the end of the section where spinning is allowed.
1771 * It has two functions. First, it is a signal that it is no longer
1772 * safe to start busy waiting for the lock. Second, it checks if
1773 * there is a busy waiter and passes the lock rights to her.
1774 *
1775 * Important: Callers lose the lock if there was a busy waiter.
1776 * They must not touch items synchronized by console_lock
1777 * in this case.
1778 *
1779 * Return: 1 if the lock rights were passed, 0 otherwise.
1780 */
1781static int console_lock_spinning_disable_and_check(void)
1782{
1783 int waiter;
1784
1785 raw_spin_lock(&console_owner_lock);
1786 waiter = READ_ONCE(console_waiter);
1787 console_owner = NULL;
1788 raw_spin_unlock(&console_owner_lock);
1789
1790 if (!waiter) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001791 spin_release(&console_owner_dep_map, _THIS_IP_);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001792 return 0;
1793 }
1794
1795 /* The waiter is now free to continue */
1796 WRITE_ONCE(console_waiter, false);
1797
Olivier Deprez157378f2022-04-04 15:47:50 +02001798 spin_release(&console_owner_dep_map, _THIS_IP_);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001799
1800 /*
1801 * Hand off console_lock to waiter. The waiter will perform
1802 * the up(). After this, the waiter is the console_lock owner.
1803 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001804 mutex_release(&console_lock_dep_map, _THIS_IP_);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001805 return 1;
1806}
1807
1808/**
1809 * console_trylock_spinning - try to get console_lock by busy waiting
1810 *
1811 * This allows to busy wait for the console_lock when the current
1812 * owner is running in specially marked sections. It means that
1813 * the current owner is running and cannot reschedule until it
1814 * is ready to lose the lock.
1815 *
1816 * Return: 1 if we got the lock, 0 othrewise
1817 */
1818static int console_trylock_spinning(void)
1819{
1820 struct task_struct *owner = NULL;
1821 bool waiter;
1822 bool spin = false;
1823 unsigned long flags;
1824
1825 if (console_trylock())
1826 return 1;
1827
1828 printk_safe_enter_irqsave(flags);
1829
1830 raw_spin_lock(&console_owner_lock);
1831 owner = READ_ONCE(console_owner);
1832 waiter = READ_ONCE(console_waiter);
1833 if (!waiter && owner && owner != current) {
1834 WRITE_ONCE(console_waiter, true);
1835 spin = true;
1836 }
1837 raw_spin_unlock(&console_owner_lock);
1838
1839 /*
1840 * If there is an active printk() writing to the
1841 * consoles, instead of having it write our data too,
1842 * see if we can offload that load from the active
1843 * printer, and do some printing ourselves.
1844 * Go into a spin only if there isn't already a waiter
1845 * spinning, and there is an active printer, and
1846 * that active printer isn't us (recursive printk?).
1847 */
1848 if (!spin) {
1849 printk_safe_exit_irqrestore(flags);
1850 return 0;
1851 }
1852
1853 /* We spin waiting for the owner to release us */
1854 spin_acquire(&console_owner_dep_map, 0, 0, _THIS_IP_);
1855 /* Owner will clear console_waiter on hand off */
1856 while (READ_ONCE(console_waiter))
1857 cpu_relax();
Olivier Deprez157378f2022-04-04 15:47:50 +02001858 spin_release(&console_owner_dep_map, _THIS_IP_);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001859
1860 printk_safe_exit_irqrestore(flags);
1861 /*
1862 * The owner passed the console lock to us.
1863 * Since we did not spin on console lock, annotate
1864 * this as a trylock. Otherwise lockdep will
1865 * complain.
1866 */
1867 mutex_acquire(&console_lock_dep_map, 0, 1, _THIS_IP_);
1868
1869 return 1;
1870}
1871
1872/*
1873 * Call the console drivers, asking them to write out
1874 * log_buf[start] to log_buf[end - 1].
1875 * The console_lock must be held.
1876 */
1877static void call_console_drivers(const char *ext_text, size_t ext_len,
1878 const char *text, size_t len)
1879{
Olivier Deprez157378f2022-04-04 15:47:50 +02001880 static char dropped_text[64];
1881 size_t dropped_len = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001882 struct console *con;
1883
1884 trace_console_rcuidle(text, len);
1885
1886 if (!console_drivers)
1887 return;
1888
Olivier Deprez157378f2022-04-04 15:47:50 +02001889 if (console_dropped) {
1890 dropped_len = snprintf(dropped_text, sizeof(dropped_text),
1891 "** %lu printk messages dropped **\n",
1892 console_dropped);
1893 console_dropped = 0;
1894 }
1895
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001896 for_each_console(con) {
1897 if (exclusive_console && con != exclusive_console)
1898 continue;
1899 if (!(con->flags & CON_ENABLED))
1900 continue;
1901 if (!con->write)
1902 continue;
1903 if (!cpu_online(smp_processor_id()) &&
1904 !(con->flags & CON_ANYTIME))
1905 continue;
1906 if (con->flags & CON_EXTENDED)
1907 con->write(con, ext_text, ext_len);
Olivier Deprez157378f2022-04-04 15:47:50 +02001908 else {
1909 if (dropped_len)
1910 con->write(con, dropped_text, dropped_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001911 con->write(con, text, len);
Olivier Deprez157378f2022-04-04 15:47:50 +02001912 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001913 }
1914}
1915
1916int printk_delay_msec __read_mostly;
1917
1918static inline void printk_delay(void)
1919{
1920 if (unlikely(printk_delay_msec)) {
1921 int m = printk_delay_msec;
1922
1923 while (m--) {
1924 mdelay(1);
1925 touch_nmi_watchdog();
1926 }
1927 }
1928}
1929
David Brazdil0f672f62019-12-10 10:32:29 +00001930static inline u32 printk_caller_id(void)
1931{
1932 return in_task() ? task_pid_nr(current) :
1933 0x80000000 + raw_smp_processor_id();
1934}
1935
Olivier Deprez157378f2022-04-04 15:47:50 +02001936static size_t log_output(int facility, int level, enum log_flags lflags,
1937 const struct dev_printk_info *dev_info,
1938 char *text, size_t text_len)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001939{
David Brazdil0f672f62019-12-10 10:32:29 +00001940 const u32 caller_id = printk_caller_id();
1941
Olivier Deprez157378f2022-04-04 15:47:50 +02001942 if (lflags & LOG_CONT) {
1943 struct prb_reserved_entry e;
1944 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001945
Olivier Deprez157378f2022-04-04 15:47:50 +02001946 prb_rec_init_wr(&r, text_len);
1947 if (prb_reserve_in_last(&e, prb, &r, caller_id, LOG_LINE_MAX)) {
1948 memcpy(&r.text_buf[r.info->text_len], text, text_len);
1949 r.info->text_len += text_len;
1950 if (lflags & LOG_NEWLINE) {
1951 r.info->flags |= LOG_NEWLINE;
1952 prb_final_commit(&e);
1953 } else {
1954 prb_commit(&e);
1955 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001956 return text_len;
Olivier Deprez157378f2022-04-04 15:47:50 +02001957 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001958 }
1959
1960 /* Store it in the record log */
David Brazdil0f672f62019-12-10 10:32:29 +00001961 return log_store(caller_id, facility, level, lflags, 0,
Olivier Deprez157378f2022-04-04 15:47:50 +02001962 dev_info, text, text_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001963}
1964
1965/* Must be called under logbuf_lock. */
1966int vprintk_store(int facility, int level,
Olivier Deprez157378f2022-04-04 15:47:50 +02001967 const struct dev_printk_info *dev_info,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001968 const char *fmt, va_list args)
1969{
1970 static char textbuf[LOG_LINE_MAX];
1971 char *text = textbuf;
1972 size_t text_len;
1973 enum log_flags lflags = 0;
1974
1975 /*
1976 * The printf needs to come first; we need the syslog
1977 * prefix which might be passed-in as a parameter.
1978 */
1979 text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
1980
1981 /* mark and strip a trailing newline */
1982 if (text_len && text[text_len-1] == '\n') {
1983 text_len--;
1984 lflags |= LOG_NEWLINE;
1985 }
1986
1987 /* strip kernel syslog prefix and extract log level or control flags */
1988 if (facility == 0) {
1989 int kern_level;
1990
1991 while ((kern_level = printk_get_level(text)) != 0) {
1992 switch (kern_level) {
1993 case '0' ... '7':
1994 if (level == LOGLEVEL_DEFAULT)
1995 level = kern_level - '0';
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001996 break;
1997 case 'c': /* KERN_CONT */
1998 lflags |= LOG_CONT;
1999 }
2000
2001 text_len -= 2;
2002 text += 2;
2003 }
2004 }
2005
2006 if (level == LOGLEVEL_DEFAULT)
2007 level = default_message_loglevel;
2008
Olivier Deprez157378f2022-04-04 15:47:50 +02002009 if (dev_info)
David Brazdil0f672f62019-12-10 10:32:29 +00002010 lflags |= LOG_NEWLINE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002011
Olivier Deprez157378f2022-04-04 15:47:50 +02002012 return log_output(facility, level, lflags, dev_info, text, text_len);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002013}
2014
2015asmlinkage int vprintk_emit(int facility, int level,
Olivier Deprez157378f2022-04-04 15:47:50 +02002016 const struct dev_printk_info *dev_info,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002017 const char *fmt, va_list args)
2018{
2019 int printed_len;
Olivier Deprez157378f2022-04-04 15:47:50 +02002020 bool in_sched = false;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002021 unsigned long flags;
David Brazdil0f672f62019-12-10 10:32:29 +00002022
2023 /* Suppress unimportant messages after panic happens */
2024 if (unlikely(suppress_printk))
2025 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002026
2027 if (level == LOGLEVEL_SCHED) {
2028 level = LOGLEVEL_DEFAULT;
2029 in_sched = true;
2030 }
2031
2032 boot_delay_msec(level);
2033 printk_delay();
2034
2035 /* This stops the holder of console_sem just where we want him */
2036 logbuf_lock_irqsave(flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02002037 printed_len = vprintk_store(facility, level, dev_info, fmt, args);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002038 logbuf_unlock_irqrestore(flags);
2039
2040 /* If called from the scheduler, we can not call up(). */
Olivier Deprez157378f2022-04-04 15:47:50 +02002041 if (!in_sched) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002042 /*
2043 * Disable preemption to avoid being preempted while holding
2044 * console_sem which would prevent anyone from printing to
2045 * console
2046 */
2047 preempt_disable();
2048 /*
2049 * Try to acquire and then immediately release the console
2050 * semaphore. The release will print out buffers and wake up
2051 * /dev/kmsg and syslog() users.
2052 */
2053 if (console_trylock_spinning())
2054 console_unlock();
2055 preempt_enable();
2056 }
2057
Olivier Deprez157378f2022-04-04 15:47:50 +02002058 wake_up_klogd();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002059 return printed_len;
2060}
2061EXPORT_SYMBOL(vprintk_emit);
2062
2063asmlinkage int vprintk(const char *fmt, va_list args)
2064{
2065 return vprintk_func(fmt, args);
2066}
2067EXPORT_SYMBOL(vprintk);
2068
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002069int vprintk_default(const char *fmt, va_list args)
2070{
Olivier Deprez157378f2022-04-04 15:47:50 +02002071 return vprintk_emit(0, LOGLEVEL_DEFAULT, NULL, fmt, args);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002072}
2073EXPORT_SYMBOL_GPL(vprintk_default);
2074
2075/**
2076 * printk - print a kernel message
2077 * @fmt: format string
2078 *
2079 * This is printk(). It can be called from any context. We want it to work.
2080 *
2081 * We try to grab the console_lock. If we succeed, it's easy - we log the
2082 * output and call the console drivers. If we fail to get the semaphore, we
2083 * place the output into the log buffer and return. The current holder of
2084 * the console_sem will notice the new output in console_unlock(); and will
2085 * send it to the consoles before releasing the lock.
2086 *
2087 * One effect of this deferred printing is that code which calls printk() and
2088 * then changes console_loglevel may break. This is because console_loglevel
2089 * is inspected when the actual printing occurs.
2090 *
2091 * See also:
2092 * printf(3)
2093 *
2094 * See the vsnprintf() documentation for format string extensions over C99.
2095 */
2096asmlinkage __visible int printk(const char *fmt, ...)
2097{
2098 va_list args;
2099 int r;
2100
2101 va_start(args, fmt);
2102 r = vprintk_func(fmt, args);
2103 va_end(args);
2104
2105 return r;
2106}
2107EXPORT_SYMBOL(printk);
2108
2109#else /* CONFIG_PRINTK */
2110
2111#define LOG_LINE_MAX 0
2112#define PREFIX_MAX 0
David Brazdil0f672f62019-12-10 10:32:29 +00002113#define printk_time false
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002114
Olivier Deprez157378f2022-04-04 15:47:50 +02002115#define prb_read_valid(rb, seq, r) false
2116#define prb_first_valid_seq(rb) 0
2117
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002118static u64 syslog_seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002119static u64 console_seq;
David Brazdil0f672f62019-12-10 10:32:29 +00002120static u64 exclusive_console_stop_seq;
Olivier Deprez157378f2022-04-04 15:47:50 +02002121static unsigned long console_dropped;
2122
2123static size_t record_print_text(const struct printk_record *r,
2124 bool syslog, bool time)
2125{
2126 return 0;
2127}
2128static ssize_t info_print_ext_header(char *buf, size_t size,
2129 struct printk_info *info)
2130{
2131 return 0;
2132}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002133static ssize_t msg_print_ext_body(char *buf, size_t size,
Olivier Deprez157378f2022-04-04 15:47:50 +02002134 char *text, size_t text_len,
2135 struct dev_printk_info *dev_info) { return 0; }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002136static void console_lock_spinning_enable(void) { }
2137static int console_lock_spinning_disable_and_check(void) { return 0; }
2138static void call_console_drivers(const char *ext_text, size_t ext_len,
2139 const char *text, size_t len) {}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002140static bool suppress_message_printing(int level) { return false; }
2141
2142#endif /* CONFIG_PRINTK */
2143
2144#ifdef CONFIG_EARLY_PRINTK
2145struct console *early_console;
2146
2147asmlinkage __visible void early_printk(const char *fmt, ...)
2148{
2149 va_list ap;
2150 char buf[512];
2151 int n;
2152
2153 if (!early_console)
2154 return;
2155
2156 va_start(ap, fmt);
2157 n = vscnprintf(buf, sizeof(buf), fmt, ap);
2158 va_end(ap);
2159
2160 early_console->write(early_console, buf, n);
2161}
2162#endif
2163
2164static int __add_preferred_console(char *name, int idx, char *options,
Olivier Deprez157378f2022-04-04 15:47:50 +02002165 char *brl_options, bool user_specified)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002166{
2167 struct console_cmdline *c;
2168 int i;
2169
2170 /*
2171 * See if this tty is not yet registered, and
2172 * if we have a slot free.
2173 */
2174 for (i = 0, c = console_cmdline;
2175 i < MAX_CMDLINECONSOLES && c->name[0];
2176 i++, c++) {
2177 if (strcmp(c->name, name) == 0 && c->index == idx) {
2178 if (!brl_options)
2179 preferred_console = i;
Olivier Deprez157378f2022-04-04 15:47:50 +02002180 if (user_specified)
2181 c->user_specified = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002182 return 0;
2183 }
2184 }
2185 if (i == MAX_CMDLINECONSOLES)
2186 return -E2BIG;
2187 if (!brl_options)
2188 preferred_console = i;
2189 strlcpy(c->name, name, sizeof(c->name));
2190 c->options = options;
Olivier Deprez157378f2022-04-04 15:47:50 +02002191 c->user_specified = user_specified;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002192 braille_set_options(c, brl_options);
2193
2194 c->index = idx;
2195 return 0;
2196}
2197
2198static int __init console_msg_format_setup(char *str)
2199{
2200 if (!strcmp(str, "syslog"))
2201 console_msg_format = MSG_FORMAT_SYSLOG;
2202 if (!strcmp(str, "default"))
2203 console_msg_format = MSG_FORMAT_DEFAULT;
2204 return 1;
2205}
2206__setup("console_msg_format=", console_msg_format_setup);
2207
2208/*
2209 * Set up a console. Called via do_early_param() in init/main.c
2210 * for each "console=" parameter in the boot command line.
2211 */
2212static int __init console_setup(char *str)
2213{
2214 char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for "ttyS" */
2215 char *s, *options, *brl_options = NULL;
2216 int idx;
2217
Olivier Deprez157378f2022-04-04 15:47:50 +02002218 /*
2219 * console="" or console=null have been suggested as a way to
2220 * disable console output. Use ttynull that has been created
2221 * for exacly this purpose.
2222 */
2223 if (str[0] == 0 || strcmp(str, "null") == 0) {
2224 __add_preferred_console("ttynull", 0, NULL, NULL, true);
Olivier Deprez0e641232021-09-23 10:07:05 +02002225 return 1;
Olivier Deprez157378f2022-04-04 15:47:50 +02002226 }
Olivier Deprez0e641232021-09-23 10:07:05 +02002227
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002228 if (_braille_console_setup(&str, &brl_options))
2229 return 1;
2230
2231 /*
2232 * Decode str into name, index, options.
2233 */
2234 if (str[0] >= '0' && str[0] <= '9') {
2235 strcpy(buf, "ttyS");
2236 strncpy(buf + 4, str, sizeof(buf) - 5);
2237 } else {
2238 strncpy(buf, str, sizeof(buf) - 1);
2239 }
2240 buf[sizeof(buf) - 1] = 0;
2241 options = strchr(str, ',');
2242 if (options)
2243 *(options++) = 0;
2244#ifdef __sparc__
2245 if (!strcmp(str, "ttya"))
2246 strcpy(buf, "ttyS0");
2247 if (!strcmp(str, "ttyb"))
2248 strcpy(buf, "ttyS1");
2249#endif
2250 for (s = buf; *s; s++)
2251 if (isdigit(*s) || *s == ',')
2252 break;
2253 idx = simple_strtoul(s, NULL, 10);
2254 *s = 0;
2255
Olivier Deprez157378f2022-04-04 15:47:50 +02002256 __add_preferred_console(buf, idx, options, brl_options, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002257 console_set_on_cmdline = 1;
2258 return 1;
2259}
2260__setup("console=", console_setup);
2261
2262/**
2263 * add_preferred_console - add a device to the list of preferred consoles.
2264 * @name: device name
2265 * @idx: device index
2266 * @options: options for this console
2267 *
2268 * The last preferred console added will be used for kernel messages
2269 * and stdin/out/err for init. Normally this is used by console_setup
2270 * above to handle user-supplied console arguments; however it can also
2271 * be used by arch-specific code either to override the user or more
2272 * commonly to provide a default console (ie from PROM variables) when
2273 * the user has not supplied one.
2274 */
2275int add_preferred_console(char *name, int idx, char *options)
2276{
Olivier Deprez157378f2022-04-04 15:47:50 +02002277 return __add_preferred_console(name, idx, options, NULL, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002278}
2279
2280bool console_suspend_enabled = true;
2281EXPORT_SYMBOL(console_suspend_enabled);
2282
2283static int __init console_suspend_disable(char *str)
2284{
2285 console_suspend_enabled = false;
2286 return 1;
2287}
2288__setup("no_console_suspend", console_suspend_disable);
2289module_param_named(console_suspend, console_suspend_enabled,
2290 bool, S_IRUGO | S_IWUSR);
2291MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
2292 " and hibernate operations");
2293
2294/**
2295 * suspend_console - suspend the console subsystem
2296 *
2297 * This disables printk() while we go into suspend states
2298 */
2299void suspend_console(void)
2300{
2301 if (!console_suspend_enabled)
2302 return;
2303 pr_info("Suspending console(s) (use no_console_suspend to debug)\n");
2304 console_lock();
2305 console_suspended = 1;
2306 up_console_sem();
2307}
2308
2309void resume_console(void)
2310{
2311 if (!console_suspend_enabled)
2312 return;
2313 down_console_sem();
2314 console_suspended = 0;
2315 console_unlock();
2316}
2317
2318/**
2319 * console_cpu_notify - print deferred console messages after CPU hotplug
2320 * @cpu: unused
2321 *
2322 * If printk() is called from a CPU that is not online yet, the messages
2323 * will be printed on the console only if there are CON_ANYTIME consoles.
2324 * This function is called when a new CPU comes online (or fails to come
2325 * up) or goes offline.
2326 */
2327static int console_cpu_notify(unsigned int cpu)
2328{
2329 if (!cpuhp_tasks_frozen) {
2330 /* If trylock fails, someone else is doing the printing */
2331 if (console_trylock())
2332 console_unlock();
2333 }
2334 return 0;
2335}
2336
2337/**
2338 * console_lock - lock the console system for exclusive use.
2339 *
2340 * Acquires a lock which guarantees that the caller has
2341 * exclusive access to the console system and the console_drivers list.
2342 *
2343 * Can sleep, returns nothing.
2344 */
2345void console_lock(void)
2346{
2347 might_sleep();
2348
2349 down_console_sem();
2350 if (console_suspended)
2351 return;
2352 console_locked = 1;
2353 console_may_schedule = 1;
2354}
2355EXPORT_SYMBOL(console_lock);
2356
2357/**
2358 * console_trylock - try to lock the console system for exclusive use.
2359 *
2360 * Try to acquire a lock which guarantees that the caller has exclusive
2361 * access to the console system and the console_drivers list.
2362 *
2363 * returns 1 on success, and 0 on failure to acquire the lock.
2364 */
2365int console_trylock(void)
2366{
2367 if (down_trylock_console_sem())
2368 return 0;
2369 if (console_suspended) {
2370 up_console_sem();
2371 return 0;
2372 }
2373 console_locked = 1;
2374 console_may_schedule = 0;
2375 return 1;
2376}
2377EXPORT_SYMBOL(console_trylock);
2378
2379int is_console_locked(void)
2380{
2381 return console_locked;
2382}
2383EXPORT_SYMBOL(is_console_locked);
2384
2385/*
2386 * Check if we have any console that is capable of printing while cpu is
2387 * booting or shutting down. Requires console_sem.
2388 */
2389static int have_callable_console(void)
2390{
2391 struct console *con;
2392
2393 for_each_console(con)
2394 if ((con->flags & CON_ENABLED) &&
2395 (con->flags & CON_ANYTIME))
2396 return 1;
2397
2398 return 0;
2399}
2400
2401/*
2402 * Can we actually use the console at this time on this cpu?
2403 *
2404 * Console drivers may assume that per-cpu resources have been allocated. So
2405 * unless they're explicitly marked as being able to cope (CON_ANYTIME) don't
2406 * call them until this CPU is officially up.
2407 */
2408static inline int can_use_console(void)
2409{
2410 return cpu_online(raw_smp_processor_id()) || have_callable_console();
2411}
2412
2413/**
2414 * console_unlock - unlock the console system
2415 *
2416 * Releases the console_lock which the caller holds on the console system
2417 * and the console driver list.
2418 *
2419 * While the console_lock was held, console output may have been buffered
2420 * by printk(). If this is the case, console_unlock(); emits
2421 * the output prior to releasing the lock.
2422 *
2423 * If there is output waiting, we wake /dev/kmsg and syslog() users.
2424 *
2425 * console_unlock(); may be called from any context.
2426 */
2427void console_unlock(void)
2428{
2429 static char ext_text[CONSOLE_EXT_LOG_MAX];
2430 static char text[LOG_LINE_MAX + PREFIX_MAX];
2431 unsigned long flags;
2432 bool do_cond_resched, retry;
Olivier Deprez157378f2022-04-04 15:47:50 +02002433 struct printk_info info;
2434 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002435
2436 if (console_suspended) {
2437 up_console_sem();
2438 return;
2439 }
2440
Olivier Deprez157378f2022-04-04 15:47:50 +02002441 prb_rec_init_rd(&r, &info, text, sizeof(text));
2442
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002443 /*
2444 * Console drivers are called with interrupts disabled, so
2445 * @console_may_schedule should be cleared before; however, we may
2446 * end up dumping a lot of lines, for example, if called from
2447 * console registration path, and should invoke cond_resched()
2448 * between lines if allowable. Not doing so can cause a very long
2449 * scheduling stall on a slow console leading to RCU stall and
2450 * softlockup warnings which exacerbate the issue with more
2451 * messages practically incapacitating the system.
2452 *
2453 * console_trylock() is not able to detect the preemptive
2454 * context reliably. Therefore the value must be stored before
Olivier Deprez157378f2022-04-04 15:47:50 +02002455 * and cleared after the "again" goto label.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002456 */
2457 do_cond_resched = console_may_schedule;
2458again:
2459 console_may_schedule = 0;
2460
2461 /*
2462 * We released the console_sem lock, so we need to recheck if
2463 * cpu is online and (if not) is there at least one CON_ANYTIME
2464 * console.
2465 */
2466 if (!can_use_console()) {
2467 console_locked = 0;
2468 up_console_sem();
2469 return;
2470 }
2471
2472 for (;;) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002473 size_t ext_len = 0;
2474 size_t len;
2475
2476 printk_safe_enter_irqsave(flags);
2477 raw_spin_lock(&logbuf_lock);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002478skip:
Olivier Deprez157378f2022-04-04 15:47:50 +02002479 if (!prb_read_valid(prb, console_seq, &r))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002480 break;
2481
Olivier Deprez157378f2022-04-04 15:47:50 +02002482 if (console_seq != r.info->seq) {
2483 console_dropped += r.info->seq - console_seq;
2484 console_seq = r.info->seq;
2485 }
2486
2487 if (suppress_message_printing(r.info->level)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002488 /*
2489 * Skip record we have buffered and already printed
2490 * directly to the console when we received it, and
2491 * record that has level above the console loglevel.
2492 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002493 console_seq++;
2494 goto skip;
2495 }
2496
David Brazdil0f672f62019-12-10 10:32:29 +00002497 /* Output to all consoles once old messages replayed. */
2498 if (unlikely(exclusive_console &&
2499 console_seq >= exclusive_console_stop_seq)) {
2500 exclusive_console = NULL;
2501 }
2502
Olivier Deprez157378f2022-04-04 15:47:50 +02002503 /*
2504 * Handle extended console text first because later
2505 * record_print_text() will modify the record buffer in-place.
2506 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002507 if (nr_ext_console_drivers) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002508 ext_len = info_print_ext_header(ext_text,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002509 sizeof(ext_text),
Olivier Deprez157378f2022-04-04 15:47:50 +02002510 r.info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002511 ext_len += msg_print_ext_body(ext_text + ext_len,
2512 sizeof(ext_text) - ext_len,
Olivier Deprez157378f2022-04-04 15:47:50 +02002513 &r.text_buf[0],
2514 r.info->text_len,
2515 &r.info->dev_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002516 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002517 len = record_print_text(&r,
2518 console_msg_format & MSG_FORMAT_SYSLOG,
2519 printk_time);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002520 console_seq++;
2521 raw_spin_unlock(&logbuf_lock);
2522
2523 /*
2524 * While actively printing out messages, if another printk()
2525 * were to occur on another CPU, it may wait for this one to
2526 * finish. This task can not be preempted if there is a
2527 * waiter waiting to take over.
2528 */
2529 console_lock_spinning_enable();
2530
2531 stop_critical_timings(); /* don't trace print latency */
2532 call_console_drivers(ext_text, ext_len, text, len);
2533 start_critical_timings();
2534
2535 if (console_lock_spinning_disable_and_check()) {
2536 printk_safe_exit_irqrestore(flags);
2537 return;
2538 }
2539
2540 printk_safe_exit_irqrestore(flags);
2541
2542 if (do_cond_resched)
2543 cond_resched();
2544 }
2545
2546 console_locked = 0;
2547
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002548 raw_spin_unlock(&logbuf_lock);
2549
2550 up_console_sem();
2551
2552 /*
2553 * Someone could have filled up the buffer again, so re-check if there's
2554 * something to flush. In case we cannot trylock the console_sem again,
2555 * there's a new owner and the console_unlock() from them will do the
2556 * flush, no worries.
2557 */
2558 raw_spin_lock(&logbuf_lock);
Olivier Deprez157378f2022-04-04 15:47:50 +02002559 retry = prb_read_valid(prb, console_seq, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002560 raw_spin_unlock(&logbuf_lock);
2561 printk_safe_exit_irqrestore(flags);
2562
2563 if (retry && console_trylock())
2564 goto again;
2565}
2566EXPORT_SYMBOL(console_unlock);
2567
2568/**
2569 * console_conditional_schedule - yield the CPU if required
2570 *
2571 * If the console code is currently allowed to sleep, and
2572 * if this CPU should yield the CPU to another task, do
2573 * so here.
2574 *
2575 * Must be called within console_lock();.
2576 */
2577void __sched console_conditional_schedule(void)
2578{
2579 if (console_may_schedule)
2580 cond_resched();
2581}
2582EXPORT_SYMBOL(console_conditional_schedule);
2583
2584void console_unblank(void)
2585{
2586 struct console *c;
2587
2588 /*
2589 * console_unblank can no longer be called in interrupt context unless
2590 * oops_in_progress is set to 1..
2591 */
2592 if (oops_in_progress) {
2593 if (down_trylock_console_sem() != 0)
2594 return;
2595 } else
2596 console_lock();
2597
2598 console_locked = 1;
2599 console_may_schedule = 0;
2600 for_each_console(c)
2601 if ((c->flags & CON_ENABLED) && c->unblank)
2602 c->unblank();
2603 console_unlock();
2604}
2605
2606/**
2607 * console_flush_on_panic - flush console content on panic
David Brazdil0f672f62019-12-10 10:32:29 +00002608 * @mode: flush all messages in buffer or just the pending ones
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002609 *
2610 * Immediately output all pending messages no matter what.
2611 */
David Brazdil0f672f62019-12-10 10:32:29 +00002612void console_flush_on_panic(enum con_flush_mode mode)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002613{
2614 /*
2615 * If someone else is holding the console lock, trylock will fail
2616 * and may_schedule may be set. Ignore and proceed to unlock so
2617 * that messages are flushed out. As this can be called from any
2618 * context and we don't want to get preempted while flushing,
2619 * ensure may_schedule is cleared.
2620 */
2621 console_trylock();
2622 console_may_schedule = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002623
2624 if (mode == CONSOLE_REPLAY_ALL) {
2625 unsigned long flags;
2626
2627 logbuf_lock_irqsave(flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02002628 console_seq = prb_first_valid_seq(prb);
David Brazdil0f672f62019-12-10 10:32:29 +00002629 logbuf_unlock_irqrestore(flags);
2630 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002631 console_unlock();
2632}
2633
2634/*
2635 * Return the console tty driver structure and its associated index
2636 */
2637struct tty_driver *console_device(int *index)
2638{
2639 struct console *c;
2640 struct tty_driver *driver = NULL;
2641
2642 console_lock();
2643 for_each_console(c) {
2644 if (!c->device)
2645 continue;
2646 driver = c->device(c, index);
2647 if (driver)
2648 break;
2649 }
2650 console_unlock();
2651 return driver;
2652}
2653
2654/*
2655 * Prevent further output on the passed console device so that (for example)
2656 * serial drivers can disable console output before suspending a port, and can
2657 * re-enable output afterwards.
2658 */
2659void console_stop(struct console *console)
2660{
2661 console_lock();
2662 console->flags &= ~CON_ENABLED;
2663 console_unlock();
2664}
2665EXPORT_SYMBOL(console_stop);
2666
2667void console_start(struct console *console)
2668{
2669 console_lock();
2670 console->flags |= CON_ENABLED;
2671 console_unlock();
2672}
2673EXPORT_SYMBOL(console_start);
2674
2675static int __read_mostly keep_bootcon;
2676
2677static int __init keep_bootcon_setup(char *str)
2678{
2679 keep_bootcon = 1;
2680 pr_info("debug: skip boot console de-registration.\n");
2681
2682 return 0;
2683}
2684
2685early_param("keep_bootcon", keep_bootcon_setup);
2686
2687/*
Olivier Deprez157378f2022-04-04 15:47:50 +02002688 * This is called by register_console() to try to match
2689 * the newly registered console with any of the ones selected
2690 * by either the command line or add_preferred_console() and
2691 * setup/enable it.
2692 *
2693 * Care need to be taken with consoles that are statically
2694 * enabled such as netconsole
2695 */
2696static int try_enable_new_console(struct console *newcon, bool user_specified)
2697{
2698 struct console_cmdline *c;
2699 int i, err;
2700
2701 for (i = 0, c = console_cmdline;
2702 i < MAX_CMDLINECONSOLES && c->name[0];
2703 i++, c++) {
2704 if (c->user_specified != user_specified)
2705 continue;
2706 if (!newcon->match ||
2707 newcon->match(newcon, c->name, c->index, c->options) != 0) {
2708 /* default matching */
2709 BUILD_BUG_ON(sizeof(c->name) != sizeof(newcon->name));
2710 if (strcmp(c->name, newcon->name) != 0)
2711 continue;
2712 if (newcon->index >= 0 &&
2713 newcon->index != c->index)
2714 continue;
2715 if (newcon->index < 0)
2716 newcon->index = c->index;
2717
2718 if (_braille_register_console(newcon, c))
2719 return 0;
2720
2721 if (newcon->setup &&
2722 (err = newcon->setup(newcon, c->options)) != 0)
2723 return err;
2724 }
2725 newcon->flags |= CON_ENABLED;
2726 if (i == preferred_console) {
2727 newcon->flags |= CON_CONSDEV;
2728 has_preferred_console = true;
2729 }
2730 return 0;
2731 }
2732
2733 /*
2734 * Some consoles, such as pstore and netconsole, can be enabled even
2735 * without matching. Accept the pre-enabled consoles only when match()
2736 * and setup() had a chance to be called.
2737 */
2738 if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
2739 return 0;
2740
2741 return -ENOENT;
2742}
2743
2744/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002745 * The console driver calls this routine during kernel initialization
2746 * to register the console printing procedure with printk() and to
2747 * print any messages that were printed by the kernel before the
2748 * console driver was initialized.
2749 *
2750 * This can happen pretty early during the boot process (because of
2751 * early_printk) - sometimes before setup_arch() completes - be careful
2752 * of what kernel features are used - they may not be initialised yet.
2753 *
2754 * There are two types of consoles - bootconsoles (early_printk) and
2755 * "real" consoles (everything which is not a bootconsole) which are
2756 * handled differently.
2757 * - Any number of bootconsoles can be registered at any time.
2758 * - As soon as a "real" console is registered, all bootconsoles
2759 * will be unregistered automatically.
2760 * - Once a "real" console is registered, any attempt to register a
2761 * bootconsoles will be rejected
2762 */
2763void register_console(struct console *newcon)
2764{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002765 unsigned long flags;
2766 struct console *bcon = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +02002767 int err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002768
Olivier Deprez157378f2022-04-04 15:47:50 +02002769 for_each_console(bcon) {
2770 if (WARN(bcon == newcon, "console '%s%d' already registered\n",
2771 bcon->name, bcon->index))
2772 return;
2773 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002774
2775 /*
2776 * before we register a new CON_BOOT console, make sure we don't
2777 * already have a valid console
2778 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002779 if (newcon->flags & CON_BOOT) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002780 for_each_console(bcon) {
2781 if (!(bcon->flags & CON_BOOT)) {
2782 pr_info("Too late to register bootconsole %s%d\n",
2783 newcon->name, newcon->index);
2784 return;
2785 }
2786 }
2787 }
2788
2789 if (console_drivers && console_drivers->flags & CON_BOOT)
2790 bcon = console_drivers;
2791
Olivier Deprez157378f2022-04-04 15:47:50 +02002792 if (!has_preferred_console || bcon || !console_drivers)
2793 has_preferred_console = preferred_console >= 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002794
2795 /*
2796 * See if we want to use this console driver. If we
2797 * didn't select a console we take the first one
2798 * that registers here.
2799 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002800 if (!has_preferred_console) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002801 if (newcon->index < 0)
2802 newcon->index = 0;
2803 if (newcon->setup == NULL ||
2804 newcon->setup(newcon, NULL) == 0) {
2805 newcon->flags |= CON_ENABLED;
2806 if (newcon->device) {
2807 newcon->flags |= CON_CONSDEV;
Olivier Deprez157378f2022-04-04 15:47:50 +02002808 has_preferred_console = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002809 }
2810 }
2811 }
2812
Olivier Deprez157378f2022-04-04 15:47:50 +02002813 /* See if this console matches one we selected on the command line */
2814 err = try_enable_new_console(newcon, true);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002815
Olivier Deprez157378f2022-04-04 15:47:50 +02002816 /* If not, try to match against the platform default(s) */
2817 if (err == -ENOENT)
2818 err = try_enable_new_console(newcon, false);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002819
Olivier Deprez157378f2022-04-04 15:47:50 +02002820 /* printk() messages are not printed to the Braille console. */
2821 if (err || newcon->flags & CON_BRL)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002822 return;
2823
2824 /*
2825 * If we have a bootconsole, and are switching to a real console,
2826 * don't print everything out again, since when the boot console, and
2827 * the real console are the same physical device, it's annoying to
2828 * see the beginning boot messages twice
2829 */
2830 if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
2831 newcon->flags &= ~CON_PRINTBUFFER;
2832
2833 /*
2834 * Put this console in the list - keep the
2835 * preferred driver at the head of the list.
2836 */
2837 console_lock();
2838 if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
2839 newcon->next = console_drivers;
2840 console_drivers = newcon;
2841 if (newcon->next)
2842 newcon->next->flags &= ~CON_CONSDEV;
Olivier Deprez157378f2022-04-04 15:47:50 +02002843 /* Ensure this flag is always set for the head of the list */
2844 newcon->flags |= CON_CONSDEV;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002845 } else {
2846 newcon->next = console_drivers->next;
2847 console_drivers->next = newcon;
2848 }
2849
2850 if (newcon->flags & CON_EXTENDED)
David Brazdil0f672f62019-12-10 10:32:29 +00002851 nr_ext_console_drivers++;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002852
2853 if (newcon->flags & CON_PRINTBUFFER) {
2854 /*
2855 * console_unlock(); will print out the buffered messages
2856 * for us.
2857 */
2858 logbuf_lock_irqsave(flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002859 /*
2860 * We're about to replay the log buffer. Only do this to the
2861 * just-registered console to avoid excessive message spam to
2862 * the already-registered consoles.
David Brazdil0f672f62019-12-10 10:32:29 +00002863 *
2864 * Set exclusive_console with disabled interrupts to reduce
2865 * race window with eventual console_flush_on_panic() that
2866 * ignores console_lock.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002867 */
2868 exclusive_console = newcon;
David Brazdil0f672f62019-12-10 10:32:29 +00002869 exclusive_console_stop_seq = console_seq;
Olivier Deprez0e641232021-09-23 10:07:05 +02002870 console_seq = syslog_seq;
David Brazdil0f672f62019-12-10 10:32:29 +00002871 logbuf_unlock_irqrestore(flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002872 }
2873 console_unlock();
2874 console_sysfs_notify();
2875
2876 /*
2877 * By unregistering the bootconsoles after we enable the real console
2878 * we get the "console xxx enabled" message on all the consoles -
2879 * boot consoles, real consoles, etc - this is to ensure that end
2880 * users know there might be something in the kernel's log buffer that
2881 * went to the bootconsole (that they do not see on the real console)
2882 */
2883 pr_info("%sconsole [%s%d] enabled\n",
2884 (newcon->flags & CON_BOOT) ? "boot" : "" ,
2885 newcon->name, newcon->index);
2886 if (bcon &&
2887 ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
2888 !keep_bootcon) {
2889 /* We need to iterate through all boot consoles, to make
2890 * sure we print everything out, before we unregister them.
2891 */
2892 for_each_console(bcon)
2893 if (bcon->flags & CON_BOOT)
2894 unregister_console(bcon);
2895 }
2896}
2897EXPORT_SYMBOL(register_console);
2898
2899int unregister_console(struct console *console)
2900{
Olivier Deprez157378f2022-04-04 15:47:50 +02002901 struct console *con;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002902 int res;
2903
2904 pr_info("%sconsole [%s%d] disabled\n",
2905 (console->flags & CON_BOOT) ? "boot" : "" ,
2906 console->name, console->index);
2907
2908 res = _braille_unregister_console(console);
Olivier Deprez157378f2022-04-04 15:47:50 +02002909 if (res < 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002910 return res;
Olivier Deprez157378f2022-04-04 15:47:50 +02002911 if (res > 0)
2912 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002913
Olivier Deprez157378f2022-04-04 15:47:50 +02002914 res = -ENODEV;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002915 console_lock();
2916 if (console_drivers == console) {
2917 console_drivers=console->next;
2918 res = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02002919 } else {
2920 for_each_console(con) {
2921 if (con->next == console) {
2922 con->next = console->next;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002923 res = 0;
2924 break;
2925 }
2926 }
2927 }
2928
Olivier Deprez157378f2022-04-04 15:47:50 +02002929 if (res)
2930 goto out_disable_unlock;
2931
2932 if (console->flags & CON_EXTENDED)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002933 nr_ext_console_drivers--;
2934
2935 /*
2936 * If this isn't the last console and it has CON_CONSDEV set, we
2937 * need to set it on the next preferred console.
2938 */
2939 if (console_drivers != NULL && console->flags & CON_CONSDEV)
2940 console_drivers->flags |= CON_CONSDEV;
2941
2942 console->flags &= ~CON_ENABLED;
2943 console_unlock();
2944 console_sysfs_notify();
Olivier Deprez157378f2022-04-04 15:47:50 +02002945
2946 if (console->exit)
2947 res = console->exit(console);
2948
2949 return res;
2950
2951out_disable_unlock:
2952 console->flags &= ~CON_ENABLED;
2953 console_unlock();
2954
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002955 return res;
2956}
2957EXPORT_SYMBOL(unregister_console);
2958
2959/*
2960 * Initialize the console device. This is called *early*, so
2961 * we can't necessarily depend on lots of kernel help here.
2962 * Just do some early initializations, and do the complex setup
2963 * later.
2964 */
2965void __init console_init(void)
2966{
2967 int ret;
2968 initcall_t call;
2969 initcall_entry_t *ce;
2970
2971 /* Setup the default TTY line discipline. */
2972 n_tty_init();
2973
2974 /*
2975 * set up the console device so that later boot sequences can
2976 * inform about problems etc..
2977 */
2978 ce = __con_initcall_start;
2979 trace_initcall_level("console");
2980 while (ce < __con_initcall_end) {
2981 call = initcall_from_entry(ce);
2982 trace_initcall_start(call);
2983 ret = call();
2984 trace_initcall_finish(call, ret);
2985 ce++;
2986 }
2987}
2988
2989/*
2990 * Some boot consoles access data that is in the init section and which will
2991 * be discarded after the initcalls have been run. To make sure that no code
2992 * will access this data, unregister the boot consoles in a late initcall.
2993 *
2994 * If for some reason, such as deferred probe or the driver being a loadable
2995 * module, the real console hasn't registered yet at this point, there will
2996 * be a brief interval in which no messages are logged to the console, which
2997 * makes it difficult to diagnose problems that occur during this time.
2998 *
2999 * To mitigate this problem somewhat, only unregister consoles whose memory
3000 * intersects with the init section. Note that all other boot consoles will
3001 * get unregistred when the real preferred console is registered.
3002 */
3003static int __init printk_late_init(void)
3004{
3005 struct console *con;
3006 int ret;
3007
3008 for_each_console(con) {
3009 if (!(con->flags & CON_BOOT))
3010 continue;
3011
3012 /* Check addresses that might be used for enabled consoles. */
3013 if (init_section_intersects(con, sizeof(*con)) ||
3014 init_section_contains(con->write, 0) ||
3015 init_section_contains(con->read, 0) ||
3016 init_section_contains(con->device, 0) ||
3017 init_section_contains(con->unblank, 0) ||
3018 init_section_contains(con->data, 0)) {
3019 /*
3020 * Please, consider moving the reported consoles out
3021 * of the init section.
3022 */
3023 pr_warn("bootconsole [%s%d] uses init memory and must be disabled even before the real one is ready\n",
3024 con->name, con->index);
3025 unregister_console(con);
3026 }
3027 }
3028 ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
3029 console_cpu_notify);
3030 WARN_ON(ret < 0);
3031 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "printk:online",
3032 console_cpu_notify, NULL);
3033 WARN_ON(ret < 0);
3034 return 0;
3035}
3036late_initcall(printk_late_init);
3037
3038#if defined CONFIG_PRINTK
3039/*
3040 * Delayed printk version, for scheduler-internal messages:
3041 */
3042#define PRINTK_PENDING_WAKEUP 0x01
3043#define PRINTK_PENDING_OUTPUT 0x02
3044
3045static DEFINE_PER_CPU(int, printk_pending);
3046
3047static void wake_up_klogd_work_func(struct irq_work *irq_work)
3048{
3049 int pending = __this_cpu_xchg(printk_pending, 0);
3050
3051 if (pending & PRINTK_PENDING_OUTPUT) {
3052 /* If trylock fails, someone else is doing the printing */
3053 if (console_trylock())
3054 console_unlock();
3055 }
3056
3057 if (pending & PRINTK_PENDING_WAKEUP)
3058 wake_up_interruptible(&log_wait);
3059}
3060
3061static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
3062 .func = wake_up_klogd_work_func,
Olivier Deprez157378f2022-04-04 15:47:50 +02003063 .flags = ATOMIC_INIT(IRQ_WORK_LAZY),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003064};
3065
3066void wake_up_klogd(void)
3067{
Olivier Deprez0e641232021-09-23 10:07:05 +02003068 if (!printk_percpu_data_ready())
3069 return;
3070
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003071 preempt_disable();
3072 if (waitqueue_active(&log_wait)) {
3073 this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
3074 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3075 }
3076 preempt_enable();
3077}
3078
3079void defer_console_output(void)
3080{
Olivier Deprez0e641232021-09-23 10:07:05 +02003081 if (!printk_percpu_data_ready())
3082 return;
3083
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003084 preempt_disable();
3085 __this_cpu_or(printk_pending, PRINTK_PENDING_OUTPUT);
3086 irq_work_queue(this_cpu_ptr(&wake_up_klogd_work));
3087 preempt_enable();
3088}
3089
3090int vprintk_deferred(const char *fmt, va_list args)
3091{
3092 int r;
3093
Olivier Deprez157378f2022-04-04 15:47:50 +02003094 r = vprintk_emit(0, LOGLEVEL_SCHED, NULL, fmt, args);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003095 defer_console_output();
3096
3097 return r;
3098}
3099
3100int printk_deferred(const char *fmt, ...)
3101{
3102 va_list args;
3103 int r;
3104
3105 va_start(args, fmt);
3106 r = vprintk_deferred(fmt, args);
3107 va_end(args);
3108
3109 return r;
3110}
3111
3112/*
3113 * printk rate limiting, lifted from the networking subsystem.
3114 *
3115 * This enforces a rate limit: not more than 10 kernel messages
3116 * every 5s to make a denial-of-service attack impossible.
3117 */
3118DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
3119
3120int __printk_ratelimit(const char *func)
3121{
3122 return ___ratelimit(&printk_ratelimit_state, func);
3123}
3124EXPORT_SYMBOL(__printk_ratelimit);
3125
3126/**
3127 * printk_timed_ratelimit - caller-controlled printk ratelimiting
3128 * @caller_jiffies: pointer to caller's state
3129 * @interval_msecs: minimum interval between prints
3130 *
3131 * printk_timed_ratelimit() returns true if more than @interval_msecs
3132 * milliseconds have elapsed since the last time printk_timed_ratelimit()
3133 * returned true.
3134 */
3135bool printk_timed_ratelimit(unsigned long *caller_jiffies,
3136 unsigned int interval_msecs)
3137{
3138 unsigned long elapsed = jiffies - *caller_jiffies;
3139
3140 if (*caller_jiffies && elapsed <= msecs_to_jiffies(interval_msecs))
3141 return false;
3142
3143 *caller_jiffies = jiffies;
3144 return true;
3145}
3146EXPORT_SYMBOL(printk_timed_ratelimit);
3147
3148static DEFINE_SPINLOCK(dump_list_lock);
3149static LIST_HEAD(dump_list);
3150
3151/**
3152 * kmsg_dump_register - register a kernel log dumper.
3153 * @dumper: pointer to the kmsg_dumper structure
3154 *
3155 * Adds a kernel log dumper to the system. The dump callback in the
3156 * structure will be called when the kernel oopses or panics and must be
3157 * set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
3158 */
3159int kmsg_dump_register(struct kmsg_dumper *dumper)
3160{
3161 unsigned long flags;
3162 int err = -EBUSY;
3163
3164 /* The dump callback needs to be set */
3165 if (!dumper->dump)
3166 return -EINVAL;
3167
3168 spin_lock_irqsave(&dump_list_lock, flags);
3169 /* Don't allow registering multiple times */
3170 if (!dumper->registered) {
3171 dumper->registered = 1;
3172 list_add_tail_rcu(&dumper->list, &dump_list);
3173 err = 0;
3174 }
3175 spin_unlock_irqrestore(&dump_list_lock, flags);
3176
3177 return err;
3178}
3179EXPORT_SYMBOL_GPL(kmsg_dump_register);
3180
3181/**
3182 * kmsg_dump_unregister - unregister a kmsg dumper.
3183 * @dumper: pointer to the kmsg_dumper structure
3184 *
3185 * Removes a dump device from the system. Returns zero on success and
3186 * %-EINVAL otherwise.
3187 */
3188int kmsg_dump_unregister(struct kmsg_dumper *dumper)
3189{
3190 unsigned long flags;
3191 int err = -EINVAL;
3192
3193 spin_lock_irqsave(&dump_list_lock, flags);
3194 if (dumper->registered) {
3195 dumper->registered = 0;
3196 list_del_rcu(&dumper->list);
3197 err = 0;
3198 }
3199 spin_unlock_irqrestore(&dump_list_lock, flags);
3200 synchronize_rcu();
3201
3202 return err;
3203}
3204EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
3205
3206static bool always_kmsg_dump;
3207module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
3208
Olivier Deprez157378f2022-04-04 15:47:50 +02003209const char *kmsg_dump_reason_str(enum kmsg_dump_reason reason)
3210{
3211 switch (reason) {
3212 case KMSG_DUMP_PANIC:
3213 return "Panic";
3214 case KMSG_DUMP_OOPS:
3215 return "Oops";
3216 case KMSG_DUMP_EMERG:
3217 return "Emergency";
3218 case KMSG_DUMP_SHUTDOWN:
3219 return "Shutdown";
3220 default:
3221 return "Unknown";
3222 }
3223}
3224EXPORT_SYMBOL_GPL(kmsg_dump_reason_str);
3225
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003226/**
3227 * kmsg_dump - dump kernel log to kernel message dumpers.
3228 * @reason: the reason (oops, panic etc) for dumping
3229 *
3230 * Call each of the registered dumper's dump() callback, which can
3231 * retrieve the kmsg records with kmsg_dump_get_line() or
3232 * kmsg_dump_get_buffer().
3233 */
3234void kmsg_dump(enum kmsg_dump_reason reason)
3235{
3236 struct kmsg_dumper *dumper;
3237 unsigned long flags;
3238
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003239 rcu_read_lock();
3240 list_for_each_entry_rcu(dumper, &dump_list, list) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003241 enum kmsg_dump_reason max_reason = dumper->max_reason;
3242
3243 /*
3244 * If client has not provided a specific max_reason, default
3245 * to KMSG_DUMP_OOPS, unless always_kmsg_dump was set.
3246 */
3247 if (max_reason == KMSG_DUMP_UNDEF) {
3248 max_reason = always_kmsg_dump ? KMSG_DUMP_MAX :
3249 KMSG_DUMP_OOPS;
3250 }
3251 if (reason > max_reason)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003252 continue;
3253
3254 /* initialize iterator with data about the stored records */
3255 dumper->active = true;
3256
3257 logbuf_lock_irqsave(flags);
3258 dumper->cur_seq = clear_seq;
Olivier Deprez157378f2022-04-04 15:47:50 +02003259 dumper->next_seq = prb_next_seq(prb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003260 logbuf_unlock_irqrestore(flags);
3261
3262 /* invoke dumper which will iterate over records */
3263 dumper->dump(dumper, reason);
3264
3265 /* reset iterator */
3266 dumper->active = false;
3267 }
3268 rcu_read_unlock();
3269}
3270
3271/**
3272 * kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
3273 * @dumper: registered kmsg dumper
3274 * @syslog: include the "<4>" prefixes
3275 * @line: buffer to copy the line to
3276 * @size: maximum size of the buffer
3277 * @len: length of line placed into buffer
3278 *
3279 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3280 * record, and copy one record into the provided buffer.
3281 *
3282 * Consecutive calls will return the next available record moving
3283 * towards the end of the buffer with the youngest messages.
3284 *
3285 * A return value of FALSE indicates that there are no more records to
3286 * read.
3287 *
3288 * The function is similar to kmsg_dump_get_line(), but grabs no locks.
3289 */
3290bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
3291 char *line, size_t size, size_t *len)
3292{
Olivier Deprez157378f2022-04-04 15:47:50 +02003293 struct printk_info info;
3294 unsigned int line_count;
3295 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003296 size_t l = 0;
3297 bool ret = false;
3298
Olivier Deprez157378f2022-04-04 15:47:50 +02003299 prb_rec_init_rd(&r, &info, line, size);
3300
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003301 if (!dumper->active)
3302 goto out;
3303
Olivier Deprez157378f2022-04-04 15:47:50 +02003304 /* Read text or count text lines? */
3305 if (line) {
3306 if (!prb_read_valid(prb, dumper->cur_seq, &r))
3307 goto out;
3308 l = record_print_text(&r, syslog, printk_time);
3309 } else {
3310 if (!prb_read_valid_info(prb, dumper->cur_seq,
3311 &info, &line_count)) {
3312 goto out;
3313 }
3314 l = get_record_print_text_size(&info, line_count, syslog,
3315 printk_time);
3316
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003317 }
3318
Olivier Deprez157378f2022-04-04 15:47:50 +02003319 dumper->cur_seq = r.info->seq + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003320 ret = true;
3321out:
3322 if (len)
3323 *len = l;
3324 return ret;
3325}
3326
3327/**
3328 * kmsg_dump_get_line - retrieve one kmsg log line
3329 * @dumper: registered kmsg dumper
3330 * @syslog: include the "<4>" prefixes
3331 * @line: buffer to copy the line to
3332 * @size: maximum size of the buffer
3333 * @len: length of line placed into buffer
3334 *
3335 * Start at the beginning of the kmsg buffer, with the oldest kmsg
3336 * record, and copy one record into the provided buffer.
3337 *
3338 * Consecutive calls will return the next available record moving
3339 * towards the end of the buffer with the youngest messages.
3340 *
3341 * A return value of FALSE indicates that there are no more records to
3342 * read.
3343 */
3344bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
3345 char *line, size_t size, size_t *len)
3346{
3347 unsigned long flags;
3348 bool ret;
3349
3350 logbuf_lock_irqsave(flags);
3351 ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
3352 logbuf_unlock_irqrestore(flags);
3353
3354 return ret;
3355}
3356EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
3357
3358/**
3359 * kmsg_dump_get_buffer - copy kmsg log lines
3360 * @dumper: registered kmsg dumper
3361 * @syslog: include the "<4>" prefixes
3362 * @buf: buffer to copy the line to
3363 * @size: maximum size of the buffer
3364 * @len: length of line placed into buffer
3365 *
3366 * Start at the end of the kmsg buffer and fill the provided buffer
Olivier Deprez157378f2022-04-04 15:47:50 +02003367 * with as many of the *youngest* kmsg records that fit into it.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003368 * If the buffer is large enough, all available kmsg records will be
3369 * copied with a single call.
3370 *
3371 * Consecutive calls will fill the buffer with the next block of
3372 * available older records, not including the earlier retrieved ones.
3373 *
3374 * A return value of FALSE indicates that there are no more records to
3375 * read.
3376 */
3377bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
3378 char *buf, size_t size, size_t *len)
3379{
Olivier Deprez157378f2022-04-04 15:47:50 +02003380 struct printk_info info;
3381 unsigned int line_count;
3382 struct printk_record r;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003383 unsigned long flags;
3384 u64 seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003385 u64 next_seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003386 size_t l = 0;
3387 bool ret = false;
David Brazdil0f672f62019-12-10 10:32:29 +00003388 bool time = printk_time;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003389
Olivier Deprez157378f2022-04-04 15:47:50 +02003390 prb_rec_init_rd(&r, &info, buf, size);
3391
3392 if (!dumper->active || !buf || !size)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003393 goto out;
3394
3395 logbuf_lock_irqsave(flags);
Olivier Deprez157378f2022-04-04 15:47:50 +02003396 if (prb_read_valid_info(prb, dumper->cur_seq, &info, NULL)) {
3397 if (info.seq != dumper->cur_seq) {
3398 /* messages are gone, move to first available one */
3399 dumper->cur_seq = info.seq;
3400 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003401 }
3402
3403 /* last entry */
3404 if (dumper->cur_seq >= dumper->next_seq) {
3405 logbuf_unlock_irqrestore(flags);
3406 goto out;
3407 }
3408
3409 /* calculate length of entire buffer */
3410 seq = dumper->cur_seq;
Olivier Deprez157378f2022-04-04 15:47:50 +02003411 while (prb_read_valid_info(prb, seq, &info, &line_count)) {
3412 if (r.info->seq >= dumper->next_seq)
3413 break;
3414 l += get_record_print_text_size(&info, line_count, syslog, time);
3415 seq = r.info->seq + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003416 }
3417
3418 /* move first record forward until length fits into the buffer */
3419 seq = dumper->cur_seq;
Olivier Deprez157378f2022-04-04 15:47:50 +02003420 while (l >= size && prb_read_valid_info(prb, seq,
3421 &info, &line_count)) {
3422 if (r.info->seq >= dumper->next_seq)
3423 break;
3424 l -= get_record_print_text_size(&info, line_count, syslog, time);
3425 seq = r.info->seq + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003426 }
3427
3428 /* last message in next interation */
3429 next_seq = seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003430
Olivier Deprez157378f2022-04-04 15:47:50 +02003431 /* actually read text into the buffer now */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003432 l = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02003433 while (prb_read_valid(prb, seq, &r)) {
3434 if (r.info->seq >= dumper->next_seq)
3435 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003436
Olivier Deprez157378f2022-04-04 15:47:50 +02003437 l += record_print_text(&r, syslog, time);
3438
3439 /* adjust record to store to remaining buffer space */
3440 prb_rec_init_rd(&r, &info, buf + l, size - l);
3441
3442 seq = r.info->seq + 1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003443 }
3444
3445 dumper->next_seq = next_seq;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003446 ret = true;
3447 logbuf_unlock_irqrestore(flags);
3448out:
3449 if (len)
3450 *len = l;
3451 return ret;
3452}
3453EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
3454
3455/**
Olivier Deprez157378f2022-04-04 15:47:50 +02003456 * kmsg_dump_rewind_nolock - reset the iterator (unlocked version)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003457 * @dumper: registered kmsg dumper
3458 *
3459 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3460 * kmsg_dump_get_buffer() can be called again and used multiple
3461 * times within the same dumper.dump() callback.
3462 *
3463 * The function is similar to kmsg_dump_rewind(), but grabs no locks.
3464 */
3465void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
3466{
3467 dumper->cur_seq = clear_seq;
Olivier Deprez157378f2022-04-04 15:47:50 +02003468 dumper->next_seq = prb_next_seq(prb);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003469}
3470
3471/**
Olivier Deprez157378f2022-04-04 15:47:50 +02003472 * kmsg_dump_rewind - reset the iterator
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003473 * @dumper: registered kmsg dumper
3474 *
3475 * Reset the dumper's iterator so that kmsg_dump_get_line() and
3476 * kmsg_dump_get_buffer() can be called again and used multiple
3477 * times within the same dumper.dump() callback.
3478 */
3479void kmsg_dump_rewind(struct kmsg_dumper *dumper)
3480{
3481 unsigned long flags;
3482
3483 logbuf_lock_irqsave(flags);
3484 kmsg_dump_rewind_nolock(dumper);
3485 logbuf_unlock_irqrestore(flags);
3486}
3487EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
3488
3489#endif