1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * printk_safe.c - Safe printk for printk-deadlock-prone contexts
6 #include <linux/preempt.h>
7 #include <linux/spinlock.h>
8 #include <linux/debug_locks.h>
10 #include <linux/cpumask.h>
11 #include <linux/irq_work.h>
12 #include <linux/printk.h>
17 * printk() could not take logbuf_lock in NMI context. Instead,
18 * it uses an alternative implementation that temporary stores
19 * the strings into a per-CPU buffer. The content of the buffer
20 * is later flushed into the main ring buffer via IRQ work.
22 * The alternative implementation is chosen transparently
23 * by examinig current printk() context mask stored in @printk_context
26 * The implementation allows to flush the strings also from another CPU.
27 * There are situations when we want to make sure that all buffers
28 * were handled or when IRQs are blocked.
30 static int printk_safe_irq_ready __read_mostly;
32 #define SAFE_LOG_BUF_LEN ((1 << CONFIG_PRINTK_SAFE_LOG_BUF_SHIFT) - \
35 sizeof(struct irq_work))
37 struct printk_safe_seq_buf {
38 atomic_t len; /* length of written data */
39 atomic_t message_lost;
40 struct irq_work work; /* IRQ work that flushes the buffer */
41 unsigned char buffer[SAFE_LOG_BUF_LEN];
44 static DEFINE_PER_CPU(struct printk_safe_seq_buf, safe_print_seq);
45 static DEFINE_PER_CPU(int, printk_context);
47 #ifdef CONFIG_PRINTK_NMI
48 static DEFINE_PER_CPU(struct printk_safe_seq_buf, nmi_print_seq);
51 /* Get flushed in a more safe context. */
52 static void queue_flush_work(struct printk_safe_seq_buf *s)
54 if (printk_safe_irq_ready)
55 irq_work_queue(&s->work);
59 * Add a message to per-CPU context-dependent buffer. NMI and printk-safe
60 * have dedicated buffers, because otherwise printk-safe preempted by
61 * NMI-printk would have overwritten the NMI messages.
63 * The messages are flushed from irq work (or from panic()), possibly,
64 * from other CPU, concurrently with printk_safe_log_store(). Should this
65 * happen, printk_safe_log_store() will notice the buffer->len mismatch
66 * and repeat the write.
68 static __printf(2, 0) int printk_safe_log_store(struct printk_safe_seq_buf *s,
69 const char *fmt, va_list args)
76 len = atomic_read(&s->len);
78 /* The trailing '\0' is not counted into len. */
79 if (len >= sizeof(s->buffer) - 1) {
80 atomic_inc(&s->message_lost);
86 * Make sure that all old data have been read before the buffer
87 * was reset. This is not needed when we just append data.
93 add = vscnprintf(s->buffer + len, sizeof(s->buffer) - len, fmt, ap);
99 * Do it once again if the buffer has been flushed in the meantime.
100 * Note that atomic_cmpxchg() is an implicit memory barrier that
101 * makes sure that the data were written before updating s->len.
103 if (atomic_cmpxchg(&s->len, len, len + add) != len)
110 static inline void printk_safe_flush_line(const char *text, int len)
113 * Avoid any console drivers calls from here, because we may be
114 * in NMI or printk_safe context (when in panic). The messages
115 * must go only into the ring buffer at this stage. Consoles will
116 * get explicitly called later when a crashdump is not generated.
118 printk_deferred("%.*s", len, text);
121 /* printk part of the temporary buffer line by line */
122 static int printk_safe_flush_buffer(const char *start, size_t len)
131 /* Print line by line. */
134 printk_safe_flush_line(start, c - start + 1);
140 /* Handle continuous lines or missing new line. */
141 if ((c + 1 < end) && printk_get_level(c)) {
143 c = printk_skip_level(c);
147 printk_safe_flush_line(start, c - start);
157 /* Check if there was a partial line. Ignore pure header. */
158 if (start < end && !header) {
159 static const char newline[] = KERN_CONT "\n";
161 printk_safe_flush_line(start, end - start);
162 printk_safe_flush_line(newline, strlen(newline));
168 static void report_message_lost(struct printk_safe_seq_buf *s)
170 int lost = atomic_xchg(&s->message_lost, 0);
173 printk_deferred("Lost %d message(s)!\n", lost);
177 * Flush data from the associated per-CPU buffer. The function
178 * can be called either via IRQ work or independently.
180 static void __printk_safe_flush(struct irq_work *work)
182 static raw_spinlock_t read_lock =
183 __RAW_SPIN_LOCK_INITIALIZER(read_lock);
184 struct printk_safe_seq_buf *s =
185 container_of(work, struct printk_safe_seq_buf, work);
191 * The lock has two functions. First, one reader has to flush all
192 * available message to make the lockless synchronization with
193 * writers easier. Second, we do not want to mix messages from
194 * different CPUs. This is especially important when printing
197 raw_spin_lock_irqsave(&read_lock, flags);
201 len = atomic_read(&s->len);
204 * This is just a paranoid check that nobody has manipulated
205 * the buffer an unexpected way. If we printed something then
206 * @len must only increase. Also it should never overflow the
209 if ((i && i >= len) || len > sizeof(s->buffer)) {
210 const char *msg = "printk_safe_flush: internal error\n";
212 printk_safe_flush_line(msg, strlen(msg));
217 goto out; /* Someone else has already flushed the buffer. */
219 /* Make sure that data has been written up to the @len */
221 i += printk_safe_flush_buffer(s->buffer + i, len - i);
224 * Check that nothing has got added in the meantime and truncate
225 * the buffer. Note that atomic_cmpxchg() is an implicit memory
226 * barrier that makes sure that the data were copied before
229 if (atomic_cmpxchg(&s->len, len, 0) != len)
233 report_message_lost(s);
234 raw_spin_unlock_irqrestore(&read_lock, flags);
238 * printk_safe_flush - flush all per-cpu nmi buffers.
240 * The buffers are flushed automatically via IRQ work. This function
241 * is useful only when someone wants to be sure that all buffers have
242 * been flushed at some point.
244 void printk_safe_flush(void)
248 for_each_possible_cpu(cpu) {
249 #ifdef CONFIG_PRINTK_NMI
250 __printk_safe_flush(&per_cpu(nmi_print_seq, cpu).work);
252 __printk_safe_flush(&per_cpu(safe_print_seq, cpu).work);
257 * printk_safe_flush_on_panic - flush all per-cpu nmi buffers when the system
260 * Similar to printk_safe_flush() but it can be called even in NMI context when
261 * the system goes down. It does the best effort to get NMI messages into
262 * the main ring buffer.
264 * Note that it could try harder when there is only one CPU online.
266 void printk_safe_flush_on_panic(void)
269 * Make sure that we could access the main ring buffer.
270 * Do not risk a double release when more CPUs are up.
272 if (raw_spin_is_locked(&logbuf_lock)) {
273 if (num_online_cpus() > 1)
277 raw_spin_lock_init(&logbuf_lock);
283 #ifdef CONFIG_PRINTK_NMI
285 * Safe printk() for NMI context. It uses a per-CPU buffer to
286 * store the message. NMIs are not nested, so there is always only
287 * one writer running. But the buffer might get flushed from another
288 * CPU, so we need to be careful.
290 static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
292 struct printk_safe_seq_buf *s = this_cpu_ptr(&nmi_print_seq);
294 return printk_safe_log_store(s, fmt, args);
297 void notrace printk_nmi_enter(void)
299 this_cpu_or(printk_context, PRINTK_NMI_CONTEXT_MASK);
302 void notrace printk_nmi_exit(void)
304 this_cpu_and(printk_context, ~PRINTK_NMI_CONTEXT_MASK);
308 * Marks a code that might produce many messages in NMI context
309 * and the risk of losing them is more critical than eventual
312 * It has effect only when called in NMI context. Then printk()
313 * will try to store the messages into the main logbuf directly
314 * and use the per-CPU buffers only as a fallback when the lock
317 void printk_nmi_direct_enter(void)
319 if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
320 this_cpu_or(printk_context, PRINTK_NMI_DIRECT_CONTEXT_MASK);
323 void printk_nmi_direct_exit(void)
325 this_cpu_and(printk_context, ~PRINTK_NMI_DIRECT_CONTEXT_MASK);
330 static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
335 #endif /* CONFIG_PRINTK_NMI */
338 * Lock-less printk(), to avoid deadlocks should the printk() recurse
339 * into itself. It uses a per-CPU buffer to store the message, just like
342 static __printf(1, 0) int vprintk_safe(const char *fmt, va_list args)
344 struct printk_safe_seq_buf *s = this_cpu_ptr(&safe_print_seq);
346 return printk_safe_log_store(s, fmt, args);
349 /* Can be preempted by NMI. */
350 void __printk_safe_enter(void)
352 this_cpu_inc(printk_context);
355 /* Can be preempted by NMI. */
356 void __printk_safe_exit(void)
358 this_cpu_dec(printk_context);
361 __printf(1, 0) int vprintk_func(const char *fmt, va_list args)
364 * Try to use the main logbuf even in NMI. But avoid calling console
365 * drivers that might have their own locks.
367 if ((this_cpu_read(printk_context) & PRINTK_NMI_DIRECT_CONTEXT_MASK) &&
368 raw_spin_trylock(&logbuf_lock)) {
371 len = vprintk_store(0, LOGLEVEL_DEFAULT, NULL, 0, fmt, args);
372 raw_spin_unlock(&logbuf_lock);
373 defer_console_output();
377 /* Use extra buffer in NMI when logbuf_lock is taken or in safe mode. */
378 if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
379 return vprintk_nmi(fmt, args);
381 /* Use extra buffer to prevent a recursion deadlock in safe mode. */
382 if (this_cpu_read(printk_context) & PRINTK_SAFE_CONTEXT_MASK)
383 return vprintk_safe(fmt, args);
386 return vprintk_default(fmt, args);
389 void __init printk_safe_init(void)
393 for_each_possible_cpu(cpu) {
394 struct printk_safe_seq_buf *s;
396 s = &per_cpu(safe_print_seq, cpu);
397 init_irq_work(&s->work, __printk_safe_flush);
399 #ifdef CONFIG_PRINTK_NMI
400 s = &per_cpu(nmi_print_seq, cpu);
401 init_irq_work(&s->work, __printk_safe_flush);
406 * In the highly unlikely event that a NMI were to trigger at
407 * this moment. Make sure IRQ work is set up before this
411 printk_safe_irq_ready = 1;
413 /* Flush pending messages that did not have scheduled IRQ works. */