printk_safe.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. again:
  77. 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);
  81. queue_flush_work(s);
  82. return 0;
  83. }
  84. /*
  85. * Make sure that all old data have been read before the buffer
  86. * was reset. This is not needed when we just append data.
  87. */
  88. if (!len)
  89. smp_rmb();
  90. add = vscnprintf(s->buffer + len, sizeof(s->buffer) - len, fmt, args);
  91. if (!add)
  92. return 0;
  93. /*
  94. * Do it once again if the buffer has been flushed in the meantime.
  95. * Note that atomic_cmpxchg() is an implicit memory barrier that
  96. * makes sure that the data were written before updating s->len.
  97. */
  98. if (atomic_cmpxchg(&s->len, len, len + add) != len)
  99. goto again;
  100. queue_flush_work(s);
  101. return add;
  102. }
  103. static inline void printk_safe_flush_line(const char *text, int len)
  104. {
  105. /*
  106. * Avoid any console drivers calls from here, because we may be
  107. * in NMI or printk_safe context (when in panic). The messages
  108. * must go only into the ring buffer at this stage. Consoles will
  109. * get explicitly called later when a crashdump is not generated.
  110. */
  111. printk_deferred("%.*s", len, text);
  112. }
  113. /* printk part of the temporary buffer line by line */
  114. static int printk_safe_flush_buffer(const char *start, size_t len)
  115. {
  116. const char *c, *end;
  117. bool header;
  118. c = start;
  119. end = start + len;
  120. header = true;
  121. /* Print line by line. */
  122. while (c < end) {
  123. if (*c == '\n') {
  124. printk_safe_flush_line(start, c - start + 1);
  125. start = ++c;
  126. header = true;
  127. continue;
  128. }
  129. /* Handle continuous lines or missing new line. */
  130. if ((c + 1 < end) && printk_get_level(c)) {
  131. if (header) {
  132. c = printk_skip_level(c);
  133. continue;
  134. }
  135. printk_safe_flush_line(start, c - start);
  136. start = c++;
  137. header = true;
  138. continue;
  139. }
  140. header = false;
  141. c++;
  142. }
  143. /* Check if there was a partial line. Ignore pure header. */
  144. if (start < end && !header) {
  145. static const char newline[] = KERN_CONT "\n";
  146. printk_safe_flush_line(start, end - start);
  147. printk_safe_flush_line(newline, strlen(newline));
  148. }
  149. return len;
  150. }
  151. static void report_message_lost(struct printk_safe_seq_buf *s)
  152. {
  153. int lost = atomic_xchg(&s->message_lost, 0);
  154. if (lost)
  155. printk_deferred("Lost %d message(s)!\n", lost);
  156. }
  157. /*
  158. * Flush data from the associated per-CPU buffer. The function
  159. * can be called either via IRQ work or independently.
  160. */
  161. static void __printk_safe_flush(struct irq_work *work)
  162. {
  163. static raw_spinlock_t read_lock =
  164. __RAW_SPIN_LOCK_INITIALIZER(read_lock);
  165. struct printk_safe_seq_buf *s =
  166. container_of(work, struct printk_safe_seq_buf, work);
  167. unsigned long flags;
  168. size_t len;
  169. int i;
  170. /*
  171. * The lock has two functions. First, one reader has to flush all
  172. * available message to make the lockless synchronization with
  173. * writers easier. Second, we do not want to mix messages from
  174. * different CPUs. This is especially important when printing
  175. * a backtrace.
  176. */
  177. raw_spin_lock_irqsave(&read_lock, flags);
  178. i = 0;
  179. more:
  180. len = atomic_read(&s->len);
  181. /*
  182. * This is just a paranoid check that nobody has manipulated
  183. * the buffer an unexpected way. If we printed something then
  184. * @len must only increase. Also it should never overflow the
  185. * buffer size.
  186. */
  187. if ((i && i >= len) || len > sizeof(s->buffer)) {
  188. const char *msg = "printk_safe_flush: internal error\n";
  189. printk_safe_flush_line(msg, strlen(msg));
  190. len = 0;
  191. }
  192. if (!len)
  193. goto out; /* Someone else has already flushed the buffer. */
  194. /* Make sure that data has been written up to the @len */
  195. smp_rmb();
  196. i += printk_safe_flush_buffer(s->buffer + i, len - i);
  197. /*
  198. * Check that nothing has got added in the meantime and truncate
  199. * the buffer. Note that atomic_cmpxchg() is an implicit memory
  200. * barrier that makes sure that the data were copied before
  201. * updating s->len.
  202. */
  203. if (atomic_cmpxchg(&s->len, len, 0) != len)
  204. goto more;
  205. out:
  206. report_message_lost(s);
  207. raw_spin_unlock_irqrestore(&read_lock, flags);
  208. }
  209. /**
  210. * printk_safe_flush - flush all per-cpu nmi buffers.
  211. *
  212. * The buffers are flushed automatically via IRQ work. This function
  213. * is useful only when someone wants to be sure that all buffers have
  214. * been flushed at some point.
  215. */
  216. void printk_safe_flush(void)
  217. {
  218. int cpu;
  219. for_each_possible_cpu(cpu) {
  220. #ifdef CONFIG_PRINTK_NMI
  221. __printk_safe_flush(&per_cpu(nmi_print_seq, cpu).work);
  222. #endif
  223. __printk_safe_flush(&per_cpu(safe_print_seq, cpu).work);
  224. }
  225. }
  226. /**
  227. * printk_safe_flush_on_panic - flush all per-cpu nmi buffers when the system
  228. * goes down.
  229. *
  230. * Similar to printk_safe_flush() but it can be called even in NMI context when
  231. * the system goes down. It does the best effort to get NMI messages into
  232. * the main ring buffer.
  233. *
  234. * Note that it could try harder when there is only one CPU online.
  235. */
  236. void printk_safe_flush_on_panic(void)
  237. {
  238. /*
  239. * Make sure that we could access the main ring buffer.
  240. * Do not risk a double release when more CPUs are up.
  241. */
  242. if (in_nmi() && raw_spin_is_locked(&logbuf_lock)) {
  243. if (num_online_cpus() > 1)
  244. return;
  245. debug_locks_off();
  246. raw_spin_lock_init(&logbuf_lock);
  247. }
  248. printk_safe_flush();
  249. }
  250. #ifdef CONFIG_PRINTK_NMI
  251. /*
  252. * Safe printk() for NMI context. It uses a per-CPU buffer to
  253. * store the message. NMIs are not nested, so there is always only
  254. * one writer running. But the buffer might get flushed from another
  255. * CPU, so we need to be careful.
  256. */
  257. static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
  258. {
  259. struct printk_safe_seq_buf *s = this_cpu_ptr(&nmi_print_seq);
  260. return printk_safe_log_store(s, fmt, args);
  261. }
  262. void printk_nmi_enter(void)
  263. {
  264. /*
  265. * The size of the extra per-CPU buffer is limited. Use it only when
  266. * the main one is locked. If this CPU is not in the safe context,
  267. * the lock must be taken on another CPU and we could wait for it.
  268. */
  269. if ((this_cpu_read(printk_context) & PRINTK_SAFE_CONTEXT_MASK) &&
  270. raw_spin_is_locked(&logbuf_lock)) {
  271. this_cpu_or(printk_context, PRINTK_NMI_CONTEXT_MASK);
  272. } else {
  273. this_cpu_or(printk_context, PRINTK_NMI_DEFERRED_CONTEXT_MASK);
  274. }
  275. }
  276. void printk_nmi_exit(void)
  277. {
  278. this_cpu_and(printk_context,
  279. ~(PRINTK_NMI_CONTEXT_MASK |
  280. PRINTK_NMI_DEFERRED_CONTEXT_MASK));
  281. }
  282. #else
  283. static __printf(1, 0) int vprintk_nmi(const char *fmt, va_list args)
  284. {
  285. return 0;
  286. }
  287. #endif /* CONFIG_PRINTK_NMI */
  288. /*
  289. * Lock-less printk(), to avoid deadlocks should the printk() recurse
  290. * into itself. It uses a per-CPU buffer to store the message, just like
  291. * NMI.
  292. */
  293. static __printf(1, 0) int vprintk_safe(const char *fmt, va_list args)
  294. {
  295. struct printk_safe_seq_buf *s = this_cpu_ptr(&safe_print_seq);
  296. return printk_safe_log_store(s, fmt, args);
  297. }
  298. /* Can be preempted by NMI. */
  299. void __printk_safe_enter(void)
  300. {
  301. this_cpu_inc(printk_context);
  302. }
  303. /* Can be preempted by NMI. */
  304. void __printk_safe_exit(void)
  305. {
  306. this_cpu_dec(printk_context);
  307. }
  308. __printf(1, 0) int vprintk_func(const char *fmt, va_list args)
  309. {
  310. /* Use extra buffer in NMI when logbuf_lock is taken or in safe mode. */
  311. if (this_cpu_read(printk_context) & PRINTK_NMI_CONTEXT_MASK)
  312. return vprintk_nmi(fmt, args);
  313. /* Use extra buffer to prevent a recursion deadlock in safe mode. */
  314. if (this_cpu_read(printk_context) & PRINTK_SAFE_CONTEXT_MASK)
  315. return vprintk_safe(fmt, args);
  316. /*
  317. * Use the main logbuf when logbuf_lock is available in NMI.
  318. * But avoid calling console drivers that might have their own locks.
  319. */
  320. if (this_cpu_read(printk_context) & PRINTK_NMI_DEFERRED_CONTEXT_MASK)
  321. return vprintk_deferred(fmt, args);
  322. /* No obstacles. */
  323. return vprintk_default(fmt, args);
  324. }
  325. void __init printk_safe_init(void)
  326. {
  327. int cpu;
  328. for_each_possible_cpu(cpu) {
  329. struct printk_safe_seq_buf *s;
  330. s = &per_cpu(safe_print_seq, cpu);
  331. init_irq_work(&s->work, __printk_safe_flush);
  332. #ifdef CONFIG_PRINTK_NMI
  333. s = &per_cpu(nmi_print_seq, cpu);
  334. init_irq_work(&s->work, __printk_safe_flush);
  335. #endif
  336. }
  337. /*
  338. * In the highly unlikely event that a NMI were to trigger at
  339. * this moment. Make sure IRQ work is set up before this
  340. * variable is set.
  341. */
  342. barrier();
  343. printk_safe_irq_ready = 1;
  344. /* Flush pending messages that did not have scheduled IRQ works. */
  345. printk_safe_flush();
  346. }