once.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. struct once_work {
  7. struct work_struct work;
  8. struct static_key_true *key;
  9. };
  10. static void once_deferred(struct work_struct *w)
  11. {
  12. struct once_work *work;
  13. work = container_of(w, struct once_work, work);
  14. BUG_ON(!static_key_enabled(work->key));
  15. static_branch_disable(work->key);
  16. kfree(work);
  17. }
  18. static void once_disable_jump(struct static_key_true *key)
  19. {
  20. struct once_work *w;
  21. w = kmalloc(sizeof(*w), GFP_ATOMIC);
  22. if (!w)
  23. return;
  24. INIT_WORK(&w->work, once_deferred);
  25. w->key = key;
  26. schedule_work(&w->work);
  27. }
  28. static DEFINE_SPINLOCK(once_lock);
  29. bool __do_once_start(bool *done, unsigned long *flags)
  30. __acquires(once_lock)
  31. {
  32. spin_lock_irqsave(&once_lock, *flags);
  33. if (*done) {
  34. spin_unlock_irqrestore(&once_lock, *flags);
  35. /* Keep sparse happy by restoring an even lock count on
  36. * this lock. In case we return here, we don't call into
  37. * __do_once_done but return early in the DO_ONCE() macro.
  38. */
  39. __acquire(once_lock);
  40. return false;
  41. }
  42. return true;
  43. }
  44. EXPORT_SYMBOL(__do_once_start);
  45. void __do_once_done(bool *done, struct static_key_true *once_key,
  46. unsigned long *flags)
  47. __releases(once_lock)
  48. {
  49. *done = true;
  50. spin_unlock_irqrestore(&once_lock, *flags);
  51. once_disable_jump(once_key);
  52. }
  53. EXPORT_SYMBOL(__do_once_done);