1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel thread helper functions.
3 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
4 * Copyright (C) 2009 Red Hat, Inc.
6 * Creation is done via kthreadd, so that we get a clean environment
7 * even if we're invoked from userspace (think modprobe, hotplug cpu,
10 #include <uapi/linux/sched/types.h>
12 #include <linux/mmu_context.h>
13 #include <linux/sched.h>
14 #include <linux/sched/mm.h>
15 #include <linux/sched/task.h>
16 #include <linux/kthread.h>
17 #include <linux/completion.h>
18 #include <linux/err.h>
19 #include <linux/cgroup.h>
20 #include <linux/cpuset.h>
21 #include <linux/unistd.h>
22 #include <linux/file.h>
23 #include <linux/export.h>
24 #include <linux/mutex.h>
25 #include <linux/slab.h>
26 #include <linux/freezer.h>
27 #include <linux/ptrace.h>
28 #include <linux/uaccess.h>
29 #include <linux/numa.h>
30 #include <trace/events/sched.h>
33 static DEFINE_SPINLOCK(kthread_create_lock);
34 static LIST_HEAD(kthread_create_list);
35 struct task_struct *kthreadd_task;
37 struct kthread_create_info
39 /* Information passed to kthread() from kthreadd. */
40 int (*threadfn)(void *data);
44 /* Result passed back to kthread_create() from kthreadd. */
45 struct task_struct *result;
46 struct completion *done;
48 struct list_head list;
56 struct completion parked;
57 struct completion exited;
58 #ifdef CONFIG_BLK_CGROUP
59 struct cgroup_subsys_state *blkcg_css;
64 KTHREAD_IS_PER_CPU = 0,
69 static inline void set_kthread_struct(void *kthread)
72 * We abuse ->set_child_tid to avoid the new member and because it
73 * can't be wrongly copied by copy_process(). We also rely on fact
74 * that the caller can't exec, so PF_KTHREAD can't be cleared.
76 current->set_child_tid = (__force void __user *)kthread;
79 static inline struct kthread *to_kthread(struct task_struct *k)
81 WARN_ON(!(k->flags & PF_KTHREAD));
82 return (__force void *)k->set_child_tid;
85 void free_kthread_struct(struct task_struct *k)
87 struct kthread *kthread;
90 * Can be NULL if this kthread was created by kernel_thread()
91 * or if kmalloc() in kthread() failed.
93 kthread = to_kthread(k);
94 #ifdef CONFIG_BLK_CGROUP
95 WARN_ON_ONCE(kthread && kthread->blkcg_css);
101 * kthread_should_stop - should this kthread return now?
103 * When someone calls kthread_stop() on your kthread, it will be woken
104 * and this will return true. You should then return, and your return
105 * value will be passed through to kthread_stop().
107 bool kthread_should_stop(void)
109 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
111 EXPORT_SYMBOL(kthread_should_stop);
113 bool __kthread_should_park(struct task_struct *k)
115 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
117 EXPORT_SYMBOL_GPL(__kthread_should_park);
120 * kthread_should_park - should this kthread park now?
122 * When someone calls kthread_park() on your kthread, it will be woken
123 * and this will return true. You should then do the necessary
124 * cleanup and call kthread_parkme()
126 * Similar to kthread_should_stop(), but this keeps the thread alive
127 * and in a park position. kthread_unpark() "restarts" the thread and
128 * calls the thread function again.
130 bool kthread_should_park(void)
132 return __kthread_should_park(current);
134 EXPORT_SYMBOL_GPL(kthread_should_park);
137 * kthread_freezable_should_stop - should this freezable kthread return now?
138 * @was_frozen: optional out parameter, indicates whether %current was frozen
140 * kthread_should_stop() for freezable kthreads, which will enter
141 * refrigerator if necessary. This function is safe from kthread_stop() /
142 * freezer deadlock and freezable kthreads should use this function instead
143 * of calling try_to_freeze() directly.
145 bool kthread_freezable_should_stop(bool *was_frozen)
151 if (unlikely(freezing(current)))
152 frozen = __refrigerator(true);
155 *was_frozen = frozen;
157 return kthread_should_stop();
159 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
162 * kthread_data - return data value specified on kthread creation
163 * @task: kthread task in question
165 * Return the data value specified when kthread @task was created.
166 * The caller is responsible for ensuring the validity of @task when
167 * calling this function.
169 void *kthread_data(struct task_struct *task)
171 return to_kthread(task)->data;
175 * kthread_probe_data - speculative version of kthread_data()
176 * @task: possible kthread task in question
178 * @task could be a kthread task. Return the data value specified when it
179 * was created if accessible. If @task isn't a kthread task or its data is
180 * inaccessible for any reason, %NULL is returned. This function requires
181 * that @task itself is safe to dereference.
183 void *kthread_probe_data(struct task_struct *task)
185 struct kthread *kthread = to_kthread(task);
188 probe_kernel_read(&data, &kthread->data, sizeof(data));
192 static void __kthread_parkme(struct kthread *self)
196 * TASK_PARKED is a special state; we must serialize against
197 * possible pending wakeups to avoid store-store collisions on
200 * Such a collision might possibly result in the task state
201 * changin from TASK_PARKED and us failing the
202 * wait_task_inactive() in kthread_park().
204 set_special_state(TASK_PARKED);
205 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
209 * Thread is going to call schedule(), do not preempt it,
210 * or the caller of kthread_park() may spend more time in
211 * wait_task_inactive().
214 complete(&self->parked);
215 schedule_preempt_disabled();
218 __set_current_state(TASK_RUNNING);
221 void kthread_parkme(void)
223 __kthread_parkme(to_kthread(current));
225 EXPORT_SYMBOL_GPL(kthread_parkme);
227 static int kthread(void *_create)
229 /* Copy data: it's on kthread's stack */
230 struct kthread_create_info *create = _create;
231 int (*threadfn)(void *data) = create->threadfn;
232 void *data = create->data;
233 struct completion *done;
234 struct kthread *self;
237 self = kzalloc(sizeof(*self), GFP_KERNEL);
238 set_kthread_struct(self);
240 /* If user was SIGKILLed, I release the structure. */
241 done = xchg(&create->done, NULL);
248 create->result = ERR_PTR(-ENOMEM);
254 init_completion(&self->exited);
255 init_completion(&self->parked);
256 current->vfork_done = &self->exited;
258 /* OK, tell user we're spawned, wait for stop or wakeup */
259 __set_current_state(TASK_UNINTERRUPTIBLE);
260 create->result = current;
262 * Thread is going to call schedule(), do not preempt it,
263 * or the creator may spend more time in wait_task_inactive().
267 schedule_preempt_disabled();
271 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
272 cgroup_kthread_ready();
273 __kthread_parkme(self);
274 ret = threadfn(data);
279 /* called from do_fork() to get node information for about to be created task */
280 int tsk_fork_get_node(struct task_struct *tsk)
283 if (tsk == kthreadd_task)
284 return tsk->pref_node_fork;
289 static void create_kthread(struct kthread_create_info *create)
294 current->pref_node_fork = create->node;
296 /* We want our own signal handler (we take no signals by default). */
297 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
299 /* If user was SIGKILLed, I release the structure. */
300 struct completion *done = xchg(&create->done, NULL);
306 create->result = ERR_PTR(pid);
311 static __printf(4, 0)
312 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
313 void *data, int node,
314 const char namefmt[],
317 DECLARE_COMPLETION_ONSTACK(done);
318 struct task_struct *task;
319 struct kthread_create_info *create = kmalloc(sizeof(*create),
323 return ERR_PTR(-ENOMEM);
324 create->threadfn = threadfn;
327 create->done = &done;
329 spin_lock(&kthread_create_lock);
330 list_add_tail(&create->list, &kthread_create_list);
331 spin_unlock(&kthread_create_lock);
333 wake_up_process(kthreadd_task);
335 * Wait for completion in killable state, for I might be chosen by
336 * the OOM killer while kthreadd is trying to allocate memory for
339 if (unlikely(wait_for_completion_killable(&done))) {
341 * If I was SIGKILLed before kthreadd (or new kernel thread)
342 * calls complete(), leave the cleanup of this structure to
345 if (xchg(&create->done, NULL))
346 return ERR_PTR(-EINTR);
348 * kthreadd (or new kernel thread) will call complete()
351 wait_for_completion(&done);
353 task = create->result;
355 static const struct sched_param param = { .sched_priority = 0 };
356 char name[TASK_COMM_LEN];
359 * task is already visible to other tasks, so updating
360 * COMM must be protected.
362 vsnprintf(name, sizeof(name), namefmt, args);
363 set_task_comm(task, name);
365 * root may have changed our (kthreadd's) priority or CPU mask.
366 * The kernel thread should not inherit these properties.
368 sched_setscheduler_nocheck(task, SCHED_NORMAL, ¶m);
369 set_cpus_allowed_ptr(task, cpu_all_mask);
376 * kthread_create_on_node - create a kthread.
377 * @threadfn: the function to run until signal_pending(current).
378 * @data: data ptr for @threadfn.
379 * @node: task and thread structures for the thread are allocated on this node
380 * @namefmt: printf-style name for the thread.
382 * Description: This helper function creates and names a kernel
383 * thread. The thread will be stopped: use wake_up_process() to start
384 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
385 * is affine to all CPUs.
387 * If thread is going to be bound on a particular cpu, give its node
388 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
389 * When woken, the thread will run @threadfn() with @data as its
390 * argument. @threadfn() can either call do_exit() directly if it is a
391 * standalone thread for which no one will call kthread_stop(), or
392 * return when 'kthread_should_stop()' is true (which means
393 * kthread_stop() has been called). The return value should be zero
394 * or a negative error number; it will be passed to kthread_stop().
396 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
398 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
399 void *data, int node,
400 const char namefmt[],
403 struct task_struct *task;
406 va_start(args, namefmt);
407 task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
412 EXPORT_SYMBOL(kthread_create_on_node);
414 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
418 if (!wait_task_inactive(p, state)) {
423 /* It's safe because the task is inactive. */
424 raw_spin_lock_irqsave(&p->pi_lock, flags);
425 do_set_cpus_allowed(p, mask);
426 p->flags |= PF_NO_SETAFFINITY;
427 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
430 static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
432 __kthread_bind_mask(p, cpumask_of(cpu), state);
435 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
437 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
441 * kthread_bind - bind a just-created kthread to a cpu.
442 * @p: thread created by kthread_create().
443 * @cpu: cpu (might not be online, must be possible) for @k to run on.
445 * Description: This function is equivalent to set_cpus_allowed(),
446 * except that @cpu doesn't need to be online, and the thread must be
447 * stopped (i.e., just returned from kthread_create()).
449 void kthread_bind(struct task_struct *p, unsigned int cpu)
451 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
453 EXPORT_SYMBOL(kthread_bind);
456 * kthread_create_on_cpu - Create a cpu bound kthread
457 * @threadfn: the function to run until signal_pending(current).
458 * @data: data ptr for @threadfn.
459 * @cpu: The cpu on which the thread should be bound,
460 * @namefmt: printf-style name for the thread. Format is restricted
461 * to "name.*%u". Code fills in cpu number.
463 * Description: This helper function creates and names a kernel thread
464 * The thread will be woken and put into park mode.
466 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
467 void *data, unsigned int cpu,
470 struct task_struct *p;
472 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
476 kthread_bind(p, cpu);
477 /* CPU hotplug need to bind once again when unparking the thread. */
478 set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
479 to_kthread(p)->cpu = cpu;
484 * kthread_unpark - unpark a thread created by kthread_create().
485 * @k: thread created by kthread_create().
487 * Sets kthread_should_park() for @k to return false, wakes it, and
488 * waits for it to return. If the thread is marked percpu then its
489 * bound to the cpu again.
491 void kthread_unpark(struct task_struct *k)
493 struct kthread *kthread = to_kthread(k);
496 * Newly created kthread was parked when the CPU was offline.
497 * The binding was lost and we need to set it again.
499 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
500 __kthread_bind(k, kthread->cpu, TASK_PARKED);
502 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
504 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
506 wake_up_state(k, TASK_PARKED);
508 EXPORT_SYMBOL_GPL(kthread_unpark);
511 * kthread_park - park a thread created by kthread_create().
512 * @k: thread created by kthread_create().
514 * Sets kthread_should_park() for @k to return true, wakes it, and
515 * waits for it to return. This can also be called after kthread_create()
516 * instead of calling wake_up_process(): the thread will park without
517 * calling threadfn().
519 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
520 * If called by the kthread itself just the park bit is set.
522 int kthread_park(struct task_struct *k)
524 struct kthread *kthread = to_kthread(k);
526 if (WARN_ON(k->flags & PF_EXITING))
529 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
532 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
536 * Wait for __kthread_parkme() to complete(), this means we
537 * _will_ have TASK_PARKED and are about to call schedule().
539 wait_for_completion(&kthread->parked);
541 * Now wait for that schedule() to complete and the task to
544 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
549 EXPORT_SYMBOL_GPL(kthread_park);
552 * kthread_stop - stop a thread created by kthread_create().
553 * @k: thread created by kthread_create().
555 * Sets kthread_should_stop() for @k to return true, wakes it, and
556 * waits for it to exit. This can also be called after kthread_create()
557 * instead of calling wake_up_process(): the thread will exit without
558 * calling threadfn().
560 * If threadfn() may call do_exit() itself, the caller must ensure
561 * task_struct can't go away.
563 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
566 int kthread_stop(struct task_struct *k)
568 struct kthread *kthread;
571 trace_sched_kthread_stop(k);
574 kthread = to_kthread(k);
575 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
578 wait_for_completion(&kthread->exited);
582 trace_sched_kthread_stop_ret(ret);
585 EXPORT_SYMBOL(kthread_stop);
587 int kthreadd(void *unused)
589 struct task_struct *tsk = current;
591 /* Setup a clean context for our children to inherit. */
592 set_task_comm(tsk, "kthreadd");
594 set_cpus_allowed_ptr(tsk, cpu_all_mask);
595 set_mems_allowed(node_states[N_MEMORY]);
597 current->flags |= PF_NOFREEZE;
598 cgroup_init_kthreadd();
601 set_current_state(TASK_INTERRUPTIBLE);
602 if (list_empty(&kthread_create_list))
604 __set_current_state(TASK_RUNNING);
606 spin_lock(&kthread_create_lock);
607 while (!list_empty(&kthread_create_list)) {
608 struct kthread_create_info *create;
610 create = list_entry(kthread_create_list.next,
611 struct kthread_create_info, list);
612 list_del_init(&create->list);
613 spin_unlock(&kthread_create_lock);
615 create_kthread(create);
617 spin_lock(&kthread_create_lock);
619 spin_unlock(&kthread_create_lock);
625 void __kthread_init_worker(struct kthread_worker *worker,
627 struct lock_class_key *key)
629 memset(worker, 0, sizeof(struct kthread_worker));
630 raw_spin_lock_init(&worker->lock);
631 lockdep_set_class_and_name(&worker->lock, key, name);
632 INIT_LIST_HEAD(&worker->work_list);
633 INIT_LIST_HEAD(&worker->delayed_work_list);
635 EXPORT_SYMBOL_GPL(__kthread_init_worker);
638 * kthread_worker_fn - kthread function to process kthread_worker
639 * @worker_ptr: pointer to initialized kthread_worker
641 * This function implements the main cycle of kthread worker. It processes
642 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
645 * The works are not allowed to keep any locks, disable preemption or interrupts
646 * when they finish. There is defined a safe point for freezing when one work
647 * finishes and before a new one is started.
649 * Also the works must not be handled by more than one worker at the same time,
650 * see also kthread_queue_work().
652 int kthread_worker_fn(void *worker_ptr)
654 struct kthread_worker *worker = worker_ptr;
655 struct kthread_work *work;
658 * FIXME: Update the check and remove the assignment when all kthread
659 * worker users are created using kthread_create_worker*() functions.
661 WARN_ON(worker->task && worker->task != current);
662 worker->task = current;
664 if (worker->flags & KTW_FREEZABLE)
668 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
670 if (kthread_should_stop()) {
671 __set_current_state(TASK_RUNNING);
672 raw_spin_lock_irq(&worker->lock);
674 raw_spin_unlock_irq(&worker->lock);
679 raw_spin_lock_irq(&worker->lock);
680 if (!list_empty(&worker->work_list)) {
681 work = list_first_entry(&worker->work_list,
682 struct kthread_work, node);
683 list_del_init(&work->node);
685 worker->current_work = work;
686 raw_spin_unlock_irq(&worker->lock);
689 __set_current_state(TASK_RUNNING);
691 } else if (!freezing(current))
698 EXPORT_SYMBOL_GPL(kthread_worker_fn);
700 static __printf(3, 0) struct kthread_worker *
701 __kthread_create_worker(int cpu, unsigned int flags,
702 const char namefmt[], va_list args)
704 struct kthread_worker *worker;
705 struct task_struct *task;
706 int node = NUMA_NO_NODE;
708 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
710 return ERR_PTR(-ENOMEM);
712 kthread_init_worker(worker);
715 node = cpu_to_node(cpu);
717 task = __kthread_create_on_node(kthread_worker_fn, worker,
718 node, namefmt, args);
723 kthread_bind(task, cpu);
725 worker->flags = flags;
727 wake_up_process(task);
732 return ERR_CAST(task);
736 * kthread_create_worker - create a kthread worker
737 * @flags: flags modifying the default behavior of the worker
738 * @namefmt: printf-style name for the kthread worker (task).
740 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
741 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
742 * when the worker was SIGKILLed.
744 struct kthread_worker *
745 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
747 struct kthread_worker *worker;
750 va_start(args, namefmt);
751 worker = __kthread_create_worker(-1, flags, namefmt, args);
756 EXPORT_SYMBOL(kthread_create_worker);
759 * kthread_create_worker_on_cpu - create a kthread worker and bind it
760 * it to a given CPU and the associated NUMA node.
762 * @flags: flags modifying the default behavior of the worker
763 * @namefmt: printf-style name for the kthread worker (task).
765 * Use a valid CPU number if you want to bind the kthread worker
766 * to the given CPU and the associated NUMA node.
768 * A good practice is to add the cpu number also into the worker name.
769 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
771 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
772 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
773 * when the worker was SIGKILLed.
775 struct kthread_worker *
776 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
777 const char namefmt[], ...)
779 struct kthread_worker *worker;
782 va_start(args, namefmt);
783 worker = __kthread_create_worker(cpu, flags, namefmt, args);
788 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
791 * Returns true when the work could not be queued at the moment.
792 * It happens when it is already pending in a worker list
793 * or when it is being cancelled.
795 static inline bool queuing_blocked(struct kthread_worker *worker,
796 struct kthread_work *work)
798 lockdep_assert_held(&worker->lock);
800 return !list_empty(&work->node) || work->canceling;
803 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
804 struct kthread_work *work)
806 lockdep_assert_held(&worker->lock);
807 WARN_ON_ONCE(!list_empty(&work->node));
808 /* Do not use a work with >1 worker, see kthread_queue_work() */
809 WARN_ON_ONCE(work->worker && work->worker != worker);
812 /* insert @work before @pos in @worker */
813 static void kthread_insert_work(struct kthread_worker *worker,
814 struct kthread_work *work,
815 struct list_head *pos)
817 kthread_insert_work_sanity_check(worker, work);
819 list_add_tail(&work->node, pos);
820 work->worker = worker;
821 if (!worker->current_work && likely(worker->task))
822 wake_up_process(worker->task);
826 * kthread_queue_work - queue a kthread_work
827 * @worker: target kthread_worker
828 * @work: kthread_work to queue
830 * Queue @work to work processor @task for async execution. @task
831 * must have been created with kthread_worker_create(). Returns %true
832 * if @work was successfully queued, %false if it was already pending.
834 * Reinitialize the work if it needs to be used by another worker.
835 * For example, when the worker was stopped and started again.
837 bool kthread_queue_work(struct kthread_worker *worker,
838 struct kthread_work *work)
843 raw_spin_lock_irqsave(&worker->lock, flags);
844 if (!queuing_blocked(worker, work)) {
845 kthread_insert_work(worker, work, &worker->work_list);
848 raw_spin_unlock_irqrestore(&worker->lock, flags);
851 EXPORT_SYMBOL_GPL(kthread_queue_work);
854 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
855 * delayed work when the timer expires.
856 * @t: pointer to the expired timer
858 * The format of the function is defined by struct timer_list.
859 * It should have been called from irqsafe timer with irq already off.
861 void kthread_delayed_work_timer_fn(struct timer_list *t)
863 struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
864 struct kthread_work *work = &dwork->work;
865 struct kthread_worker *worker = work->worker;
869 * This might happen when a pending work is reinitialized.
870 * It means that it is used a wrong way.
872 if (WARN_ON_ONCE(!worker))
875 raw_spin_lock_irqsave(&worker->lock, flags);
876 /* Work must not be used with >1 worker, see kthread_queue_work(). */
877 WARN_ON_ONCE(work->worker != worker);
879 /* Move the work from worker->delayed_work_list. */
880 WARN_ON_ONCE(list_empty(&work->node));
881 list_del_init(&work->node);
882 kthread_insert_work(worker, work, &worker->work_list);
884 raw_spin_unlock_irqrestore(&worker->lock, flags);
886 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
888 static void __kthread_queue_delayed_work(struct kthread_worker *worker,
889 struct kthread_delayed_work *dwork,
892 struct timer_list *timer = &dwork->timer;
893 struct kthread_work *work = &dwork->work;
895 WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn);
898 * If @delay is 0, queue @dwork->work immediately. This is for
899 * both optimization and correctness. The earliest @timer can
900 * expire is on the closest next tick and delayed_work users depend
901 * on that there's no such delay when @delay is 0.
904 kthread_insert_work(worker, work, &worker->work_list);
908 /* Be paranoid and try to detect possible races already now. */
909 kthread_insert_work_sanity_check(worker, work);
911 list_add(&work->node, &worker->delayed_work_list);
912 work->worker = worker;
913 timer->expires = jiffies + delay;
918 * kthread_queue_delayed_work - queue the associated kthread work
920 * @worker: target kthread_worker
921 * @dwork: kthread_delayed_work to queue
922 * @delay: number of jiffies to wait before queuing
924 * If the work has not been pending it starts a timer that will queue
925 * the work after the given @delay. If @delay is zero, it queues the
928 * Return: %false if the @work has already been pending. It means that
929 * either the timer was running or the work was queued. It returns %true
932 bool kthread_queue_delayed_work(struct kthread_worker *worker,
933 struct kthread_delayed_work *dwork,
936 struct kthread_work *work = &dwork->work;
940 raw_spin_lock_irqsave(&worker->lock, flags);
942 if (!queuing_blocked(worker, work)) {
943 __kthread_queue_delayed_work(worker, dwork, delay);
947 raw_spin_unlock_irqrestore(&worker->lock, flags);
950 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
952 struct kthread_flush_work {
953 struct kthread_work work;
954 struct completion done;
957 static void kthread_flush_work_fn(struct kthread_work *work)
959 struct kthread_flush_work *fwork =
960 container_of(work, struct kthread_flush_work, work);
961 complete(&fwork->done);
965 * kthread_flush_work - flush a kthread_work
966 * @work: work to flush
968 * If @work is queued or executing, wait for it to finish execution.
970 void kthread_flush_work(struct kthread_work *work)
972 struct kthread_flush_work fwork = {
973 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
974 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
976 struct kthread_worker *worker;
979 worker = work->worker;
983 raw_spin_lock_irq(&worker->lock);
984 /* Work must not be used with >1 worker, see kthread_queue_work(). */
985 WARN_ON_ONCE(work->worker != worker);
987 if (!list_empty(&work->node))
988 kthread_insert_work(worker, &fwork.work, work->node.next);
989 else if (worker->current_work == work)
990 kthread_insert_work(worker, &fwork.work,
991 worker->work_list.next);
995 raw_spin_unlock_irq(&worker->lock);
998 wait_for_completion(&fwork.done);
1000 EXPORT_SYMBOL_GPL(kthread_flush_work);
1003 * This function removes the work from the worker queue. Also it makes sure
1004 * that it won't get queued later via the delayed work's timer.
1006 * The work might still be in use when this function finishes. See the
1007 * current_work proceed by the worker.
1009 * Return: %true if @work was pending and successfully canceled,
1010 * %false if @work was not pending
1012 static bool __kthread_cancel_work(struct kthread_work *work, bool is_dwork,
1013 unsigned long *flags)
1015 /* Try to cancel the timer if exists. */
1017 struct kthread_delayed_work *dwork =
1018 container_of(work, struct kthread_delayed_work, work);
1019 struct kthread_worker *worker = work->worker;
1022 * del_timer_sync() must be called to make sure that the timer
1023 * callback is not running. The lock must be temporary released
1024 * to avoid a deadlock with the callback. In the meantime,
1025 * any queuing is blocked by setting the canceling counter.
1028 raw_spin_unlock_irqrestore(&worker->lock, *flags);
1029 del_timer_sync(&dwork->timer);
1030 raw_spin_lock_irqsave(&worker->lock, *flags);
1035 * Try to remove the work from a worker list. It might either
1036 * be from worker->work_list or from worker->delayed_work_list.
1038 if (!list_empty(&work->node)) {
1039 list_del_init(&work->node);
1047 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1048 * @worker: kthread worker to use
1049 * @dwork: kthread delayed work to queue
1050 * @delay: number of jiffies to wait before queuing
1052 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1053 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1054 * @work is guaranteed to be queued immediately.
1056 * Return: %true if @dwork was pending and its timer was modified,
1059 * A special case is when the work is being canceled in parallel.
1060 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1061 * or yet another kthread_mod_delayed_work() call. We let the other command
1062 * win and return %false here. The caller is supposed to synchronize these
1063 * operations a reasonable way.
1065 * This function is safe to call from any context including IRQ handler.
1066 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1069 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1070 struct kthread_delayed_work *dwork,
1071 unsigned long delay)
1073 struct kthread_work *work = &dwork->work;
1074 unsigned long flags;
1077 raw_spin_lock_irqsave(&worker->lock, flags);
1079 /* Do not bother with canceling when never queued. */
1083 /* Work must not be used with >1 worker, see kthread_queue_work() */
1084 WARN_ON_ONCE(work->worker != worker);
1086 /* Do not fight with another command that is canceling this work. */
1087 if (work->canceling)
1090 ret = __kthread_cancel_work(work, true, &flags);
1092 __kthread_queue_delayed_work(worker, dwork, delay);
1094 raw_spin_unlock_irqrestore(&worker->lock, flags);
1097 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1099 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1101 struct kthread_worker *worker = work->worker;
1102 unsigned long flags;
1108 raw_spin_lock_irqsave(&worker->lock, flags);
1109 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1110 WARN_ON_ONCE(work->worker != worker);
1112 ret = __kthread_cancel_work(work, is_dwork, &flags);
1114 if (worker->current_work != work)
1118 * The work is in progress and we need to wait with the lock released.
1119 * In the meantime, block any queuing by setting the canceling counter.
1122 raw_spin_unlock_irqrestore(&worker->lock, flags);
1123 kthread_flush_work(work);
1124 raw_spin_lock_irqsave(&worker->lock, flags);
1128 raw_spin_unlock_irqrestore(&worker->lock, flags);
1134 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1135 * @work: the kthread work to cancel
1137 * Cancel @work and wait for its execution to finish. This function
1138 * can be used even if the work re-queues itself. On return from this
1139 * function, @work is guaranteed to be not pending or executing on any CPU.
1141 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1142 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1144 * The caller must ensure that the worker on which @work was last
1145 * queued can't be destroyed before this function returns.
1147 * Return: %true if @work was pending, %false otherwise.
1149 bool kthread_cancel_work_sync(struct kthread_work *work)
1151 return __kthread_cancel_work_sync(work, false);
1153 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1156 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1157 * wait for it to finish.
1158 * @dwork: the kthread delayed work to cancel
1160 * This is kthread_cancel_work_sync() for delayed works.
1162 * Return: %true if @dwork was pending, %false otherwise.
1164 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1166 return __kthread_cancel_work_sync(&dwork->work, true);
1168 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1171 * kthread_flush_worker - flush all current works on a kthread_worker
1172 * @worker: worker to flush
1174 * Wait until all currently executing or pending works on @worker are
1177 void kthread_flush_worker(struct kthread_worker *worker)
1179 struct kthread_flush_work fwork = {
1180 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1181 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1184 kthread_queue_work(worker, &fwork.work);
1185 wait_for_completion(&fwork.done);
1187 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1190 * kthread_destroy_worker - destroy a kthread worker
1191 * @worker: worker to be destroyed
1193 * Flush and destroy @worker. The simple flush is enough because the kthread
1194 * worker API is used only in trivial scenarios. There are no multi-step state
1197 void kthread_destroy_worker(struct kthread_worker *worker)
1199 struct task_struct *task;
1201 task = worker->task;
1205 kthread_flush_worker(worker);
1207 WARN_ON(!list_empty(&worker->work_list));
1210 EXPORT_SYMBOL(kthread_destroy_worker);
1213 * kthread_use_mm - make the calling kthread operate on an address space
1214 * @mm: address space to operate on
1216 void kthread_use_mm(struct mm_struct *mm)
1218 struct mm_struct *active_mm;
1219 struct task_struct *tsk = current;
1221 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1222 WARN_ON_ONCE(tsk->mm);
1225 active_mm = tsk->active_mm;
1226 if (active_mm != mm) {
1228 tsk->active_mm = mm;
1231 switch_mm(active_mm, mm, tsk);
1233 #ifdef finish_arch_post_lock_switch
1234 finish_arch_post_lock_switch();
1237 if (active_mm != mm)
1240 to_kthread(tsk)->oldfs = get_fs();
1243 EXPORT_SYMBOL_GPL(kthread_use_mm);
1246 * kthread_unuse_mm - reverse the effect of kthread_use_mm()
1247 * @mm: address space to operate on
1249 void kthread_unuse_mm(struct mm_struct *mm)
1251 struct task_struct *tsk = current;
1253 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1254 WARN_ON_ONCE(!tsk->mm);
1256 set_fs(to_kthread(tsk)->oldfs);
1261 /* active_mm is still 'mm' */
1262 enter_lazy_tlb(mm, tsk);
1265 EXPORT_SYMBOL_GPL(kthread_unuse_mm);
1267 #ifdef CONFIG_BLK_CGROUP
1269 * kthread_associate_blkcg - associate blkcg to current kthread
1270 * @css: the cgroup info
1272 * Current thread must be a kthread. The thread is running jobs on behalf of
1273 * other threads. In some cases, we expect the jobs attach cgroup info of
1274 * original threads instead of that of current thread. This function stores
1275 * original thread's cgroup info in current kthread context for later
1278 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1280 struct kthread *kthread;
1282 if (!(current->flags & PF_KTHREAD))
1284 kthread = to_kthread(current);
1288 if (kthread->blkcg_css) {
1289 css_put(kthread->blkcg_css);
1290 kthread->blkcg_css = NULL;
1294 kthread->blkcg_css = css;
1297 EXPORT_SYMBOL(kthread_associate_blkcg);
1300 * kthread_blkcg - get associated blkcg css of current kthread
1302 * Current thread must be a kthread.
1304 struct cgroup_subsys_state *kthread_blkcg(void)
1306 struct kthread *kthread;
1308 if (current->flags & PF_KTHREAD) {
1309 kthread = to_kthread(current);
1311 return kthread->blkcg_css;
1315 EXPORT_SYMBOL(kthread_blkcg);