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;
55 struct completion parked;
56 struct completion exited;
57 #ifdef CONFIG_BLK_CGROUP
58 struct cgroup_subsys_state *blkcg_css;
63 KTHREAD_IS_PER_CPU = 0,
68 static inline void set_kthread_struct(void *kthread)
71 * We abuse ->set_child_tid to avoid the new member and because it
72 * can't be wrongly copied by copy_process(). We also rely on fact
73 * that the caller can't exec, so PF_KTHREAD can't be cleared.
75 current->set_child_tid = (__force void __user *)kthread;
78 static inline struct kthread *to_kthread(struct task_struct *k)
80 WARN_ON(!(k->flags & PF_KTHREAD));
81 return (__force void *)k->set_child_tid;
84 void free_kthread_struct(struct task_struct *k)
86 struct kthread *kthread;
89 * Can be NULL if this kthread was created by kernel_thread()
90 * or if kmalloc() in kthread() failed.
92 kthread = to_kthread(k);
93 #ifdef CONFIG_BLK_CGROUP
94 WARN_ON_ONCE(kthread && kthread->blkcg_css);
100 * kthread_should_stop - should this kthread return now?
102 * When someone calls kthread_stop() on your kthread, it will be woken
103 * and this will return true. You should then return, and your return
104 * value will be passed through to kthread_stop().
106 bool kthread_should_stop(void)
108 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
110 EXPORT_SYMBOL(kthread_should_stop);
112 bool __kthread_should_park(struct task_struct *k)
114 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
116 EXPORT_SYMBOL_GPL(__kthread_should_park);
119 * kthread_should_park - should this kthread park now?
121 * When someone calls kthread_park() on your kthread, it will be woken
122 * and this will return true. You should then do the necessary
123 * cleanup and call kthread_parkme()
125 * Similar to kthread_should_stop(), but this keeps the thread alive
126 * and in a park position. kthread_unpark() "restarts" the thread and
127 * calls the thread function again.
129 bool kthread_should_park(void)
131 return __kthread_should_park(current);
133 EXPORT_SYMBOL_GPL(kthread_should_park);
136 * kthread_freezable_should_stop - should this freezable kthread return now?
137 * @was_frozen: optional out parameter, indicates whether %current was frozen
139 * kthread_should_stop() for freezable kthreads, which will enter
140 * refrigerator if necessary. This function is safe from kthread_stop() /
141 * freezer deadlock and freezable kthreads should use this function instead
142 * of calling try_to_freeze() directly.
144 bool kthread_freezable_should_stop(bool *was_frozen)
150 if (unlikely(freezing(current)))
151 frozen = __refrigerator(true);
154 *was_frozen = frozen;
156 return kthread_should_stop();
158 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
161 * kthread_data - return data value specified on kthread creation
162 * @task: kthread task in question
164 * Return the data value specified when kthread @task was created.
165 * The caller is responsible for ensuring the validity of @task when
166 * calling this function.
168 void *kthread_data(struct task_struct *task)
170 return to_kthread(task)->data;
174 * kthread_probe_data - speculative version of kthread_data()
175 * @task: possible kthread task in question
177 * @task could be a kthread task. Return the data value specified when it
178 * was created if accessible. If @task isn't a kthread task or its data is
179 * inaccessible for any reason, %NULL is returned. This function requires
180 * that @task itself is safe to dereference.
182 void *kthread_probe_data(struct task_struct *task)
184 struct kthread *kthread = to_kthread(task);
187 probe_kernel_read(&data, &kthread->data, sizeof(data));
191 static void __kthread_parkme(struct kthread *self)
195 * TASK_PARKED is a special state; we must serialize against
196 * possible pending wakeups to avoid store-store collisions on
199 * Such a collision might possibly result in the task state
200 * changin from TASK_PARKED and us failing the
201 * wait_task_inactive() in kthread_park().
203 set_special_state(TASK_PARKED);
204 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
208 * Thread is going to call schedule(), do not preempt it,
209 * or the caller of kthread_park() may spend more time in
210 * wait_task_inactive().
213 complete(&self->parked);
214 schedule_preempt_disabled();
217 __set_current_state(TASK_RUNNING);
220 void kthread_parkme(void)
222 __kthread_parkme(to_kthread(current));
224 EXPORT_SYMBOL_GPL(kthread_parkme);
226 static int kthread(void *_create)
228 /* Copy data: it's on kthread's stack */
229 struct kthread_create_info *create = _create;
230 int (*threadfn)(void *data) = create->threadfn;
231 void *data = create->data;
232 struct completion *done;
233 struct kthread *self;
236 self = kzalloc(sizeof(*self), GFP_KERNEL);
237 set_kthread_struct(self);
239 /* If user was SIGKILLed, I release the structure. */
240 done = xchg(&create->done, NULL);
247 create->result = ERR_PTR(-ENOMEM);
253 init_completion(&self->exited);
254 init_completion(&self->parked);
255 current->vfork_done = &self->exited;
257 /* OK, tell user we're spawned, wait for stop or wakeup */
258 __set_current_state(TASK_UNINTERRUPTIBLE);
259 create->result = current;
261 * Thread is going to call schedule(), do not preempt it,
262 * or the creator may spend more time in wait_task_inactive().
266 schedule_preempt_disabled();
270 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
271 cgroup_kthread_ready();
272 __kthread_parkme(self);
273 ret = threadfn(data);
278 /* called from do_fork() to get node information for about to be created task */
279 int tsk_fork_get_node(struct task_struct *tsk)
282 if (tsk == kthreadd_task)
283 return tsk->pref_node_fork;
288 static void create_kthread(struct kthread_create_info *create)
293 current->pref_node_fork = create->node;
295 /* We want our own signal handler (we take no signals by default). */
296 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
298 /* If user was SIGKILLed, I release the structure. */
299 struct completion *done = xchg(&create->done, NULL);
305 create->result = ERR_PTR(pid);
310 static __printf(4, 0)
311 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
312 void *data, int node,
313 const char namefmt[],
316 DECLARE_COMPLETION_ONSTACK(done);
317 struct task_struct *task;
318 struct kthread_create_info *create = kmalloc(sizeof(*create),
322 return ERR_PTR(-ENOMEM);
323 create->threadfn = threadfn;
326 create->done = &done;
328 spin_lock(&kthread_create_lock);
329 list_add_tail(&create->list, &kthread_create_list);
330 spin_unlock(&kthread_create_lock);
332 wake_up_process(kthreadd_task);
334 * Wait for completion in killable state, for I might be chosen by
335 * the OOM killer while kthreadd is trying to allocate memory for
338 if (unlikely(wait_for_completion_killable(&done))) {
340 * If I was SIGKILLed before kthreadd (or new kernel thread)
341 * calls complete(), leave the cleanup of this structure to
344 if (xchg(&create->done, NULL))
345 return ERR_PTR(-EINTR);
347 * kthreadd (or new kernel thread) will call complete()
350 wait_for_completion(&done);
352 task = create->result;
354 static const struct sched_param param = { .sched_priority = 0 };
355 char name[TASK_COMM_LEN];
358 * task is already visible to other tasks, so updating
359 * COMM must be protected.
361 vsnprintf(name, sizeof(name), namefmt, args);
362 set_task_comm(task, name);
364 * root may have changed our (kthreadd's) priority or CPU mask.
365 * The kernel thread should not inherit these properties.
367 sched_setscheduler_nocheck(task, SCHED_NORMAL, ¶m);
368 set_cpus_allowed_ptr(task, cpu_all_mask);
375 * kthread_create_on_node - create a kthread.
376 * @threadfn: the function to run until signal_pending(current).
377 * @data: data ptr for @threadfn.
378 * @node: task and thread structures for the thread are allocated on this node
379 * @namefmt: printf-style name for the thread.
381 * Description: This helper function creates and names a kernel
382 * thread. The thread will be stopped: use wake_up_process() to start
383 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
384 * is affine to all CPUs.
386 * If thread is going to be bound on a particular cpu, give its node
387 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
388 * When woken, the thread will run @threadfn() with @data as its
389 * argument. @threadfn() can either call do_exit() directly if it is a
390 * standalone thread for which no one will call kthread_stop(), or
391 * return when 'kthread_should_stop()' is true (which means
392 * kthread_stop() has been called). The return value should be zero
393 * or a negative error number; it will be passed to kthread_stop().
395 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
397 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
398 void *data, int node,
399 const char namefmt[],
402 struct task_struct *task;
405 va_start(args, namefmt);
406 task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
411 EXPORT_SYMBOL(kthread_create_on_node);
413 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, long state)
417 if (!wait_task_inactive(p, state)) {
422 /* It's safe because the task is inactive. */
423 raw_spin_lock_irqsave(&p->pi_lock, flags);
424 do_set_cpus_allowed(p, mask);
425 p->flags |= PF_NO_SETAFFINITY;
426 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
429 static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
431 __kthread_bind_mask(p, cpumask_of(cpu), state);
434 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
436 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
440 * kthread_bind - bind a just-created kthread to a cpu.
441 * @p: thread created by kthread_create().
442 * @cpu: cpu (might not be online, must be possible) for @k to run on.
444 * Description: This function is equivalent to set_cpus_allowed(),
445 * except that @cpu doesn't need to be online, and the thread must be
446 * stopped (i.e., just returned from kthread_create()).
448 void kthread_bind(struct task_struct *p, unsigned int cpu)
450 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
452 EXPORT_SYMBOL(kthread_bind);
455 * kthread_create_on_cpu - Create a cpu bound kthread
456 * @threadfn: the function to run until signal_pending(current).
457 * @data: data ptr for @threadfn.
458 * @cpu: The cpu on which the thread should be bound,
459 * @namefmt: printf-style name for the thread. Format is restricted
460 * to "name.*%u". Code fills in cpu number.
462 * Description: This helper function creates and names a kernel thread
463 * The thread will be woken and put into park mode.
465 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
466 void *data, unsigned int cpu,
469 struct task_struct *p;
471 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
475 kthread_bind(p, cpu);
476 /* CPU hotplug need to bind once again when unparking the thread. */
477 set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
478 to_kthread(p)->cpu = cpu;
483 * kthread_unpark - unpark a thread created by kthread_create().
484 * @k: thread created by kthread_create().
486 * Sets kthread_should_park() for @k to return false, wakes it, and
487 * waits for it to return. If the thread is marked percpu then its
488 * bound to the cpu again.
490 void kthread_unpark(struct task_struct *k)
492 struct kthread *kthread = to_kthread(k);
495 * Newly created kthread was parked when the CPU was offline.
496 * The binding was lost and we need to set it again.
498 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
499 __kthread_bind(k, kthread->cpu, TASK_PARKED);
501 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
503 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
505 wake_up_state(k, TASK_PARKED);
507 EXPORT_SYMBOL_GPL(kthread_unpark);
510 * kthread_park - park a thread created by kthread_create().
511 * @k: thread created by kthread_create().
513 * Sets kthread_should_park() for @k to return true, wakes it, and
514 * waits for it to return. This can also be called after kthread_create()
515 * instead of calling wake_up_process(): the thread will park without
516 * calling threadfn().
518 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
519 * If called by the kthread itself just the park bit is set.
521 int kthread_park(struct task_struct *k)
523 struct kthread *kthread = to_kthread(k);
525 if (WARN_ON(k->flags & PF_EXITING))
528 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
531 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
535 * Wait for __kthread_parkme() to complete(), this means we
536 * _will_ have TASK_PARKED and are about to call schedule().
538 wait_for_completion(&kthread->parked);
540 * Now wait for that schedule() to complete and the task to
543 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
548 EXPORT_SYMBOL_GPL(kthread_park);
551 * kthread_stop - stop a thread created by kthread_create().
552 * @k: thread created by kthread_create().
554 * Sets kthread_should_stop() for @k to return true, wakes it, and
555 * waits for it to exit. This can also be called after kthread_create()
556 * instead of calling wake_up_process(): the thread will exit without
557 * calling threadfn().
559 * If threadfn() may call do_exit() itself, the caller must ensure
560 * task_struct can't go away.
562 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
565 int kthread_stop(struct task_struct *k)
567 struct kthread *kthread;
570 trace_sched_kthread_stop(k);
573 kthread = to_kthread(k);
574 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
577 wait_for_completion(&kthread->exited);
581 trace_sched_kthread_stop_ret(ret);
584 EXPORT_SYMBOL(kthread_stop);
586 int kthreadd(void *unused)
588 struct task_struct *tsk = current;
590 /* Setup a clean context for our children to inherit. */
591 set_task_comm(tsk, "kthreadd");
593 set_cpus_allowed_ptr(tsk, cpu_all_mask);
594 set_mems_allowed(node_states[N_MEMORY]);
596 current->flags |= PF_NOFREEZE;
597 cgroup_init_kthreadd();
600 set_current_state(TASK_INTERRUPTIBLE);
601 if (list_empty(&kthread_create_list))
603 __set_current_state(TASK_RUNNING);
605 spin_lock(&kthread_create_lock);
606 while (!list_empty(&kthread_create_list)) {
607 struct kthread_create_info *create;
609 create = list_entry(kthread_create_list.next,
610 struct kthread_create_info, list);
611 list_del_init(&create->list);
612 spin_unlock(&kthread_create_lock);
614 create_kthread(create);
616 spin_lock(&kthread_create_lock);
618 spin_unlock(&kthread_create_lock);
624 void __kthread_init_worker(struct kthread_worker *worker,
626 struct lock_class_key *key)
628 memset(worker, 0, sizeof(struct kthread_worker));
629 raw_spin_lock_init(&worker->lock);
630 lockdep_set_class_and_name(&worker->lock, key, name);
631 INIT_LIST_HEAD(&worker->work_list);
632 INIT_LIST_HEAD(&worker->delayed_work_list);
634 EXPORT_SYMBOL_GPL(__kthread_init_worker);
637 * kthread_worker_fn - kthread function to process kthread_worker
638 * @worker_ptr: pointer to initialized kthread_worker
640 * This function implements the main cycle of kthread worker. It processes
641 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
644 * The works are not allowed to keep any locks, disable preemption or interrupts
645 * when they finish. There is defined a safe point for freezing when one work
646 * finishes and before a new one is started.
648 * Also the works must not be handled by more than one worker at the same time,
649 * see also kthread_queue_work().
651 int kthread_worker_fn(void *worker_ptr)
653 struct kthread_worker *worker = worker_ptr;
654 struct kthread_work *work;
657 * FIXME: Update the check and remove the assignment when all kthread
658 * worker users are created using kthread_create_worker*() functions.
660 WARN_ON(worker->task && worker->task != current);
661 worker->task = current;
663 if (worker->flags & KTW_FREEZABLE)
667 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
669 if (kthread_should_stop()) {
670 __set_current_state(TASK_RUNNING);
671 raw_spin_lock_irq(&worker->lock);
673 raw_spin_unlock_irq(&worker->lock);
678 raw_spin_lock_irq(&worker->lock);
679 if (!list_empty(&worker->work_list)) {
680 work = list_first_entry(&worker->work_list,
681 struct kthread_work, node);
682 list_del_init(&work->node);
684 worker->current_work = work;
685 raw_spin_unlock_irq(&worker->lock);
688 __set_current_state(TASK_RUNNING);
690 } else if (!freezing(current))
697 EXPORT_SYMBOL_GPL(kthread_worker_fn);
699 static __printf(3, 0) struct kthread_worker *
700 __kthread_create_worker(int cpu, unsigned int flags,
701 const char namefmt[], va_list args)
703 struct kthread_worker *worker;
704 struct task_struct *task;
705 int node = NUMA_NO_NODE;
707 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
709 return ERR_PTR(-ENOMEM);
711 kthread_init_worker(worker);
714 node = cpu_to_node(cpu);
716 task = __kthread_create_on_node(kthread_worker_fn, worker,
717 node, namefmt, args);
722 kthread_bind(task, cpu);
724 worker->flags = flags;
726 wake_up_process(task);
731 return ERR_CAST(task);
735 * kthread_create_worker - create a kthread worker
736 * @flags: flags modifying the default behavior of the worker
737 * @namefmt: printf-style name for the kthread worker (task).
739 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
740 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
741 * when the worker was SIGKILLed.
743 struct kthread_worker *
744 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
746 struct kthread_worker *worker;
749 va_start(args, namefmt);
750 worker = __kthread_create_worker(-1, flags, namefmt, args);
755 EXPORT_SYMBOL(kthread_create_worker);
758 * kthread_create_worker_on_cpu - create a kthread worker and bind it
759 * it to a given CPU and the associated NUMA node.
761 * @flags: flags modifying the default behavior of the worker
762 * @namefmt: printf-style name for the kthread worker (task).
764 * Use a valid CPU number if you want to bind the kthread worker
765 * to the given CPU and the associated NUMA node.
767 * A good practice is to add the cpu number also into the worker name.
768 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
770 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
771 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
772 * when the worker was SIGKILLed.
774 struct kthread_worker *
775 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
776 const char namefmt[], ...)
778 struct kthread_worker *worker;
781 va_start(args, namefmt);
782 worker = __kthread_create_worker(cpu, flags, namefmt, args);
787 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
790 * Returns true when the work could not be queued at the moment.
791 * It happens when it is already pending in a worker list
792 * or when it is being cancelled.
794 static inline bool queuing_blocked(struct kthread_worker *worker,
795 struct kthread_work *work)
797 lockdep_assert_held(&worker->lock);
799 return !list_empty(&work->node) || work->canceling;
802 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
803 struct kthread_work *work)
805 lockdep_assert_held(&worker->lock);
806 WARN_ON_ONCE(!list_empty(&work->node));
807 /* Do not use a work with >1 worker, see kthread_queue_work() */
808 WARN_ON_ONCE(work->worker && work->worker != worker);
811 /* insert @work before @pos in @worker */
812 static void kthread_insert_work(struct kthread_worker *worker,
813 struct kthread_work *work,
814 struct list_head *pos)
816 kthread_insert_work_sanity_check(worker, work);
818 list_add_tail(&work->node, pos);
819 work->worker = worker;
820 if (!worker->current_work && likely(worker->task))
821 wake_up_process(worker->task);
825 * kthread_queue_work - queue a kthread_work
826 * @worker: target kthread_worker
827 * @work: kthread_work to queue
829 * Queue @work to work processor @task for async execution. @task
830 * must have been created with kthread_worker_create(). Returns %true
831 * if @work was successfully queued, %false if it was already pending.
833 * Reinitialize the work if it needs to be used by another worker.
834 * For example, when the worker was stopped and started again.
836 bool kthread_queue_work(struct kthread_worker *worker,
837 struct kthread_work *work)
842 raw_spin_lock_irqsave(&worker->lock, flags);
843 if (!queuing_blocked(worker, work)) {
844 kthread_insert_work(worker, work, &worker->work_list);
847 raw_spin_unlock_irqrestore(&worker->lock, flags);
850 EXPORT_SYMBOL_GPL(kthread_queue_work);
853 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
854 * delayed work when the timer expires.
855 * @t: pointer to the expired timer
857 * The format of the function is defined by struct timer_list.
858 * It should have been called from irqsafe timer with irq already off.
860 void kthread_delayed_work_timer_fn(struct timer_list *t)
862 struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
863 struct kthread_work *work = &dwork->work;
864 struct kthread_worker *worker = work->worker;
868 * This might happen when a pending work is reinitialized.
869 * It means that it is used a wrong way.
871 if (WARN_ON_ONCE(!worker))
874 raw_spin_lock_irqsave(&worker->lock, flags);
875 /* Work must not be used with >1 worker, see kthread_queue_work(). */
876 WARN_ON_ONCE(work->worker != worker);
878 /* Move the work from worker->delayed_work_list. */
879 WARN_ON_ONCE(list_empty(&work->node));
880 list_del_init(&work->node);
881 kthread_insert_work(worker, work, &worker->work_list);
883 raw_spin_unlock_irqrestore(&worker->lock, flags);
885 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
887 static void __kthread_queue_delayed_work(struct kthread_worker *worker,
888 struct kthread_delayed_work *dwork,
891 struct timer_list *timer = &dwork->timer;
892 struct kthread_work *work = &dwork->work;
894 WARN_ON_ONCE(timer->function != kthread_delayed_work_timer_fn);
897 * If @delay is 0, queue @dwork->work immediately. This is for
898 * both optimization and correctness. The earliest @timer can
899 * expire is on the closest next tick and delayed_work users depend
900 * on that there's no such delay when @delay is 0.
903 kthread_insert_work(worker, work, &worker->work_list);
907 /* Be paranoid and try to detect possible races already now. */
908 kthread_insert_work_sanity_check(worker, work);
910 list_add(&work->node, &worker->delayed_work_list);
911 work->worker = worker;
912 timer->expires = jiffies + delay;
917 * kthread_queue_delayed_work - queue the associated kthread work
919 * @worker: target kthread_worker
920 * @dwork: kthread_delayed_work to queue
921 * @delay: number of jiffies to wait before queuing
923 * If the work has not been pending it starts a timer that will queue
924 * the work after the given @delay. If @delay is zero, it queues the
927 * Return: %false if the @work has already been pending. It means that
928 * either the timer was running or the work was queued. It returns %true
931 bool kthread_queue_delayed_work(struct kthread_worker *worker,
932 struct kthread_delayed_work *dwork,
935 struct kthread_work *work = &dwork->work;
939 raw_spin_lock_irqsave(&worker->lock, flags);
941 if (!queuing_blocked(worker, work)) {
942 __kthread_queue_delayed_work(worker, dwork, delay);
946 raw_spin_unlock_irqrestore(&worker->lock, flags);
949 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
951 struct kthread_flush_work {
952 struct kthread_work work;
953 struct completion done;
956 static void kthread_flush_work_fn(struct kthread_work *work)
958 struct kthread_flush_work *fwork =
959 container_of(work, struct kthread_flush_work, work);
960 complete(&fwork->done);
964 * kthread_flush_work - flush a kthread_work
965 * @work: work to flush
967 * If @work is queued or executing, wait for it to finish execution.
969 void kthread_flush_work(struct kthread_work *work)
971 struct kthread_flush_work fwork = {
972 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
973 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
975 struct kthread_worker *worker;
978 worker = work->worker;
982 raw_spin_lock_irq(&worker->lock);
983 /* Work must not be used with >1 worker, see kthread_queue_work(). */
984 WARN_ON_ONCE(work->worker != worker);
986 if (!list_empty(&work->node))
987 kthread_insert_work(worker, &fwork.work, work->node.next);
988 else if (worker->current_work == work)
989 kthread_insert_work(worker, &fwork.work,
990 worker->work_list.next);
994 raw_spin_unlock_irq(&worker->lock);
997 wait_for_completion(&fwork.done);
999 EXPORT_SYMBOL_GPL(kthread_flush_work);
1002 * This function removes the work from the worker queue. Also it makes sure
1003 * that it won't get queued later via the delayed work's timer.
1005 * The work might still be in use when this function finishes. See the
1006 * current_work proceed by the worker.
1008 * Return: %true if @work was pending and successfully canceled,
1009 * %false if @work was not pending
1011 static bool __kthread_cancel_work(struct kthread_work *work, bool is_dwork,
1012 unsigned long *flags)
1014 /* Try to cancel the timer if exists. */
1016 struct kthread_delayed_work *dwork =
1017 container_of(work, struct kthread_delayed_work, work);
1018 struct kthread_worker *worker = work->worker;
1021 * del_timer_sync() must be called to make sure that the timer
1022 * callback is not running. The lock must be temporary released
1023 * to avoid a deadlock with the callback. In the meantime,
1024 * any queuing is blocked by setting the canceling counter.
1027 raw_spin_unlock_irqrestore(&worker->lock, *flags);
1028 del_timer_sync(&dwork->timer);
1029 raw_spin_lock_irqsave(&worker->lock, *flags);
1034 * Try to remove the work from a worker list. It might either
1035 * be from worker->work_list or from worker->delayed_work_list.
1037 if (!list_empty(&work->node)) {
1038 list_del_init(&work->node);
1046 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1047 * @worker: kthread worker to use
1048 * @dwork: kthread delayed work to queue
1049 * @delay: number of jiffies to wait before queuing
1051 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1052 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1053 * @work is guaranteed to be queued immediately.
1055 * Return: %true if @dwork was pending and its timer was modified,
1058 * A special case is when the work is being canceled in parallel.
1059 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1060 * or yet another kthread_mod_delayed_work() call. We let the other command
1061 * win and return %false here. The caller is supposed to synchronize these
1062 * operations a reasonable way.
1064 * This function is safe to call from any context including IRQ handler.
1065 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1068 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1069 struct kthread_delayed_work *dwork,
1070 unsigned long delay)
1072 struct kthread_work *work = &dwork->work;
1073 unsigned long flags;
1076 raw_spin_lock_irqsave(&worker->lock, flags);
1078 /* Do not bother with canceling when never queued. */
1082 /* Work must not be used with >1 worker, see kthread_queue_work() */
1083 WARN_ON_ONCE(work->worker != worker);
1085 /* Do not fight with another command that is canceling this work. */
1086 if (work->canceling)
1089 ret = __kthread_cancel_work(work, true, &flags);
1091 __kthread_queue_delayed_work(worker, dwork, delay);
1093 raw_spin_unlock_irqrestore(&worker->lock, flags);
1096 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1098 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1100 struct kthread_worker *worker = work->worker;
1101 unsigned long flags;
1107 raw_spin_lock_irqsave(&worker->lock, flags);
1108 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1109 WARN_ON_ONCE(work->worker != worker);
1111 ret = __kthread_cancel_work(work, is_dwork, &flags);
1113 if (worker->current_work != work)
1117 * The work is in progress and we need to wait with the lock released.
1118 * In the meantime, block any queuing by setting the canceling counter.
1121 raw_spin_unlock_irqrestore(&worker->lock, flags);
1122 kthread_flush_work(work);
1123 raw_spin_lock_irqsave(&worker->lock, flags);
1127 raw_spin_unlock_irqrestore(&worker->lock, flags);
1133 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1134 * @work: the kthread work to cancel
1136 * Cancel @work and wait for its execution to finish. This function
1137 * can be used even if the work re-queues itself. On return from this
1138 * function, @work is guaranteed to be not pending or executing on any CPU.
1140 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1141 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1143 * The caller must ensure that the worker on which @work was last
1144 * queued can't be destroyed before this function returns.
1146 * Return: %true if @work was pending, %false otherwise.
1148 bool kthread_cancel_work_sync(struct kthread_work *work)
1150 return __kthread_cancel_work_sync(work, false);
1152 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1155 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1156 * wait for it to finish.
1157 * @dwork: the kthread delayed work to cancel
1159 * This is kthread_cancel_work_sync() for delayed works.
1161 * Return: %true if @dwork was pending, %false otherwise.
1163 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1165 return __kthread_cancel_work_sync(&dwork->work, true);
1167 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1170 * kthread_flush_worker - flush all current works on a kthread_worker
1171 * @worker: worker to flush
1173 * Wait until all currently executing or pending works on @worker are
1176 void kthread_flush_worker(struct kthread_worker *worker)
1178 struct kthread_flush_work fwork = {
1179 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1180 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1183 kthread_queue_work(worker, &fwork.work);
1184 wait_for_completion(&fwork.done);
1186 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1189 * kthread_destroy_worker - destroy a kthread worker
1190 * @worker: worker to be destroyed
1192 * Flush and destroy @worker. The simple flush is enough because the kthread
1193 * worker API is used only in trivial scenarios. There are no multi-step state
1196 void kthread_destroy_worker(struct kthread_worker *worker)
1198 struct task_struct *task;
1200 task = worker->task;
1204 kthread_flush_worker(worker);
1206 WARN_ON(!list_empty(&worker->work_list));
1209 EXPORT_SYMBOL(kthread_destroy_worker);
1212 * kthread_use_mm - make the calling kthread operate on an address space
1213 * @mm: address space to operate on
1215 void kthread_use_mm(struct mm_struct *mm)
1217 struct mm_struct *active_mm;
1218 struct task_struct *tsk = current;
1220 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1221 WARN_ON_ONCE(tsk->mm);
1224 active_mm = tsk->active_mm;
1225 if (active_mm != mm) {
1227 tsk->active_mm = mm;
1230 switch_mm(active_mm, mm, tsk);
1232 #ifdef finish_arch_post_lock_switch
1233 finish_arch_post_lock_switch();
1236 if (active_mm != mm)
1239 EXPORT_SYMBOL_GPL(kthread_use_mm);
1242 * kthread_unuse_mm - reverse the effect of kthread_use_mm()
1243 * @mm: address space to operate on
1245 void kthread_unuse_mm(struct mm_struct *mm)
1247 struct task_struct *tsk = current;
1249 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1250 WARN_ON_ONCE(!tsk->mm);
1255 /* active_mm is still 'mm' */
1256 enter_lazy_tlb(mm, tsk);
1259 EXPORT_SYMBOL_GPL(kthread_unuse_mm);
1261 #ifdef CONFIG_BLK_CGROUP
1263 * kthread_associate_blkcg - associate blkcg to current kthread
1264 * @css: the cgroup info
1266 * Current thread must be a kthread. The thread is running jobs on behalf of
1267 * other threads. In some cases, we expect the jobs attach cgroup info of
1268 * original threads instead of that of current thread. This function stores
1269 * original thread's cgroup info in current kthread context for later
1272 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1274 struct kthread *kthread;
1276 if (!(current->flags & PF_KTHREAD))
1278 kthread = to_kthread(current);
1282 if (kthread->blkcg_css) {
1283 css_put(kthread->blkcg_css);
1284 kthread->blkcg_css = NULL;
1288 kthread->blkcg_css = css;
1291 EXPORT_SYMBOL(kthread_associate_blkcg);
1294 * kthread_blkcg - get associated blkcg css of current kthread
1296 * Current thread must be a kthread.
1298 struct cgroup_subsys_state *kthread_blkcg(void)
1300 struct kthread *kthread;
1302 if (current->flags & PF_KTHREAD) {
1303 kthread = to_kthread(current);
1305 return kthread->blkcg_css;
1309 EXPORT_SYMBOL(kthread_blkcg);