printk_safe.c 11 KB

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