task_work.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <linux/spinlock.h>
  2. #include <linux/task_work.h>
  3. #include <linux/tracehook.h>
  4. int
  5. task_work_add(struct task_struct *task, struct task_work *twork, bool notify)
  6. {
  7. unsigned long flags;
  8. int err = -ESRCH;
  9. #ifndef TIF_NOTIFY_RESUME
  10. if (notify)
  11. return -ENOTSUPP;
  12. #endif
  13. /*
  14. * We must not insert the new work if the task has already passed
  15. * exit_task_work(). We rely on do_exit()->raw_spin_unlock_wait()
  16. * and check PF_EXITING under pi_lock.
  17. */
  18. raw_spin_lock_irqsave(&task->pi_lock, flags);
  19. if (likely(!(task->flags & PF_EXITING))) {
  20. hlist_add_head(&twork->hlist, &task->task_works);
  21. err = 0;
  22. }
  23. raw_spin_unlock_irqrestore(&task->pi_lock, flags);
  24. /* test_and_set_bit() implies mb(), see tracehook_notify_resume(). */
  25. if (likely(!err) && notify)
  26. set_notify_resume(task);
  27. return err;
  28. }
  29. struct task_work *
  30. task_work_cancel(struct task_struct *task, task_work_func_t func)
  31. {
  32. unsigned long flags;
  33. struct task_work *twork;
  34. struct hlist_node *pos;
  35. raw_spin_lock_irqsave(&task->pi_lock, flags);
  36. hlist_for_each_entry(twork, pos, &task->task_works, hlist) {
  37. if (twork->func == func) {
  38. hlist_del(&twork->hlist);
  39. goto found;
  40. }
  41. }
  42. twork = NULL;
  43. found:
  44. raw_spin_unlock_irqrestore(&task->pi_lock, flags);
  45. return twork;
  46. }
  47. void task_work_run(void)
  48. {
  49. struct task_struct *task = current;
  50. struct hlist_head task_works;
  51. struct hlist_node *pos;
  52. raw_spin_lock_irq(&task->pi_lock);
  53. hlist_move_list(&task->task_works, &task_works);
  54. raw_spin_unlock_irq(&task->pi_lock);
  55. if (unlikely(hlist_empty(&task_works)))
  56. return;
  57. /*
  58. * We use hlist to save the space in task_struct, but we want fifo.
  59. * Find the last entry, the list should be short, then process them
  60. * in reverse order.
  61. */
  62. for (pos = task_works.first; pos->next; pos = pos->next)
  63. ;
  64. for (;;) {
  65. struct hlist_node **pprev = pos->pprev;
  66. struct task_work *twork = container_of(pos, struct task_work,
  67. hlist);
  68. twork->func(twork);
  69. if (pprev == &task_works.first)
  70. break;
  71. pos = container_of(pprev, struct hlist_node, next);
  72. }
  73. }