xref: /linux-6.15/kernel/kthread.c (revision 5eacb68a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel thread helper functions.
3  *   Copyright (C) 2004 IBM Corporation, Rusty Russell.
4  *   Copyright (C) 2009 Red Hat, Inc.
5  *
6  * Creation is done via kthreadd, so that we get a clean environment
7  * even if we're invoked from userspace (think modprobe, hotplug cpu,
8  * etc.).
9  */
10 #include <uapi/linux/sched/types.h>
11 #include <linux/mm.h>
12 #include <linux/mmu_context.h>
13 #include <linux/sched.h>
14 #include <linux/sched/mm.h>
15 #include <linux/sched/task.h>
16 #include <linux/kthread.h>
17 #include <linux/completion.h>
18 #include <linux/err.h>
19 #include <linux/cgroup.h>
20 #include <linux/cpuset.h>
21 #include <linux/unistd.h>
22 #include <linux/file.h>
23 #include <linux/export.h>
24 #include <linux/mutex.h>
25 #include <linux/slab.h>
26 #include <linux/freezer.h>
27 #include <linux/ptrace.h>
28 #include <linux/uaccess.h>
29 #include <linux/numa.h>
30 #include <linux/sched/isolation.h>
31 #include <trace/events/sched.h>
32 
33 
34 static DEFINE_SPINLOCK(kthread_create_lock);
35 static LIST_HEAD(kthread_create_list);
36 struct task_struct *kthreadd_task;
37 
38 struct kthread_create_info
39 {
40 	/* Information passed to kthread() from kthreadd. */
41 	char *full_name;
42 	int (*threadfn)(void *data);
43 	void *data;
44 	int node;
45 
46 	/* Result passed back to kthread_create() from kthreadd. */
47 	struct task_struct *result;
48 	struct completion *done;
49 
50 	struct list_head list;
51 };
52 
53 struct kthread {
54 	unsigned long flags;
55 	unsigned int cpu;
56 	int started;
57 	int result;
58 	int (*threadfn)(void *);
59 	void *data;
60 	struct completion parked;
61 	struct completion exited;
62 #ifdef CONFIG_BLK_CGROUP
63 	struct cgroup_subsys_state *blkcg_css;
64 #endif
65 	/* To store the full name if task comm is truncated. */
66 	char *full_name;
67 };
68 
69 enum KTHREAD_BITS {
70 	KTHREAD_IS_PER_CPU = 0,
71 	KTHREAD_SHOULD_STOP,
72 	KTHREAD_SHOULD_PARK,
73 };
74 
75 static inline struct kthread *to_kthread(struct task_struct *k)
76 {
77 	WARN_ON(!(k->flags & PF_KTHREAD));
78 	return k->worker_private;
79 }
80 
81 /*
82  * Variant of to_kthread() that doesn't assume @p is a kthread.
83  *
84  * Per construction; when:
85  *
86  *   (p->flags & PF_KTHREAD) && p->worker_private
87  *
88  * the task is both a kthread and struct kthread is persistent. However
89  * PF_KTHREAD on it's own is not, kernel_thread() can exec() (See umh.c and
90  * begin_new_exec()).
91  */
92 static inline struct kthread *__to_kthread(struct task_struct *p)
93 {
94 	void *kthread = p->worker_private;
95 	if (kthread && !(p->flags & PF_KTHREAD))
96 		kthread = NULL;
97 	return kthread;
98 }
99 
100 void get_kthread_comm(char *buf, size_t buf_size, struct task_struct *tsk)
101 {
102 	struct kthread *kthread = to_kthread(tsk);
103 
104 	if (!kthread || !kthread->full_name) {
105 		strscpy(buf, tsk->comm, buf_size);
106 		return;
107 	}
108 
109 	strscpy_pad(buf, kthread->full_name, buf_size);
110 }
111 
112 bool set_kthread_struct(struct task_struct *p)
113 {
114 	struct kthread *kthread;
115 
116 	if (WARN_ON_ONCE(to_kthread(p)))
117 		return false;
118 
119 	kthread = kzalloc(sizeof(*kthread), GFP_KERNEL);
120 	if (!kthread)
121 		return false;
122 
123 	init_completion(&kthread->exited);
124 	init_completion(&kthread->parked);
125 	p->vfork_done = &kthread->exited;
126 
127 	p->worker_private = kthread;
128 	return true;
129 }
130 
131 void free_kthread_struct(struct task_struct *k)
132 {
133 	struct kthread *kthread;
134 
135 	/*
136 	 * Can be NULL if kmalloc() in set_kthread_struct() failed.
137 	 */
138 	kthread = to_kthread(k);
139 	if (!kthread)
140 		return;
141 
142 #ifdef CONFIG_BLK_CGROUP
143 	WARN_ON_ONCE(kthread->blkcg_css);
144 #endif
145 	k->worker_private = NULL;
146 	kfree(kthread->full_name);
147 	kfree(kthread);
148 }
149 
150 /**
151  * kthread_should_stop - should this kthread return now?
152  *
153  * When someone calls kthread_stop() on your kthread, it will be woken
154  * and this will return true.  You should then return, and your return
155  * value will be passed through to kthread_stop().
156  */
157 bool kthread_should_stop(void)
158 {
159 	return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
160 }
161 EXPORT_SYMBOL(kthread_should_stop);
162 
163 static bool __kthread_should_park(struct task_struct *k)
164 {
165 	return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
166 }
167 
168 /**
169  * kthread_should_park - should this kthread park now?
170  *
171  * When someone calls kthread_park() on your kthread, it will be woken
172  * and this will return true.  You should then do the necessary
173  * cleanup and call kthread_parkme()
174  *
175  * Similar to kthread_should_stop(), but this keeps the thread alive
176  * and in a park position. kthread_unpark() "restarts" the thread and
177  * calls the thread function again.
178  */
179 bool kthread_should_park(void)
180 {
181 	return __kthread_should_park(current);
182 }
183 EXPORT_SYMBOL_GPL(kthread_should_park);
184 
185 bool kthread_should_stop_or_park(void)
186 {
187 	struct kthread *kthread = __to_kthread(current);
188 
189 	if (!kthread)
190 		return false;
191 
192 	return kthread->flags & (BIT(KTHREAD_SHOULD_STOP) | BIT(KTHREAD_SHOULD_PARK));
193 }
194 
195 /**
196  * kthread_freezable_should_stop - should this freezable kthread return now?
197  * @was_frozen: optional out parameter, indicates whether %current was frozen
198  *
199  * kthread_should_stop() for freezable kthreads, which will enter
200  * refrigerator if necessary.  This function is safe from kthread_stop() /
201  * freezer deadlock and freezable kthreads should use this function instead
202  * of calling try_to_freeze() directly.
203  */
204 bool kthread_freezable_should_stop(bool *was_frozen)
205 {
206 	bool frozen = false;
207 
208 	might_sleep();
209 
210 	if (unlikely(freezing(current)))
211 		frozen = __refrigerator(true);
212 
213 	if (was_frozen)
214 		*was_frozen = frozen;
215 
216 	return kthread_should_stop();
217 }
218 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
219 
220 /**
221  * kthread_func - return the function specified on kthread creation
222  * @task: kthread task in question
223  *
224  * Returns NULL if the task is not a kthread.
225  */
226 void *kthread_func(struct task_struct *task)
227 {
228 	struct kthread *kthread = __to_kthread(task);
229 	if (kthread)
230 		return kthread->threadfn;
231 	return NULL;
232 }
233 EXPORT_SYMBOL_GPL(kthread_func);
234 
235 /**
236  * kthread_data - return data value specified on kthread creation
237  * @task: kthread task in question
238  *
239  * Return the data value specified when kthread @task was created.
240  * The caller is responsible for ensuring the validity of @task when
241  * calling this function.
242  */
243 void *kthread_data(struct task_struct *task)
244 {
245 	return to_kthread(task)->data;
246 }
247 EXPORT_SYMBOL_GPL(kthread_data);
248 
249 /**
250  * kthread_probe_data - speculative version of kthread_data()
251  * @task: possible kthread task in question
252  *
253  * @task could be a kthread task.  Return the data value specified when it
254  * was created if accessible.  If @task isn't a kthread task or its data is
255  * inaccessible for any reason, %NULL is returned.  This function requires
256  * that @task itself is safe to dereference.
257  */
258 void *kthread_probe_data(struct task_struct *task)
259 {
260 	struct kthread *kthread = __to_kthread(task);
261 	void *data = NULL;
262 
263 	if (kthread)
264 		copy_from_kernel_nofault(&data, &kthread->data, sizeof(data));
265 	return data;
266 }
267 
268 static void __kthread_parkme(struct kthread *self)
269 {
270 	for (;;) {
271 		/*
272 		 * TASK_PARKED is a special state; we must serialize against
273 		 * possible pending wakeups to avoid store-store collisions on
274 		 * task->state.
275 		 *
276 		 * Such a collision might possibly result in the task state
277 		 * changin from TASK_PARKED and us failing the
278 		 * wait_task_inactive() in kthread_park().
279 		 */
280 		set_special_state(TASK_PARKED);
281 		if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
282 			break;
283 
284 		/*
285 		 * Thread is going to call schedule(), do not preempt it,
286 		 * or the caller of kthread_park() may spend more time in
287 		 * wait_task_inactive().
288 		 */
289 		preempt_disable();
290 		complete(&self->parked);
291 		schedule_preempt_disabled();
292 		preempt_enable();
293 	}
294 	__set_current_state(TASK_RUNNING);
295 }
296 
297 void kthread_parkme(void)
298 {
299 	__kthread_parkme(to_kthread(current));
300 }
301 EXPORT_SYMBOL_GPL(kthread_parkme);
302 
303 /**
304  * kthread_exit - Cause the current kthread return @result to kthread_stop().
305  * @result: The integer value to return to kthread_stop().
306  *
307  * While kthread_exit can be called directly, it exists so that
308  * functions which do some additional work in non-modular code such as
309  * module_put_and_kthread_exit can be implemented.
310  *
311  * Does not return.
312  */
313 void __noreturn kthread_exit(long result)
314 {
315 	struct kthread *kthread = to_kthread(current);
316 	kthread->result = result;
317 	do_exit(0);
318 }
319 EXPORT_SYMBOL(kthread_exit);
320 
321 /**
322  * kthread_complete_and_exit - Exit the current kthread.
323  * @comp: Completion to complete
324  * @code: The integer value to return to kthread_stop().
325  *
326  * If present, complete @comp and then return code to kthread_stop().
327  *
328  * A kernel thread whose module may be removed after the completion of
329  * @comp can use this function to exit safely.
330  *
331  * Does not return.
332  */
333 void __noreturn kthread_complete_and_exit(struct completion *comp, long code)
334 {
335 	if (comp)
336 		complete(comp);
337 
338 	kthread_exit(code);
339 }
340 EXPORT_SYMBOL(kthread_complete_and_exit);
341 
342 static int kthread(void *_create)
343 {
344 	static const struct sched_param param = { .sched_priority = 0 };
345 	/* Copy data: it's on kthread's stack */
346 	struct kthread_create_info *create = _create;
347 	int (*threadfn)(void *data) = create->threadfn;
348 	void *data = create->data;
349 	struct completion *done;
350 	struct kthread *self;
351 	int ret;
352 
353 	self = to_kthread(current);
354 
355 	/* Release the structure when caller killed by a fatal signal. */
356 	done = xchg(&create->done, NULL);
357 	if (!done) {
358 		kfree(create->full_name);
359 		kfree(create);
360 		kthread_exit(-EINTR);
361 	}
362 
363 	self->full_name = create->full_name;
364 	self->threadfn = threadfn;
365 	self->data = data;
366 
367 	/*
368 	 * The new thread inherited kthreadd's priority and CPU mask. Reset
369 	 * back to default in case they have been changed.
370 	 */
371 	sched_setscheduler_nocheck(current, SCHED_NORMAL, &param);
372 	set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_KTHREAD));
373 
374 	/* OK, tell user we're spawned, wait for stop or wakeup */
375 	__set_current_state(TASK_UNINTERRUPTIBLE);
376 	create->result = current;
377 	/*
378 	 * Thread is going to call schedule(), do not preempt it,
379 	 * or the creator may spend more time in wait_task_inactive().
380 	 */
381 	preempt_disable();
382 	complete(done);
383 	schedule_preempt_disabled();
384 	preempt_enable();
385 
386 	self->started = 1;
387 
388 	ret = -EINTR;
389 	if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
390 		cgroup_kthread_ready();
391 		__kthread_parkme(self);
392 		ret = threadfn(data);
393 	}
394 	kthread_exit(ret);
395 }
396 
397 /* called from kernel_clone() to get node information for about to be created task */
398 int tsk_fork_get_node(struct task_struct *tsk)
399 {
400 #ifdef CONFIG_NUMA
401 	if (tsk == kthreadd_task)
402 		return tsk->pref_node_fork;
403 #endif
404 	return NUMA_NO_NODE;
405 }
406 
407 static void create_kthread(struct kthread_create_info *create)
408 {
409 	int pid;
410 
411 #ifdef CONFIG_NUMA
412 	current->pref_node_fork = create->node;
413 #endif
414 	/* We want our own signal handler (we take no signals by default). */
415 	pid = kernel_thread(kthread, create, create->full_name,
416 			    CLONE_FS | CLONE_FILES | SIGCHLD);
417 	if (pid < 0) {
418 		/* Release the structure when caller killed by a fatal signal. */
419 		struct completion *done = xchg(&create->done, NULL);
420 
421 		kfree(create->full_name);
422 		if (!done) {
423 			kfree(create);
424 			return;
425 		}
426 		create->result = ERR_PTR(pid);
427 		complete(done);
428 	}
429 }
430 
431 static __printf(4, 0)
432 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
433 						    void *data, int node,
434 						    const char namefmt[],
435 						    va_list args)
436 {
437 	DECLARE_COMPLETION_ONSTACK(done);
438 	struct task_struct *task;
439 	struct kthread_create_info *create = kmalloc(sizeof(*create),
440 						     GFP_KERNEL);
441 
442 	if (!create)
443 		return ERR_PTR(-ENOMEM);
444 	create->threadfn = threadfn;
445 	create->data = data;
446 	create->node = node;
447 	create->done = &done;
448 	create->full_name = kvasprintf(GFP_KERNEL, namefmt, args);
449 	if (!create->full_name) {
450 		task = ERR_PTR(-ENOMEM);
451 		goto free_create;
452 	}
453 
454 	spin_lock(&kthread_create_lock);
455 	list_add_tail(&create->list, &kthread_create_list);
456 	spin_unlock(&kthread_create_lock);
457 
458 	wake_up_process(kthreadd_task);
459 	/*
460 	 * Wait for completion in killable state, for I might be chosen by
461 	 * the OOM killer while kthreadd is trying to allocate memory for
462 	 * new kernel thread.
463 	 */
464 	if (unlikely(wait_for_completion_killable(&done))) {
465 		/*
466 		 * If I was killed by a fatal signal before kthreadd (or new
467 		 * kernel thread) calls complete(), leave the cleanup of this
468 		 * structure to that thread.
469 		 */
470 		if (xchg(&create->done, NULL))
471 			return ERR_PTR(-EINTR);
472 		/*
473 		 * kthreadd (or new kernel thread) will call complete()
474 		 * shortly.
475 		 */
476 		wait_for_completion(&done);
477 	}
478 	task = create->result;
479 free_create:
480 	kfree(create);
481 	return task;
482 }
483 
484 /**
485  * kthread_create_on_node - create a kthread.
486  * @threadfn: the function to run until signal_pending(current).
487  * @data: data ptr for @threadfn.
488  * @node: task and thread structures for the thread are allocated on this node
489  * @namefmt: printf-style name for the thread.
490  *
491  * Description: This helper function creates and names a kernel
492  * thread.  The thread will be stopped: use wake_up_process() to start
493  * it.  See also kthread_run().  The new thread has SCHED_NORMAL policy and
494  * is affine to all CPUs.
495  *
496  * If thread is going to be bound on a particular cpu, give its node
497  * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
498  * When woken, the thread will run @threadfn() with @data as its
499  * argument. @threadfn() can either return directly if it is a
500  * standalone thread for which no one will call kthread_stop(), or
501  * return when 'kthread_should_stop()' is true (which means
502  * kthread_stop() has been called).  The return value should be zero
503  * or a negative error number; it will be passed to kthread_stop().
504  *
505  * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
506  */
507 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
508 					   void *data, int node,
509 					   const char namefmt[],
510 					   ...)
511 {
512 	struct task_struct *task;
513 	va_list args;
514 
515 	va_start(args, namefmt);
516 	task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
517 	va_end(args);
518 
519 	return task;
520 }
521 EXPORT_SYMBOL(kthread_create_on_node);
522 
523 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, unsigned int state)
524 {
525 	unsigned long flags;
526 
527 	if (!wait_task_inactive(p, state)) {
528 		WARN_ON(1);
529 		return;
530 	}
531 
532 	/* It's safe because the task is inactive. */
533 	raw_spin_lock_irqsave(&p->pi_lock, flags);
534 	do_set_cpus_allowed(p, mask);
535 	p->flags |= PF_NO_SETAFFINITY;
536 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
537 }
538 
539 static void __kthread_bind(struct task_struct *p, unsigned int cpu, unsigned int state)
540 {
541 	__kthread_bind_mask(p, cpumask_of(cpu), state);
542 }
543 
544 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
545 {
546 	struct kthread *kthread = to_kthread(p);
547 	__kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
548 	WARN_ON_ONCE(kthread->started);
549 }
550 
551 /**
552  * kthread_bind - bind a just-created kthread to a cpu.
553  * @p: thread created by kthread_create().
554  * @cpu: cpu (might not be online, must be possible) for @k to run on.
555  *
556  * Description: This function is equivalent to set_cpus_allowed(),
557  * except that @cpu doesn't need to be online, and the thread must be
558  * stopped (i.e., just returned from kthread_create()).
559  */
560 void kthread_bind(struct task_struct *p, unsigned int cpu)
561 {
562 	struct kthread *kthread = to_kthread(p);
563 	__kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
564 	WARN_ON_ONCE(kthread->started);
565 }
566 EXPORT_SYMBOL(kthread_bind);
567 
568 /**
569  * kthread_create_on_cpu - Create a cpu bound kthread
570  * @threadfn: the function to run until signal_pending(current).
571  * @data: data ptr for @threadfn.
572  * @cpu: The cpu on which the thread should be bound,
573  * @namefmt: printf-style name for the thread. Format is restricted
574  *	     to "name.*%u". Code fills in cpu number.
575  *
576  * Description: This helper function creates and names a kernel thread
577  */
578 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
579 					  void *data, unsigned int cpu,
580 					  const char *namefmt)
581 {
582 	struct task_struct *p;
583 
584 	p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
585 				   cpu);
586 	if (IS_ERR(p))
587 		return p;
588 	kthread_bind(p, cpu);
589 	/* CPU hotplug need to bind once again when unparking the thread. */
590 	to_kthread(p)->cpu = cpu;
591 	return p;
592 }
593 EXPORT_SYMBOL(kthread_create_on_cpu);
594 
595 void kthread_set_per_cpu(struct task_struct *k, int cpu)
596 {
597 	struct kthread *kthread = to_kthread(k);
598 	if (!kthread)
599 		return;
600 
601 	WARN_ON_ONCE(!(k->flags & PF_NO_SETAFFINITY));
602 
603 	if (cpu < 0) {
604 		clear_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
605 		return;
606 	}
607 
608 	kthread->cpu = cpu;
609 	set_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
610 }
611 
612 bool kthread_is_per_cpu(struct task_struct *p)
613 {
614 	struct kthread *kthread = __to_kthread(p);
615 	if (!kthread)
616 		return false;
617 
618 	return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
619 }
620 
621 /**
622  * kthread_unpark - unpark a thread created by kthread_create().
623  * @k:		thread created by kthread_create().
624  *
625  * Sets kthread_should_park() for @k to return false, wakes it, and
626  * waits for it to return. If the thread is marked percpu then its
627  * bound to the cpu again.
628  */
629 void kthread_unpark(struct task_struct *k)
630 {
631 	struct kthread *kthread = to_kthread(k);
632 
633 	if (!test_bit(KTHREAD_SHOULD_PARK, &kthread->flags))
634 		return;
635 	/*
636 	 * Newly created kthread was parked when the CPU was offline.
637 	 * The binding was lost and we need to set it again.
638 	 */
639 	if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
640 		__kthread_bind(k, kthread->cpu, TASK_PARKED);
641 
642 	clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
643 	/*
644 	 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
645 	 */
646 	wake_up_state(k, TASK_PARKED);
647 }
648 EXPORT_SYMBOL_GPL(kthread_unpark);
649 
650 /**
651  * kthread_park - park a thread created by kthread_create().
652  * @k: thread created by kthread_create().
653  *
654  * Sets kthread_should_park() for @k to return true, wakes it, and
655  * waits for it to return. This can also be called after kthread_create()
656  * instead of calling wake_up_process(): the thread will park without
657  * calling threadfn().
658  *
659  * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
660  * If called by the kthread itself just the park bit is set.
661  */
662 int kthread_park(struct task_struct *k)
663 {
664 	struct kthread *kthread = to_kthread(k);
665 
666 	if (WARN_ON(k->flags & PF_EXITING))
667 		return -ENOSYS;
668 
669 	if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
670 		return -EBUSY;
671 
672 	set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
673 	if (k != current) {
674 		wake_up_process(k);
675 		/*
676 		 * Wait for __kthread_parkme() to complete(), this means we
677 		 * _will_ have TASK_PARKED and are about to call schedule().
678 		 */
679 		wait_for_completion(&kthread->parked);
680 		/*
681 		 * Now wait for that schedule() to complete and the task to
682 		 * get scheduled out.
683 		 */
684 		WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
685 	}
686 
687 	return 0;
688 }
689 EXPORT_SYMBOL_GPL(kthread_park);
690 
691 /**
692  * kthread_stop - stop a thread created by kthread_create().
693  * @k: thread created by kthread_create().
694  *
695  * Sets kthread_should_stop() for @k to return true, wakes it, and
696  * waits for it to exit. This can also be called after kthread_create()
697  * instead of calling wake_up_process(): the thread will exit without
698  * calling threadfn().
699  *
700  * If threadfn() may call kthread_exit() itself, the caller must ensure
701  * task_struct can't go away.
702  *
703  * Returns the result of threadfn(), or %-EINTR if wake_up_process()
704  * was never called.
705  */
706 int kthread_stop(struct task_struct *k)
707 {
708 	struct kthread *kthread;
709 	int ret;
710 
711 	trace_sched_kthread_stop(k);
712 
713 	get_task_struct(k);
714 	kthread = to_kthread(k);
715 	set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
716 	kthread_unpark(k);
717 	set_tsk_thread_flag(k, TIF_NOTIFY_SIGNAL);
718 	wake_up_process(k);
719 	wait_for_completion(&kthread->exited);
720 	ret = kthread->result;
721 	put_task_struct(k);
722 
723 	trace_sched_kthread_stop_ret(ret);
724 	return ret;
725 }
726 EXPORT_SYMBOL(kthread_stop);
727 
728 /**
729  * kthread_stop_put - stop a thread and put its task struct
730  * @k: thread created by kthread_create().
731  *
732  * Stops a thread created by kthread_create() and put its task_struct.
733  * Only use when holding an extra task struct reference obtained by
734  * calling get_task_struct().
735  */
736 int kthread_stop_put(struct task_struct *k)
737 {
738 	int ret;
739 
740 	ret = kthread_stop(k);
741 	put_task_struct(k);
742 	return ret;
743 }
744 EXPORT_SYMBOL(kthread_stop_put);
745 
746 int kthreadd(void *unused)
747 {
748 	struct task_struct *tsk = current;
749 
750 	/* Setup a clean context for our children to inherit. */
751 	set_task_comm(tsk, "kthreadd");
752 	ignore_signals(tsk);
753 	set_cpus_allowed_ptr(tsk, housekeeping_cpumask(HK_TYPE_KTHREAD));
754 	set_mems_allowed(node_states[N_MEMORY]);
755 
756 	current->flags |= PF_NOFREEZE;
757 	cgroup_init_kthreadd();
758 
759 	for (;;) {
760 		set_current_state(TASK_INTERRUPTIBLE);
761 		if (list_empty(&kthread_create_list))
762 			schedule();
763 		__set_current_state(TASK_RUNNING);
764 
765 		spin_lock(&kthread_create_lock);
766 		while (!list_empty(&kthread_create_list)) {
767 			struct kthread_create_info *create;
768 
769 			create = list_entry(kthread_create_list.next,
770 					    struct kthread_create_info, list);
771 			list_del_init(&create->list);
772 			spin_unlock(&kthread_create_lock);
773 
774 			create_kthread(create);
775 
776 			spin_lock(&kthread_create_lock);
777 		}
778 		spin_unlock(&kthread_create_lock);
779 	}
780 
781 	return 0;
782 }
783 
784 void __kthread_init_worker(struct kthread_worker *worker,
785 				const char *name,
786 				struct lock_class_key *key)
787 {
788 	memset(worker, 0, sizeof(struct kthread_worker));
789 	raw_spin_lock_init(&worker->lock);
790 	lockdep_set_class_and_name(&worker->lock, key, name);
791 	INIT_LIST_HEAD(&worker->work_list);
792 	INIT_LIST_HEAD(&worker->delayed_work_list);
793 }
794 EXPORT_SYMBOL_GPL(__kthread_init_worker);
795 
796 /**
797  * kthread_worker_fn - kthread function to process kthread_worker
798  * @worker_ptr: pointer to initialized kthread_worker
799  *
800  * This function implements the main cycle of kthread worker. It processes
801  * work_list until it is stopped with kthread_stop(). It sleeps when the queue
802  * is empty.
803  *
804  * The works are not allowed to keep any locks, disable preemption or interrupts
805  * when they finish. There is defined a safe point for freezing when one work
806  * finishes and before a new one is started.
807  *
808  * Also the works must not be handled by more than one worker at the same time,
809  * see also kthread_queue_work().
810  */
811 int kthread_worker_fn(void *worker_ptr)
812 {
813 	struct kthread_worker *worker = worker_ptr;
814 	struct kthread_work *work;
815 
816 	/*
817 	 * FIXME: Update the check and remove the assignment when all kthread
818 	 * worker users are created using kthread_create_worker*() functions.
819 	 */
820 	WARN_ON(worker->task && worker->task != current);
821 	worker->task = current;
822 
823 	if (worker->flags & KTW_FREEZABLE)
824 		set_freezable();
825 
826 repeat:
827 	set_current_state(TASK_INTERRUPTIBLE);	/* mb paired w/ kthread_stop */
828 
829 	if (kthread_should_stop()) {
830 		__set_current_state(TASK_RUNNING);
831 		raw_spin_lock_irq(&worker->lock);
832 		worker->task = NULL;
833 		raw_spin_unlock_irq(&worker->lock);
834 		return 0;
835 	}
836 
837 	work = NULL;
838 	raw_spin_lock_irq(&worker->lock);
839 	if (!list_empty(&worker->work_list)) {
840 		work = list_first_entry(&worker->work_list,
841 					struct kthread_work, node);
842 		list_del_init(&work->node);
843 	}
844 	worker->current_work = work;
845 	raw_spin_unlock_irq(&worker->lock);
846 
847 	if (work) {
848 		kthread_work_func_t func = work->func;
849 		__set_current_state(TASK_RUNNING);
850 		trace_sched_kthread_work_execute_start(work);
851 		work->func(work);
852 		/*
853 		 * Avoid dereferencing work after this point.  The trace
854 		 * event only cares about the address.
855 		 */
856 		trace_sched_kthread_work_execute_end(work, func);
857 	} else if (!freezing(current)) {
858 		schedule();
859 	} else {
860 		/*
861 		 * Handle the case where the current remains
862 		 * TASK_INTERRUPTIBLE. try_to_freeze() expects
863 		 * the current to be TASK_RUNNING.
864 		 */
865 		__set_current_state(TASK_RUNNING);
866 	}
867 
868 	try_to_freeze();
869 	cond_resched();
870 	goto repeat;
871 }
872 EXPORT_SYMBOL_GPL(kthread_worker_fn);
873 
874 static __printf(3, 0) struct kthread_worker *
875 __kthread_create_worker(int cpu, unsigned int flags,
876 			const char namefmt[], va_list args)
877 {
878 	struct kthread_worker *worker;
879 	struct task_struct *task;
880 	int node = NUMA_NO_NODE;
881 
882 	worker = kzalloc(sizeof(*worker), GFP_KERNEL);
883 	if (!worker)
884 		return ERR_PTR(-ENOMEM);
885 
886 	kthread_init_worker(worker);
887 
888 	if (cpu >= 0)
889 		node = cpu_to_node(cpu);
890 
891 	task = __kthread_create_on_node(kthread_worker_fn, worker,
892 						node, namefmt, args);
893 	if (IS_ERR(task))
894 		goto fail_task;
895 
896 	if (cpu >= 0)
897 		kthread_bind(task, cpu);
898 
899 	worker->flags = flags;
900 	worker->task = task;
901 	wake_up_process(task);
902 	return worker;
903 
904 fail_task:
905 	kfree(worker);
906 	return ERR_CAST(task);
907 }
908 
909 /**
910  * kthread_create_worker - create a kthread worker
911  * @flags: flags modifying the default behavior of the worker
912  * @namefmt: printf-style name for the kthread worker (task).
913  *
914  * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
915  * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
916  * when the caller was killed by a fatal signal.
917  */
918 struct kthread_worker *
919 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
920 {
921 	struct kthread_worker *worker;
922 	va_list args;
923 
924 	va_start(args, namefmt);
925 	worker = __kthread_create_worker(-1, flags, namefmt, args);
926 	va_end(args);
927 
928 	return worker;
929 }
930 EXPORT_SYMBOL(kthread_create_worker);
931 
932 /**
933  * kthread_create_worker_on_cpu - create a kthread worker and bind it
934  *	to a given CPU and the associated NUMA node.
935  * @cpu: CPU number
936  * @flags: flags modifying the default behavior of the worker
937  * @namefmt: printf-style name for the kthread worker (task).
938  *
939  * Use a valid CPU number if you want to bind the kthread worker
940  * to the given CPU and the associated NUMA node.
941  *
942  * A good practice is to add the cpu number also into the worker name.
943  * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
944  *
945  * CPU hotplug:
946  * The kthread worker API is simple and generic. It just provides a way
947  * to create, use, and destroy workers.
948  *
949  * It is up to the API user how to handle CPU hotplug. They have to decide
950  * how to handle pending work items, prevent queuing new ones, and
951  * restore the functionality when the CPU goes off and on. There are a
952  * few catches:
953  *
954  *    - CPU affinity gets lost when it is scheduled on an offline CPU.
955  *
956  *    - The worker might not exist when the CPU was off when the user
957  *      created the workers.
958  *
959  * Good practice is to implement two CPU hotplug callbacks and to
960  * destroy/create the worker when the CPU goes down/up.
961  *
962  * Return:
963  * The pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
964  * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
965  * when the caller was killed by a fatal signal.
966  */
967 struct kthread_worker *
968 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
969 			     const char namefmt[], ...)
970 {
971 	struct kthread_worker *worker;
972 	va_list args;
973 
974 	va_start(args, namefmt);
975 	worker = __kthread_create_worker(cpu, flags, namefmt, args);
976 	va_end(args);
977 
978 	return worker;
979 }
980 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
981 
982 /*
983  * Returns true when the work could not be queued at the moment.
984  * It happens when it is already pending in a worker list
985  * or when it is being cancelled.
986  */
987 static inline bool queuing_blocked(struct kthread_worker *worker,
988 				   struct kthread_work *work)
989 {
990 	lockdep_assert_held(&worker->lock);
991 
992 	return !list_empty(&work->node) || work->canceling;
993 }
994 
995 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
996 					     struct kthread_work *work)
997 {
998 	lockdep_assert_held(&worker->lock);
999 	WARN_ON_ONCE(!list_empty(&work->node));
1000 	/* Do not use a work with >1 worker, see kthread_queue_work() */
1001 	WARN_ON_ONCE(work->worker && work->worker != worker);
1002 }
1003 
1004 /* insert @work before @pos in @worker */
1005 static void kthread_insert_work(struct kthread_worker *worker,
1006 				struct kthread_work *work,
1007 				struct list_head *pos)
1008 {
1009 	kthread_insert_work_sanity_check(worker, work);
1010 
1011 	trace_sched_kthread_work_queue_work(worker, work);
1012 
1013 	list_add_tail(&work->node, pos);
1014 	work->worker = worker;
1015 	if (!worker->current_work && likely(worker->task))
1016 		wake_up_process(worker->task);
1017 }
1018 
1019 /**
1020  * kthread_queue_work - queue a kthread_work
1021  * @worker: target kthread_worker
1022  * @work: kthread_work to queue
1023  *
1024  * Queue @work to work processor @task for async execution.  @task
1025  * must have been created with kthread_worker_create().  Returns %true
1026  * if @work was successfully queued, %false if it was already pending.
1027  *
1028  * Reinitialize the work if it needs to be used by another worker.
1029  * For example, when the worker was stopped and started again.
1030  */
1031 bool kthread_queue_work(struct kthread_worker *worker,
1032 			struct kthread_work *work)
1033 {
1034 	bool ret = false;
1035 	unsigned long flags;
1036 
1037 	raw_spin_lock_irqsave(&worker->lock, flags);
1038 	if (!queuing_blocked(worker, work)) {
1039 		kthread_insert_work(worker, work, &worker->work_list);
1040 		ret = true;
1041 	}
1042 	raw_spin_unlock_irqrestore(&worker->lock, flags);
1043 	return ret;
1044 }
1045 EXPORT_SYMBOL_GPL(kthread_queue_work);
1046 
1047 /**
1048  * kthread_delayed_work_timer_fn - callback that queues the associated kthread
1049  *	delayed work when the timer expires.
1050  * @t: pointer to the expired timer
1051  *
1052  * The format of the function is defined by struct timer_list.
1053  * It should have been called from irqsafe timer with irq already off.
1054  */
1055 void kthread_delayed_work_timer_fn(struct timer_list *t)
1056 {
1057 	struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
1058 	struct kthread_work *work = &dwork->work;
1059 	struct kthread_worker *worker = work->worker;
1060 	unsigned long flags;
1061 
1062 	/*
1063 	 * This might happen when a pending work is reinitialized.
1064 	 * It means that it is used a wrong way.
1065 	 */
1066 	if (WARN_ON_ONCE(!worker))
1067 		return;
1068 
1069 	raw_spin_lock_irqsave(&worker->lock, flags);
1070 	/* Work must not be used with >1 worker, see kthread_queue_work(). */
1071 	WARN_ON_ONCE(work->worker != worker);
1072 
1073 	/* Move the work from worker->delayed_work_list. */
1074 	WARN_ON_ONCE(list_empty(&work->node));
1075 	list_del_init(&work->node);
1076 	if (!work->canceling)
1077 		kthread_insert_work(worker, work, &worker->work_list);
1078 
1079 	raw_spin_unlock_irqrestore(&worker->lock, flags);
1080 }
1081 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
1082 
1083 static void __kthread_queue_delayed_work(struct kthread_worker *worker,
1084 					 struct kthread_delayed_work *dwork,
1085 					 unsigned long delay)
1086 {
1087 	struct timer_list *timer = &dwork->timer;
1088 	struct kthread_work *work = &dwork->work;
1089 
1090 	WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn);
1091 
1092 	/*
1093 	 * If @delay is 0, queue @dwork->work immediately.  This is for
1094 	 * both optimization and correctness.  The earliest @timer can
1095 	 * expire is on the closest next tick and delayed_work users depend
1096 	 * on that there's no such delay when @delay is 0.
1097 	 */
1098 	if (!delay) {
1099 		kthread_insert_work(worker, work, &worker->work_list);
1100 		return;
1101 	}
1102 
1103 	/* Be paranoid and try to detect possible races already now. */
1104 	kthread_insert_work_sanity_check(worker, work);
1105 
1106 	list_add(&work->node, &worker->delayed_work_list);
1107 	work->worker = worker;
1108 	timer->expires = jiffies + delay;
1109 	add_timer(timer);
1110 }
1111 
1112 /**
1113  * kthread_queue_delayed_work - queue the associated kthread work
1114  *	after a delay.
1115  * @worker: target kthread_worker
1116  * @dwork: kthread_delayed_work to queue
1117  * @delay: number of jiffies to wait before queuing
1118  *
1119  * If the work has not been pending it starts a timer that will queue
1120  * the work after the given @delay. If @delay is zero, it queues the
1121  * work immediately.
1122  *
1123  * Return: %false if the @work has already been pending. It means that
1124  * either the timer was running or the work was queued. It returns %true
1125  * otherwise.
1126  */
1127 bool kthread_queue_delayed_work(struct kthread_worker *worker,
1128 				struct kthread_delayed_work *dwork,
1129 				unsigned long delay)
1130 {
1131 	struct kthread_work *work = &dwork->work;
1132 	unsigned long flags;
1133 	bool ret = false;
1134 
1135 	raw_spin_lock_irqsave(&worker->lock, flags);
1136 
1137 	if (!queuing_blocked(worker, work)) {
1138 		__kthread_queue_delayed_work(worker, dwork, delay);
1139 		ret = true;
1140 	}
1141 
1142 	raw_spin_unlock_irqrestore(&worker->lock, flags);
1143 	return ret;
1144 }
1145 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
1146 
1147 struct kthread_flush_work {
1148 	struct kthread_work	work;
1149 	struct completion	done;
1150 };
1151 
1152 static void kthread_flush_work_fn(struct kthread_work *work)
1153 {
1154 	struct kthread_flush_work *fwork =
1155 		container_of(work, struct kthread_flush_work, work);
1156 	complete(&fwork->done);
1157 }
1158 
1159 /**
1160  * kthread_flush_work - flush a kthread_work
1161  * @work: work to flush
1162  *
1163  * If @work is queued or executing, wait for it to finish execution.
1164  */
1165 void kthread_flush_work(struct kthread_work *work)
1166 {
1167 	struct kthread_flush_work fwork = {
1168 		KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1169 		COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1170 	};
1171 	struct kthread_worker *worker;
1172 	bool noop = false;
1173 
1174 	worker = work->worker;
1175 	if (!worker)
1176 		return;
1177 
1178 	raw_spin_lock_irq(&worker->lock);
1179 	/* Work must not be used with >1 worker, see kthread_queue_work(). */
1180 	WARN_ON_ONCE(work->worker != worker);
1181 
1182 	if (!list_empty(&work->node))
1183 		kthread_insert_work(worker, &fwork.work, work->node.next);
1184 	else if (worker->current_work == work)
1185 		kthread_insert_work(worker, &fwork.work,
1186 				    worker->work_list.next);
1187 	else
1188 		noop = true;
1189 
1190 	raw_spin_unlock_irq(&worker->lock);
1191 
1192 	if (!noop)
1193 		wait_for_completion(&fwork.done);
1194 }
1195 EXPORT_SYMBOL_GPL(kthread_flush_work);
1196 
1197 /*
1198  * Make sure that the timer is neither set nor running and could
1199  * not manipulate the work list_head any longer.
1200  *
1201  * The function is called under worker->lock. The lock is temporary
1202  * released but the timer can't be set again in the meantime.
1203  */
1204 static void kthread_cancel_delayed_work_timer(struct kthread_work *work,
1205 					      unsigned long *flags)
1206 {
1207 	struct kthread_delayed_work *dwork =
1208 		container_of(work, struct kthread_delayed_work, work);
1209 	struct kthread_worker *worker = work->worker;
1210 
1211 	/*
1212 	 * del_timer_sync() must be called to make sure that the timer
1213 	 * callback is not running. The lock must be temporary released
1214 	 * to avoid a deadlock with the callback. In the meantime,
1215 	 * any queuing is blocked by setting the canceling counter.
1216 	 */
1217 	work->canceling++;
1218 	raw_spin_unlock_irqrestore(&worker->lock, *flags);
1219 	del_timer_sync(&dwork->timer);
1220 	raw_spin_lock_irqsave(&worker->lock, *flags);
1221 	work->canceling--;
1222 }
1223 
1224 /*
1225  * This function removes the work from the worker queue.
1226  *
1227  * It is called under worker->lock. The caller must make sure that
1228  * the timer used by delayed work is not running, e.g. by calling
1229  * kthread_cancel_delayed_work_timer().
1230  *
1231  * The work might still be in use when this function finishes. See the
1232  * current_work proceed by the worker.
1233  *
1234  * Return: %true if @work was pending and successfully canceled,
1235  *	%false if @work was not pending
1236  */
1237 static bool __kthread_cancel_work(struct kthread_work *work)
1238 {
1239 	/*
1240 	 * Try to remove the work from a worker list. It might either
1241 	 * be from worker->work_list or from worker->delayed_work_list.
1242 	 */
1243 	if (!list_empty(&work->node)) {
1244 		list_del_init(&work->node);
1245 		return true;
1246 	}
1247 
1248 	return false;
1249 }
1250 
1251 /**
1252  * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1253  * @worker: kthread worker to use
1254  * @dwork: kthread delayed work to queue
1255  * @delay: number of jiffies to wait before queuing
1256  *
1257  * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1258  * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1259  * @work is guaranteed to be queued immediately.
1260  *
1261  * Return: %false if @dwork was idle and queued, %true otherwise.
1262  *
1263  * A special case is when the work is being canceled in parallel.
1264  * It might be caused either by the real kthread_cancel_delayed_work_sync()
1265  * or yet another kthread_mod_delayed_work() call. We let the other command
1266  * win and return %true here. The return value can be used for reference
1267  * counting and the number of queued works stays the same. Anyway, the caller
1268  * is supposed to synchronize these operations a reasonable way.
1269  *
1270  * This function is safe to call from any context including IRQ handler.
1271  * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1272  * for details.
1273  */
1274 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1275 			      struct kthread_delayed_work *dwork,
1276 			      unsigned long delay)
1277 {
1278 	struct kthread_work *work = &dwork->work;
1279 	unsigned long flags;
1280 	int ret;
1281 
1282 	raw_spin_lock_irqsave(&worker->lock, flags);
1283 
1284 	/* Do not bother with canceling when never queued. */
1285 	if (!work->worker) {
1286 		ret = false;
1287 		goto fast_queue;
1288 	}
1289 
1290 	/* Work must not be used with >1 worker, see kthread_queue_work() */
1291 	WARN_ON_ONCE(work->worker != worker);
1292 
1293 	/*
1294 	 * Temporary cancel the work but do not fight with another command
1295 	 * that is canceling the work as well.
1296 	 *
1297 	 * It is a bit tricky because of possible races with another
1298 	 * mod_delayed_work() and cancel_delayed_work() callers.
1299 	 *
1300 	 * The timer must be canceled first because worker->lock is released
1301 	 * when doing so. But the work can be removed from the queue (list)
1302 	 * only when it can be queued again so that the return value can
1303 	 * be used for reference counting.
1304 	 */
1305 	kthread_cancel_delayed_work_timer(work, &flags);
1306 	if (work->canceling) {
1307 		/* The number of works in the queue does not change. */
1308 		ret = true;
1309 		goto out;
1310 	}
1311 	ret = __kthread_cancel_work(work);
1312 
1313 fast_queue:
1314 	__kthread_queue_delayed_work(worker, dwork, delay);
1315 out:
1316 	raw_spin_unlock_irqrestore(&worker->lock, flags);
1317 	return ret;
1318 }
1319 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1320 
1321 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1322 {
1323 	struct kthread_worker *worker = work->worker;
1324 	unsigned long flags;
1325 	int ret = false;
1326 
1327 	if (!worker)
1328 		goto out;
1329 
1330 	raw_spin_lock_irqsave(&worker->lock, flags);
1331 	/* Work must not be used with >1 worker, see kthread_queue_work(). */
1332 	WARN_ON_ONCE(work->worker != worker);
1333 
1334 	if (is_dwork)
1335 		kthread_cancel_delayed_work_timer(work, &flags);
1336 
1337 	ret = __kthread_cancel_work(work);
1338 
1339 	if (worker->current_work != work)
1340 		goto out_fast;
1341 
1342 	/*
1343 	 * The work is in progress and we need to wait with the lock released.
1344 	 * In the meantime, block any queuing by setting the canceling counter.
1345 	 */
1346 	work->canceling++;
1347 	raw_spin_unlock_irqrestore(&worker->lock, flags);
1348 	kthread_flush_work(work);
1349 	raw_spin_lock_irqsave(&worker->lock, flags);
1350 	work->canceling--;
1351 
1352 out_fast:
1353 	raw_spin_unlock_irqrestore(&worker->lock, flags);
1354 out:
1355 	return ret;
1356 }
1357 
1358 /**
1359  * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1360  * @work: the kthread work to cancel
1361  *
1362  * Cancel @work and wait for its execution to finish.  This function
1363  * can be used even if the work re-queues itself. On return from this
1364  * function, @work is guaranteed to be not pending or executing on any CPU.
1365  *
1366  * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1367  * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1368  *
1369  * The caller must ensure that the worker on which @work was last
1370  * queued can't be destroyed before this function returns.
1371  *
1372  * Return: %true if @work was pending, %false otherwise.
1373  */
1374 bool kthread_cancel_work_sync(struct kthread_work *work)
1375 {
1376 	return __kthread_cancel_work_sync(work, false);
1377 }
1378 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1379 
1380 /**
1381  * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1382  *	wait for it to finish.
1383  * @dwork: the kthread delayed work to cancel
1384  *
1385  * This is kthread_cancel_work_sync() for delayed works.
1386  *
1387  * Return: %true if @dwork was pending, %false otherwise.
1388  */
1389 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1390 {
1391 	return __kthread_cancel_work_sync(&dwork->work, true);
1392 }
1393 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1394 
1395 /**
1396  * kthread_flush_worker - flush all current works on a kthread_worker
1397  * @worker: worker to flush
1398  *
1399  * Wait until all currently executing or pending works on @worker are
1400  * finished.
1401  */
1402 void kthread_flush_worker(struct kthread_worker *worker)
1403 {
1404 	struct kthread_flush_work fwork = {
1405 		KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1406 		COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1407 	};
1408 
1409 	kthread_queue_work(worker, &fwork.work);
1410 	wait_for_completion(&fwork.done);
1411 }
1412 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1413 
1414 /**
1415  * kthread_destroy_worker - destroy a kthread worker
1416  * @worker: worker to be destroyed
1417  *
1418  * Flush and destroy @worker.  The simple flush is enough because the kthread
1419  * worker API is used only in trivial scenarios.  There are no multi-step state
1420  * machines needed.
1421  *
1422  * Note that this function is not responsible for handling delayed work, so
1423  * caller should be responsible for queuing or canceling all delayed work items
1424  * before invoke this function.
1425  */
1426 void kthread_destroy_worker(struct kthread_worker *worker)
1427 {
1428 	struct task_struct *task;
1429 
1430 	task = worker->task;
1431 	if (WARN_ON(!task))
1432 		return;
1433 
1434 	kthread_flush_worker(worker);
1435 	kthread_stop(task);
1436 	WARN_ON(!list_empty(&worker->delayed_work_list));
1437 	WARN_ON(!list_empty(&worker->work_list));
1438 	kfree(worker);
1439 }
1440 EXPORT_SYMBOL(kthread_destroy_worker);
1441 
1442 /**
1443  * kthread_use_mm - make the calling kthread operate on an address space
1444  * @mm: address space to operate on
1445  */
1446 void kthread_use_mm(struct mm_struct *mm)
1447 {
1448 	struct mm_struct *active_mm;
1449 	struct task_struct *tsk = current;
1450 
1451 	WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1452 	WARN_ON_ONCE(tsk->mm);
1453 
1454 	/*
1455 	 * It is possible for mm to be the same as tsk->active_mm, but
1456 	 * we must still mmgrab(mm) and mmdrop_lazy_tlb(active_mm),
1457 	 * because these references are not equivalent.
1458 	 */
1459 	mmgrab(mm);
1460 
1461 	task_lock(tsk);
1462 	/* Hold off tlb flush IPIs while switching mm's */
1463 	local_irq_disable();
1464 	active_mm = tsk->active_mm;
1465 	tsk->active_mm = mm;
1466 	tsk->mm = mm;
1467 	membarrier_update_current_mm(mm);
1468 	switch_mm_irqs_off(active_mm, mm, tsk);
1469 	local_irq_enable();
1470 	task_unlock(tsk);
1471 #ifdef finish_arch_post_lock_switch
1472 	finish_arch_post_lock_switch();
1473 #endif
1474 
1475 	/*
1476 	 * When a kthread starts operating on an address space, the loop
1477 	 * in membarrier_{private,global}_expedited() may not observe
1478 	 * that tsk->mm, and not issue an IPI. Membarrier requires a
1479 	 * memory barrier after storing to tsk->mm, before accessing
1480 	 * user-space memory. A full memory barrier for membarrier
1481 	 * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by
1482 	 * mmdrop_lazy_tlb().
1483 	 */
1484 	mmdrop_lazy_tlb(active_mm);
1485 }
1486 EXPORT_SYMBOL_GPL(kthread_use_mm);
1487 
1488 /**
1489  * kthread_unuse_mm - reverse the effect of kthread_use_mm()
1490  * @mm: address space to operate on
1491  */
1492 void kthread_unuse_mm(struct mm_struct *mm)
1493 {
1494 	struct task_struct *tsk = current;
1495 
1496 	WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1497 	WARN_ON_ONCE(!tsk->mm);
1498 
1499 	task_lock(tsk);
1500 	/*
1501 	 * When a kthread stops operating on an address space, the loop
1502 	 * in membarrier_{private,global}_expedited() may not observe
1503 	 * that tsk->mm, and not issue an IPI. Membarrier requires a
1504 	 * memory barrier after accessing user-space memory, before
1505 	 * clearing tsk->mm.
1506 	 */
1507 	smp_mb__after_spinlock();
1508 	local_irq_disable();
1509 	tsk->mm = NULL;
1510 	membarrier_update_current_mm(NULL);
1511 	mmgrab_lazy_tlb(mm);
1512 	/* active_mm is still 'mm' */
1513 	enter_lazy_tlb(mm, tsk);
1514 	local_irq_enable();
1515 	task_unlock(tsk);
1516 
1517 	mmdrop(mm);
1518 }
1519 EXPORT_SYMBOL_GPL(kthread_unuse_mm);
1520 
1521 #ifdef CONFIG_BLK_CGROUP
1522 /**
1523  * kthread_associate_blkcg - associate blkcg to current kthread
1524  * @css: the cgroup info
1525  *
1526  * Current thread must be a kthread. The thread is running jobs on behalf of
1527  * other threads. In some cases, we expect the jobs attach cgroup info of
1528  * original threads instead of that of current thread. This function stores
1529  * original thread's cgroup info in current kthread context for later
1530  * retrieval.
1531  */
1532 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1533 {
1534 	struct kthread *kthread;
1535 
1536 	if (!(current->flags & PF_KTHREAD))
1537 		return;
1538 	kthread = to_kthread(current);
1539 	if (!kthread)
1540 		return;
1541 
1542 	if (kthread->blkcg_css) {
1543 		css_put(kthread->blkcg_css);
1544 		kthread->blkcg_css = NULL;
1545 	}
1546 	if (css) {
1547 		css_get(css);
1548 		kthread->blkcg_css = css;
1549 	}
1550 }
1551 EXPORT_SYMBOL(kthread_associate_blkcg);
1552 
1553 /**
1554  * kthread_blkcg - get associated blkcg css of current kthread
1555  *
1556  * Current thread must be a kthread.
1557  */
1558 struct cgroup_subsys_state *kthread_blkcg(void)
1559 {
1560 	struct kthread *kthread;
1561 
1562 	if (current->flags & PF_KTHREAD) {
1563 		kthread = to_kthread(current);
1564 		if (kthread)
1565 			return kthread->blkcg_css;
1566 	}
1567 	return NULL;
1568 }
1569 #endif
1570