1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel thread helper functions.
3 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
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,
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>
28 static DEFINE_SPINLOCK(kthread_create_lock);
29 static LIST_HEAD(kthread_create_list);
30 struct task_struct *kthreadd_task;
32 struct kthread_create_info
34 /* Information passed to kthread() from kthreadd. */
35 int (*threadfn)(void *data);
39 /* Result passed back to kthread_create() from kthreadd. */
40 struct task_struct *result;
41 struct completion *done;
43 struct list_head list;
50 struct completion parked;
51 struct completion exited;
52 #ifdef CONFIG_BLK_CGROUP
53 struct cgroup_subsys_state *blkcg_css;
58 KTHREAD_IS_PER_CPU = 0,
63 static inline void set_kthread_struct(void *kthread)
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.
70 current->set_child_tid = (__force void __user *)kthread;
73 static inline struct kthread *to_kthread(struct task_struct *k)
75 WARN_ON(!(k->flags & PF_KTHREAD));
76 return (__force void *)k->set_child_tid;
80 * Variant of to_kthread() that doesn't assume @p is a kthread.
82 * Per construction; when:
84 * (p->flags & PF_KTHREAD) && p->set_child_tid
86 * the task is both a kthread and struct kthread is persistent. However
87 * PF_KTHREAD on it's own is not, kernel_thread() can exec() (See umh.c and
90 static inline struct kthread *__to_kthread(struct task_struct *p)
92 void *kthread = (__force void *)p->set_child_tid;
93 if (kthread && !(p->flags & PF_KTHREAD))
98 void free_kthread_struct(struct task_struct *k)
100 struct kthread *kthread;
103 * Can be NULL if this kthread was created by kernel_thread()
104 * or if kmalloc() in kthread() failed.
106 kthread = to_kthread(k);
107 #ifdef CONFIG_BLK_CGROUP
108 WARN_ON_ONCE(kthread && kthread->blkcg_css);
114 * kthread_should_stop - should this kthread return now?
116 * When someone calls kthread_stop() on your kthread, it will be woken
117 * and this will return true. You should then return, and your return
118 * value will be passed through to kthread_stop().
120 bool kthread_should_stop(void)
122 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
124 EXPORT_SYMBOL(kthread_should_stop);
126 bool __kthread_should_park(struct task_struct *k)
128 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
130 EXPORT_SYMBOL_GPL(__kthread_should_park);
133 * kthread_should_park - should this kthread park now?
135 * When someone calls kthread_park() on your kthread, it will be woken
136 * and this will return true. You should then do the necessary
137 * cleanup and call kthread_parkme()
139 * Similar to kthread_should_stop(), but this keeps the thread alive
140 * and in a park position. kthread_unpark() "restarts" the thread and
141 * calls the thread function again.
143 bool kthread_should_park(void)
145 return __kthread_should_park(current);
147 EXPORT_SYMBOL_GPL(kthread_should_park);
150 * kthread_freezable_should_stop - should this freezable kthread return now?
151 * @was_frozen: optional out parameter, indicates whether %current was frozen
153 * kthread_should_stop() for freezable kthreads, which will enter
154 * refrigerator if necessary. This function is safe from kthread_stop() /
155 * freezer deadlock and freezable kthreads should use this function instead
156 * of calling try_to_freeze() directly.
158 bool kthread_freezable_should_stop(bool *was_frozen)
164 if (unlikely(freezing(current)))
165 frozen = __refrigerator(true);
168 *was_frozen = frozen;
170 return kthread_should_stop();
172 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
175 * kthread_data - return data value specified on kthread creation
176 * @task: kthread task in question
178 * Return the data value specified when kthread @task was created.
179 * The caller is responsible for ensuring the validity of @task when
180 * calling this function.
182 void *kthread_data(struct task_struct *task)
184 return to_kthread(task)->data;
188 * kthread_probe_data - speculative version of kthread_data()
189 * @task: possible kthread task in question
191 * @task could be a kthread task. Return the data value specified when it
192 * was created if accessible. If @task isn't a kthread task or its data is
193 * inaccessible for any reason, %NULL is returned. This function requires
194 * that @task itself is safe to dereference.
196 void *kthread_probe_data(struct task_struct *task)
198 struct kthread *kthread = __to_kthread(task);
202 probe_kernel_read(&data, &kthread->data, sizeof(data));
206 static void __kthread_parkme(struct kthread *self)
210 * TASK_PARKED is a special state; we must serialize against
211 * possible pending wakeups to avoid store-store collisions on
214 * Such a collision might possibly result in the task state
215 * changin from TASK_PARKED and us failing the
216 * wait_task_inactive() in kthread_park().
218 set_special_state(TASK_PARKED);
219 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
223 * Thread is going to call schedule(), do not preempt it,
224 * or the caller of kthread_park() may spend more time in
225 * wait_task_inactive().
228 complete(&self->parked);
229 schedule_preempt_disabled();
232 __set_current_state(TASK_RUNNING);
235 void kthread_parkme(void)
237 __kthread_parkme(to_kthread(current));
239 EXPORT_SYMBOL_GPL(kthread_parkme);
241 static int kthread(void *_create)
243 /* Copy data: it's on kthread's stack */
244 struct kthread_create_info *create = _create;
245 int (*threadfn)(void *data) = create->threadfn;
246 void *data = create->data;
247 struct completion *done;
248 struct kthread *self;
251 self = kzalloc(sizeof(*self), GFP_KERNEL);
252 set_kthread_struct(self);
254 /* If user was SIGKILLed, I release the structure. */
255 done = xchg(&create->done, NULL);
262 create->result = ERR_PTR(-ENOMEM);
268 init_completion(&self->exited);
269 init_completion(&self->parked);
270 current->vfork_done = &self->exited;
272 /* OK, tell user we're spawned, wait for stop or wakeup */
273 __set_current_state(TASK_UNINTERRUPTIBLE);
274 create->result = current;
276 * Thread is going to call schedule(), do not preempt it,
277 * or the creator may spend more time in wait_task_inactive().
281 schedule_preempt_disabled();
285 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
286 cgroup_kthread_ready();
287 __kthread_parkme(self);
288 ret = threadfn(data);
293 /* called from do_fork() to get node information for about to be created task */
294 int tsk_fork_get_node(struct task_struct *tsk)
297 if (tsk == kthreadd_task)
298 return tsk->pref_node_fork;
303 static void create_kthread(struct kthread_create_info *create)
308 current->pref_node_fork = create->node;
310 /* We want our own signal handler (we take no signals by default). */
311 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
313 /* If user was SIGKILLed, I release the structure. */
314 struct completion *done = xchg(&create->done, NULL);
320 create->result = ERR_PTR(pid);
325 static __printf(4, 0)
326 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
327 void *data, int node,
328 const char namefmt[],
331 DECLARE_COMPLETION_ONSTACK(done);
332 struct task_struct *task;
333 struct kthread_create_info *create = kmalloc(sizeof(*create),
337 return ERR_PTR(-ENOMEM);
338 create->threadfn = threadfn;
341 create->done = &done;
343 spin_lock(&kthread_create_lock);
344 list_add_tail(&create->list, &kthread_create_list);
345 spin_unlock(&kthread_create_lock);
347 wake_up_process(kthreadd_task);
349 * Wait for completion in killable state, for I might be chosen by
350 * the OOM killer while kthreadd is trying to allocate memory for
353 if (unlikely(wait_for_completion_killable(&done))) {
355 * If I was SIGKILLed before kthreadd (or new kernel thread)
356 * calls complete(), leave the cleanup of this structure to
359 if (xchg(&create->done, NULL))
360 return ERR_PTR(-EINTR);
362 * kthreadd (or new kernel thread) will call complete()
365 wait_for_completion(&done);
367 task = create->result;
369 static const struct sched_param param = { .sched_priority = 0 };
370 char name[TASK_COMM_LEN];
373 * task is already visible to other tasks, so updating
374 * COMM must be protected.
376 vsnprintf(name, sizeof(name), namefmt, args);
377 set_task_comm(task, name);
379 * root may have changed our (kthreadd's) priority or CPU mask.
380 * The kernel thread should not inherit these properties.
382 sched_setscheduler_nocheck(task, SCHED_NORMAL, ¶m);
383 set_cpus_allowed_ptr(task, cpu_all_mask);
390 * kthread_create_on_node - create a kthread.
391 * @threadfn: the function to run until signal_pending(current).
392 * @data: data ptr for @threadfn.
393 * @node: task and thread structures for the thread are allocated on this node
394 * @namefmt: printf-style name for the thread.
396 * Description: This helper function creates and names a kernel
397 * thread. The thread will be stopped: use wake_up_process() to start
398 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
399 * is affine to all CPUs.
401 * If thread is going to be bound on a particular cpu, give its node
402 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
403 * When woken, the thread will run @threadfn() with @data as its
404 * argument. @threadfn() can either call do_exit() directly if it is a
405 * standalone thread for which no one will call kthread_stop(), or
406 * return when 'kthread_should_stop()' is true (which means
407 * kthread_stop() has been called). The return value should be zero
408 * or a negative error number; it will be passed to kthread_stop().
410 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
412 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
413 void *data, int node,
414 const char namefmt[],
417 struct task_struct *task;
420 va_start(args, namefmt);
421 task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
426 EXPORT_SYMBOL(kthread_create_on_node);
428 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
432 if (!wait_task_inactive(p, state)) {
437 /* It's safe because the task is inactive. */
438 raw_spin_lock_irqsave(&p->pi_lock, flags);
439 do_set_cpus_allowed(p, mask);
440 p->flags |= PF_NO_SETAFFINITY;
441 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
444 static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
446 __kthread_bind_mask(p, cpumask_of(cpu), state);
449 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
451 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
455 * kthread_bind - bind a just-created kthread to a cpu.
456 * @p: thread created by kthread_create().
457 * @cpu: cpu (might not be online, must be possible) for @k to run on.
459 * Description: This function is equivalent to set_cpus_allowed(),
460 * except that @cpu doesn't need to be online, and the thread must be
461 * stopped (i.e., just returned from kthread_create()).
463 void kthread_bind(struct task_struct *p, unsigned int cpu)
465 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
467 EXPORT_SYMBOL(kthread_bind);
470 * kthread_create_on_cpu - Create a cpu bound kthread
471 * @threadfn: the function to run until signal_pending(current).
472 * @data: data ptr for @threadfn.
473 * @cpu: The cpu on which the thread should be bound,
474 * @namefmt: printf-style name for the thread. Format is restricted
475 * to "name.*%u". Code fills in cpu number.
477 * Description: This helper function creates and names a kernel thread
478 * The thread will be woken and put into park mode.
480 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
481 void *data, unsigned int cpu,
484 struct task_struct *p;
486 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
490 kthread_bind(p, cpu);
491 /* CPU hotplug need to bind once again when unparking the thread. */
492 to_kthread(p)->cpu = cpu;
496 void kthread_set_per_cpu(struct task_struct *k, int cpu)
498 struct kthread *kthread = to_kthread(k);
502 WARN_ON_ONCE(!(k->flags & PF_NO_SETAFFINITY));
505 clear_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
510 set_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
513 bool kthread_is_per_cpu(struct task_struct *p)
515 struct kthread *kthread = __to_kthread(p);
519 return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
523 * kthread_unpark - unpark a thread created by kthread_create().
524 * @k: thread created by kthread_create().
526 * Sets kthread_should_park() for @k to return false, wakes it, and
527 * waits for it to return. If the thread is marked percpu then its
528 * bound to the cpu again.
530 void kthread_unpark(struct task_struct *k)
532 struct kthread *kthread = to_kthread(k);
535 * Newly created kthread was parked when the CPU was offline.
536 * The binding was lost and we need to set it again.
538 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
539 __kthread_bind(k, kthread->cpu, TASK_PARKED);
541 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
543 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
545 wake_up_state(k, TASK_PARKED);
547 EXPORT_SYMBOL_GPL(kthread_unpark);
550 * kthread_park - park a thread created by kthread_create().
551 * @k: thread created by kthread_create().
553 * Sets kthread_should_park() for @k to return true, wakes it, and
554 * waits for it to return. This can also be called after kthread_create()
555 * instead of calling wake_up_process(): the thread will park without
556 * calling threadfn().
558 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
559 * If called by the kthread itself just the park bit is set.
561 int kthread_park(struct task_struct *k)
563 struct kthread *kthread = to_kthread(k);
565 if (WARN_ON(k->flags & PF_EXITING))
568 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
571 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
575 * Wait for __kthread_parkme() to complete(), this means we
576 * _will_ have TASK_PARKED and are about to call schedule().
578 wait_for_completion(&kthread->parked);
580 * Now wait for that schedule() to complete and the task to
583 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
588 EXPORT_SYMBOL_GPL(kthread_park);
591 * kthread_stop - stop a thread created by kthread_create().
592 * @k: thread created by kthread_create().
594 * Sets kthread_should_stop() for @k to return true, wakes it, and
595 * waits for it to exit. This can also be called after kthread_create()
596 * instead of calling wake_up_process(): the thread will exit without
597 * calling threadfn().
599 * If threadfn() may call do_exit() itself, the caller must ensure
600 * task_struct can't go away.
602 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
605 int kthread_stop(struct task_struct *k)
607 struct kthread *kthread;
610 trace_sched_kthread_stop(k);
613 kthread = to_kthread(k);
614 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
617 wait_for_completion(&kthread->exited);
621 trace_sched_kthread_stop_ret(ret);
624 EXPORT_SYMBOL(kthread_stop);
626 int kthreadd(void *unused)
628 struct task_struct *tsk = current;
630 /* Setup a clean context for our children to inherit. */
631 set_task_comm(tsk, "kthreadd");
633 set_cpus_allowed_ptr(tsk, cpu_all_mask);
634 set_mems_allowed(node_states[N_MEMORY]);
636 current->flags |= PF_NOFREEZE;
637 cgroup_init_kthreadd();
640 set_current_state(TASK_INTERRUPTIBLE);
641 if (list_empty(&kthread_create_list))
643 __set_current_state(TASK_RUNNING);
645 spin_lock(&kthread_create_lock);
646 while (!list_empty(&kthread_create_list)) {
647 struct kthread_create_info *create;
649 create = list_entry(kthread_create_list.next,
650 struct kthread_create_info, list);
651 list_del_init(&create->list);
652 spin_unlock(&kthread_create_lock);
654 create_kthread(create);
656 spin_lock(&kthread_create_lock);
658 spin_unlock(&kthread_create_lock);
664 void __kthread_init_worker(struct kthread_worker *worker,
666 struct lock_class_key *key)
668 memset(worker, 0, sizeof(struct kthread_worker));
669 raw_spin_lock_init(&worker->lock);
670 lockdep_set_class_and_name(&worker->lock, key, name);
671 INIT_LIST_HEAD(&worker->work_list);
672 INIT_LIST_HEAD(&worker->delayed_work_list);
674 EXPORT_SYMBOL_GPL(__kthread_init_worker);
677 * kthread_worker_fn - kthread function to process kthread_worker
678 * @worker_ptr: pointer to initialized kthread_worker
680 * This function implements the main cycle of kthread worker. It processes
681 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
684 * The works are not allowed to keep any locks, disable preemption or interrupts
685 * when they finish. There is defined a safe point for freezing when one work
686 * finishes and before a new one is started.
688 * Also the works must not be handled by more than one worker at the same time,
689 * see also kthread_queue_work().
691 int kthread_worker_fn(void *worker_ptr)
693 struct kthread_worker *worker = worker_ptr;
694 struct kthread_work *work;
697 * FIXME: Update the check and remove the assignment when all kthread
698 * worker users are created using kthread_create_worker*() functions.
700 WARN_ON(worker->task && worker->task != current);
701 worker->task = current;
703 if (worker->flags & KTW_FREEZABLE)
707 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
709 if (kthread_should_stop()) {
710 __set_current_state(TASK_RUNNING);
711 raw_spin_lock_irq(&worker->lock);
713 raw_spin_unlock_irq(&worker->lock);
718 raw_spin_lock_irq(&worker->lock);
719 if (!list_empty(&worker->work_list)) {
720 work = list_first_entry(&worker->work_list,
721 struct kthread_work, node);
722 list_del_init(&work->node);
724 worker->current_work = work;
725 raw_spin_unlock_irq(&worker->lock);
728 __set_current_state(TASK_RUNNING);
730 } else if (!freezing(current))
737 EXPORT_SYMBOL_GPL(kthread_worker_fn);
739 static __printf(3, 0) struct kthread_worker *
740 __kthread_create_worker(int cpu, unsigned int flags,
741 const char namefmt[], va_list args)
743 struct kthread_worker *worker;
744 struct task_struct *task;
745 int node = NUMA_NO_NODE;
747 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
749 return ERR_PTR(-ENOMEM);
751 kthread_init_worker(worker);
754 node = cpu_to_node(cpu);
756 task = __kthread_create_on_node(kthread_worker_fn, worker,
757 node, namefmt, args);
762 kthread_bind(task, cpu);
764 worker->flags = flags;
766 wake_up_process(task);
771 return ERR_CAST(task);
775 * kthread_create_worker - create a kthread worker
776 * @flags: flags modifying the default behavior of the worker
777 * @namefmt: printf-style name for the kthread worker (task).
779 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
780 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
781 * when the worker was SIGKILLed.
783 struct kthread_worker *
784 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
786 struct kthread_worker *worker;
789 va_start(args, namefmt);
790 worker = __kthread_create_worker(-1, flags, namefmt, args);
795 EXPORT_SYMBOL(kthread_create_worker);
798 * kthread_create_worker_on_cpu - create a kthread worker and bind it
799 * it to a given CPU and the associated NUMA node.
801 * @flags: flags modifying the default behavior of the worker
802 * @namefmt: printf-style name for the kthread worker (task).
804 * Use a valid CPU number if you want to bind the kthread worker
805 * to the given CPU and the associated NUMA node.
807 * A good practice is to add the cpu number also into the worker name.
808 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
810 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
811 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
812 * when the worker was SIGKILLed.
814 struct kthread_worker *
815 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
816 const char namefmt[], ...)
818 struct kthread_worker *worker;
821 va_start(args, namefmt);
822 worker = __kthread_create_worker(cpu, flags, namefmt, args);
827 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
830 * Returns true when the work could not be queued at the moment.
831 * It happens when it is already pending in a worker list
832 * or when it is being cancelled.
834 static inline bool queuing_blocked(struct kthread_worker *worker,
835 struct kthread_work *work)
837 lockdep_assert_held(&worker->lock);
839 return !list_empty(&work->node) || work->canceling;
842 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
843 struct kthread_work *work)
845 lockdep_assert_held(&worker->lock);
846 WARN_ON_ONCE(!list_empty(&work->node));
847 /* Do not use a work with >1 worker, see kthread_queue_work() */
848 WARN_ON_ONCE(work->worker && work->worker != worker);
851 /* insert @work before @pos in @worker */
852 static void kthread_insert_work(struct kthread_worker *worker,
853 struct kthread_work *work,
854 struct list_head *pos)
856 kthread_insert_work_sanity_check(worker, work);
858 list_add_tail(&work->node, pos);
859 work->worker = worker;
860 if (!worker->current_work && likely(worker->task))
861 wake_up_process(worker->task);
865 * kthread_queue_work - queue a kthread_work
866 * @worker: target kthread_worker
867 * @work: kthread_work to queue
869 * Queue @work to work processor @task for async execution. @task
870 * must have been created with kthread_worker_create(). Returns %true
871 * if @work was successfully queued, %false if it was already pending.
873 * Reinitialize the work if it needs to be used by another worker.
874 * For example, when the worker was stopped and started again.
876 bool kthread_queue_work(struct kthread_worker *worker,
877 struct kthread_work *work)
882 raw_spin_lock_irqsave(&worker->lock, flags);
883 if (!queuing_blocked(worker, work)) {
884 kthread_insert_work(worker, work, &worker->work_list);
887 raw_spin_unlock_irqrestore(&worker->lock, flags);
890 EXPORT_SYMBOL_GPL(kthread_queue_work);
893 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
894 * delayed work when the timer expires.
895 * @t: pointer to the expired timer
897 * The format of the function is defined by struct timer_list.
898 * It should have been called from irqsafe timer with irq already off.
900 void kthread_delayed_work_timer_fn(struct timer_list *t)
902 struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
903 struct kthread_work *work = &dwork->work;
904 struct kthread_worker *worker = work->worker;
908 * This might happen when a pending work is reinitialized.
909 * It means that it is used a wrong way.
911 if (WARN_ON_ONCE(!worker))
914 raw_spin_lock_irqsave(&worker->lock, flags);
915 /* Work must not be used with >1 worker, see kthread_queue_work(). */
916 WARN_ON_ONCE(work->worker != worker);
918 /* Move the work from worker->delayed_work_list. */
919 WARN_ON_ONCE(list_empty(&work->node));
920 list_del_init(&work->node);
921 if (!work->canceling)
922 kthread_insert_work(worker, work, &worker->work_list);
924 raw_spin_unlock_irqrestore(&worker->lock, flags);
926 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
928 static void __kthread_queue_delayed_work(struct kthread_worker *worker,
929 struct kthread_delayed_work *dwork,
932 struct timer_list *timer = &dwork->timer;
933 struct kthread_work *work = &dwork->work;
935 WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn);
938 * If @delay is 0, queue @dwork->work immediately. This is for
939 * both optimization and correctness. The earliest @timer can
940 * expire is on the closest next tick and delayed_work users depend
941 * on that there's no such delay when @delay is 0.
944 kthread_insert_work(worker, work, &worker->work_list);
948 /* Be paranoid and try to detect possible races already now. */
949 kthread_insert_work_sanity_check(worker, work);
951 list_add(&work->node, &worker->delayed_work_list);
952 work->worker = worker;
953 timer->expires = jiffies + delay;
958 * kthread_queue_delayed_work - queue the associated kthread work
960 * @worker: target kthread_worker
961 * @dwork: kthread_delayed_work to queue
962 * @delay: number of jiffies to wait before queuing
964 * If the work has not been pending it starts a timer that will queue
965 * the work after the given @delay. If @delay is zero, it queues the
968 * Return: %false if the @work has already been pending. It means that
969 * either the timer was running or the work was queued. It returns %true
972 bool kthread_queue_delayed_work(struct kthread_worker *worker,
973 struct kthread_delayed_work *dwork,
976 struct kthread_work *work = &dwork->work;
980 raw_spin_lock_irqsave(&worker->lock, flags);
982 if (!queuing_blocked(worker, work)) {
983 __kthread_queue_delayed_work(worker, dwork, delay);
987 raw_spin_unlock_irqrestore(&worker->lock, flags);
990 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
992 struct kthread_flush_work {
993 struct kthread_work work;
994 struct completion done;
997 static void kthread_flush_work_fn(struct kthread_work *work)
999 struct kthread_flush_work *fwork =
1000 container_of(work, struct kthread_flush_work, work);
1001 complete(&fwork->done);
1005 * kthread_flush_work - flush a kthread_work
1006 * @work: work to flush
1008 * If @work is queued or executing, wait for it to finish execution.
1010 void kthread_flush_work(struct kthread_work *work)
1012 struct kthread_flush_work fwork = {
1013 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1014 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1016 struct kthread_worker *worker;
1019 worker = work->worker;
1023 raw_spin_lock_irq(&worker->lock);
1024 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1025 WARN_ON_ONCE(work->worker != worker);
1027 if (!list_empty(&work->node))
1028 kthread_insert_work(worker, &fwork.work, work->node.next);
1029 else if (worker->current_work == work)
1030 kthread_insert_work(worker, &fwork.work,
1031 worker->work_list.next);
1035 raw_spin_unlock_irq(&worker->lock);
1038 wait_for_completion(&fwork.done);
1040 EXPORT_SYMBOL_GPL(kthread_flush_work);
1043 * Make sure that the timer is neither set nor running and could
1044 * not manipulate the work list_head any longer.
1046 * The function is called under worker->lock. The lock is temporary
1047 * released but the timer can't be set again in the meantime.
1049 static void kthread_cancel_delayed_work_timer(struct kthread_work *work,
1050 unsigned long *flags)
1052 struct kthread_delayed_work *dwork =
1053 container_of(work, struct kthread_delayed_work, work);
1054 struct kthread_worker *worker = work->worker;
1057 * del_timer_sync() must be called to make sure that the timer
1058 * callback is not running. The lock must be temporary released
1059 * to avoid a deadlock with the callback. In the meantime,
1060 * any queuing is blocked by setting the canceling counter.
1063 raw_spin_unlock_irqrestore(&worker->lock, *flags);
1064 del_timer_sync(&dwork->timer);
1065 raw_spin_lock_irqsave(&worker->lock, *flags);
1070 * This function removes the work from the worker queue.
1072 * It is called under worker->lock. The caller must make sure that
1073 * the timer used by delayed work is not running, e.g. by calling
1074 * kthread_cancel_delayed_work_timer().
1076 * The work might still be in use when this function finishes. See the
1077 * current_work proceed by the worker.
1079 * Return: %true if @work was pending and successfully canceled,
1080 * %false if @work was not pending
1082 static bool __kthread_cancel_work(struct kthread_work *work)
1085 * Try to remove the work from a worker list. It might either
1086 * be from worker->work_list or from worker->delayed_work_list.
1088 if (!list_empty(&work->node)) {
1089 list_del_init(&work->node);
1097 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1098 * @worker: kthread worker to use
1099 * @dwork: kthread delayed work to queue
1100 * @delay: number of jiffies to wait before queuing
1102 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1103 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1104 * @work is guaranteed to be queued immediately.
1106 * Return: %false if @dwork was idle and queued, %true otherwise.
1108 * A special case is when the work is being canceled in parallel.
1109 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1110 * or yet another kthread_mod_delayed_work() call. We let the other command
1111 * win and return %true here. The return value can be used for reference
1112 * counting and the number of queued works stays the same. Anyway, the caller
1113 * is supposed to synchronize these operations a reasonable way.
1115 * This function is safe to call from any context including IRQ handler.
1116 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1119 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1120 struct kthread_delayed_work *dwork,
1121 unsigned long delay)
1123 struct kthread_work *work = &dwork->work;
1124 unsigned long flags;
1127 raw_spin_lock_irqsave(&worker->lock, flags);
1129 /* Do not bother with canceling when never queued. */
1130 if (!work->worker) {
1135 /* Work must not be used with >1 worker, see kthread_queue_work() */
1136 WARN_ON_ONCE(work->worker != worker);
1139 * Temporary cancel the work but do not fight with another command
1140 * that is canceling the work as well.
1142 * It is a bit tricky because of possible races with another
1143 * mod_delayed_work() and cancel_delayed_work() callers.
1145 * The timer must be canceled first because worker->lock is released
1146 * when doing so. But the work can be removed from the queue (list)
1147 * only when it can be queued again so that the return value can
1148 * be used for reference counting.
1150 kthread_cancel_delayed_work_timer(work, &flags);
1151 if (work->canceling) {
1152 /* The number of works in the queue does not change. */
1156 ret = __kthread_cancel_work(work);
1159 __kthread_queue_delayed_work(worker, dwork, delay);
1161 raw_spin_unlock_irqrestore(&worker->lock, flags);
1164 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1166 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1168 struct kthread_worker *worker = work->worker;
1169 unsigned long flags;
1175 raw_spin_lock_irqsave(&worker->lock, flags);
1176 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1177 WARN_ON_ONCE(work->worker != worker);
1180 kthread_cancel_delayed_work_timer(work, &flags);
1182 ret = __kthread_cancel_work(work);
1184 if (worker->current_work != work)
1188 * The work is in progress and we need to wait with the lock released.
1189 * In the meantime, block any queuing by setting the canceling counter.
1192 raw_spin_unlock_irqrestore(&worker->lock, flags);
1193 kthread_flush_work(work);
1194 raw_spin_lock_irqsave(&worker->lock, flags);
1198 raw_spin_unlock_irqrestore(&worker->lock, flags);
1204 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1205 * @work: the kthread work to cancel
1207 * Cancel @work and wait for its execution to finish. This function
1208 * can be used even if the work re-queues itself. On return from this
1209 * function, @work is guaranteed to be not pending or executing on any CPU.
1211 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1212 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1214 * The caller must ensure that the worker on which @work was last
1215 * queued can't be destroyed before this function returns.
1217 * Return: %true if @work was pending, %false otherwise.
1219 bool kthread_cancel_work_sync(struct kthread_work *work)
1221 return __kthread_cancel_work_sync(work, false);
1223 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1226 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1227 * wait for it to finish.
1228 * @dwork: the kthread delayed work to cancel
1230 * This is kthread_cancel_work_sync() for delayed works.
1232 * Return: %true if @dwork was pending, %false otherwise.
1234 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1236 return __kthread_cancel_work_sync(&dwork->work, true);
1238 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1241 * kthread_flush_worker - flush all current works on a kthread_worker
1242 * @worker: worker to flush
1244 * Wait until all currently executing or pending works on @worker are
1247 void kthread_flush_worker(struct kthread_worker *worker)
1249 struct kthread_flush_work fwork = {
1250 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1251 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1254 kthread_queue_work(worker, &fwork.work);
1255 wait_for_completion(&fwork.done);
1257 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1260 * kthread_destroy_worker - destroy a kthread worker
1261 * @worker: worker to be destroyed
1263 * Flush and destroy @worker. The simple flush is enough because the kthread
1264 * worker API is used only in trivial scenarios. There are no multi-step state
1267 void kthread_destroy_worker(struct kthread_worker *worker)
1269 struct task_struct *task;
1271 task = worker->task;
1275 kthread_flush_worker(worker);
1277 WARN_ON(!list_empty(&worker->work_list));
1280 EXPORT_SYMBOL(kthread_destroy_worker);
1282 #ifdef CONFIG_BLK_CGROUP
1284 * kthread_associate_blkcg - associate blkcg to current kthread
1285 * @css: the cgroup info
1287 * Current thread must be a kthread. The thread is running jobs on behalf of
1288 * other threads. In some cases, we expect the jobs attach cgroup info of
1289 * original threads instead of that of current thread. This function stores
1290 * original thread's cgroup info in current kthread context for later
1293 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1295 struct kthread *kthread = __to_kthread(current);
1301 if (kthread->blkcg_css) {
1302 css_put(kthread->blkcg_css);
1303 kthread->blkcg_css = NULL;
1307 kthread->blkcg_css = css;
1310 EXPORT_SYMBOL(kthread_associate_blkcg);
1313 * kthread_blkcg - get associated blkcg css of current kthread
1315 * Current thread must be a kthread.
1317 struct cgroup_subsys_state *kthread_blkcg(void)
1319 struct kthread *kthread = __to_kthread(current);
1322 return kthread->blkcg_css;
1325 EXPORT_SYMBOL(kthread_blkcg);