printk_safe.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. void __printk_deferred_enter(void)
  24. {
  25. cant_migrate();
  26. __printk_safe_enter();
  27. }
  28. void __printk_deferred_exit(void)
  29. {
  30. cant_migrate();
  31. __printk_safe_exit();
  32. }
  33. bool is_printk_legacy_deferred(void)
  34. {
  35. /*
  36. * The per-CPU variable @printk_context can be read safely in any
  37. * context. CPU migration is always disabled when set.
  38. *
  39. * A context holding the printk_cpu_sync must not spin waiting for
  40. * another CPU. For legacy printing, it could be the console_lock
  41. * or the port lock.
  42. */
  43. return (force_legacy_kthread() ||
  44. this_cpu_read(printk_context) ||
  45. in_nmi() ||
  46. is_printk_cpu_sync_owner());
  47. }
  48. asmlinkage int vprintk(const char *fmt, va_list args)
  49. {
  50. #ifdef CONFIG_KGDB_KDB
  51. /* Allow to pass printk() to kdb but avoid a recursion. */
  52. if (unlikely(kdb_trap_printk && kdb_printf_cpu < 0))
  53. return vkdb_printf(KDB_MSGSRC_PRINTK, fmt, args);
  54. #endif
  55. /*
  56. * Use the main logbuf even in NMI. But avoid calling console
  57. * drivers that might have their own locks.
  58. */
  59. if (is_printk_legacy_deferred())
  60. return vprintk_deferred(fmt, args);
  61. /* No obstacles. */
  62. return vprintk_default(fmt, args);
  63. }
  64. EXPORT_SYMBOL(vprintk);