printk_safe.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * printk_safe.c - Safe printk for printk-deadlock-prone contexts
  4. */
  5. #include <linux/preempt.h>
  6. #include <linux/kdb.h>
  7. #include <linux/smp.h>
  8. #include <linux/cpumask.h>
  9. #include <linux/printk.h>
  10. #include <linux/kprobes.h>
  11. #include "internal.h"
  12. static DEFINE_PER_CPU(int, printk_context);
  13. /* Can be preempted by NMI. */
  14. void __printk_safe_enter(void)
  15. {
  16. this_cpu_inc(printk_context);
  17. }
  18. /* Can be preempted by NMI. */
  19. void __printk_safe_exit(void)
  20. {
  21. this_cpu_dec(printk_context);
  22. }
  23. asmlinkage int vprintk(const char *fmt, va_list args)
  24. {
  25. #ifdef CONFIG_KGDB_KDB
  26. /* Allow to pass printk() to kdb but avoid a recursion. */
  27. if (unlikely(kdb_trap_printk && kdb_printf_cpu < 0))
  28. return vkdb_printf(KDB_MSGSRC_PRINTK, fmt, args);
  29. #endif
  30. /*
  31. * Use the main logbuf even in NMI. But avoid calling console
  32. * drivers that might have their own locks.
  33. */
  34. if (this_cpu_read(printk_context) || in_nmi())
  35. return vprintk_deferred(fmt, args);
  36. /* No obstacles. */
  37. return vprintk_default(fmt, args);
  38. }
  39. EXPORT_SYMBOL(vprintk);