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