• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Kernel thread helper functions.
2  *   Copyright (C) 2004 IBM Corporation, Rusty Russell.
3  *
4  * Creation is done via kthreadd, so that we get a clean environment
5  * even if we're invoked from userspace (think modprobe, hotplug cpu,
6  * etc.).
7  */
8 #include <linux/sched.h>
9 #include <linux/kthread.h>
10 #include <linux/completion.h>
11 #include <linux/err.h>
12 #include <linux/cpuset.h>
13 #include <linux/unistd.h>
14 #include <linux/file.h>
15 #include <linux/export.h>
16 #include <linux/mutex.h>
17 #include <linux/slab.h>
18 #include <linux/freezer.h>
19 #include <linux/ptrace.h>
20 #include <linux/uaccess.h>
21 #include <linux/cgroup.h>
22 #include <trace/events/sched.h>
23 
24 static DEFINE_SPINLOCK(kthread_create_lock);
25 static LIST_HEAD(kthread_create_list);
26 struct task_struct *kthreadd_task;
27 
28 struct kthread_create_info
29 {
30 	/* Information passed to kthread() from kthreadd. */
31 	int (*threadfn)(void *data);
32 	void *data;
33 	int node;
34 
35 	/* Result passed back to kthread_create() from kthreadd. */
36 	struct task_struct *result;
37 	struct completion *done;
38 
39 	struct list_head list;
40 };
41 
42 struct kthread {
43 	unsigned long flags;
44 	unsigned int cpu;
45 	void *data;
46 	struct completion parked;
47 	struct completion exited;
48 };
49 
50 enum KTHREAD_BITS {
51 	KTHREAD_IS_PER_CPU = 0,
52 	KTHREAD_SHOULD_STOP,
53 	KTHREAD_SHOULD_PARK,
54 	KTHREAD_IS_PARKED,
55 };
56 
57 #define __to_kthread(vfork)	\
58 	container_of(vfork, struct kthread, exited)
59 
to_kthread(struct task_struct * k)60 static inline struct kthread *to_kthread(struct task_struct *k)
61 {
62 	return __to_kthread(k->vfork_done);
63 }
64 
to_live_kthread(struct task_struct * k)65 static struct kthread *to_live_kthread(struct task_struct *k)
66 {
67 	struct completion *vfork = ACCESS_ONCE(k->vfork_done);
68 	if (likely(vfork) && try_get_task_stack(k))
69 		return __to_kthread(vfork);
70 	return NULL;
71 }
72 
73 /**
74  * kthread_should_stop - should this kthread return now?
75  *
76  * When someone calls kthread_stop() on your kthread, it will be woken
77  * and this will return true.  You should then return, and your return
78  * value will be passed through to kthread_stop().
79  */
kthread_should_stop(void)80 bool kthread_should_stop(void)
81 {
82 	return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
83 }
84 EXPORT_SYMBOL(kthread_should_stop);
85 
86 /**
87  * kthread_should_park - should this kthread park now?
88  *
89  * When someone calls kthread_park() on your kthread, it will be woken
90  * and this will return true.  You should then do the necessary
91  * cleanup and call kthread_parkme()
92  *
93  * Similar to kthread_should_stop(), but this keeps the thread alive
94  * and in a park position. kthread_unpark() "restarts" the thread and
95  * calls the thread function again.
96  */
kthread_should_park(void)97 bool kthread_should_park(void)
98 {
99 	return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
100 }
101 EXPORT_SYMBOL_GPL(kthread_should_park);
102 
103 /**
104  * kthread_freezable_should_stop - should this freezable kthread return now?
105  * @was_frozen: optional out parameter, indicates whether %current was frozen
106  *
107  * kthread_should_stop() for freezable kthreads, which will enter
108  * refrigerator if necessary.  This function is safe from kthread_stop() /
109  * freezer deadlock and freezable kthreads should use this function instead
110  * of calling try_to_freeze() directly.
111  */
kthread_freezable_should_stop(bool * was_frozen)112 bool kthread_freezable_should_stop(bool *was_frozen)
113 {
114 	bool frozen = false;
115 
116 	might_sleep();
117 
118 	if (unlikely(freezing(current)))
119 		frozen = __refrigerator(true);
120 
121 	if (was_frozen)
122 		*was_frozen = frozen;
123 
124 	return kthread_should_stop();
125 }
126 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
127 
128 /**
129  * kthread_data - return data value specified on kthread creation
130  * @task: kthread task in question
131  *
132  * Return the data value specified when kthread @task was created.
133  * The caller is responsible for ensuring the validity of @task when
134  * calling this function.
135  */
kthread_data(struct task_struct * task)136 void *kthread_data(struct task_struct *task)
137 {
138 	return to_kthread(task)->data;
139 }
140 
141 /**
142  * probe_kthread_data - speculative version of kthread_data()
143  * @task: possible kthread task in question
144  *
145  * @task could be a kthread task.  Return the data value specified when it
146  * was created if accessible.  If @task isn't a kthread task or its data is
147  * inaccessible for any reason, %NULL is returned.  This function requires
148  * that @task itself is safe to dereference.
149  */
probe_kthread_data(struct task_struct * task)150 void *probe_kthread_data(struct task_struct *task)
151 {
152 	struct kthread *kthread = to_kthread(task);
153 	void *data = NULL;
154 
155 	probe_kernel_read(&data, &kthread->data, sizeof(data));
156 	return data;
157 }
158 
__kthread_parkme(struct kthread * self)159 static void __kthread_parkme(struct kthread *self)
160 {
161 	__set_current_state(TASK_PARKED);
162 	while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
163 		if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
164 			complete(&self->parked);
165 		schedule();
166 		__set_current_state(TASK_PARKED);
167 	}
168 	clear_bit(KTHREAD_IS_PARKED, &self->flags);
169 	__set_current_state(TASK_RUNNING);
170 }
171 
kthread_parkme(void)172 void kthread_parkme(void)
173 {
174 	__kthread_parkme(to_kthread(current));
175 }
176 EXPORT_SYMBOL_GPL(kthread_parkme);
177 
kthread(void * _create)178 static int kthread(void *_create)
179 {
180 	/* Copy data: it's on kthread's stack */
181 	struct kthread_create_info *create = _create;
182 	int (*threadfn)(void *data) = create->threadfn;
183 	void *data = create->data;
184 	struct completion *done;
185 	struct kthread self;
186 	int ret;
187 
188 	self.flags = 0;
189 	self.data = data;
190 	init_completion(&self.exited);
191 	init_completion(&self.parked);
192 	current->vfork_done = &self.exited;
193 
194 	/* If user was SIGKILLed, I release the structure. */
195 	done = xchg(&create->done, NULL);
196 	if (!done) {
197 		kfree(create);
198 		do_exit(-EINTR);
199 	}
200 	/* OK, tell user we're spawned, wait for stop or wakeup */
201 	__set_current_state(TASK_UNINTERRUPTIBLE);
202 	create->result = current;
203 	complete(done);
204 	schedule();
205 
206 	ret = -EINTR;
207 
208 	if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
209 		cgroup_kthread_ready();
210 		__kthread_parkme(&self);
211 		ret = threadfn(data);
212 	}
213 	/* we can't just return, we must preserve "self" on stack */
214 	do_exit(ret);
215 }
216 
217 /* called from do_fork() to get node information for about to be created task */
tsk_fork_get_node(struct task_struct * tsk)218 int tsk_fork_get_node(struct task_struct *tsk)
219 {
220 #ifdef CONFIG_NUMA
221 	if (tsk == kthreadd_task)
222 		return tsk->pref_node_fork;
223 #endif
224 	return NUMA_NO_NODE;
225 }
226 
create_kthread(struct kthread_create_info * create)227 static void create_kthread(struct kthread_create_info *create)
228 {
229 	int pid;
230 
231 #ifdef CONFIG_NUMA
232 	current->pref_node_fork = create->node;
233 #endif
234 	/* We want our own signal handler (we take no signals by default). */
235 	pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
236 	if (pid < 0) {
237 		/* If user was SIGKILLed, I release the structure. */
238 		struct completion *done = xchg(&create->done, NULL);
239 
240 		if (!done) {
241 			kfree(create);
242 			return;
243 		}
244 		create->result = ERR_PTR(pid);
245 		complete(done);
246 	}
247 }
248 
249 /**
250  * kthread_create_on_node - create a kthread.
251  * @threadfn: the function to run until signal_pending(current).
252  * @data: data ptr for @threadfn.
253  * @node: task and thread structures for the thread are allocated on this node
254  * @namefmt: printf-style name for the thread.
255  *
256  * Description: This helper function creates and names a kernel
257  * thread.  The thread will be stopped: use wake_up_process() to start
258  * it.  See also kthread_run().  The new thread has SCHED_NORMAL policy and
259  * is affine to all CPUs.
260  *
261  * If thread is going to be bound on a particular cpu, give its node
262  * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
263  * When woken, the thread will run @threadfn() with @data as its
264  * argument. @threadfn() can either call do_exit() directly if it is a
265  * standalone thread for which no one will call kthread_stop(), or
266  * return when 'kthread_should_stop()' is true (which means
267  * kthread_stop() has been called).  The return value should be zero
268  * or a negative error number; it will be passed to kthread_stop().
269  *
270  * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
271  */
kthread_create_on_node(int (* threadfn)(void * data),void * data,int node,const char namefmt[],...)272 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
273 					   void *data, int node,
274 					   const char namefmt[],
275 					   ...)
276 {
277 	DECLARE_COMPLETION_ONSTACK(done);
278 	struct task_struct *task;
279 	struct kthread_create_info *create = kmalloc(sizeof(*create),
280 						     GFP_KERNEL);
281 
282 	if (!create)
283 		return ERR_PTR(-ENOMEM);
284 	create->threadfn = threadfn;
285 	create->data = data;
286 	create->node = node;
287 	create->done = &done;
288 
289 	spin_lock(&kthread_create_lock);
290 	list_add_tail(&create->list, &kthread_create_list);
291 	spin_unlock(&kthread_create_lock);
292 
293 	wake_up_process(kthreadd_task);
294 	/*
295 	 * Wait for completion in killable state, for I might be chosen by
296 	 * the OOM killer while kthreadd is trying to allocate memory for
297 	 * new kernel thread.
298 	 */
299 	if (unlikely(wait_for_completion_killable(&done))) {
300 		/*
301 		 * If I was SIGKILLed before kthreadd (or new kernel thread)
302 		 * calls complete(), leave the cleanup of this structure to
303 		 * that thread.
304 		 */
305 		if (xchg(&create->done, NULL))
306 			return ERR_PTR(-EINTR);
307 		/*
308 		 * kthreadd (or new kernel thread) will call complete()
309 		 * shortly.
310 		 */
311 		wait_for_completion(&done);
312 	}
313 	task = create->result;
314 	if (!IS_ERR(task)) {
315 		static const struct sched_param param = { .sched_priority = 0 };
316 		char name[TASK_COMM_LEN];
317 		va_list args;
318 
319 		va_start(args, namefmt);
320 		/*
321 		 * task is already visible to other tasks, so updating
322 		 * COMM must be protected.
323 		 */
324 		vsnprintf(name, sizeof(name), namefmt, args);
325 		set_task_comm(task, name);
326 		va_end(args);
327 		/*
328 		 * root may have changed our (kthreadd's) priority or CPU mask.
329 		 * The kernel thread should not inherit these properties.
330 		 */
331 		sched_setscheduler_nocheck(task, SCHED_NORMAL, &param);
332 		set_cpus_allowed_ptr(task, cpu_all_mask);
333 	}
334 	kfree(create);
335 	return task;
336 }
337 EXPORT_SYMBOL(kthread_create_on_node);
338 
__kthread_bind_mask(struct task_struct * p,const struct cpumask * mask,long state)339 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
340 {
341 	unsigned long flags;
342 
343 	if (!wait_task_inactive(p, state)) {
344 		WARN_ON(1);
345 		return;
346 	}
347 
348 	/* It's safe because the task is inactive. */
349 	raw_spin_lock_irqsave(&p->pi_lock, flags);
350 	do_set_cpus_allowed(p, mask);
351 	p->flags |= PF_NO_SETAFFINITY;
352 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
353 }
354 
__kthread_bind(struct task_struct * p,unsigned int cpu,long state)355 static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
356 {
357 	__kthread_bind_mask(p, cpumask_of(cpu), state);
358 }
359 
kthread_bind_mask(struct task_struct * p,const struct cpumask * mask)360 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
361 {
362 	__kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
363 }
364 
365 /**
366  * kthread_bind - bind a just-created kthread to a cpu.
367  * @p: thread created by kthread_create().
368  * @cpu: cpu (might not be online, must be possible) for @k to run on.
369  *
370  * Description: This function is equivalent to set_cpus_allowed(),
371  * except that @cpu doesn't need to be online, and the thread must be
372  * stopped (i.e., just returned from kthread_create()).
373  */
kthread_bind(struct task_struct * p,unsigned int cpu)374 void kthread_bind(struct task_struct *p, unsigned int cpu)
375 {
376 	__kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
377 }
378 EXPORT_SYMBOL(kthread_bind);
379 
380 /**
381  * kthread_create_on_cpu - Create a cpu bound kthread
382  * @threadfn: the function to run until signal_pending(current).
383  * @data: data ptr for @threadfn.
384  * @cpu: The cpu on which the thread should be bound,
385  * @namefmt: printf-style name for the thread. Format is restricted
386  *	     to "name.*%u". Code fills in cpu number.
387  *
388  * Description: This helper function creates and names a kernel thread
389  * The thread will be woken and put into park mode.
390  */
kthread_create_on_cpu(int (* threadfn)(void * data),void * data,unsigned int cpu,const char * namefmt)391 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
392 					  void *data, unsigned int cpu,
393 					  const char *namefmt)
394 {
395 	struct task_struct *p;
396 
397 	p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
398 				   cpu);
399 	if (IS_ERR(p))
400 		return p;
401 	set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
402 	to_kthread(p)->cpu = cpu;
403 	/* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */
404 	kthread_park(p);
405 	return p;
406 }
407 
__kthread_unpark(struct task_struct * k,struct kthread * kthread)408 static void __kthread_unpark(struct task_struct *k, struct kthread *kthread)
409 {
410 	clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
411 	/*
412 	 * We clear the IS_PARKED bit here as we don't wait
413 	 * until the task has left the park code. So if we'd
414 	 * park before that happens we'd see the IS_PARKED bit
415 	 * which might be about to be cleared.
416 	 */
417 	if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
418 		if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
419 			__kthread_bind(k, kthread->cpu, TASK_PARKED);
420 		wake_up_state(k, TASK_PARKED);
421 	}
422 }
423 
424 /**
425  * kthread_unpark - unpark a thread created by kthread_create().
426  * @k:		thread created by kthread_create().
427  *
428  * Sets kthread_should_park() for @k to return false, wakes it, and
429  * waits for it to return. If the thread is marked percpu then its
430  * bound to the cpu again.
431  */
kthread_unpark(struct task_struct * k)432 void kthread_unpark(struct task_struct *k)
433 {
434 	struct kthread *kthread = to_live_kthread(k);
435 
436 	if (kthread) {
437 		__kthread_unpark(k, kthread);
438 		put_task_stack(k);
439 	}
440 }
441 EXPORT_SYMBOL_GPL(kthread_unpark);
442 
443 /**
444  * kthread_park - park a thread created by kthread_create().
445  * @k: thread created by kthread_create().
446  *
447  * Sets kthread_should_park() for @k to return true, wakes it, and
448  * waits for it to return. This can also be called after kthread_create()
449  * instead of calling wake_up_process(): the thread will park without
450  * calling threadfn().
451  *
452  * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
453  * If called by the kthread itself just the park bit is set.
454  */
kthread_park(struct task_struct * k)455 int kthread_park(struct task_struct *k)
456 {
457 	struct kthread *kthread = to_live_kthread(k);
458 	int ret = -ENOSYS;
459 
460 	if (kthread) {
461 		if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
462 			set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
463 			if (k != current) {
464 				wake_up_process(k);
465 				wait_for_completion(&kthread->parked);
466 			}
467 		}
468 		put_task_stack(k);
469 		ret = 0;
470 	}
471 	return ret;
472 }
473 EXPORT_SYMBOL_GPL(kthread_park);
474 
475 /**
476  * kthread_stop - stop a thread created by kthread_create().
477  * @k: thread created by kthread_create().
478  *
479  * Sets kthread_should_stop() for @k to return true, wakes it, and
480  * waits for it to exit. This can also be called after kthread_create()
481  * instead of calling wake_up_process(): the thread will exit without
482  * calling threadfn().
483  *
484  * If threadfn() may call do_exit() itself, the caller must ensure
485  * task_struct can't go away.
486  *
487  * Returns the result of threadfn(), or %-EINTR if wake_up_process()
488  * was never called.
489  */
kthread_stop(struct task_struct * k)490 int kthread_stop(struct task_struct *k)
491 {
492 	struct kthread *kthread;
493 	int ret;
494 
495 	trace_sched_kthread_stop(k);
496 
497 	get_task_struct(k);
498 	kthread = to_live_kthread(k);
499 	if (kthread) {
500 		set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
501 		__kthread_unpark(k, kthread);
502 		wake_up_process(k);
503 		wait_for_completion(&kthread->exited);
504 		put_task_stack(k);
505 	}
506 	ret = k->exit_code;
507 	put_task_struct(k);
508 
509 	trace_sched_kthread_stop_ret(ret);
510 	return ret;
511 }
512 EXPORT_SYMBOL(kthread_stop);
513 
kthreadd(void * unused)514 int kthreadd(void *unused)
515 {
516 	struct task_struct *tsk = current;
517 
518 	/* Setup a clean context for our children to inherit. */
519 	set_task_comm(tsk, "kthreadd");
520 	ignore_signals(tsk);
521 	set_cpus_allowed_ptr(tsk, cpu_all_mask);
522 	set_mems_allowed(node_states[N_MEMORY]);
523 
524 	current->flags |= PF_NOFREEZE;
525 	cgroup_init_kthreadd();
526 
527 	for (;;) {
528 		set_current_state(TASK_INTERRUPTIBLE);
529 		if (list_empty(&kthread_create_list))
530 			schedule();
531 		__set_current_state(TASK_RUNNING);
532 
533 		spin_lock(&kthread_create_lock);
534 		while (!list_empty(&kthread_create_list)) {
535 			struct kthread_create_info *create;
536 
537 			create = list_entry(kthread_create_list.next,
538 					    struct kthread_create_info, list);
539 			list_del_init(&create->list);
540 			spin_unlock(&kthread_create_lock);
541 
542 			create_kthread(create);
543 
544 			spin_lock(&kthread_create_lock);
545 		}
546 		spin_unlock(&kthread_create_lock);
547 	}
548 
549 	return 0;
550 }
551 
__init_kthread_worker(struct kthread_worker * worker,const char * name,struct lock_class_key * key)552 void __init_kthread_worker(struct kthread_worker *worker,
553 				const char *name,
554 				struct lock_class_key *key)
555 {
556 	spin_lock_init(&worker->lock);
557 	lockdep_set_class_and_name(&worker->lock, key, name);
558 	INIT_LIST_HEAD(&worker->work_list);
559 	worker->task = NULL;
560 }
561 EXPORT_SYMBOL_GPL(__init_kthread_worker);
562 
563 /**
564  * kthread_worker_fn - kthread function to process kthread_worker
565  * @worker_ptr: pointer to initialized kthread_worker
566  *
567  * This function can be used as @threadfn to kthread_create() or
568  * kthread_run() with @worker_ptr argument pointing to an initialized
569  * kthread_worker.  The started kthread will process work_list until
570  * the it is stopped with kthread_stop().  A kthread can also call
571  * this function directly after extra initialization.
572  *
573  * Different kthreads can be used for the same kthread_worker as long
574  * as there's only one kthread attached to it at any given time.  A
575  * kthread_worker without an attached kthread simply collects queued
576  * kthread_works.
577  */
kthread_worker_fn(void * worker_ptr)578 int kthread_worker_fn(void *worker_ptr)
579 {
580 	struct kthread_worker *worker = worker_ptr;
581 	struct kthread_work *work;
582 
583 	WARN_ON(worker->task);
584 	worker->task = current;
585 repeat:
586 	set_current_state(TASK_INTERRUPTIBLE);	/* mb paired w/ kthread_stop */
587 
588 	if (kthread_should_stop()) {
589 		__set_current_state(TASK_RUNNING);
590 		spin_lock_irq(&worker->lock);
591 		worker->task = NULL;
592 		spin_unlock_irq(&worker->lock);
593 		return 0;
594 	}
595 
596 	work = NULL;
597 	spin_lock_irq(&worker->lock);
598 	if (!list_empty(&worker->work_list)) {
599 		work = list_first_entry(&worker->work_list,
600 					struct kthread_work, node);
601 		list_del_init(&work->node);
602 	}
603 	worker->current_work = work;
604 	spin_unlock_irq(&worker->lock);
605 
606 	if (work) {
607 		__set_current_state(TASK_RUNNING);
608 		work->func(work);
609 	} else if (!freezing(current))
610 		schedule();
611 
612 	try_to_freeze();
613 	goto repeat;
614 }
615 EXPORT_SYMBOL_GPL(kthread_worker_fn);
616 
617 /*
618  * Returns true when the work could not be queued at the moment.
619  * It happens when it is already pending in a worker list
620  * or when it is being cancelled.
621  */
queuing_blocked(struct kthread_worker * worker,struct kthread_work * work)622 static inline bool queuing_blocked(struct kthread_worker *worker,
623 				   struct kthread_work *work)
624 {
625 	lockdep_assert_held(&worker->lock);
626 
627 	return !list_empty(&work->node) || work->canceling;
628 }
629 
630 /* insert @work before @pos in @worker */
insert_kthread_work(struct kthread_worker * worker,struct kthread_work * work,struct list_head * pos)631 static void insert_kthread_work(struct kthread_worker *worker,
632 			       struct kthread_work *work,
633 			       struct list_head *pos)
634 {
635 	lockdep_assert_held(&worker->lock);
636 
637 	list_add_tail(&work->node, pos);
638 	work->worker = worker;
639 	if (!worker->current_work && likely(worker->task))
640 		wake_up_process(worker->task);
641 }
642 
643 /**
644  * queue_kthread_work - queue a kthread_work
645  * @worker: target kthread_worker
646  * @work: kthread_work to queue
647  *
648  * Queue @work to work processor @task for async execution.  @task
649  * must have been created with kthread_worker_create().  Returns %true
650  * if @work was successfully queued, %false if it was already pending.
651  */
queue_kthread_work(struct kthread_worker * worker,struct kthread_work * work)652 bool queue_kthread_work(struct kthread_worker *worker,
653 			struct kthread_work *work)
654 {
655 	bool ret = false;
656 	unsigned long flags;
657 
658 	spin_lock_irqsave(&worker->lock, flags);
659 	if (!queuing_blocked(worker, work)) {
660 		insert_kthread_work(worker, work, &worker->work_list);
661 		ret = true;
662 	}
663 	spin_unlock_irqrestore(&worker->lock, flags);
664 	return ret;
665 }
666 EXPORT_SYMBOL_GPL(queue_kthread_work);
667 
668 struct kthread_flush_work {
669 	struct kthread_work	work;
670 	struct completion	done;
671 };
672 
kthread_flush_work_fn(struct kthread_work * work)673 static void kthread_flush_work_fn(struct kthread_work *work)
674 {
675 	struct kthread_flush_work *fwork =
676 		container_of(work, struct kthread_flush_work, work);
677 	complete(&fwork->done);
678 }
679 
680 /**
681  * flush_kthread_work - flush a kthread_work
682  * @work: work to flush
683  *
684  * If @work is queued or executing, wait for it to finish execution.
685  */
flush_kthread_work(struct kthread_work * work)686 void flush_kthread_work(struct kthread_work *work)
687 {
688 	struct kthread_flush_work fwork = {
689 		KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
690 		COMPLETION_INITIALIZER_ONSTACK(fwork.done),
691 	};
692 	struct kthread_worker *worker;
693 	bool noop = false;
694 
695 retry:
696 	worker = work->worker;
697 	if (!worker)
698 		return;
699 
700 	spin_lock_irq(&worker->lock);
701 	if (work->worker != worker) {
702 		spin_unlock_irq(&worker->lock);
703 		goto retry;
704 	}
705 
706 	if (!list_empty(&work->node))
707 		insert_kthread_work(worker, &fwork.work, work->node.next);
708 	else if (worker->current_work == work)
709 		insert_kthread_work(worker, &fwork.work, worker->work_list.next);
710 	else
711 		noop = true;
712 
713 	spin_unlock_irq(&worker->lock);
714 
715 	if (!noop)
716 		wait_for_completion(&fwork.done);
717 }
718 EXPORT_SYMBOL_GPL(flush_kthread_work);
719 
720 /*
721  * This function removes the work from the worker queue. Also it makes sure
722  * that it won't get queued later via the delayed work's timer.
723  *
724  * The work might still be in use when this function finishes. See the
725  * current_work proceed by the worker.
726  *
727  * Return: %true if @work was pending and successfully canceled,
728  *	%false if @work was not pending
729  */
__kthread_cancel_work(struct kthread_work * work,unsigned long * flags)730 static bool __kthread_cancel_work(struct kthread_work *work,
731 				  unsigned long *flags)
732 {
733 	/*
734 	 * Try to remove the work from a worker list. It might either
735 	 * be from worker->work_list or from worker->delayed_work_list.
736 	 */
737 	if (!list_empty(&work->node)) {
738 		list_del_init(&work->node);
739 		return true;
740 	}
741 
742 	return false;
743 }
744 
__kthread_cancel_work_sync(struct kthread_work * work)745 static bool __kthread_cancel_work_sync(struct kthread_work *work)
746 {
747 	struct kthread_worker *worker = work->worker;
748 	unsigned long flags;
749 	int ret = false;
750 
751 	if (!worker)
752 		goto out;
753 
754 	spin_lock_irqsave(&worker->lock, flags);
755 	/* Work must not be used with >1 worker, see kthread_queue_work(). */
756 	WARN_ON_ONCE(work->worker != worker);
757 
758 	ret = __kthread_cancel_work(work, &flags);
759 
760 	if (worker->current_work != work)
761 		goto out_fast;
762 
763 	/*
764 	 * The work is in progress and we need to wait with the lock released.
765 	 * In the meantime, block any queuing by setting the canceling counter.
766 	 */
767 	work->canceling++;
768 	spin_unlock_irqrestore(&worker->lock, flags);
769 	flush_kthread_work(work);
770 	spin_lock_irqsave(&worker->lock, flags);
771 	work->canceling--;
772 
773 out_fast:
774 	spin_unlock_irqrestore(&worker->lock, flags);
775 out:
776 	return ret;
777 }
778 
779 /**
780  * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
781  * @work: the kthread work to cancel
782  *
783  * Cancel @work and wait for its execution to finish.  This function
784  * can be used even if the work re-queues itself. On return from this
785  * function, @work is guaranteed to be not pending or executing on any CPU.
786  *
787  * kthread_cancel_work_sync(&delayed_work->work) must not be used for
788  * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
789  *
790  * The caller must ensure that the worker on which @work was last
791  * queued can't be destroyed before this function returns.
792  *
793  * Return: %true if @work was pending, %false otherwise.
794  */
kthread_cancel_work_sync(struct kthread_work * work)795 bool kthread_cancel_work_sync(struct kthread_work *work)
796 {
797 	return __kthread_cancel_work_sync(work);
798 }
799 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
800 
801 /**
802  * flush_kthread_worker - flush all current works on a kthread_worker
803  * @worker: worker to flush
804  *
805  * Wait until all currently executing or pending works on @worker are
806  * finished.
807  */
flush_kthread_worker(struct kthread_worker * worker)808 void flush_kthread_worker(struct kthread_worker *worker)
809 {
810 	struct kthread_flush_work fwork = {
811 		KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
812 		COMPLETION_INITIALIZER_ONSTACK(fwork.done),
813 	};
814 
815 	queue_kthread_work(worker, &fwork.work);
816 	wait_for_completion(&fwork.done);
817 }
818 EXPORT_SYMBOL_GPL(flush_kthread_worker);
819