GNU Linux-libre 4.19.264-gnu1
[releases.git] / kernel / printk / printk_safe.c
1 /*
2  * printk_safe.c - Safe printk for printk-deadlock-prone contexts
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include <linux/preempt.h>
19 #include <linux/spinlock.h>
20 #include <linux/debug_locks.h>
21 #include <linux/smp.h>
22 #include <linux/cpumask.h>
23 #include <linux/irq_work.h>
24 #include <linux/printk.h>
25
26 #include "internal.h"
27
28 /*
29  * printk() could not take logbuf_lock in NMI context. Instead,
30  * it uses an alternative implementation that temporary stores
31  * the strings into a per-CPU buffer. The content of the buffer
32  * is later flushed into the main ring buffer via IRQ work.
33  *
34  * The alternative implementation is chosen transparently
35  * by examinig current printk() context mask stored in @printk_context
36  * per-CPU variable.
37  *
38  * The implementation allows to flush the strings also from another CPU.
39  * There are situations when we want to make sure that all buffers
40  * were handled or when IRQs are blocked.
41  */
42
43 #define SAFE_LOG_BUF_LEN ((1 << CONFIG_PRINTK_SAFE_LOG_BUF_SHIFT) -     \
44                                 sizeof(atomic_t) -                      \
45                                 sizeof(atomic_t) -                      \
46                                 sizeof(struct irq_work))
47
48 struct printk_safe_seq_buf {
49         atomic_t                len;    /* length of written data */
50         atomic_t                message_lost;
51         struct irq_work         work;   /* IRQ work that flushes the buffer */
52         unsigned char           buffer[SAFE_LOG_BUF_LEN];
53 };
54
55 static DEFINE_PER_CPU(struct printk_safe_seq_buf, safe_print_seq);
56 static DEFINE_PER_CPU(int, printk_context);
57
58 static DEFINE_RAW_SPINLOCK(safe_read_lock);
59
60 #ifdef CONFIG_PRINTK_NMI
61 static DEFINE_PER_CPU(struct printk_safe_seq_buf, nmi_print_seq);
62 #endif
63
64 /* Get flushed in a more safe context. */
65 static void queue_flush_work(struct printk_safe_seq_buf *s)
66 {
67         if (printk_percpu_data_ready())
68                 irq_work_queue(&s->work);
69 }
70
71 /*
72  * Add a message to per-CPU context-dependent buffer. NMI and printk-safe
73  * have dedicated buffers, because otherwise printk-safe preempted by
74  * NMI-printk would have overwritten the NMI messages.
75  *
76  * The messages are flushed from irq work (or from panic()), possibly,
77  * from other CPU, concurrently with printk_safe_log_store(). Should this
78  * happen, printk_safe_log_store() will notice the buffer->len mismatch
79  * and repeat the write.
80  */
81 static __printf(2, 0) int printk_safe_log_store(struct printk_safe_seq_buf *s,
82                                                 const char *fmt, va_list args)
83 {
84         int add;
85         size_t len;
86         va_list ap;
87
88 again:
89         len = atomic_read(&s->len);
90
91         /* The trailing '\0' is not counted into len. */
92         if (len >= sizeof(s->buffer) - 1) {
93                 atomic_inc(&s->message_lost);
94                 queue_flush_work(s);
95                 return 0;
96         }
97
98         /*
99          * Make sure that all old data have been read before the buffer
100          * was reset. This is not needed when we just append data.
101          */
102         if (!len)
103                 smp_rmb();
104
105         va_copy(ap, args);
106         add = vscnprintf(s->buffer + len, sizeof(s->buffer) - len, fmt, ap);
107         va_end(ap);
108         if (!add)
109                 return 0;
110
111         /*
112          * Do it once again if the buffer has been flushed in the meantime.
113          * Note that atomic_cmpxchg() is an implicit memory barrier that
114          * makes sure that the data were written before updating s->len.
115          */
116         if (atomic_cmpxchg(&s->len, len, len + add) != len)
117                 goto again;
118
119         queue_flush_work(s);
120         return add;
121 }
122
123 static inline void printk_safe_flush_line(const char *text, int len)
124 {
125         /*
126          * Avoid any console drivers calls from here, because we may be
127          * in NMI or printk_safe context (when in panic). The messages
128          * must go only into the ring buffer at this stage.  Consoles will
129          * get explicitly called later when a crashdump is not generated.
130          */
131         printk_deferred("%.*s", len, text);
132 }
133
134 /* printk part of the temporary buffer line by line */
135 static int printk_safe_flush_buffer(const char *start, size_t len)
136 {
137         const char *c, *end;
138         bool header;
139
140         c = start;
141         end = start + len;
142         header = true;
143
144         /* Print line by line. */
145         while (c < end) {
146                 if (*c == '\n') {
147                         printk_safe_flush_line(start, c - start + 1);
148                         start = ++c;
149                         header = true;
150                         continue;
151                 }
152
153                 /* Handle continuous lines or missing new line. */
154                 if ((c + 1 < end) && printk_get_level(c)) {
155                         if (header) {
156                                 c = printk_skip_level(c);
157                                 continue;
158                         }
159
160                         printk_safe_flush_line(start, c - start);
161                         start = c++;
162                         header = true;
163                         continue;
164                 }
165
166                 header = false;
167                 c++;
168         }
169
170         /* Check if there was a partial line. Ignore pure header. */
171         if (start < end && !header) {
172                 static const char newline[] = KERN_CONT "\n";
173
174                 printk_safe_flush_line(start, end - start);
175                 printk_safe_flush_line(newline, strlen(newline));
176         }
177
178         return len;
179 }
180
181 static void report_message_lost(struct printk_safe_seq_buf *s)
182 {
183         int lost = atomic_xchg(&s->message_lost, 0);
184
185         if (lost)
186                 printk_deferred("Lost %d message(s)!\n", lost);
187 }
188
189 /*
190  * Flush data from the associated per-CPU buffer. The function
191  * can be called either via IRQ work or independently.
192  */
193 static void __printk_safe_flush(struct irq_work *work)
194 {
195         struct printk_safe_seq_buf *s =
196                 container_of(work, struct printk_safe_seq_buf, work);
197         unsigned long flags;
198         size_t len;
199         int i;
200
201         /*
202          * The lock has two functions. First, one reader has to flush all
203          * available message to make the lockless synchronization with
204          * writers easier. Second, we do not want to mix messages from
205          * different CPUs. This is especially important when printing
206          * a backtrace.
207          */
208         raw_spin_lock_irqsave(&safe_read_lock, flags);
209
210         i = 0;
211 more:
212         len = atomic_read(&s->len);
213
214         /*
215          * This is just a paranoid check that nobody has manipulated
216          * the buffer an unexpected way. If we printed something then
217          * @len must only increase. Also it should never overflow the
218          * buffer size.
219          */
220         if ((i && i >= len) || len > sizeof(s->buffer)) {
221                 const char *msg = "printk_safe_flush: internal error\n";
222
223                 printk_safe_flush_line(msg, strlen(msg));
224                 len = 0;
225         }
226
227         if (!len)
228                 goto out; /* Someone else has already flushed the buffer. */
229
230         /* Make sure that data has been written up to the @len */
231         smp_rmb();
232         i += printk_safe_flush_buffer(s->buffer + i, len - i);
233
234         /*
235          * Check that nothing has got added in the meantime and truncate
236          * the buffer. Note that atomic_cmpxchg() is an implicit memory
237          * barrier that makes sure that the data were copied before
238          * updating s->len.
239          */
240         if (atomic_cmpxchg(&s->len, len, 0) != len)
241                 goto more;
242
243 out:
244         report_message_lost(s);
245         raw_spin_unlock_irqrestore(&safe_read_lock, flags);
246 }
247
248 /**
249  * printk_safe_flush - flush all per-cpu nmi buffers.
250  *
251  * The buffers are flushed automatically via IRQ work. This function
252  * is useful only when someone wants to be sure that all buffers have
253  * been flushed at some point.
254  */
255 void printk_safe_flush(void)
256 {
257         int cpu;
258
259         for_each_possible_cpu(cpu) {
260 #ifdef CONFIG_PRINTK_NMI
261                 __printk_safe_flush(&per_cpu(nmi_print_seq, cpu).work);
262 #endif
263                 __printk_safe_flush(&per_cpu(safe_print_seq, cpu).work);
264         }
265 }
266
267 /**
268  * printk_safe_flush_on_panic - flush all per-cpu nmi buffers when the system
269  *      goes down.
270  *
271  * Similar to printk_safe_flush() but it can be called even in NMI context when
272  * the system goes down. It does the best effort to get NMI messages into
273  * the main ring buffer.
274  *
275  * Note that it could try harder when there is only one CPU online.
276  */
277 void printk_safe_flush_on_panic(void)
278 {
279         /*
280          * Make sure that we could access the main ring buffer.
281          * Do not risk a double release when more CPUs are up.
282          */
283         if (raw_spin_is_locked(&logbuf_lock)) {
284                 if (num_online_cpus() > 1)
285                         return;
286
287                 debug_locks_off();
288                 raw_spin_lock_init(&logbuf_lock);
289         }
290
291         if (raw_spin_is_locked(&safe_read_lock)) {
292                 if (num_online_cpus() > 1)
293                         return;
294
295                 debug_locks_off();
296                 raw_spin_lock_init(&safe_read_lock);
297         }
298
299         printk_safe_flush();
300 }
301
302 #ifdef CONFIG_PRINTK_NMI
303 /*
304  * Safe printk() for NMI context. It uses a per-CPU buffer to
305  * store the message. NMIs are not nested, so there is always only
306  * one writer running. But the buffer might get flushed from another
307  * CPU, so we need to be careful.
308  */
309 static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
310 {
311         struct printk_safe_seq_buf *s = this_cpu_ptr(&nmi_print_seq);
312
313         return printk_safe_log_store(s, fmt, args);
314 }
315
316 void notrace printk_nmi_enter(void)
317 {
318         this_cpu_or(printk_context, PRINTK_NMI_CONTEXT_MASK);
319 }
320
321 void notrace printk_nmi_exit(void)
322 {
323         this_cpu_and(printk_context, ~PRINTK_NMI_CONTEXT_MASK);
324 }
325
326 /*
327  * Marks a code that might produce many messages in NMI context
328  * and the risk of losing them is more critical than eventual
329  * reordering.
330  *
331  * It has effect only when called in NMI context. Then printk()
332  * will try to store the messages into the main logbuf directly
333  * and use the per-CPU buffers only as a fallback when the lock
334  * is not available.
335  */
336 void printk_nmi_direct_enter(void)
337 {
338         if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
339                 this_cpu_or(printk_context, PRINTK_NMI_DIRECT_CONTEXT_MASK);
340 }
341
342 void printk_nmi_direct_exit(void)
343 {
344         this_cpu_and(printk_context, ~PRINTK_NMI_DIRECT_CONTEXT_MASK);
345 }
346
347 #else
348
349 static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
350 {
351         return 0;
352 }
353
354 #endif /* CONFIG_PRINTK_NMI */
355
356 /*
357  * Lock-less printk(), to avoid deadlocks should the printk() recurse
358  * into itself. It uses a per-CPU buffer to store the message, just like
359  * NMI.
360  */
361 static __printf(1, 0) int vprintk_safe(const char *fmt, va_list args)
362 {
363         struct printk_safe_seq_buf *s = this_cpu_ptr(&safe_print_seq);
364
365         return printk_safe_log_store(s, fmt, args);
366 }
367
368 /* Can be preempted by NMI. */
369 void __printk_safe_enter(void)
370 {
371         this_cpu_inc(printk_context);
372 }
373
374 /* Can be preempted by NMI. */
375 void __printk_safe_exit(void)
376 {
377         this_cpu_dec(printk_context);
378 }
379
380 __printf(1, 0) int vprintk_func(const char *fmt, va_list args)
381 {
382         /*
383          * Try to use the main logbuf even in NMI. But avoid calling console
384          * drivers that might have their own locks.
385          */
386         if ((this_cpu_read(printk_context) & PRINTK_NMI_DIRECT_CONTEXT_MASK) &&
387             raw_spin_trylock(&logbuf_lock)) {
388                 int len;
389
390                 len = vprintk_store(0, LOGLEVEL_DEFAULT, NULL, 0, fmt, args);
391                 raw_spin_unlock(&logbuf_lock);
392                 defer_console_output();
393                 return len;
394         }
395
396         /* Use extra buffer in NMI when logbuf_lock is taken or in safe mode. */
397         if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
398                 return vprintk_nmi(fmt, args);
399
400         /* Use extra buffer to prevent a recursion deadlock in safe mode. */
401         if (this_cpu_read(printk_context) & PRINTK_SAFE_CONTEXT_MASK)
402                 return vprintk_safe(fmt, args);
403
404         /* No obstacles. */
405         return vprintk_default(fmt, args);
406 }
407
408 void __init printk_safe_init(void)
409 {
410         int cpu;
411
412         for_each_possible_cpu(cpu) {
413                 struct printk_safe_seq_buf *s;
414
415                 s = &per_cpu(safe_print_seq, cpu);
416                 init_irq_work(&s->work, __printk_safe_flush);
417
418 #ifdef CONFIG_PRINTK_NMI
419                 s = &per_cpu(nmi_print_seq, cpu);
420                 init_irq_work(&s->work, __printk_safe_flush);
421 #endif
422         }
423
424         /* Flush pending messages that did not have scheduled IRQ works. */
425         printk_safe_flush();
426 }