task_work.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <linux/spinlock.h>
  2. #include <linux/task_work.h>
  3. #include <linux/tracehook.h>
  4. static struct callback_head work_exited; /* all we need is ->next == NULL */
  5. int
  6. task_work_add(struct task_struct *task, struct callback_head *work, bool notify)
  7. {
  8. struct callback_head *head;
  9. do {
  10. head = ACCESS_ONCE(task->task_works);
  11. if (unlikely(head == &work_exited))
  12. return -ESRCH;
  13. work->next = head;
  14. } while (cmpxchg(&task->task_works, head, work) != head);
  15. if (notify)
  16. set_notify_resume(task);
  17. return 0;
  18. }
  19. struct callback_head *
  20. task_work_cancel(struct task_struct *task, task_work_func_t func)
  21. {
  22. struct callback_head **pprev = &task->task_works;
  23. struct callback_head *work = NULL;
  24. unsigned long flags;
  25. /*
  26. * If cmpxchg() fails we continue without updating pprev.
  27. * Either we raced with task_work_add() which added the
  28. * new entry before this work, we will find it again. Or
  29. * we raced with task_work_run(), *pprev == NULL/exited.
  30. */
  31. raw_spin_lock_irqsave(&task->pi_lock, flags);
  32. while ((work = ACCESS_ONCE(*pprev))) {
  33. read_barrier_depends();
  34. if (work->func != func)
  35. pprev = &work->next;
  36. else if (cmpxchg(pprev, work, work->next) == work)
  37. break;
  38. }
  39. raw_spin_unlock_irqrestore(&task->pi_lock, flags);
  40. return work;
  41. }
  42. void task_work_run(void)
  43. {
  44. struct task_struct *task = current;
  45. struct callback_head *work, *head, *next;
  46. for (;;) {
  47. /*
  48. * work->func() can do task_work_add(), do not set
  49. * work_exited unless the list is empty.
  50. */
  51. do {
  52. work = ACCESS_ONCE(task->task_works);
  53. head = !work && (task->flags & PF_EXITING) ?
  54. &work_exited : NULL;
  55. } while (cmpxchg(&task->task_works, work, head) != work);
  56. if (!work)
  57. break;
  58. /*
  59. * Synchronize with task_work_cancel(). It can't remove
  60. * the first entry == work, cmpxchg(task_works) should
  61. * fail, but it can play with *work and other entries.
  62. */
  63. raw_spin_unlock_wait(&task->pi_lock);
  64. smp_mb();
  65. /* Reverse the list to run the works in fifo order */
  66. head = NULL;
  67. do {
  68. next = work->next;
  69. work->next = head;
  70. head = work;
  71. work = next;
  72. } while (work);
  73. work = head;
  74. do {
  75. next = work->next;
  76. work->func(work);
  77. work = next;
  78. cond_resched();
  79. } while (work);
  80. }
  81. }