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