printk_safe.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. static int printk_safe_irq_ready __read_mostly;
  40. #define SAFE_LOG_BUF_LEN ((1 << CONFIG_PRINTK_SAFE_LOG_BUF_SHIFT) - \
  41. sizeof(atomic_t) - \
  42. sizeof(atomic_t) - \
  43. sizeof(struct irq_work))
  44. struct printk_safe_seq_buf {
  45. atomic_t len; /* length of written data */
  46. atomic_t message_lost;
  47. struct irq_work work; /* IRQ work that flushes the buffer */
  48. unsigned char buffer[SAFE_LOG_BUF_LEN];
  49. };
  50. static DEFINE_PER_CPU(struct printk_safe_seq_buf, safe_print_seq);
  51. static DEFINE_PER_CPU(int, printk_context);
  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_safe_irq_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. static raw_spinlock_t read_lock =
  167. __RAW_SPIN_LOCK_INITIALIZER(read_lock);
  168. struct printk_safe_seq_buf *s =
  169. container_of(work, struct printk_safe_seq_buf, work);
  170. unsigned long flags;
  171. size_t len;
  172. int i;
  173. /*
  174. * The lock has two functions. First, one reader has to flush all
  175. * available message to make the lockless synchronization with
  176. * writers easier. Second, we do not want to mix messages from
  177. * different CPUs. This is especially important when printing
  178. * a backtrace.
  179. */
  180. raw_spin_lock_irqsave(&read_lock, flags);
  181. i = 0;
  182. more:
  183. len = atomic_read(&s->len);
  184. /*
  185. * This is just a paranoid check that nobody has manipulated
  186. * the buffer an unexpected way. If we printed something then
  187. * @len must only increase. Also it should never overflow the
  188. * buffer size.
  189. */
  190. if ((i && i >= len) || len > sizeof(s->buffer)) {
  191. const char *msg = "printk_safe_flush: internal error\n";
  192. printk_safe_flush_line(msg, strlen(msg));
  193. len = 0;
  194. }
  195. if (!len)
  196. goto out; /* Someone else has already flushed the buffer. */
  197. /* Make sure that data has been written up to the @len */
  198. smp_rmb();
  199. i += printk_safe_flush_buffer(s->buffer + i, len - i);
  200. /*
  201. * Check that nothing has got added in the meantime and truncate
  202. * the buffer. Note that atomic_cmpxchg() is an implicit memory
  203. * barrier that makes sure that the data were copied before
  204. * updating s->len.
  205. */
  206. if (atomic_cmpxchg(&s->len, len, 0) != len)
  207. goto more;
  208. out:
  209. report_message_lost(s);
  210. raw_spin_unlock_irqrestore(&read_lock, flags);
  211. }
  212. /**
  213. * printk_safe_flush - flush all per-cpu nmi buffers.
  214. *
  215. * The buffers are flushed automatically via IRQ work. This function
  216. * is useful only when someone wants to be sure that all buffers have
  217. * been flushed at some point.
  218. */
  219. void printk_safe_flush(void)
  220. {
  221. int cpu;
  222. for_each_possible_cpu(cpu) {
  223. #ifdef CONFIG_PRINTK_NMI
  224. __printk_safe_flush(&per_cpu(nmi_print_seq, cpu).work);
  225. #endif
  226. __printk_safe_flush(&per_cpu(safe_print_seq, cpu).work);
  227. }
  228. }
  229. /**
  230. * printk_safe_flush_on_panic - flush all per-cpu nmi buffers when the system
  231. * goes down.
  232. *
  233. * Similar to printk_safe_flush() but it can be called even in NMI context when
  234. * the system goes down. It does the best effort to get NMI messages into
  235. * the main ring buffer.
  236. *
  237. * Note that it could try harder when there is only one CPU online.
  238. */
  239. void printk_safe_flush_on_panic(void)
  240. {
  241. /*
  242. * Make sure that we could access the main ring buffer.
  243. * Do not risk a double release when more CPUs are up.
  244. */
  245. if (raw_spin_is_locked(&logbuf_lock)) {
  246. if (num_online_cpus() > 1)
  247. return;
  248. debug_locks_off();
  249. raw_spin_lock_init(&logbuf_lock);
  250. }
  251. printk_safe_flush();
  252. }
  253. #ifdef CONFIG_PRINTK_NMI
  254. /*
  255. * Safe printk() for NMI context. It uses a per-CPU buffer to
  256. * store the message. NMIs are not nested, so there is always only
  257. * one writer running. But the buffer might get flushed from another
  258. * CPU, so we need to be careful.
  259. */
  260. static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
  261. {
  262. struct printk_safe_seq_buf *s = this_cpu_ptr(&nmi_print_seq);
  263. return printk_safe_log_store(s, fmt, args);
  264. }
  265. void notrace printk_nmi_enter(void)
  266. {
  267. this_cpu_or(printk_context, PRINTK_NMI_CONTEXT_MASK);
  268. }
  269. void notrace printk_nmi_exit(void)
  270. {
  271. this_cpu_and(printk_context, ~PRINTK_NMI_CONTEXT_MASK);
  272. }
  273. /*
  274. * Marks a code that might produce many messages in NMI context
  275. * and the risk of losing them is more critical than eventual
  276. * reordering.
  277. *
  278. * It has effect only when called in NMI context. Then printk()
  279. * will try to store the messages into the main logbuf directly
  280. * and use the per-CPU buffers only as a fallback when the lock
  281. * is not available.
  282. */
  283. void printk_nmi_direct_enter(void)
  284. {
  285. if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
  286. this_cpu_or(printk_context, PRINTK_NMI_DIRECT_CONTEXT_MASK);
  287. }
  288. void printk_nmi_direct_exit(void)
  289. {
  290. this_cpu_and(printk_context, ~PRINTK_NMI_DIRECT_CONTEXT_MASK);
  291. }
  292. #else
  293. static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
  294. {
  295. return 0;
  296. }
  297. #endif /* CONFIG_PRINTK_NMI */
  298. /*
  299. * Lock-less printk(), to avoid deadlocks should the printk() recurse
  300. * into itself. It uses a per-CPU buffer to store the message, just like
  301. * NMI.
  302. */
  303. static __printf(1, 0) int vprintk_safe(const char *fmt, va_list args)
  304. {
  305. struct printk_safe_seq_buf *s = this_cpu_ptr(&safe_print_seq);
  306. return printk_safe_log_store(s, fmt, args);
  307. }
  308. /* Can be preempted by NMI. */
  309. void __printk_safe_enter(void)
  310. {
  311. this_cpu_inc(printk_context);
  312. }
  313. /* Can be preempted by NMI. */
  314. void __printk_safe_exit(void)
  315. {
  316. this_cpu_dec(printk_context);
  317. }
  318. __printf(1, 0) int vprintk_func(const char *fmt, va_list args)
  319. {
  320. /*
  321. * Try to use the main logbuf even in NMI. But avoid calling console
  322. * drivers that might have their own locks.
  323. */
  324. if ((this_cpu_read(printk_context) & PRINTK_NMI_DIRECT_CONTEXT_MASK) &&
  325. raw_spin_trylock(&logbuf_lock)) {
  326. int len;
  327. len = vprintk_store(0, LOGLEVEL_DEFAULT, NULL, 0, fmt, args);
  328. raw_spin_unlock(&logbuf_lock);
  329. defer_console_output();
  330. return len;
  331. }
  332. /* Use extra buffer in NMI when logbuf_lock is taken or in safe mode. */
  333. if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
  334. return vprintk_nmi(fmt, args);
  335. /* Use extra buffer to prevent a recursion deadlock in safe mode. */
  336. if (this_cpu_read(printk_context) & PRINTK_SAFE_CONTEXT_MASK)
  337. return vprintk_safe(fmt, args);
  338. /* No obstacles. */
  339. return vprintk_default(fmt, args);
  340. }
  341. void __init printk_safe_init(void)
  342. {
  343. int cpu;
  344. for_each_possible_cpu(cpu) {
  345. struct printk_safe_seq_buf *s;
  346. s = &per_cpu(safe_print_seq, cpu);
  347. init_irq_work(&s->work, __printk_safe_flush);
  348. #ifdef CONFIG_PRINTK_NMI
  349. s = &per_cpu(nmi_print_seq, cpu);
  350. init_irq_work(&s->work, __printk_safe_flush);
  351. #endif
  352. }
  353. /*
  354. * In the highly unlikely event that a NMI were to trigger at
  355. * this moment. Make sure IRQ work is set up before this
  356. * variable is set.
  357. */
  358. barrier();
  359. printk_safe_irq_ready = 1;
  360. /* Flush pending messages that did not have scheduled IRQ works. */
  361. printk_safe_flush();
  362. }