once.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/slab.h>
  3. #include <linux/spinlock.h>
  4. #include <linux/once.h>
  5. #include <linux/random.h>
  6. #include <linux/module.h>
  7. struct once_work {
  8. struct work_struct work;
  9. struct static_key_true *key;
  10. struct module *module;
  11. };
  12. static void once_deferred(struct work_struct *w)
  13. {
  14. struct once_work *work;
  15. work = container_of(w, struct once_work, work);
  16. BUG_ON(!static_key_enabled(work->key));
  17. static_branch_disable(work->key);
  18. module_put(work->module);
  19. kfree(work);
  20. }
  21. static void once_disable_jump(struct static_key_true *key, struct module *mod)
  22. {
  23. struct once_work *w;
  24. w = kmalloc(sizeof(*w), GFP_ATOMIC);
  25. if (!w)
  26. return;
  27. INIT_WORK(&w->work, once_deferred);
  28. w->key = key;
  29. w->module = mod;
  30. __module_get(mod);
  31. schedule_work(&w->work);
  32. }
  33. static DEFINE_SPINLOCK(once_lock);
  34. bool __do_once_start(bool *done, unsigned long *flags)
  35. __acquires(once_lock)
  36. {
  37. spin_lock_irqsave(&once_lock, *flags);
  38. if (*done) {
  39. spin_unlock_irqrestore(&once_lock, *flags);
  40. /* Keep sparse happy by restoring an even lock count on
  41. * this lock. In case we return here, we don't call into
  42. * __do_once_done but return early in the DO_ONCE() macro.
  43. */
  44. __acquire(once_lock);
  45. return false;
  46. }
  47. return true;
  48. }
  49. EXPORT_SYMBOL(__do_once_start);
  50. void __do_once_done(bool *done, struct static_key_true *once_key,
  51. unsigned long *flags, struct module *mod)
  52. __releases(once_lock)
  53. {
  54. *done = true;
  55. spin_unlock_irqrestore(&once_lock, *flags);
  56. once_disable_jump(once_key, mod);
  57. }
  58. EXPORT_SYMBOL(__do_once_done);
  59. static DEFINE_MUTEX(once_mutex);
  60. bool __do_once_sleepable_start(bool *done)
  61. __acquires(once_mutex)
  62. {
  63. mutex_lock(&once_mutex);
  64. if (*done) {
  65. mutex_unlock(&once_mutex);
  66. /* Keep sparse happy by restoring an even lock count on
  67. * this mutex. In case we return here, we don't call into
  68. * __do_once_done but return early in the DO_ONCE_SLEEPABLE() macro.
  69. */
  70. __acquire(once_mutex);
  71. return false;
  72. }
  73. return true;
  74. }
  75. EXPORT_SYMBOL(__do_once_sleepable_start);
  76. void __do_once_sleepable_done(bool *done, struct static_key_true *once_key,
  77. struct module *mod)
  78. __releases(once_mutex)
  79. {
  80. *done = true;
  81. mutex_unlock(&once_mutex);
  82. once_disable_jump(once_key, mod);
  83. }
  84. EXPORT_SYMBOL(__do_once_sleepable_done);