task_work.c 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <linux/spinlock.h>
#include <linux/task_work.h>
#include <linux/tracehook.h>

int
task_work_add(struct task_struct *task, struct task_work *twork, bool notify)
{
	unsigned long flags;
	int err = -ESRCH;

#ifndef TIF_NOTIFY_RESUME
	if (notify)
		return -ENOTSUPP;
#endif
	/*
	 * We must not insert the new work if the task has already passed
	 * exit_task_work(). We rely on do_exit()->raw_spin_unlock_wait()
	 * and check PF_EXITING under pi_lock.
	 */
	raw_spin_lock_irqsave(&task->pi_lock, flags);
	if (likely(!(task->flags & PF_EXITING))) {
A
Al Viro 已提交
22 23 24 25 26 27
		struct task_work *last = task->task_works;
		struct task_work *first = last ? last->next : twork;
		twork->next = first;
		if (last)
			last->next = twork;
		task->task_works = twork;
28 29 30 31 32 33 34 35 36 37 38 39 40 41
		err = 0;
	}
	raw_spin_unlock_irqrestore(&task->pi_lock, flags);

	/* test_and_set_bit() implies mb(), see tracehook_notify_resume(). */
	if (likely(!err) && notify)
		set_notify_resume(task);
	return err;
}

struct task_work *
task_work_cancel(struct task_struct *task, task_work_func_t func)
{
	unsigned long flags;
A
Al Viro 已提交
42
	struct task_work *last, *res = NULL;
43 44

	raw_spin_lock_irqsave(&task->pi_lock, flags);
A
Al Viro 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
	last = task->task_works;
	if (last) {
		struct task_work *q = last, *p = q->next;
		while (1) {
			if (p->func == func) {
				q->next = p->next;
				if (p == last)
					task->task_works = q == p ? NULL : q;
				res = p;
				break;
			}
			if (p == last)
				break;
			q = p;
			p = q->next;
60 61 62
		}
	}
	raw_spin_unlock_irqrestore(&task->pi_lock, flags);
A
Al Viro 已提交
63
	return res;
64 65 66 67 68
}

void task_work_run(void)
{
	struct task_struct *task = current;
A
Al Viro 已提交
69
	struct task_work *p, *q;
70 71

	raw_spin_lock_irq(&task->pi_lock);
A
Al Viro 已提交
72 73
	p = task->task_works;
	task->task_works = NULL;
74 75
	raw_spin_unlock_irq(&task->pi_lock);

A
Al Viro 已提交
76
	if (unlikely(!p))
77 78
		return;

A
Al Viro 已提交
79 80 81 82 83 84
	q = p->next; /* head */
	p->next = NULL; /* cut it */
	while (q) {
		p = q->next;
		q->func(q);
		q = p;
85 86
	}
}