]> git.proxmox.com Git - mirror_ubuntu-eoan-kernel.git/blob - kernel/kthread.c
bpf: Fix bpf_event_output re-entry issue
[mirror_ubuntu-eoan-kernel.git] / kernel / kthread.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel thread helper functions.
3 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
4 *
5 * Creation is done via kthreadd, so that we get a clean environment
6 * even if we're invoked from userspace (think modprobe, hotplug cpu,
7 * etc.).
8 */
9 #include <uapi/linux/sched/types.h>
10 #include <linux/sched.h>
11 #include <linux/sched/task.h>
12 #include <linux/kthread.h>
13 #include <linux/completion.h>
14 #include <linux/err.h>
15 #include <linux/cgroup.h>
16 #include <linux/cpuset.h>
17 #include <linux/unistd.h>
18 #include <linux/file.h>
19 #include <linux/export.h>
20 #include <linux/mutex.h>
21 #include <linux/slab.h>
22 #include <linux/freezer.h>
23 #include <linux/ptrace.h>
24 #include <linux/uaccess.h>
25 #include <linux/numa.h>
26 #include <trace/events/sched.h>
27
28 static DEFINE_SPINLOCK(kthread_create_lock);
29 static LIST_HEAD(kthread_create_list);
30 struct task_struct *kthreadd_task;
31
32 struct kthread_create_info
33 {
34 /* Information passed to kthread() from kthreadd. */
35 int (*threadfn)(void *data);
36 void *data;
37 int node;
38
39 /* Result passed back to kthread_create() from kthreadd. */
40 struct task_struct *result;
41 struct completion *done;
42
43 struct list_head list;
44 };
45
46 struct kthread {
47 unsigned long flags;
48 unsigned int cpu;
49 void *data;
50 struct completion parked;
51 struct completion exited;
52 #ifdef CONFIG_BLK_CGROUP
53 struct cgroup_subsys_state *blkcg_css;
54 #endif
55 };
56
57 enum KTHREAD_BITS {
58 KTHREAD_IS_PER_CPU = 0,
59 KTHREAD_SHOULD_STOP,
60 KTHREAD_SHOULD_PARK,
61 };
62
63 static inline void set_kthread_struct(void *kthread)
64 {
65 /*
66 * We abuse ->set_child_tid to avoid the new member and because it
67 * can't be wrongly copied by copy_process(). We also rely on fact
68 * that the caller can't exec, so PF_KTHREAD can't be cleared.
69 */
70 current->set_child_tid = (__force void __user *)kthread;
71 }
72
73 static inline struct kthread *to_kthread(struct task_struct *k)
74 {
75 WARN_ON(!(k->flags & PF_KTHREAD));
76 return (__force void *)k->set_child_tid;
77 }
78
79 void free_kthread_struct(struct task_struct *k)
80 {
81 struct kthread *kthread;
82
83 /*
84 * Can be NULL if this kthread was created by kernel_thread()
85 * or if kmalloc() in kthread() failed.
86 */
87 kthread = to_kthread(k);
88 #ifdef CONFIG_BLK_CGROUP
89 WARN_ON_ONCE(kthread && kthread->blkcg_css);
90 #endif
91 kfree(kthread);
92 }
93
94 /**
95 * kthread_should_stop - should this kthread return now?
96 *
97 * When someone calls kthread_stop() on your kthread, it will be woken
98 * and this will return true. You should then return, and your return
99 * value will be passed through to kthread_stop().
100 */
101 bool kthread_should_stop(void)
102 {
103 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
104 }
105 EXPORT_SYMBOL(kthread_should_stop);
106
107 bool __kthread_should_park(struct task_struct *k)
108 {
109 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
110 }
111 EXPORT_SYMBOL_GPL(__kthread_should_park);
112
113 /**
114 * kthread_should_park - should this kthread park now?
115 *
116 * When someone calls kthread_park() on your kthread, it will be woken
117 * and this will return true. You should then do the necessary
118 * cleanup and call kthread_parkme()
119 *
120 * Similar to kthread_should_stop(), but this keeps the thread alive
121 * and in a park position. kthread_unpark() "restarts" the thread and
122 * calls the thread function again.
123 */
124 bool kthread_should_park(void)
125 {
126 return __kthread_should_park(current);
127 }
128 EXPORT_SYMBOL_GPL(kthread_should_park);
129
130 /**
131 * kthread_freezable_should_stop - should this freezable kthread return now?
132 * @was_frozen: optional out parameter, indicates whether %current was frozen
133 *
134 * kthread_should_stop() for freezable kthreads, which will enter
135 * refrigerator if necessary. This function is safe from kthread_stop() /
136 * freezer deadlock and freezable kthreads should use this function instead
137 * of calling try_to_freeze() directly.
138 */
139 bool kthread_freezable_should_stop(bool *was_frozen)
140 {
141 bool frozen = false;
142
143 might_sleep();
144
145 if (unlikely(freezing(current)))
146 frozen = __refrigerator(true);
147
148 if (was_frozen)
149 *was_frozen = frozen;
150
151 return kthread_should_stop();
152 }
153 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
154
155 /**
156 * kthread_data - return data value specified on kthread creation
157 * @task: kthread task in question
158 *
159 * Return the data value specified when kthread @task was created.
160 * The caller is responsible for ensuring the validity of @task when
161 * calling this function.
162 */
163 void *kthread_data(struct task_struct *task)
164 {
165 return to_kthread(task)->data;
166 }
167
168 /**
169 * kthread_probe_data - speculative version of kthread_data()
170 * @task: possible kthread task in question
171 *
172 * @task could be a kthread task. Return the data value specified when it
173 * was created if accessible. If @task isn't a kthread task or its data is
174 * inaccessible for any reason, %NULL is returned. This function requires
175 * that @task itself is safe to dereference.
176 */
177 void *kthread_probe_data(struct task_struct *task)
178 {
179 struct kthread *kthread = to_kthread(task);
180 void *data = NULL;
181
182 probe_kernel_read(&data, &kthread->data, sizeof(data));
183 return data;
184 }
185
186 static void __kthread_parkme(struct kthread *self)
187 {
188 for (;;) {
189 /*
190 * TASK_PARKED is a special state; we must serialize against
191 * possible pending wakeups to avoid store-store collisions on
192 * task->state.
193 *
194 * Such a collision might possibly result in the task state
195 * changin from TASK_PARKED and us failing the
196 * wait_task_inactive() in kthread_park().
197 */
198 set_special_state(TASK_PARKED);
199 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
200 break;
201
202 complete(&self->parked);
203 schedule();
204 }
205 __set_current_state(TASK_RUNNING);
206 }
207
208 void kthread_parkme(void)
209 {
210 __kthread_parkme(to_kthread(current));
211 }
212 EXPORT_SYMBOL_GPL(kthread_parkme);
213
214 static int kthread(void *_create)
215 {
216 /* Copy data: it's on kthread's stack */
217 struct kthread_create_info *create = _create;
218 int (*threadfn)(void *data) = create->threadfn;
219 void *data = create->data;
220 struct completion *done;
221 struct kthread *self;
222 int ret;
223
224 self = kzalloc(sizeof(*self), GFP_KERNEL);
225 set_kthread_struct(self);
226
227 /* If user was SIGKILLed, I release the structure. */
228 done = xchg(&create->done, NULL);
229 if (!done) {
230 kfree(create);
231 do_exit(-EINTR);
232 }
233
234 if (!self) {
235 create->result = ERR_PTR(-ENOMEM);
236 complete(done);
237 do_exit(-ENOMEM);
238 }
239
240 self->data = data;
241 init_completion(&self->exited);
242 init_completion(&self->parked);
243 current->vfork_done = &self->exited;
244
245 /* OK, tell user we're spawned, wait for stop or wakeup */
246 __set_current_state(TASK_UNINTERRUPTIBLE);
247 create->result = current;
248 complete(done);
249 schedule();
250
251 ret = -EINTR;
252 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
253 cgroup_kthread_ready();
254 __kthread_parkme(self);
255 ret = threadfn(data);
256 }
257 do_exit(ret);
258 }
259
260 /* called from do_fork() to get node information for about to be created task */
261 int tsk_fork_get_node(struct task_struct *tsk)
262 {
263 #ifdef CONFIG_NUMA
264 if (tsk == kthreadd_task)
265 return tsk->pref_node_fork;
266 #endif
267 return NUMA_NO_NODE;
268 }
269
270 static void create_kthread(struct kthread_create_info *create)
271 {
272 int pid;
273
274 #ifdef CONFIG_NUMA
275 current->pref_node_fork = create->node;
276 #endif
277 /* We want our own signal handler (we take no signals by default). */
278 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
279 if (pid < 0) {
280 /* If user was SIGKILLed, I release the structure. */
281 struct completion *done = xchg(&create->done, NULL);
282
283 if (!done) {
284 kfree(create);
285 return;
286 }
287 create->result = ERR_PTR(pid);
288 complete(done);
289 }
290 }
291
292 static __printf(4, 0)
293 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
294 void *data, int node,
295 const char namefmt[],
296 va_list args)
297 {
298 DECLARE_COMPLETION_ONSTACK(done);
299 struct task_struct *task;
300 struct kthread_create_info *create = kmalloc(sizeof(*create),
301 GFP_KERNEL);
302
303 if (!create)
304 return ERR_PTR(-ENOMEM);
305 create->threadfn = threadfn;
306 create->data = data;
307 create->node = node;
308 create->done = &done;
309
310 spin_lock(&kthread_create_lock);
311 list_add_tail(&create->list, &kthread_create_list);
312 spin_unlock(&kthread_create_lock);
313
314 wake_up_process(kthreadd_task);
315 /*
316 * Wait for completion in killable state, for I might be chosen by
317 * the OOM killer while kthreadd is trying to allocate memory for
318 * new kernel thread.
319 */
320 if (unlikely(wait_for_completion_killable(&done))) {
321 int i = 0;
322
323 /*
324 * I got SIGKILL, but wait for 10 more seconds for completion
325 * unless chosen by the OOM killer. This delay is there as a
326 * workaround for boot failure caused by SIGKILL upon device
327 * driver initialization timeout.
328 */
329 while (i++ < 10 && !test_tsk_thread_flag(current, TIF_MEMDIE))
330 if (wait_for_completion_timeout(&done, HZ))
331 goto ready;
332 /*
333 * If I was SIGKILLed before kthreadd (or new kernel thread)
334 * calls complete(), leave the cleanup of this structure to
335 * that thread.
336 */
337 if (xchg(&create->done, NULL))
338 return ERR_PTR(-EINTR);
339 /*
340 * kthreadd (or new kernel thread) will call complete()
341 * shortly.
342 */
343 wait_for_completion(&done);
344 }
345 ready:
346 task = create->result;
347 if (!IS_ERR(task)) {
348 static const struct sched_param param = { .sched_priority = 0 };
349 char name[TASK_COMM_LEN];
350
351 /*
352 * task is already visible to other tasks, so updating
353 * COMM must be protected.
354 */
355 vsnprintf(name, sizeof(name), namefmt, args);
356 set_task_comm(task, name);
357 /*
358 * root may have changed our (kthreadd's) priority or CPU mask.
359 * The kernel thread should not inherit these properties.
360 */
361 sched_setscheduler_nocheck(task, SCHED_NORMAL, &param);
362 set_cpus_allowed_ptr(task, cpu_all_mask);
363 }
364 kfree(create);
365 return task;
366 }
367
368 /**
369 * kthread_create_on_node - create a kthread.
370 * @threadfn: the function to run until signal_pending(current).
371 * @data: data ptr for @threadfn.
372 * @node: task and thread structures for the thread are allocated on this node
373 * @namefmt: printf-style name for the thread.
374 *
375 * Description: This helper function creates and names a kernel
376 * thread. The thread will be stopped: use wake_up_process() to start
377 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
378 * is affine to all CPUs.
379 *
380 * If thread is going to be bound on a particular cpu, give its node
381 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
382 * When woken, the thread will run @threadfn() with @data as its
383 * argument. @threadfn() can either call do_exit() directly if it is a
384 * standalone thread for which no one will call kthread_stop(), or
385 * return when 'kthread_should_stop()' is true (which means
386 * kthread_stop() has been called). The return value should be zero
387 * or a negative error number; it will be passed to kthread_stop().
388 *
389 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
390 */
391 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
392 void *data, int node,
393 const char namefmt[],
394 ...)
395 {
396 struct task_struct *task;
397 va_list args;
398
399 va_start(args, namefmt);
400 task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
401 va_end(args);
402
403 return task;
404 }
405 EXPORT_SYMBOL(kthread_create_on_node);
406
407 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
408 {
409 unsigned long flags;
410
411 if (!wait_task_inactive(p, state)) {
412 WARN_ON(1);
413 return;
414 }
415
416 /* It's safe because the task is inactive. */
417 raw_spin_lock_irqsave(&p->pi_lock, flags);
418 do_set_cpus_allowed(p, mask);
419 p->flags |= PF_NO_SETAFFINITY;
420 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
421 }
422
423 static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
424 {
425 __kthread_bind_mask(p, cpumask_of(cpu), state);
426 }
427
428 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
429 {
430 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
431 }
432
433 /**
434 * kthread_bind - bind a just-created kthread to a cpu.
435 * @p: thread created by kthread_create().
436 * @cpu: cpu (might not be online, must be possible) for @k to run on.
437 *
438 * Description: This function is equivalent to set_cpus_allowed(),
439 * except that @cpu doesn't need to be online, and the thread must be
440 * stopped (i.e., just returned from kthread_create()).
441 */
442 void kthread_bind(struct task_struct *p, unsigned int cpu)
443 {
444 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
445 }
446 EXPORT_SYMBOL(kthread_bind);
447
448 /**
449 * kthread_create_on_cpu - Create a cpu bound kthread
450 * @threadfn: the function to run until signal_pending(current).
451 * @data: data ptr for @threadfn.
452 * @cpu: The cpu on which the thread should be bound,
453 * @namefmt: printf-style name for the thread. Format is restricted
454 * to "name.*%u". Code fills in cpu number.
455 *
456 * Description: This helper function creates and names a kernel thread
457 * The thread will be woken and put into park mode.
458 */
459 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
460 void *data, unsigned int cpu,
461 const char *namefmt)
462 {
463 struct task_struct *p;
464
465 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
466 cpu);
467 if (IS_ERR(p))
468 return p;
469 kthread_bind(p, cpu);
470 /* CPU hotplug need to bind once again when unparking the thread. */
471 set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
472 to_kthread(p)->cpu = cpu;
473 return p;
474 }
475
476 /**
477 * kthread_unpark - unpark a thread created by kthread_create().
478 * @k: thread created by kthread_create().
479 *
480 * Sets kthread_should_park() for @k to return false, wakes it, and
481 * waits for it to return. If the thread is marked percpu then its
482 * bound to the cpu again.
483 */
484 void kthread_unpark(struct task_struct *k)
485 {
486 struct kthread *kthread = to_kthread(k);
487
488 /*
489 * Newly created kthread was parked when the CPU was offline.
490 * The binding was lost and we need to set it again.
491 */
492 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
493 __kthread_bind(k, kthread->cpu, TASK_PARKED);
494
495 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
496 /*
497 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
498 */
499 wake_up_state(k, TASK_PARKED);
500 }
501 EXPORT_SYMBOL_GPL(kthread_unpark);
502
503 /**
504 * kthread_park - park a thread created by kthread_create().
505 * @k: thread created by kthread_create().
506 *
507 * Sets kthread_should_park() for @k to return true, wakes it, and
508 * waits for it to return. This can also be called after kthread_create()
509 * instead of calling wake_up_process(): the thread will park without
510 * calling threadfn().
511 *
512 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
513 * If called by the kthread itself just the park bit is set.
514 */
515 int kthread_park(struct task_struct *k)
516 {
517 struct kthread *kthread = to_kthread(k);
518
519 if (WARN_ON(k->flags & PF_EXITING))
520 return -ENOSYS;
521
522 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
523 return -EBUSY;
524
525 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
526 if (k != current) {
527 wake_up_process(k);
528 /*
529 * Wait for __kthread_parkme() to complete(), this means we
530 * _will_ have TASK_PARKED and are about to call schedule().
531 */
532 wait_for_completion(&kthread->parked);
533 /*
534 * Now wait for that schedule() to complete and the task to
535 * get scheduled out.
536 */
537 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
538 }
539
540 return 0;
541 }
542 EXPORT_SYMBOL_GPL(kthread_park);
543
544 /**
545 * kthread_stop - stop a thread created by kthread_create().
546 * @k: thread created by kthread_create().
547 *
548 * Sets kthread_should_stop() for @k to return true, wakes it, and
549 * waits for it to exit. This can also be called after kthread_create()
550 * instead of calling wake_up_process(): the thread will exit without
551 * calling threadfn().
552 *
553 * If threadfn() may call do_exit() itself, the caller must ensure
554 * task_struct can't go away.
555 *
556 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
557 * was never called.
558 */
559 int kthread_stop(struct task_struct *k)
560 {
561 struct kthread *kthread;
562 int ret;
563
564 trace_sched_kthread_stop(k);
565
566 get_task_struct(k);
567 kthread = to_kthread(k);
568 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
569 kthread_unpark(k);
570 wake_up_process(k);
571 wait_for_completion(&kthread->exited);
572 ret = k->exit_code;
573 put_task_struct(k);
574
575 trace_sched_kthread_stop_ret(ret);
576 return ret;
577 }
578 EXPORT_SYMBOL(kthread_stop);
579
580 int kthreadd(void *unused)
581 {
582 struct task_struct *tsk = current;
583
584 /* Setup a clean context for our children to inherit. */
585 set_task_comm(tsk, "kthreadd");
586 ignore_signals(tsk);
587 set_cpus_allowed_ptr(tsk, cpu_all_mask);
588 set_mems_allowed(node_states[N_MEMORY]);
589
590 current->flags |= PF_NOFREEZE;
591 cgroup_init_kthreadd();
592
593 for (;;) {
594 set_current_state(TASK_INTERRUPTIBLE);
595 if (list_empty(&kthread_create_list))
596 schedule();
597 __set_current_state(TASK_RUNNING);
598
599 spin_lock(&kthread_create_lock);
600 while (!list_empty(&kthread_create_list)) {
601 struct kthread_create_info *create;
602
603 create = list_entry(kthread_create_list.next,
604 struct kthread_create_info, list);
605 list_del_init(&create->list);
606 spin_unlock(&kthread_create_lock);
607
608 create_kthread(create);
609
610 spin_lock(&kthread_create_lock);
611 }
612 spin_unlock(&kthread_create_lock);
613 }
614
615 return 0;
616 }
617
618 void __kthread_init_worker(struct kthread_worker *worker,
619 const char *name,
620 struct lock_class_key *key)
621 {
622 memset(worker, 0, sizeof(struct kthread_worker));
623 raw_spin_lock_init(&worker->lock);
624 lockdep_set_class_and_name(&worker->lock, key, name);
625 INIT_LIST_HEAD(&worker->work_list);
626 INIT_LIST_HEAD(&worker->delayed_work_list);
627 }
628 EXPORT_SYMBOL_GPL(__kthread_init_worker);
629
630 /**
631 * kthread_worker_fn - kthread function to process kthread_worker
632 * @worker_ptr: pointer to initialized kthread_worker
633 *
634 * This function implements the main cycle of kthread worker. It processes
635 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
636 * is empty.
637 *
638 * The works are not allowed to keep any locks, disable preemption or interrupts
639 * when they finish. There is defined a safe point for freezing when one work
640 * finishes and before a new one is started.
641 *
642 * Also the works must not be handled by more than one worker at the same time,
643 * see also kthread_queue_work().
644 */
645 int kthread_worker_fn(void *worker_ptr)
646 {
647 struct kthread_worker *worker = worker_ptr;
648 struct kthread_work *work;
649
650 /*
651 * FIXME: Update the check and remove the assignment when all kthread
652 * worker users are created using kthread_create_worker*() functions.
653 */
654 WARN_ON(worker->task && worker->task != current);
655 worker->task = current;
656
657 if (worker->flags & KTW_FREEZABLE)
658 set_freezable();
659
660 repeat:
661 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
662
663 if (kthread_should_stop()) {
664 __set_current_state(TASK_RUNNING);
665 raw_spin_lock_irq(&worker->lock);
666 worker->task = NULL;
667 raw_spin_unlock_irq(&worker->lock);
668 return 0;
669 }
670
671 work = NULL;
672 raw_spin_lock_irq(&worker->lock);
673 if (!list_empty(&worker->work_list)) {
674 work = list_first_entry(&worker->work_list,
675 struct kthread_work, node);
676 list_del_init(&work->node);
677 }
678 worker->current_work = work;
679 raw_spin_unlock_irq(&worker->lock);
680
681 if (work) {
682 __set_current_state(TASK_RUNNING);
683 work->func(work);
684 } else if (!freezing(current))
685 schedule();
686
687 try_to_freeze();
688 cond_resched();
689 goto repeat;
690 }
691 EXPORT_SYMBOL_GPL(kthread_worker_fn);
692
693 static __printf(3, 0) struct kthread_worker *
694 __kthread_create_worker(int cpu, unsigned int flags,
695 const char namefmt[], va_list args)
696 {
697 struct kthread_worker *worker;
698 struct task_struct *task;
699 int node = NUMA_NO_NODE;
700
701 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
702 if (!worker)
703 return ERR_PTR(-ENOMEM);
704
705 kthread_init_worker(worker);
706
707 if (cpu >= 0)
708 node = cpu_to_node(cpu);
709
710 task = __kthread_create_on_node(kthread_worker_fn, worker,
711 node, namefmt, args);
712 if (IS_ERR(task))
713 goto fail_task;
714
715 if (cpu >= 0)
716 kthread_bind(task, cpu);
717
718 worker->flags = flags;
719 worker->task = task;
720 wake_up_process(task);
721 return worker;
722
723 fail_task:
724 kfree(worker);
725 return ERR_CAST(task);
726 }
727
728 /**
729 * kthread_create_worker - create a kthread worker
730 * @flags: flags modifying the default behavior of the worker
731 * @namefmt: printf-style name for the kthread worker (task).
732 *
733 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
734 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
735 * when the worker was SIGKILLed.
736 */
737 struct kthread_worker *
738 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
739 {
740 struct kthread_worker *worker;
741 va_list args;
742
743 va_start(args, namefmt);
744 worker = __kthread_create_worker(-1, flags, namefmt, args);
745 va_end(args);
746
747 return worker;
748 }
749 EXPORT_SYMBOL(kthread_create_worker);
750
751 /**
752 * kthread_create_worker_on_cpu - create a kthread worker and bind it
753 * it to a given CPU and the associated NUMA node.
754 * @cpu: CPU number
755 * @flags: flags modifying the default behavior of the worker
756 * @namefmt: printf-style name for the kthread worker (task).
757 *
758 * Use a valid CPU number if you want to bind the kthread worker
759 * to the given CPU and the associated NUMA node.
760 *
761 * A good practice is to add the cpu number also into the worker name.
762 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
763 *
764 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
765 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
766 * when the worker was SIGKILLed.
767 */
768 struct kthread_worker *
769 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
770 const char namefmt[], ...)
771 {
772 struct kthread_worker *worker;
773 va_list args;
774
775 va_start(args, namefmt);
776 worker = __kthread_create_worker(cpu, flags, namefmt, args);
777 va_end(args);
778
779 return worker;
780 }
781 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
782
783 /*
784 * Returns true when the work could not be queued at the moment.
785 * It happens when it is already pending in a worker list
786 * or when it is being cancelled.
787 */
788 static inline bool queuing_blocked(struct kthread_worker *worker,
789 struct kthread_work *work)
790 {
791 lockdep_assert_held(&worker->lock);
792
793 return !list_empty(&work->node) || work->canceling;
794 }
795
796 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
797 struct kthread_work *work)
798 {
799 lockdep_assert_held(&worker->lock);
800 WARN_ON_ONCE(!list_empty(&work->node));
801 /* Do not use a work with >1 worker, see kthread_queue_work() */
802 WARN_ON_ONCE(work->worker && work->worker != worker);
803 }
804
805 /* insert @work before @pos in @worker */
806 static void kthread_insert_work(struct kthread_worker *worker,
807 struct kthread_work *work,
808 struct list_head *pos)
809 {
810 kthread_insert_work_sanity_check(worker, work);
811
812 list_add_tail(&work->node, pos);
813 work->worker = worker;
814 if (!worker->current_work && likely(worker->task))
815 wake_up_process(worker->task);
816 }
817
818 /**
819 * kthread_queue_work - queue a kthread_work
820 * @worker: target kthread_worker
821 * @work: kthread_work to queue
822 *
823 * Queue @work to work processor @task for async execution. @task
824 * must have been created with kthread_worker_create(). Returns %true
825 * if @work was successfully queued, %false if it was already pending.
826 *
827 * Reinitialize the work if it needs to be used by another worker.
828 * For example, when the worker was stopped and started again.
829 */
830 bool kthread_queue_work(struct kthread_worker *worker,
831 struct kthread_work *work)
832 {
833 bool ret = false;
834 unsigned long flags;
835
836 raw_spin_lock_irqsave(&worker->lock, flags);
837 if (!queuing_blocked(worker, work)) {
838 kthread_insert_work(worker, work, &worker->work_list);
839 ret = true;
840 }
841 raw_spin_unlock_irqrestore(&worker->lock, flags);
842 return ret;
843 }
844 EXPORT_SYMBOL_GPL(kthread_queue_work);
845
846 /**
847 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
848 * delayed work when the timer expires.
849 * @t: pointer to the expired timer
850 *
851 * The format of the function is defined by struct timer_list.
852 * It should have been called from irqsafe timer with irq already off.
853 */
854 void kthread_delayed_work_timer_fn(struct timer_list *t)
855 {
856 struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
857 struct kthread_work *work = &dwork->work;
858 struct kthread_worker *worker = work->worker;
859 unsigned long flags;
860
861 /*
862 * This might happen when a pending work is reinitialized.
863 * It means that it is used a wrong way.
864 */
865 if (WARN_ON_ONCE(!worker))
866 return;
867
868 raw_spin_lock_irqsave(&worker->lock, flags);
869 /* Work must not be used with >1 worker, see kthread_queue_work(). */
870 WARN_ON_ONCE(work->worker != worker);
871
872 /* Move the work from worker->delayed_work_list. */
873 WARN_ON_ONCE(list_empty(&work->node));
874 list_del_init(&work->node);
875 kthread_insert_work(worker, work, &worker->work_list);
876
877 raw_spin_unlock_irqrestore(&worker->lock, flags);
878 }
879 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
880
881 void __kthread_queue_delayed_work(struct kthread_worker *worker,
882 struct kthread_delayed_work *dwork,
883 unsigned long delay)
884 {
885 struct timer_list *timer = &dwork->timer;
886 struct kthread_work *work = &dwork->work;
887
888 WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn);
889
890 /*
891 * If @delay is 0, queue @dwork->work immediately. This is for
892 * both optimization and correctness. The earliest @timer can
893 * expire is on the closest next tick and delayed_work users depend
894 * on that there's no such delay when @delay is 0.
895 */
896 if (!delay) {
897 kthread_insert_work(worker, work, &worker->work_list);
898 return;
899 }
900
901 /* Be paranoid and try to detect possible races already now. */
902 kthread_insert_work_sanity_check(worker, work);
903
904 list_add(&work->node, &worker->delayed_work_list);
905 work->worker = worker;
906 timer->expires = jiffies + delay;
907 add_timer(timer);
908 }
909
910 /**
911 * kthread_queue_delayed_work - queue the associated kthread work
912 * after a delay.
913 * @worker: target kthread_worker
914 * @dwork: kthread_delayed_work to queue
915 * @delay: number of jiffies to wait before queuing
916 *
917 * If the work has not been pending it starts a timer that will queue
918 * the work after the given @delay. If @delay is zero, it queues the
919 * work immediately.
920 *
921 * Return: %false if the @work has already been pending. It means that
922 * either the timer was running or the work was queued. It returns %true
923 * otherwise.
924 */
925 bool kthread_queue_delayed_work(struct kthread_worker *worker,
926 struct kthread_delayed_work *dwork,
927 unsigned long delay)
928 {
929 struct kthread_work *work = &dwork->work;
930 unsigned long flags;
931 bool ret = false;
932
933 raw_spin_lock_irqsave(&worker->lock, flags);
934
935 if (!queuing_blocked(worker, work)) {
936 __kthread_queue_delayed_work(worker, dwork, delay);
937 ret = true;
938 }
939
940 raw_spin_unlock_irqrestore(&worker->lock, flags);
941 return ret;
942 }
943 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
944
945 struct kthread_flush_work {
946 struct kthread_work work;
947 struct completion done;
948 };
949
950 static void kthread_flush_work_fn(struct kthread_work *work)
951 {
952 struct kthread_flush_work *fwork =
953 container_of(work, struct kthread_flush_work, work);
954 complete(&fwork->done);
955 }
956
957 /**
958 * kthread_flush_work - flush a kthread_work
959 * @work: work to flush
960 *
961 * If @work is queued or executing, wait for it to finish execution.
962 */
963 void kthread_flush_work(struct kthread_work *work)
964 {
965 struct kthread_flush_work fwork = {
966 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
967 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
968 };
969 struct kthread_worker *worker;
970 bool noop = false;
971
972 worker = work->worker;
973 if (!worker)
974 return;
975
976 raw_spin_lock_irq(&worker->lock);
977 /* Work must not be used with >1 worker, see kthread_queue_work(). */
978 WARN_ON_ONCE(work->worker != worker);
979
980 if (!list_empty(&work->node))
981 kthread_insert_work(worker, &fwork.work, work->node.next);
982 else if (worker->current_work == work)
983 kthread_insert_work(worker, &fwork.work,
984 worker->work_list.next);
985 else
986 noop = true;
987
988 raw_spin_unlock_irq(&worker->lock);
989
990 if (!noop)
991 wait_for_completion(&fwork.done);
992 }
993 EXPORT_SYMBOL_GPL(kthread_flush_work);
994
995 /*
996 * This function removes the work from the worker queue. Also it makes sure
997 * that it won't get queued later via the delayed work's timer.
998 *
999 * The work might still be in use when this function finishes. See the
1000 * current_work proceed by the worker.
1001 *
1002 * Return: %true if @work was pending and successfully canceled,
1003 * %false if @work was not pending
1004 */
1005 static bool __kthread_cancel_work(struct kthread_work *work, bool is_dwork,
1006 unsigned long *flags)
1007 {
1008 /* Try to cancel the timer if exists. */
1009 if (is_dwork) {
1010 struct kthread_delayed_work *dwork =
1011 container_of(work, struct kthread_delayed_work, work);
1012 struct kthread_worker *worker = work->worker;
1013
1014 /*
1015 * del_timer_sync() must be called to make sure that the timer
1016 * callback is not running. The lock must be temporary released
1017 * to avoid a deadlock with the callback. In the meantime,
1018 * any queuing is blocked by setting the canceling counter.
1019 */
1020 work->canceling++;
1021 raw_spin_unlock_irqrestore(&worker->lock, *flags);
1022 del_timer_sync(&dwork->timer);
1023 raw_spin_lock_irqsave(&worker->lock, *flags);
1024 work->canceling--;
1025 }
1026
1027 /*
1028 * Try to remove the work from a worker list. It might either
1029 * be from worker->work_list or from worker->delayed_work_list.
1030 */
1031 if (!list_empty(&work->node)) {
1032 list_del_init(&work->node);
1033 return true;
1034 }
1035
1036 return false;
1037 }
1038
1039 /**
1040 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1041 * @worker: kthread worker to use
1042 * @dwork: kthread delayed work to queue
1043 * @delay: number of jiffies to wait before queuing
1044 *
1045 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1046 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1047 * @work is guaranteed to be queued immediately.
1048 *
1049 * Return: %true if @dwork was pending and its timer was modified,
1050 * %false otherwise.
1051 *
1052 * A special case is when the work is being canceled in parallel.
1053 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1054 * or yet another kthread_mod_delayed_work() call. We let the other command
1055 * win and return %false here. The caller is supposed to synchronize these
1056 * operations a reasonable way.
1057 *
1058 * This function is safe to call from any context including IRQ handler.
1059 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1060 * for details.
1061 */
1062 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1063 struct kthread_delayed_work *dwork,
1064 unsigned long delay)
1065 {
1066 struct kthread_work *work = &dwork->work;
1067 unsigned long flags;
1068 int ret = false;
1069
1070 raw_spin_lock_irqsave(&worker->lock, flags);
1071
1072 /* Do not bother with canceling when never queued. */
1073 if (!work->worker)
1074 goto fast_queue;
1075
1076 /* Work must not be used with >1 worker, see kthread_queue_work() */
1077 WARN_ON_ONCE(work->worker != worker);
1078
1079 /* Do not fight with another command that is canceling this work. */
1080 if (work->canceling)
1081 goto out;
1082
1083 ret = __kthread_cancel_work(work, true, &flags);
1084 fast_queue:
1085 __kthread_queue_delayed_work(worker, dwork, delay);
1086 out:
1087 raw_spin_unlock_irqrestore(&worker->lock, flags);
1088 return ret;
1089 }
1090 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1091
1092 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1093 {
1094 struct kthread_worker *worker = work->worker;
1095 unsigned long flags;
1096 int ret = false;
1097
1098 if (!worker)
1099 goto out;
1100
1101 raw_spin_lock_irqsave(&worker->lock, flags);
1102 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1103 WARN_ON_ONCE(work->worker != worker);
1104
1105 ret = __kthread_cancel_work(work, is_dwork, &flags);
1106
1107 if (worker->current_work != work)
1108 goto out_fast;
1109
1110 /*
1111 * The work is in progress and we need to wait with the lock released.
1112 * In the meantime, block any queuing by setting the canceling counter.
1113 */
1114 work->canceling++;
1115 raw_spin_unlock_irqrestore(&worker->lock, flags);
1116 kthread_flush_work(work);
1117 raw_spin_lock_irqsave(&worker->lock, flags);
1118 work->canceling--;
1119
1120 out_fast:
1121 raw_spin_unlock_irqrestore(&worker->lock, flags);
1122 out:
1123 return ret;
1124 }
1125
1126 /**
1127 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1128 * @work: the kthread work to cancel
1129 *
1130 * Cancel @work and wait for its execution to finish. This function
1131 * can be used even if the work re-queues itself. On return from this
1132 * function, @work is guaranteed to be not pending or executing on any CPU.
1133 *
1134 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1135 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1136 *
1137 * The caller must ensure that the worker on which @work was last
1138 * queued can't be destroyed before this function returns.
1139 *
1140 * Return: %true if @work was pending, %false otherwise.
1141 */
1142 bool kthread_cancel_work_sync(struct kthread_work *work)
1143 {
1144 return __kthread_cancel_work_sync(work, false);
1145 }
1146 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1147
1148 /**
1149 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1150 * wait for it to finish.
1151 * @dwork: the kthread delayed work to cancel
1152 *
1153 * This is kthread_cancel_work_sync() for delayed works.
1154 *
1155 * Return: %true if @dwork was pending, %false otherwise.
1156 */
1157 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1158 {
1159 return __kthread_cancel_work_sync(&dwork->work, true);
1160 }
1161 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1162
1163 /**
1164 * kthread_flush_worker - flush all current works on a kthread_worker
1165 * @worker: worker to flush
1166 *
1167 * Wait until all currently executing or pending works on @worker are
1168 * finished.
1169 */
1170 void kthread_flush_worker(struct kthread_worker *worker)
1171 {
1172 struct kthread_flush_work fwork = {
1173 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1174 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1175 };
1176
1177 kthread_queue_work(worker, &fwork.work);
1178 wait_for_completion(&fwork.done);
1179 }
1180 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1181
1182 /**
1183 * kthread_destroy_worker - destroy a kthread worker
1184 * @worker: worker to be destroyed
1185 *
1186 * Flush and destroy @worker. The simple flush is enough because the kthread
1187 * worker API is used only in trivial scenarios. There are no multi-step state
1188 * machines needed.
1189 */
1190 void kthread_destroy_worker(struct kthread_worker *worker)
1191 {
1192 struct task_struct *task;
1193
1194 task = worker->task;
1195 if (WARN_ON(!task))
1196 return;
1197
1198 kthread_flush_worker(worker);
1199 kthread_stop(task);
1200 WARN_ON(!list_empty(&worker->work_list));
1201 kfree(worker);
1202 }
1203 EXPORT_SYMBOL(kthread_destroy_worker);
1204
1205 #ifdef CONFIG_BLK_CGROUP
1206 /**
1207 * kthread_associate_blkcg - associate blkcg to current kthread
1208 * @css: the cgroup info
1209 *
1210 * Current thread must be a kthread. The thread is running jobs on behalf of
1211 * other threads. In some cases, we expect the jobs attach cgroup info of
1212 * original threads instead of that of current thread. This function stores
1213 * original thread's cgroup info in current kthread context for later
1214 * retrieval.
1215 */
1216 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1217 {
1218 struct kthread *kthread;
1219
1220 if (!(current->flags & PF_KTHREAD))
1221 return;
1222 kthread = to_kthread(current);
1223 if (!kthread)
1224 return;
1225
1226 if (kthread->blkcg_css) {
1227 css_put(kthread->blkcg_css);
1228 kthread->blkcg_css = NULL;
1229 }
1230 if (css) {
1231 css_get(css);
1232 kthread->blkcg_css = css;
1233 }
1234 }
1235 EXPORT_SYMBOL(kthread_associate_blkcg);
1236
1237 /**
1238 * kthread_blkcg - get associated blkcg css of current kthread
1239 *
1240 * Current thread must be a kthread.
1241 */
1242 struct cgroup_subsys_state *kthread_blkcg(void)
1243 {
1244 struct kthread *kthread;
1245
1246 if (current->flags & PF_KTHREAD) {
1247 kthread = to_kthread(current);
1248 if (kthread)
1249 return kthread->blkcg_css;
1250 }
1251 return NULL;
1252 }
1253 EXPORT_SYMBOL(kthread_blkcg);
1254 #endif