]> git.ipfire.org Git - thirdparty/linux.git/blame - kernel/kthread.c
Merge tag 'hid-for-linus-2025070502' of git://git.kernel.org/pub/scm/linux/kernel...
[thirdparty/linux.git] / kernel / kthread.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/* Kernel thread helper functions.
3 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
9bf5b9eb 4 * Copyright (C) 2009 Red Hat, Inc.
1da177e4 5 *
73c27992 6 * Creation is done via kthreadd, so that we get a clean environment
1da177e4
LT
7 * even if we're invoked from userspace (think modprobe, hotplug cpu,
8 * etc.).
9 */
ae7e81c0 10#include <uapi/linux/sched/types.h>
9bf5b9eb
CH
11#include <linux/mm.h>
12#include <linux/mmu_context.h>
1da177e4 13#include <linux/sched.h>
9bf5b9eb 14#include <linux/sched/mm.h>
29930025 15#include <linux/sched/task.h>
1da177e4
LT
16#include <linux/kthread.h>
17#include <linux/completion.h>
18#include <linux/err.h>
8af0c18a 19#include <linux/cgroup.h>
58568d2a 20#include <linux/cpuset.h>
1da177e4
LT
21#include <linux/unistd.h>
22#include <linux/file.h>
9984de1a 23#include <linux/export.h>
97d1f15b 24#include <linux/mutex.h>
b56c0d89
TH
25#include <linux/slab.h>
26#include <linux/freezer.h>
a74fb73c 27#include <linux/ptrace.h>
cd42d559 28#include <linux/uaccess.h>
98fa15f3 29#include <linux/numa.h>
9cc5b865 30#include <linux/sched/isolation.h>
ad8d75ff 31#include <trace/events/sched.h>
1da177e4 32
9bf5b9eb 33
73c27992
EB
34static DEFINE_SPINLOCK(kthread_create_lock);
35static LIST_HEAD(kthread_create_list);
36struct task_struct *kthreadd_task;
1da177e4 37
d1a89197
FW
38static LIST_HEAD(kthreads_hotplug);
39static DEFINE_MUTEX(kthreads_hotplug_lock);
40
1da177e4
LT
41struct kthread_create_info
42{
73c27992 43 /* Information passed to kthread() from kthreadd. */
73e0c116 44 char *full_name;
1da177e4
LT
45 int (*threadfn)(void *data);
46 void *data;
207205a2 47 int node;
1da177e4 48
73c27992 49 /* Result passed back to kthread_create() from kthreadd. */
1da177e4 50 struct task_struct *result;
786235ee 51 struct completion *done;
65f27f38 52
73c27992 53 struct list_head list;
1da177e4
LT
54};
55
63706172 56struct kthread {
2a1d4460
TG
57 unsigned long flags;
58 unsigned int cpu;
d1a89197 59 unsigned int node;
5eacb68a 60 int started;
6b124879 61 int result;
52782c92 62 int (*threadfn)(void *);
82805ab7 63 void *data;
2a1d4460 64 struct completion parked;
63706172 65 struct completion exited;
0b508bc9 66#ifdef CONFIG_BLK_CGROUP
05e3db95
SL
67 struct cgroup_subsys_state *blkcg_css;
68#endif
d6986ce2
YS
69 /* To store the full name if task comm is truncated. */
70 char *full_name;
d1a89197
FW
71 struct task_struct *task;
72 struct list_head hotplug_node;
4d13f430 73 struct cpumask *preferred_affinity;
1da177e4
LT
74};
75
2a1d4460
TG
76enum KTHREAD_BITS {
77 KTHREAD_IS_PER_CPU = 0,
78 KTHREAD_SHOULD_STOP,
79 KTHREAD_SHOULD_PARK,
2a1d4460
TG
80};
81
4ecdafc8
ON
82static inline struct kthread *to_kthread(struct task_struct *k)
83{
1da5c46f 84 WARN_ON(!(k->flags & PF_KTHREAD));
e32cf5df 85 return k->worker_private;
4ecdafc8
ON
86}
87
3a7956e2
PZ
88/*
89 * Variant of to_kthread() that doesn't assume @p is a kthread.
90 *
91 * Per construction; when:
92 *
e32cf5df 93 * (p->flags & PF_KTHREAD) && p->worker_private
3a7956e2
PZ
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 */
99static inline struct kthread *__to_kthread(struct task_struct *p)
100{
e32cf5df 101 void *kthread = p->worker_private;
3a7956e2
PZ
102 if (kthread && !(p->flags & PF_KTHREAD))
103 kthread = NULL;
104 return kthread;
105}
106
d6986ce2
YS
107void 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) {
4cc0473d 112 strscpy(buf, tsk->comm, buf_size);
d6986ce2
YS
113 return;
114 }
115
116 strscpy_pad(buf, kthread->full_name, buf_size);
117}
118
40966e31 119bool set_kthread_struct(struct task_struct *p)
00b89fe0
VS
120{
121 struct kthread *kthread;
122
40966e31
EB
123 if (WARN_ON_ONCE(to_kthread(p)))
124 return false;
00b89fe0
VS
125
126 kthread = kzalloc(sizeof(*kthread), GFP_KERNEL);
40966e31
EB
127 if (!kthread)
128 return false;
129
130 init_completion(&kthread->exited);
131 init_completion(&kthread->parked);
d1a89197 132 INIT_LIST_HEAD(&kthread->hotplug_node);
40966e31
EB
133 p->vfork_done = &kthread->exited;
134
d1a89197
FW
135 kthread->task = p;
136 kthread->node = tsk_fork_get_node(current);
e32cf5df 137 p->worker_private = kthread;
40966e31 138 return true;
00b89fe0
VS
139}
140
1da5c46f
ON
141void free_kthread_struct(struct task_struct *k)
142{
05e3db95
SL
143 struct kthread *kthread;
144
1da5c46f 145 /*
40966e31 146 * Can be NULL if kmalloc() in set_kthread_struct() failed.
1da5c46f 147 */
05e3db95 148 kthread = to_kthread(k);
d6986ce2
YS
149 if (!kthread)
150 return;
151
0b508bc9 152#ifdef CONFIG_BLK_CGROUP
d6986ce2 153 WARN_ON_ONCE(kthread->blkcg_css);
05e3db95 154#endif
e32cf5df 155 k->worker_private = NULL;
d6986ce2 156 kfree(kthread->full_name);
05e3db95 157 kfree(kthread);
1da5c46f
ON
158}
159
9e37bd30
RD
160/**
161 * kthread_should_stop - should this kthread return now?
162 *
72fd4a35 163 * When someone calls kthread_stop() on your kthread, it will be woken
9e37bd30
RD
164 * and this will return true. You should then return, and your return
165 * value will be passed through to kthread_stop().
166 */
2a1d4460 167bool kthread_should_stop(void)
1da177e4 168{
2a1d4460 169 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
1da177e4
LT
170}
171EXPORT_SYMBOL(kthread_should_stop);
172
be33db21 173static bool __kthread_should_park(struct task_struct *k)
0121805d
MK
174{
175 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
176}
0121805d 177
2a1d4460
TG
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 */
189bool kthread_should_park(void)
190{
0121805d 191 return __kthread_should_park(current);
2a1d4460 192}
18896451 193EXPORT_SYMBOL_GPL(kthread_should_park);
2a1d4460 194
ef73d6a4
AH
195bool 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
8a32c441
TH
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 */
214bool 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}
228EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
229
52782c92
BF
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 */
236void *kthread_func(struct task_struct *task)
237{
3a7956e2
PZ
238 struct kthread *kthread = __to_kthread(task);
239 if (kthread)
240 return kthread->threadfn;
52782c92
BF
241 return NULL;
242}
243EXPORT_SYMBOL_GPL(kthread_func);
244
82805ab7
TH
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 */
253void *kthread_data(struct task_struct *task)
254{
255 return to_kthread(task)->data;
256}
52782c92 257EXPORT_SYMBOL_GPL(kthread_data);
82805ab7 258
cd42d559 259/**
e700591a 260 * kthread_probe_data - speculative version of kthread_data()
cd42d559
TH
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 */
e700591a 268void *kthread_probe_data(struct task_struct *task)
cd42d559 269{
3a7956e2 270 struct kthread *kthread = __to_kthread(task);
cd42d559
TH
271 void *data = NULL;
272
3a7956e2
PZ
273 if (kthread)
274 copy_from_kernel_nofault(&data, &kthread->data, sizeof(data));
cd42d559
TH
275 return data;
276}
277
2a1d4460
TG
278static void __kthread_parkme(struct kthread *self)
279{
741a76b3 280 for (;;) {
1cef1150
PZ
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);
741a76b3
PZ
291 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
292 break;
1cef1150 293
26c7295b
LC
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();
f83ee19b 300 complete(&self->parked);
26c7295b
LC
301 schedule_preempt_disabled();
302 preempt_enable();
2a1d4460 303 }
2a1d4460
TG
304 __set_current_state(TASK_RUNNING);
305}
306
307void kthread_parkme(void)
308{
309 __kthread_parkme(to_kthread(current));
310}
18896451 311EXPORT_SYMBOL_GPL(kthread_parkme);
2a1d4460 312
bbda86e9
EB
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 */
323void __noreturn kthread_exit(long result)
324{
6b124879
EB
325 struct kthread *kthread = to_kthread(current);
326 kthread->result = result;
d1a89197
FW
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);
4d13f430
FW
331
332 if (kthread->preferred_affinity) {
333 kfree(kthread->preferred_affinity);
334 kthread->preferred_affinity = NULL;
335 }
d1a89197 336 }
6b124879 337 do_exit(0);
bbda86e9 338}
3a35c130 339EXPORT_SYMBOL(kthread_exit);
bbda86e9 340
cead1855 341/**
5eb6f228 342 * kthread_complete_and_exit - Exit the current kthread.
cead1855
EB
343 * @comp: Completion to complete
344 * @code: The integer value to return to kthread_stop().
345 *
6a25212d 346 * If present, complete @comp and then return code to kthread_stop().
cead1855
EB
347 *
348 * A kernel thread whose module may be removed after the completion of
6a25212d 349 * @comp can use this function to exit safely.
cead1855
EB
350 *
351 * Does not return.
352 */
353void __noreturn kthread_complete_and_exit(struct completion *comp, long code)
354{
355 if (comp)
356 complete(comp);
357
358 kthread_exit(code);
359}
360EXPORT_SYMBOL(kthread_complete_and_exit);
361
d1a89197
FW
362static void kthread_fetch_affinity(struct kthread *kthread, struct cpumask *cpumask)
363{
4d13f430
FW
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 }
d1a89197 373
4d13f430 374 cpumask_and(cpumask, pref, housekeeping_cpumask(HK_TYPE_KTHREAD));
d1a89197
FW
375 if (cpumask_empty(cpumask))
376 cpumask_copy(cpumask, housekeeping_cpumask(HK_TYPE_KTHREAD));
377}
378
379static 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
1da177e4
LT
412static int kthread(void *_create)
413{
1a7243ca 414 static const struct sched_param param = { .sched_priority = 0 };
63706172 415 /* Copy data: it's on kthread's stack */
1da177e4 416 struct kthread_create_info *create = _create;
63706172
ON
417 int (*threadfn)(void *data) = create->threadfn;
418 void *data = create->data;
786235ee 419 struct completion *done;
1da5c46f 420 struct kthread *self;
63706172 421 int ret;
1da177e4 422
00b89fe0 423 self = to_kthread(current);
1da177e4 424
d25c83c6 425 /* Release the structure when caller killed by a fatal signal. */
786235ee
TH
426 done = xchg(&create->done, NULL);
427 if (!done) {
73e0c116 428 kfree(create->full_name);
786235ee 429 kfree(create);
bbda86e9 430 kthread_exit(-EINTR);
1da5c46f
ON
431 }
432
73e0c116 433 self->full_name = create->full_name;
52782c92 434 self->threadfn = threadfn;
1da5c46f 435 self->data = data;
1da5c46f 436
1a7243ca
SAS
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);
1a7243ca 442
1da177e4 443 /* OK, tell user we're spawned, wait for stop or wakeup */
a076e4bc 444 __set_current_state(TASK_UNINTERRUPTIBLE);
3217ab97 445 create->result = current;
26c7295b
LC
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();
786235ee 451 complete(done);
26c7295b
LC
452 schedule_preempt_disabled();
453 preempt_enable();
1da177e4 454
5eacb68a
FW
455 self->started = 1;
456
4d13f430 457 if (!(current->flags & PF_NO_SETAFFINITY) && !self->preferred_affinity)
d1a89197
FW
458 kthread_affine_node();
459
63706172 460 ret = -EINTR;
1da5c46f 461 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
77f88796 462 cgroup_kthread_ready();
1da5c46f 463 __kthread_parkme(self);
2a1d4460
TG
464 ret = threadfn(data);
465 }
bbda86e9 466 kthread_exit(ret);
1da177e4
LT
467}
468
cb5021ca 469/* called from kernel_clone() to get node information for about to be created task */
207205a2
ED
470int 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
81c98869 476 return NUMA_NO_NODE;
207205a2
ED
477}
478
73c27992 479static void create_kthread(struct kthread_create_info *create)
1da177e4 480{
1da177e4
LT
481 int pid;
482
207205a2
ED
483#ifdef CONFIG_NUMA
484 current->pref_node_fork = create->node;
485#endif
1da177e4 486 /* We want our own signal handler (we take no signals by default). */
73e0c116 487 pid = kernel_thread(kthread, create, create->full_name,
cf587db2 488 CLONE_FS | CLONE_FILES | SIGCHLD);
cdd140bd 489 if (pid < 0) {
d25c83c6 490 /* Release the structure when caller killed by a fatal signal. */
786235ee
TH
491 struct completion *done = xchg(&create->done, NULL);
492
73e0c116 493 kfree(create->full_name);
786235ee
TH
494 if (!done) {
495 kfree(create);
496 return;
497 }
1da177e4 498 create->result = ERR_PTR(pid);
786235ee 499 complete(done);
cdd140bd 500 }
1da177e4
LT
501}
502
c0b942a7
NI
503static __printf(4, 0)
504struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
255451e4
PM
505 void *data, int node,
506 const char namefmt[],
507 va_list args)
1da177e4 508{
786235ee
TH
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;
73e0c116
MC
520 create->full_name = kvasprintf(GFP_KERNEL, namefmt, args);
521 if (!create->full_name) {
522 task = ERR_PTR(-ENOMEM);
523 goto free_create;
524 }
73c27992
EB
525
526 spin_lock(&kthread_create_lock);
786235ee 527 list_add_tail(&create->list, &kthread_create_list);
73c27992
EB
528 spin_unlock(&kthread_create_lock);
529
cbd9b67b 530 wake_up_process(kthreadd_task);
786235ee
TH
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 /*
d25c83c6
PM
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.
786235ee
TH
541 */
542 if (xchg(&create->done, NULL))
8fe6929c 543 return ERR_PTR(-EINTR);
786235ee
TH
544 /*
545 * kthreadd (or new kernel thread) will call complete()
546 * shortly.
547 */
548 wait_for_completion(&done);
549 }
550 task = create->result;
73e0c116 551free_create:
786235ee
TH
552 kfree(create);
553 return task;
1da177e4 554}
255451e4
PM
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
111e7049 571 * argument. @threadfn() can either return directly if it is a
255451e4
PM
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 */
579struct 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}
207205a2 593EXPORT_SYMBOL(kthread_create_on_node);
1da177e4 594
2f064a59 595static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, unsigned int state)
2a1d4460 596{
25834c73
PZ
597 unsigned long flags;
598
f2530dc7
TG
599 if (!wait_task_inactive(p, state)) {
600 WARN_ON(1);
601 return;
602 }
25834c73 603
2a1d4460 604 /* It's safe because the task is inactive. */
25834c73
PZ
605 raw_spin_lock_irqsave(&p->pi_lock, flags);
606 do_set_cpus_allowed(p, mask);
14a40ffc 607 p->flags |= PF_NO_SETAFFINITY;
25834c73
PZ
608 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
609}
610
2f064a59 611static void __kthread_bind(struct task_struct *p, unsigned int cpu, unsigned int state)
25834c73
PZ
612{
613 __kthread_bind_mask(p, cpumask_of(cpu), state);
614}
615
616void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
617{
5eacb68a 618 struct kthread *kthread = to_kthread(p);
25834c73 619 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
5eacb68a 620 WARN_ON_ONCE(kthread->started);
2a1d4460
TG
621}
622
881232b7
PZ
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 */
632void kthread_bind(struct task_struct *p, unsigned int cpu)
633{
5eacb68a 634 struct kthread *kthread = to_kthread(p);
f2530dc7 635 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
5eacb68a 636 WARN_ON_ONCE(kthread->started);
881232b7
PZ
637}
638EXPORT_SYMBOL(kthread_bind);
639
2a1d4460
TG
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
2a1d4460
TG
649 */
650struct 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
10922838 656 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
2a1d4460
TG
657 cpu);
658 if (IS_ERR(p))
659 return p;
a65d4096
PM
660 kthread_bind(p, cpu);
661 /* CPU hotplug need to bind once again when unparking the thread. */
2a1d4460 662 to_kthread(p)->cpu = cpu;
2a1d4460
TG
663 return p;
664}
800977f6 665EXPORT_SYMBOL(kthread_create_on_cpu);
2a1d4460 666
ac687e6e
PZ
667void 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
3a7956e2 684bool kthread_is_per_cpu(struct task_struct *p)
ac687e6e 685{
3a7956e2 686 struct kthread *kthread = __to_kthread(p);
ac687e6e
PZ
687 if (!kthread)
688 return false;
689
690 return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
691}
692
cf380a4a
ON
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 */
701void kthread_unpark(struct task_struct *k)
f2530dc7 702{
cf380a4a
ON
703 struct kthread *kthread = to_kthread(k);
704
214e01ad
FW
705 if (!test_bit(KTHREAD_SHOULD_PARK, &kthread->flags))
706 return;
f2530dc7 707 /*
85f1abe0
PZ
708 * Newly created kthread was parked when the CPU was offline.
709 * The binding was lost and we need to set it again.
f2530dc7 710 */
85f1abe0
PZ
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);
1cef1150
PZ
715 /*
716 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
717 */
85f1abe0 718 wake_up_state(k, TASK_PARKED);
f2530dc7 719}
18896451 720EXPORT_SYMBOL_GPL(kthread_unpark);
2a1d4460
TG
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 */
734int kthread_park(struct task_struct *k)
735{
cf380a4a
ON
736 struct kthread *kthread = to_kthread(k);
737
738 if (WARN_ON(k->flags & PF_EXITING))
739 return -ENOSYS;
740
f83ee19b
PZ
741 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
742 return -EBUSY;
743
85f1abe0
PZ
744 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
745 if (k != current) {
746 wake_up_process(k);
1cef1150
PZ
747 /*
748 * Wait for __kthread_parkme() to complete(), this means we
749 * _will_ have TASK_PARKED and are about to call schedule().
750 */
85f1abe0 751 wait_for_completion(&kthread->parked);
1cef1150
PZ
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));
2a1d4460 757 }
cf380a4a
ON
758
759 return 0;
2a1d4460 760}
18896451 761EXPORT_SYMBOL_GPL(kthread_park);
2a1d4460 762
9e37bd30
RD
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
9ae26027
ON
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 *
bbda86e9 772 * If threadfn() may call kthread_exit() itself, the caller must ensure
9ae26027 773 * task_struct can't go away.
9e37bd30
RD
774 *
775 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
776 * was never called.
777 */
1da177e4
LT
778int kthread_stop(struct task_struct *k)
779{
b5c5442b 780 struct kthread *kthread;
1da177e4
LT
781 int ret;
782
0a16b607 783 trace_sched_kthread_stop(k);
b5c5442b
ON
784
785 get_task_struct(k);
efb29fbf
ON
786 kthread = to_kthread(k);
787 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
cf380a4a 788 kthread_unpark(k);
a7c01fa9 789 set_tsk_thread_flag(k, TIF_NOTIFY_SIGNAL);
efb29fbf
ON
790 wake_up_process(k);
791 wait_for_completion(&kthread->exited);
6b124879 792 ret = kthread->result;
1da177e4 793 put_task_struct(k);
0a16b607 794
b5c5442b 795 trace_sched_kthread_stop_ret(ret);
1da177e4
LT
796 return ret;
797}
52e92e57 798EXPORT_SYMBOL(kthread_stop);
1da177e4 799
6309727e
AG
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 */
808int 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}
816EXPORT_SYMBOL(kthread_stop_put);
817
e804a4a4 818int kthreadd(void *unused)
1da177e4 819{
3a3f61ce 820 static const char comm[TASK_COMM_LEN] = "kthreadd";
73c27992 821 struct task_struct *tsk = current;
1da177e4 822
e804a4a4 823 /* Setup a clean context for our children to inherit. */
3a3f61ce 824 set_task_comm(tsk, comm);
10ab825b 825 ignore_signals(tsk);
04d4e665 826 set_cpus_allowed_ptr(tsk, housekeeping_cpumask(HK_TYPE_KTHREAD));
aee4faa4 827 set_mems_allowed(node_states[N_MEMORY]);
73c27992 828
34b087e4 829 current->flags |= PF_NOFREEZE;
77f88796 830 cgroup_init_kthreadd();
73c27992
EB
831
832 for (;;) {
833 set_current_state(TASK_INTERRUPTIBLE);
834 if (list_empty(&kthread_create_list))
835 schedule();
836 __set_current_state(TASK_RUNNING);
837
838 spin_lock(&kthread_create_lock);
839 while (!list_empty(&kthread_create_list)) {
840 struct kthread_create_info *create;
841
842 create = list_entry(kthread_create_list.next,
843 struct kthread_create_info, list);
844 list_del_init(&create->list);
845 spin_unlock(&kthread_create_lock);
846
847 create_kthread(create);
848
849 spin_lock(&kthread_create_lock);
850 }
851 spin_unlock(&kthread_create_lock);
852 }
853
854 return 0;
855}
b56c0d89 856
4d13f430
FW
857int kthread_affine_preferred(struct task_struct *p, const struct cpumask *mask)
858{
859 struct kthread *kthread = to_kthread(p);
860 cpumask_var_t affinity;
861 unsigned long flags;
1b0332a4 862 int ret = 0;
4d13f430
FW
863
864 if (!wait_task_inactive(p, TASK_UNINTERRUPTIBLE) || kthread->started) {
865 WARN_ON(1);
866 return -EINVAL;
867 }
868
869 WARN_ON_ONCE(kthread->preferred_affinity);
870
871 if (!zalloc_cpumask_var(&affinity, GFP_KERNEL))
872 return -ENOMEM;
873
874 kthread->preferred_affinity = kzalloc(sizeof(struct cpumask), GFP_KERNEL);
875 if (!kthread->preferred_affinity) {
876 ret = -ENOMEM;
877 goto out;
878 }
879
880 mutex_lock(&kthreads_hotplug_lock);
881 cpumask_copy(kthread->preferred_affinity, mask);
882 WARN_ON_ONCE(!list_empty(&kthread->hotplug_node));
883 list_add_tail(&kthread->hotplug_node, &kthreads_hotplug);
884 kthread_fetch_affinity(kthread, affinity);
885
886 /* It's safe because the task is inactive. */
887 raw_spin_lock_irqsave(&p->pi_lock, flags);
888 do_set_cpus_allowed(p, affinity);
889 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
890
891 mutex_unlock(&kthreads_hotplug_lock);
892out:
893 free_cpumask_var(affinity);
894
1b0332a4 895 return ret;
4d13f430
FW
896}
897
d1a89197
FW
898/*
899 * Re-affine kthreads according to their preferences
900 * and the newly online CPU. The CPU down part is handled
901 * by select_fallback_rq() which default re-affines to
4d13f430
FW
902 * housekeepers from other nodes in case the preferred
903 * affinity doesn't apply anymore.
d1a89197
FW
904 */
905static int kthreads_online_cpu(unsigned int cpu)
906{
907 cpumask_var_t affinity;
908 struct kthread *k;
909 int ret;
910
911 guard(mutex)(&kthreads_hotplug_lock);
912
913 if (list_empty(&kthreads_hotplug))
914 return 0;
915
916 if (!zalloc_cpumask_var(&affinity, GFP_KERNEL))
917 return -ENOMEM;
918
919 ret = 0;
920
921 list_for_each_entry(k, &kthreads_hotplug, hotplug_node) {
922 if (WARN_ON_ONCE((k->task->flags & PF_NO_SETAFFINITY) ||
4d13f430 923 kthread_is_per_cpu(k->task))) {
d1a89197
FW
924 ret = -EINVAL;
925 continue;
926 }
927 kthread_fetch_affinity(k, affinity);
928 set_cpus_allowed_ptr(k->task, affinity);
929 }
930
931 free_cpumask_var(affinity);
932
933 return ret;
934}
935
936static int kthreads_init(void)
937{
938 return cpuhp_setup_state(CPUHP_AP_KTHREADS_ONLINE, "kthreads:online",
939 kthreads_online_cpu, NULL);
940}
941early_initcall(kthreads_init);
942
3989144f 943void __kthread_init_worker(struct kthread_worker *worker,
4f32e9b1
YZ
944 const char *name,
945 struct lock_class_key *key)
946{
dbf52682 947 memset(worker, 0, sizeof(struct kthread_worker));
fe99a4f4 948 raw_spin_lock_init(&worker->lock);
4f32e9b1
YZ
949 lockdep_set_class_and_name(&worker->lock, key, name);
950 INIT_LIST_HEAD(&worker->work_list);
22597dc3 951 INIT_LIST_HEAD(&worker->delayed_work_list);
4f32e9b1 952}
3989144f 953EXPORT_SYMBOL_GPL(__kthread_init_worker);
4f32e9b1 954
b56c0d89
TH
955/**
956 * kthread_worker_fn - kthread function to process kthread_worker
957 * @worker_ptr: pointer to initialized kthread_worker
958 *
fbae2d44
PM
959 * This function implements the main cycle of kthread worker. It processes
960 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
961 * is empty.
b56c0d89 962 *
fbae2d44
PM
963 * The works are not allowed to keep any locks, disable preemption or interrupts
964 * when they finish. There is defined a safe point for freezing when one work
965 * finishes and before a new one is started.
8197b3d4
PM
966 *
967 * Also the works must not be handled by more than one worker at the same time,
968 * see also kthread_queue_work().
b56c0d89
TH
969 */
970int kthread_worker_fn(void *worker_ptr)
971{
972 struct kthread_worker *worker = worker_ptr;
973 struct kthread_work *work;
974
fbae2d44
PM
975 /*
976 * FIXME: Update the check and remove the assignment when all kthread
977 * worker users are created using kthread_create_worker*() functions.
978 */
979 WARN_ON(worker->task && worker->task != current);
b56c0d89 980 worker->task = current;
dbf52682
PM
981
982 if (worker->flags & KTW_FREEZABLE)
983 set_freezable();
984
b56c0d89
TH
985repeat:
986 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
987
988 if (kthread_should_stop()) {
989 __set_current_state(TASK_RUNNING);
fe99a4f4 990 raw_spin_lock_irq(&worker->lock);
b56c0d89 991 worker->task = NULL;
fe99a4f4 992 raw_spin_unlock_irq(&worker->lock);
b56c0d89
TH
993 return 0;
994 }
995
996 work = NULL;
fe99a4f4 997 raw_spin_lock_irq(&worker->lock);
b56c0d89
TH
998 if (!list_empty(&worker->work_list)) {
999 work = list_first_entry(&worker->work_list,
1000 struct kthread_work, node);
1001 list_del_init(&work->node);
1002 }
46f3d976 1003 worker->current_work = work;
fe99a4f4 1004 raw_spin_unlock_irq(&worker->lock);
b56c0d89
TH
1005
1006 if (work) {
f630c7c6 1007 kthread_work_func_t func = work->func;
b56c0d89 1008 __set_current_state(TASK_RUNNING);
f630c7c6 1009 trace_sched_kthread_work_execute_start(work);
b56c0d89 1010 work->func(work);
f630c7c6
RC
1011 /*
1012 * Avoid dereferencing work after this point. The trace
1013 * event only cares about the address.
1014 */
1015 trace_sched_kthread_work_execute_end(work, func);
6b9ccbc0 1016 } else if (!freezing(current)) {
b56c0d89 1017 schedule();
6b9ccbc0
CY
1018 } else {
1019 /*
1020 * Handle the case where the current remains
1021 * TASK_INTERRUPTIBLE. try_to_freeze() expects
1022 * the current to be TASK_RUNNING.
1023 */
1024 __set_current_state(TASK_RUNNING);
1025 }
b56c0d89
TH
1026
1027 try_to_freeze();
22cf8bc6 1028 cond_resched();
b56c0d89
TH
1029 goto repeat;
1030}
1031EXPORT_SYMBOL_GPL(kthread_worker_fn);
1032
c0b942a7 1033static __printf(3, 0) struct kthread_worker *
41f70d8e
FW
1034__kthread_create_worker_on_node(unsigned int flags, int node,
1035 const char namefmt[], va_list args)
fbae2d44
PM
1036{
1037 struct kthread_worker *worker;
1038 struct task_struct *task;
1039
1040 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
1041 if (!worker)
1042 return ERR_PTR(-ENOMEM);
1043
1044 kthread_init_worker(worker);
1045
8fb9dcbd 1046 task = __kthread_create_on_node(kthread_worker_fn, worker,
41f70d8e 1047 node, namefmt, args);
fbae2d44
PM
1048 if (IS_ERR(task))
1049 goto fail_task;
1050
dbf52682 1051 worker->flags = flags;
fbae2d44 1052 worker->task = task;
41f70d8e 1053
fbae2d44
PM
1054 return worker;
1055
1056fail_task:
1057 kfree(worker);
1058 return ERR_CAST(task);
1059}
1060
1061/**
d8b4bf4e 1062 * kthread_create_worker_on_node - create a kthread worker
dbf52682 1063 * @flags: flags modifying the default behavior of the worker
41f70d8e 1064 * @node: task structure for the thread is allocated on this node
fbae2d44
PM
1065 * @namefmt: printf-style name for the kthread worker (task).
1066 *
1067 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
1068 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
d25c83c6 1069 * when the caller was killed by a fatal signal.
fbae2d44
PM
1070 */
1071struct kthread_worker *
41f70d8e 1072kthread_create_worker_on_node(unsigned int flags, int node, const char namefmt[], ...)
fbae2d44
PM
1073{
1074 struct kthread_worker *worker;
1075 va_list args;
1076
1077 va_start(args, namefmt);
41f70d8e 1078 worker = __kthread_create_worker_on_node(flags, node, namefmt, args);
fbae2d44
PM
1079 va_end(args);
1080
1081 return worker;
1082}
41f70d8e 1083EXPORT_SYMBOL(kthread_create_worker_on_node);
fbae2d44
PM
1084
1085/**
1086 * kthread_create_worker_on_cpu - create a kthread worker and bind it
7b7b8a2c 1087 * to a given CPU and the associated NUMA node.
fbae2d44 1088 * @cpu: CPU number
dbf52682 1089 * @flags: flags modifying the default behavior of the worker
41f70d8e
FW
1090 * @namefmt: printf-style name for the thread. Format is restricted
1091 * to "name.*%u". Code fills in cpu number.
fbae2d44
PM
1092 *
1093 * Use a valid CPU number if you want to bind the kthread worker
1094 * to the given CPU and the associated NUMA node.
1095 *
1096 * A good practice is to add the cpu number also into the worker name.
1097 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
1098 *
ebb2bdce
PM
1099 * CPU hotplug:
1100 * The kthread worker API is simple and generic. It just provides a way
1101 * to create, use, and destroy workers.
1102 *
1103 * It is up to the API user how to handle CPU hotplug. They have to decide
1104 * how to handle pending work items, prevent queuing new ones, and
1105 * restore the functionality when the CPU goes off and on. There are a
1106 * few catches:
1107 *
1108 * - CPU affinity gets lost when it is scheduled on an offline CPU.
1109 *
1110 * - The worker might not exist when the CPU was off when the user
1111 * created the workers.
1112 *
1113 * Good practice is to implement two CPU hotplug callbacks and to
1114 * destroy/create the worker when the CPU goes down/up.
1115 *
1116 * Return:
1117 * The pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
fbae2d44 1118 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
d25c83c6 1119 * when the caller was killed by a fatal signal.
fbae2d44
PM
1120 */
1121struct kthread_worker *
dbf52682 1122kthread_create_worker_on_cpu(int cpu, unsigned int flags,
41f70d8e 1123 const char namefmt[])
fbae2d44
PM
1124{
1125 struct kthread_worker *worker;
fbae2d44 1126
b04e317b
FW
1127 worker = kthread_create_worker_on_node(flags, cpu_to_node(cpu), namefmt, cpu);
1128 if (!IS_ERR(worker))
1129 kthread_bind(worker->task, cpu);
fbae2d44
PM
1130
1131 return worker;
1132}
1133EXPORT_SYMBOL(kthread_create_worker_on_cpu);
1134
37be45d4
PM
1135/*
1136 * Returns true when the work could not be queued at the moment.
1137 * It happens when it is already pending in a worker list
1138 * or when it is being cancelled.
1139 */
1140static inline bool queuing_blocked(struct kthread_worker *worker,
1141 struct kthread_work *work)
1142{
1143 lockdep_assert_held(&worker->lock);
1144
1145 return !list_empty(&work->node) || work->canceling;
1146}
1147
8197b3d4
PM
1148static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
1149 struct kthread_work *work)
1150{
1151 lockdep_assert_held(&worker->lock);
1152 WARN_ON_ONCE(!list_empty(&work->node));
1153 /* Do not use a work with >1 worker, see kthread_queue_work() */
1154 WARN_ON_ONCE(work->worker && work->worker != worker);
1155}
1156
9a2e03d8 1157/* insert @work before @pos in @worker */
3989144f 1158static void kthread_insert_work(struct kthread_worker *worker,
8197b3d4
PM
1159 struct kthread_work *work,
1160 struct list_head *pos)
9a2e03d8 1161{
8197b3d4 1162 kthread_insert_work_sanity_check(worker, work);
9a2e03d8 1163
f630c7c6
RC
1164 trace_sched_kthread_work_queue_work(worker, work);
1165
9a2e03d8 1166 list_add_tail(&work->node, pos);
46f3d976 1167 work->worker = worker;
ed1403ec 1168 if (!worker->current_work && likely(worker->task))
9a2e03d8
TH
1169 wake_up_process(worker->task);
1170}
1171
b56c0d89 1172/**
3989144f 1173 * kthread_queue_work - queue a kthread_work
b56c0d89
TH
1174 * @worker: target kthread_worker
1175 * @work: kthread_work to queue
1176 *
1177 * Queue @work to work processor @task for async execution. @task
97549ce6 1178 * must have been created with kthread_create_worker(). Returns %true
b56c0d89 1179 * if @work was successfully queued, %false if it was already pending.
8197b3d4
PM
1180 *
1181 * Reinitialize the work if it needs to be used by another worker.
1182 * For example, when the worker was stopped and started again.
b56c0d89 1183 */
3989144f 1184bool kthread_queue_work(struct kthread_worker *worker,
b56c0d89
TH
1185 struct kthread_work *work)
1186{
1187 bool ret = false;
1188 unsigned long flags;
1189
fe99a4f4 1190 raw_spin_lock_irqsave(&worker->lock, flags);
37be45d4 1191 if (!queuing_blocked(worker, work)) {
3989144f 1192 kthread_insert_work(worker, work, &worker->work_list);
b56c0d89
TH
1193 ret = true;
1194 }
fe99a4f4 1195 raw_spin_unlock_irqrestore(&worker->lock, flags);
b56c0d89
TH
1196 return ret;
1197}
3989144f 1198EXPORT_SYMBOL_GPL(kthread_queue_work);
b56c0d89 1199
22597dc3
PM
1200/**
1201 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
1202 * delayed work when the timer expires.
fe5c3b69 1203 * @t: pointer to the expired timer
22597dc3
PM
1204 *
1205 * The format of the function is defined by struct timer_list.
1206 * It should have been called from irqsafe timer with irq already off.
1207 */
fe5c3b69 1208void kthread_delayed_work_timer_fn(struct timer_list *t)
22597dc3 1209{
41cb0855
IM
1210 struct kthread_delayed_work *dwork = timer_container_of(dwork, t,
1211 timer);
22597dc3
PM
1212 struct kthread_work *work = &dwork->work;
1213 struct kthread_worker *worker = work->worker;
ad01423a 1214 unsigned long flags;
22597dc3
PM
1215
1216 /*
1217 * This might happen when a pending work is reinitialized.
1218 * It means that it is used a wrong way.
1219 */
1220 if (WARN_ON_ONCE(!worker))
1221 return;
1222
ad01423a 1223 raw_spin_lock_irqsave(&worker->lock, flags);
22597dc3
PM
1224 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1225 WARN_ON_ONCE(work->worker != worker);
1226
1227 /* Move the work from worker->delayed_work_list. */
1228 WARN_ON_ONCE(list_empty(&work->node));
1229 list_del_init(&work->node);
6993d0fd
Z
1230 if (!work->canceling)
1231 kthread_insert_work(worker, work, &worker->work_list);
22597dc3 1232
ad01423a 1233 raw_spin_unlock_irqrestore(&worker->lock, flags);
22597dc3
PM
1234}
1235EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
1236
bc88f85c
BD
1237static void __kthread_queue_delayed_work(struct kthread_worker *worker,
1238 struct kthread_delayed_work *dwork,
1239 unsigned long delay)
22597dc3
PM
1240{
1241 struct timer_list *timer = &dwork->timer;
1242 struct kthread_work *work = &dwork->work;
1243
4b243563 1244 WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn);
22597dc3
PM
1245
1246 /*
1247 * If @delay is 0, queue @dwork->work immediately. This is for
1248 * both optimization and correctness. The earliest @timer can
1249 * expire is on the closest next tick and delayed_work users depend
1250 * on that there's no such delay when @delay is 0.
1251 */
1252 if (!delay) {
1253 kthread_insert_work(worker, work, &worker->work_list);
1254 return;
1255 }
1256
1257 /* Be paranoid and try to detect possible races already now. */
1258 kthread_insert_work_sanity_check(worker, work);
1259
1260 list_add(&work->node, &worker->delayed_work_list);
1261 work->worker = worker;
22597dc3
PM
1262 timer->expires = jiffies + delay;
1263 add_timer(timer);
1264}
1265
1266/**
1267 * kthread_queue_delayed_work - queue the associated kthread work
1268 * after a delay.
1269 * @worker: target kthread_worker
1270 * @dwork: kthread_delayed_work to queue
1271 * @delay: number of jiffies to wait before queuing
1272 *
1273 * If the work has not been pending it starts a timer that will queue
1274 * the work after the given @delay. If @delay is zero, it queues the
1275 * work immediately.
1276 *
1277 * Return: %false if the @work has already been pending. It means that
1278 * either the timer was running or the work was queued. It returns %true
1279 * otherwise.
1280 */
1281bool kthread_queue_delayed_work(struct kthread_worker *worker,
1282 struct kthread_delayed_work *dwork,
1283 unsigned long delay)
1284{
1285 struct kthread_work *work = &dwork->work;
1286 unsigned long flags;
1287 bool ret = false;
1288
fe99a4f4 1289 raw_spin_lock_irqsave(&worker->lock, flags);
22597dc3 1290
37be45d4 1291 if (!queuing_blocked(worker, work)) {
22597dc3
PM
1292 __kthread_queue_delayed_work(worker, dwork, delay);
1293 ret = true;
1294 }
1295
fe99a4f4 1296 raw_spin_unlock_irqrestore(&worker->lock, flags);
22597dc3
PM
1297 return ret;
1298}
1299EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
1300
9a2e03d8
TH
1301struct kthread_flush_work {
1302 struct kthread_work work;
1303 struct completion done;
1304};
1305
1306static void kthread_flush_work_fn(struct kthread_work *work)
1307{
1308 struct kthread_flush_work *fwork =
1309 container_of(work, struct kthread_flush_work, work);
1310 complete(&fwork->done);
1311}
1312
b56c0d89 1313/**
3989144f 1314 * kthread_flush_work - flush a kthread_work
b56c0d89
TH
1315 * @work: work to flush
1316 *
1317 * If @work is queued or executing, wait for it to finish execution.
1318 */
3989144f 1319void kthread_flush_work(struct kthread_work *work)
b56c0d89 1320{
46f3d976
TH
1321 struct kthread_flush_work fwork = {
1322 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1323 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1324 };
1325 struct kthread_worker *worker;
1326 bool noop = false;
1327
46f3d976
TH
1328 worker = work->worker;
1329 if (!worker)
1330 return;
b56c0d89 1331
fe99a4f4 1332 raw_spin_lock_irq(&worker->lock);
8197b3d4
PM
1333 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1334 WARN_ON_ONCE(work->worker != worker);
b56c0d89 1335
46f3d976 1336 if (!list_empty(&work->node))
3989144f 1337 kthread_insert_work(worker, &fwork.work, work->node.next);
46f3d976 1338 else if (worker->current_work == work)
3989144f
PM
1339 kthread_insert_work(worker, &fwork.work,
1340 worker->work_list.next);
46f3d976
TH
1341 else
1342 noop = true;
b56c0d89 1343
fe99a4f4 1344 raw_spin_unlock_irq(&worker->lock);
b56c0d89 1345
46f3d976
TH
1346 if (!noop)
1347 wait_for_completion(&fwork.done);
b56c0d89 1348}
3989144f 1349EXPORT_SYMBOL_GPL(kthread_flush_work);
b56c0d89 1350
34b3d534
PM
1351/*
1352 * Make sure that the timer is neither set nor running and could
1353 * not manipulate the work list_head any longer.
1354 *
1355 * The function is called under worker->lock. The lock is temporary
1356 * released but the timer can't be set again in the meantime.
1357 */
1358static void kthread_cancel_delayed_work_timer(struct kthread_work *work,
1359 unsigned long *flags)
1360{
1361 struct kthread_delayed_work *dwork =
1362 container_of(work, struct kthread_delayed_work, work);
1363 struct kthread_worker *worker = work->worker;
1364
1365 /*
8fa7292f 1366 * timer_delete_sync() must be called to make sure that the timer
34b3d534
PM
1367 * callback is not running. The lock must be temporary released
1368 * to avoid a deadlock with the callback. In the meantime,
1369 * any queuing is blocked by setting the canceling counter.
1370 */
1371 work->canceling++;
1372 raw_spin_unlock_irqrestore(&worker->lock, *flags);
8fa7292f 1373 timer_delete_sync(&dwork->timer);
34b3d534
PM
1374 raw_spin_lock_irqsave(&worker->lock, *flags);
1375 work->canceling--;
1376}
1377
37be45d4 1378/*
5fa54346
PM
1379 * This function removes the work from the worker queue.
1380 *
1381 * It is called under worker->lock. The caller must make sure that
1382 * the timer used by delayed work is not running, e.g. by calling
1383 * kthread_cancel_delayed_work_timer().
37be45d4
PM
1384 *
1385 * The work might still be in use when this function finishes. See the
1386 * current_work proceed by the worker.
1387 *
1388 * Return: %true if @work was pending and successfully canceled,
1389 * %false if @work was not pending
1390 */
5fa54346 1391static bool __kthread_cancel_work(struct kthread_work *work)
37be45d4 1392{
37be45d4
PM
1393 /*
1394 * Try to remove the work from a worker list. It might either
1395 * be from worker->work_list or from worker->delayed_work_list.
1396 */
1397 if (!list_empty(&work->node)) {
1398 list_del_init(&work->node);
1399 return true;
1400 }
1401
1402 return false;
1403}
1404
9a6b06c8
PM
1405/**
1406 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1407 * @worker: kthread worker to use
1408 * @dwork: kthread delayed work to queue
1409 * @delay: number of jiffies to wait before queuing
1410 *
1411 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1412 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1413 * @work is guaranteed to be queued immediately.
1414 *
d71ba164 1415 * Return: %false if @dwork was idle and queued, %true otherwise.
9a6b06c8
PM
1416 *
1417 * A special case is when the work is being canceled in parallel.
1418 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1419 * or yet another kthread_mod_delayed_work() call. We let the other command
d71ba164
PM
1420 * win and return %true here. The return value can be used for reference
1421 * counting and the number of queued works stays the same. Anyway, the caller
1422 * is supposed to synchronize these operations a reasonable way.
9a6b06c8
PM
1423 *
1424 * This function is safe to call from any context including IRQ handler.
1425 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1426 * for details.
1427 */
1428bool kthread_mod_delayed_work(struct kthread_worker *worker,
1429 struct kthread_delayed_work *dwork,
1430 unsigned long delay)
1431{
1432 struct kthread_work *work = &dwork->work;
1433 unsigned long flags;
d71ba164 1434 int ret;
9a6b06c8 1435
fe99a4f4 1436 raw_spin_lock_irqsave(&worker->lock, flags);
9a6b06c8
PM
1437
1438 /* Do not bother with canceling when never queued. */
d71ba164
PM
1439 if (!work->worker) {
1440 ret = false;
9a6b06c8 1441 goto fast_queue;
d71ba164 1442 }
9a6b06c8
PM
1443
1444 /* Work must not be used with >1 worker, see kthread_queue_work() */
1445 WARN_ON_ONCE(work->worker != worker);
1446
5fa54346
PM
1447 /*
1448 * Temporary cancel the work but do not fight with another command
1449 * that is canceling the work as well.
1450 *
1451 * It is a bit tricky because of possible races with another
1452 * mod_delayed_work() and cancel_delayed_work() callers.
1453 *
1454 * The timer must be canceled first because worker->lock is released
1455 * when doing so. But the work can be removed from the queue (list)
1456 * only when it can be queued again so that the return value can
1457 * be used for reference counting.
1458 */
1459 kthread_cancel_delayed_work_timer(work, &flags);
d71ba164
PM
1460 if (work->canceling) {
1461 /* The number of works in the queue does not change. */
1462 ret = true;
9a6b06c8 1463 goto out;
d71ba164 1464 }
5fa54346 1465 ret = __kthread_cancel_work(work);
9a6b06c8 1466
9a6b06c8
PM
1467fast_queue:
1468 __kthread_queue_delayed_work(worker, dwork, delay);
1469out:
fe99a4f4 1470 raw_spin_unlock_irqrestore(&worker->lock, flags);
9a6b06c8
PM
1471 return ret;
1472}
1473EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1474
37be45d4
PM
1475static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1476{
1477 struct kthread_worker *worker = work->worker;
1478 unsigned long flags;
1479 int ret = false;
1480
1481 if (!worker)
1482 goto out;
1483
fe99a4f4 1484 raw_spin_lock_irqsave(&worker->lock, flags);
37be45d4
PM
1485 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1486 WARN_ON_ONCE(work->worker != worker);
1487
5fa54346
PM
1488 if (is_dwork)
1489 kthread_cancel_delayed_work_timer(work, &flags);
1490
1491 ret = __kthread_cancel_work(work);
37be45d4
PM
1492
1493 if (worker->current_work != work)
1494 goto out_fast;
1495
1496 /*
1497 * The work is in progress and we need to wait with the lock released.
1498 * In the meantime, block any queuing by setting the canceling counter.
1499 */
1500 work->canceling++;
fe99a4f4 1501 raw_spin_unlock_irqrestore(&worker->lock, flags);
37be45d4 1502 kthread_flush_work(work);
fe99a4f4 1503 raw_spin_lock_irqsave(&worker->lock, flags);
37be45d4
PM
1504 work->canceling--;
1505
1506out_fast:
fe99a4f4 1507 raw_spin_unlock_irqrestore(&worker->lock, flags);
37be45d4
PM
1508out:
1509 return ret;
1510}
1511
1512/**
1513 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1514 * @work: the kthread work to cancel
1515 *
1516 * Cancel @work and wait for its execution to finish. This function
1517 * can be used even if the work re-queues itself. On return from this
1518 * function, @work is guaranteed to be not pending or executing on any CPU.
1519 *
1520 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1521 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1522 *
1523 * The caller must ensure that the worker on which @work was last
1524 * queued can't be destroyed before this function returns.
1525 *
1526 * Return: %true if @work was pending, %false otherwise.
1527 */
1528bool kthread_cancel_work_sync(struct kthread_work *work)
1529{
1530 return __kthread_cancel_work_sync(work, false);
1531}
1532EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1533
1534/**
1535 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1536 * wait for it to finish.
1537 * @dwork: the kthread delayed work to cancel
1538 *
1539 * This is kthread_cancel_work_sync() for delayed works.
1540 *
1541 * Return: %true if @dwork was pending, %false otherwise.
1542 */
1543bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1544{
1545 return __kthread_cancel_work_sync(&dwork->work, true);
1546}
1547EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1548
b56c0d89 1549/**
3989144f 1550 * kthread_flush_worker - flush all current works on a kthread_worker
b56c0d89
TH
1551 * @worker: worker to flush
1552 *
1553 * Wait until all currently executing or pending works on @worker are
1554 * finished.
1555 */
3989144f 1556void kthread_flush_worker(struct kthread_worker *worker)
b56c0d89
TH
1557{
1558 struct kthread_flush_work fwork = {
1559 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1560 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1561 };
1562
3989144f 1563 kthread_queue_work(worker, &fwork.work);
b56c0d89
TH
1564 wait_for_completion(&fwork.done);
1565}
3989144f 1566EXPORT_SYMBOL_GPL(kthread_flush_worker);
35033fe9
PM
1567
1568/**
1569 * kthread_destroy_worker - destroy a kthread worker
1570 * @worker: worker to be destroyed
1571 *
1572 * Flush and destroy @worker. The simple flush is enough because the kthread
1573 * worker API is used only in trivial scenarios. There are no multi-step state
1574 * machines needed.
eb79fa7e
Z
1575 *
1576 * Note that this function is not responsible for handling delayed work, so
1577 * caller should be responsible for queuing or canceling all delayed work items
1578 * before invoke this function.
35033fe9
PM
1579 */
1580void kthread_destroy_worker(struct kthread_worker *worker)
1581{
1582 struct task_struct *task;
1583
1584 task = worker->task;
1585 if (WARN_ON(!task))
1586 return;
1587
1588 kthread_flush_worker(worker);
1589 kthread_stop(task);
eb79fa7e 1590 WARN_ON(!list_empty(&worker->delayed_work_list));
35033fe9
PM
1591 WARN_ON(!list_empty(&worker->work_list));
1592 kfree(worker);
1593}
1594EXPORT_SYMBOL(kthread_destroy_worker);
05e3db95 1595
f5678e7f
CH
1596/**
1597 * kthread_use_mm - make the calling kthread operate on an address space
1598 * @mm: address space to operate on
9bf5b9eb 1599 */
f5678e7f 1600void kthread_use_mm(struct mm_struct *mm)
9bf5b9eb
CH
1601{
1602 struct mm_struct *active_mm;
1603 struct task_struct *tsk = current;
1604
f5678e7f
CH
1605 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1606 WARN_ON_ONCE(tsk->mm);
1607
aa464ba9
NP
1608 /*
1609 * It is possible for mm to be the same as tsk->active_mm, but
1610 * we must still mmgrab(mm) and mmdrop_lazy_tlb(active_mm),
1611 * because these references are not equivalent.
1612 */
6cad87b0
NP
1613 mmgrab(mm);
1614
9bf5b9eb 1615 task_lock(tsk);
38cf307c
PZ
1616 /* Hold off tlb flush IPIs while switching mm's */
1617 local_irq_disable();
9bf5b9eb 1618 active_mm = tsk->active_mm;
6cad87b0 1619 tsk->active_mm = mm;
9bf5b9eb 1620 tsk->mm = mm;
618758ed 1621 membarrier_update_current_mm(mm);
38cf307c
PZ
1622 switch_mm_irqs_off(active_mm, mm, tsk);
1623 local_irq_enable();
9bf5b9eb
CH
1624 task_unlock(tsk);
1625#ifdef finish_arch_post_lock_switch
1626 finish_arch_post_lock_switch();
1627#endif
1628
618758ed
MD
1629 /*
1630 * When a kthread starts operating on an address space, the loop
1631 * in membarrier_{private,global}_expedited() may not observe
1632 * that tsk->mm, and not issue an IPI. Membarrier requires a
1633 * memory barrier after storing to tsk->mm, before accessing
1634 * user-space memory. A full memory barrier for membarrier
1635 * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by
aa464ba9 1636 * mmdrop_lazy_tlb().
618758ed 1637 */
aa464ba9 1638 mmdrop_lazy_tlb(active_mm);
9bf5b9eb 1639}
f5678e7f 1640EXPORT_SYMBOL_GPL(kthread_use_mm);
9bf5b9eb 1641
f5678e7f
CH
1642/**
1643 * kthread_unuse_mm - reverse the effect of kthread_use_mm()
1644 * @mm: address space to operate on
9bf5b9eb 1645 */
f5678e7f 1646void kthread_unuse_mm(struct mm_struct *mm)
9bf5b9eb
CH
1647{
1648 struct task_struct *tsk = current;
1649
f5678e7f
CH
1650 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1651 WARN_ON_ONCE(!tsk->mm);
1652
9bf5b9eb 1653 task_lock(tsk);
618758ed
MD
1654 /*
1655 * When a kthread stops operating on an address space, the loop
1656 * in membarrier_{private,global}_expedited() may not observe
1657 * that tsk->mm, and not issue an IPI. Membarrier requires a
1658 * memory barrier after accessing user-space memory, before
1659 * clearing tsk->mm.
1660 */
1661 smp_mb__after_spinlock();
38cf307c 1662 local_irq_disable();
9bf5b9eb 1663 tsk->mm = NULL;
618758ed 1664 membarrier_update_current_mm(NULL);
aa464ba9 1665 mmgrab_lazy_tlb(mm);
9bf5b9eb
CH
1666 /* active_mm is still 'mm' */
1667 enter_lazy_tlb(mm, tsk);
38cf307c 1668 local_irq_enable();
9bf5b9eb 1669 task_unlock(tsk);
aa464ba9
NP
1670
1671 mmdrop(mm);
9bf5b9eb 1672}
f5678e7f 1673EXPORT_SYMBOL_GPL(kthread_unuse_mm);
9bf5b9eb 1674
0b508bc9 1675#ifdef CONFIG_BLK_CGROUP
05e3db95
SL
1676/**
1677 * kthread_associate_blkcg - associate blkcg to current kthread
1678 * @css: the cgroup info
1679 *
1680 * Current thread must be a kthread. The thread is running jobs on behalf of
1681 * other threads. In some cases, we expect the jobs attach cgroup info of
1682 * original threads instead of that of current thread. This function stores
1683 * original thread's cgroup info in current kthread context for later
1684 * retrieval.
1685 */
1686void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1687{
1688 struct kthread *kthread;
1689
1690 if (!(current->flags & PF_KTHREAD))
1691 return;
1692 kthread = to_kthread(current);
1693 if (!kthread)
1694 return;
1695
1696 if (kthread->blkcg_css) {
1697 css_put(kthread->blkcg_css);
1698 kthread->blkcg_css = NULL;
1699 }
1700 if (css) {
1701 css_get(css);
1702 kthread->blkcg_css = css;
1703 }
1704}
1705EXPORT_SYMBOL(kthread_associate_blkcg);
1706
1707/**
1708 * kthread_blkcg - get associated blkcg css of current kthread
1709 *
1710 * Current thread must be a kthread.
1711 */
1712struct cgroup_subsys_state *kthread_blkcg(void)
1713{
1714 struct kthread *kthread;
1715
1716 if (current->flags & PF_KTHREAD) {
1717 kthread = to_kthread(current);
1718 if (kthread)
1719 return kthread->blkcg_css;
1720 }
1721 return NULL;
1722}
05e3db95 1723#endif