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 <linux/sched/isolation.h>
31 #include <trace/events/sched.h>
34 static DEFINE_SPINLOCK(kthread_create_lock);
35 static LIST_HEAD(kthread_create_list);
36 struct task_struct *kthreadd_task;
38 struct kthread_create_info
40 /* Information passed to kthread() from kthreadd. */
41 int (*threadfn)(void *data);
45 /* Result passed back to kthread_create() from kthreadd. */
46 struct task_struct *result;
47 struct completion *done;
49 struct list_head list;
56 int (*threadfn)(void *);
59 struct completion parked;
60 struct completion exited;
61 #ifdef CONFIG_BLK_CGROUP
62 struct cgroup_subsys_state *blkcg_css;
67 KTHREAD_IS_PER_CPU = 0,
72 static inline struct kthread *to_kthread(struct task_struct *k)
74 WARN_ON(!(k->flags & PF_KTHREAD));
75 return k->worker_private;
79 * Variant of to_kthread() that doesn't assume @p is a kthread.
81 * Per construction; when:
83 * (p->flags & PF_KTHREAD) && p->worker_private
85 * the task is both a kthread and struct kthread is persistent. However
86 * PF_KTHREAD on it's own is not, kernel_thread() can exec() (See umh.c and
89 static inline struct kthread *__to_kthread(struct task_struct *p)
91 void *kthread = p->worker_private;
92 if (kthread && !(p->flags & PF_KTHREAD))
97 bool set_kthread_struct(struct task_struct *p)
99 struct kthread *kthread;
101 if (WARN_ON_ONCE(to_kthread(p)))
104 kthread = kzalloc(sizeof(*kthread), GFP_KERNEL);
108 init_completion(&kthread->exited);
109 init_completion(&kthread->parked);
110 p->vfork_done = &kthread->exited;
112 p->worker_private = kthread;
116 void free_kthread_struct(struct task_struct *k)
118 struct kthread *kthread;
121 * Can be NULL if kmalloc() in set_kthread_struct() failed.
123 kthread = to_kthread(k);
124 #ifdef CONFIG_BLK_CGROUP
125 WARN_ON_ONCE(kthread && kthread->blkcg_css);
127 k->worker_private = NULL;
132 * kthread_should_stop - should this kthread return now?
134 * When someone calls kthread_stop() on your kthread, it will be woken
135 * and this will return true. You should then return, and your return
136 * value will be passed through to kthread_stop().
138 bool kthread_should_stop(void)
140 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
142 EXPORT_SYMBOL(kthread_should_stop);
144 bool __kthread_should_park(struct task_struct *k)
146 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(k)->flags);
148 EXPORT_SYMBOL_GPL(__kthread_should_park);
151 * kthread_should_park - should this kthread park now?
153 * When someone calls kthread_park() on your kthread, it will be woken
154 * and this will return true. You should then do the necessary
155 * cleanup and call kthread_parkme()
157 * Similar to kthread_should_stop(), but this keeps the thread alive
158 * and in a park position. kthread_unpark() "restarts" the thread and
159 * calls the thread function again.
161 bool kthread_should_park(void)
163 return __kthread_should_park(current);
165 EXPORT_SYMBOL_GPL(kthread_should_park);
168 * kthread_freezable_should_stop - should this freezable kthread return now?
169 * @was_frozen: optional out parameter, indicates whether %current was frozen
171 * kthread_should_stop() for freezable kthreads, which will enter
172 * refrigerator if necessary. This function is safe from kthread_stop() /
173 * freezer deadlock and freezable kthreads should use this function instead
174 * of calling try_to_freeze() directly.
176 bool kthread_freezable_should_stop(bool *was_frozen)
182 if (unlikely(freezing(current)))
183 frozen = __refrigerator(true);
186 *was_frozen = frozen;
188 return kthread_should_stop();
190 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
193 * kthread_func - return the function specified on kthread creation
194 * @task: kthread task in question
196 * Returns NULL if the task is not a kthread.
198 void *kthread_func(struct task_struct *task)
200 struct kthread *kthread = __to_kthread(task);
202 return kthread->threadfn;
205 EXPORT_SYMBOL_GPL(kthread_func);
208 * kthread_data - return data value specified on kthread creation
209 * @task: kthread task in question
211 * Return the data value specified when kthread @task was created.
212 * The caller is responsible for ensuring the validity of @task when
213 * calling this function.
215 void *kthread_data(struct task_struct *task)
217 return to_kthread(task)->data;
219 EXPORT_SYMBOL_GPL(kthread_data);
222 * kthread_probe_data - speculative version of kthread_data()
223 * @task: possible kthread task in question
225 * @task could be a kthread task. Return the data value specified when it
226 * was created if accessible. If @task isn't a kthread task or its data is
227 * inaccessible for any reason, %NULL is returned. This function requires
228 * that @task itself is safe to dereference.
230 void *kthread_probe_data(struct task_struct *task)
232 struct kthread *kthread = __to_kthread(task);
236 copy_from_kernel_nofault(&data, &kthread->data, sizeof(data));
240 static void __kthread_parkme(struct kthread *self)
244 * TASK_PARKED is a special state; we must serialize against
245 * possible pending wakeups to avoid store-store collisions on
248 * Such a collision might possibly result in the task state
249 * changin from TASK_PARKED and us failing the
250 * wait_task_inactive() in kthread_park().
252 set_special_state(TASK_PARKED);
253 if (!test_bit(KTHREAD_SHOULD_PARK, &self->flags))
257 * Thread is going to call schedule(), do not preempt it,
258 * or the caller of kthread_park() may spend more time in
259 * wait_task_inactive().
262 complete(&self->parked);
263 schedule_preempt_disabled();
266 __set_current_state(TASK_RUNNING);
269 void kthread_parkme(void)
271 __kthread_parkme(to_kthread(current));
273 EXPORT_SYMBOL_GPL(kthread_parkme);
276 * kthread_exit - Cause the current kthread return @result to kthread_stop().
277 * @result: The integer value to return to kthread_stop().
279 * While kthread_exit can be called directly, it exists so that
280 * functions which do some additional work in non-modular code such as
281 * module_put_and_kthread_exit can be implemented.
285 void __noreturn kthread_exit(long result)
287 struct kthread *kthread = to_kthread(current);
288 kthread->result = result;
293 * kthread_complete_and_exit - Exit the current kthread.
294 * @comp: Completion to complete
295 * @code: The integer value to return to kthread_stop().
297 * If present complete @comp and the reuturn code to kthread_stop().
299 * A kernel thread whose module may be removed after the completion of
300 * @comp can use this function exit safely.
304 void __noreturn kthread_complete_and_exit(struct completion *comp, long code)
311 EXPORT_SYMBOL(kthread_complete_and_exit);
313 static int kthread(void *_create)
315 static const struct sched_param param = { .sched_priority = 0 };
316 /* Copy data: it's on kthread's stack */
317 struct kthread_create_info *create = _create;
318 int (*threadfn)(void *data) = create->threadfn;
319 void *data = create->data;
320 struct completion *done;
321 struct kthread *self;
324 self = to_kthread(current);
326 /* If user was SIGKILLed, I release the structure. */
327 done = xchg(&create->done, NULL);
330 kthread_exit(-EINTR);
333 self->threadfn = threadfn;
337 * The new thread inherited kthreadd's priority and CPU mask. Reset
338 * back to default in case they have been changed.
340 sched_setscheduler_nocheck(current, SCHED_NORMAL, ¶m);
341 set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_KTHREAD));
343 /* OK, tell user we're spawned, wait for stop or wakeup */
344 __set_current_state(TASK_UNINTERRUPTIBLE);
345 create->result = current;
347 * Thread is going to call schedule(), do not preempt it,
348 * or the creator may spend more time in wait_task_inactive().
352 schedule_preempt_disabled();
356 if (!test_bit(KTHREAD_SHOULD_STOP, &self->flags)) {
357 cgroup_kthread_ready();
358 __kthread_parkme(self);
359 ret = threadfn(data);
364 /* called from kernel_clone() to get node information for about to be created task */
365 int tsk_fork_get_node(struct task_struct *tsk)
368 if (tsk == kthreadd_task)
369 return tsk->pref_node_fork;
374 static void create_kthread(struct kthread_create_info *create)
379 current->pref_node_fork = create->node;
381 /* We want our own signal handler (we take no signals by default). */
382 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
384 /* If user was SIGKILLed, I release the structure. */
385 struct completion *done = xchg(&create->done, NULL);
391 create->result = ERR_PTR(pid);
396 static __printf(4, 0)
397 struct task_struct *__kthread_create_on_node(int (*threadfn)(void *data),
398 void *data, int node,
399 const char namefmt[],
402 DECLARE_COMPLETION_ONSTACK(done);
403 struct task_struct *task;
404 struct kthread_create_info *create = kmalloc(sizeof(*create),
408 return ERR_PTR(-ENOMEM);
409 create->threadfn = threadfn;
412 create->done = &done;
414 spin_lock(&kthread_create_lock);
415 list_add_tail(&create->list, &kthread_create_list);
416 spin_unlock(&kthread_create_lock);
418 wake_up_process(kthreadd_task);
420 * Wait for completion in killable state, for I might be chosen by
421 * the OOM killer while kthreadd is trying to allocate memory for
424 if (unlikely(wait_for_completion_killable(&done))) {
426 * If I was SIGKILLed before kthreadd (or new kernel thread)
427 * calls complete(), leave the cleanup of this structure to
430 if (xchg(&create->done, NULL))
431 return ERR_PTR(-EINTR);
433 * kthreadd (or new kernel thread) will call complete()
436 wait_for_completion(&done);
438 task = create->result;
440 char name[TASK_COMM_LEN];
443 * task is already visible to other tasks, so updating
444 * COMM must be protected.
446 vsnprintf(name, sizeof(name), namefmt, args);
447 set_task_comm(task, name);
454 * kthread_create_on_node - create a kthread.
455 * @threadfn: the function to run until signal_pending(current).
456 * @data: data ptr for @threadfn.
457 * @node: task and thread structures for the thread are allocated on this node
458 * @namefmt: printf-style name for the thread.
460 * Description: This helper function creates and names a kernel
461 * thread. The thread will be stopped: use wake_up_process() to start
462 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
463 * is affine to all CPUs.
465 * If thread is going to be bound on a particular cpu, give its node
466 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
467 * When woken, the thread will run @threadfn() with @data as its
468 * argument. @threadfn() can either return directly if it is a
469 * standalone thread for which no one will call kthread_stop(), or
470 * return when 'kthread_should_stop()' is true (which means
471 * kthread_stop() has been called). The return value should be zero
472 * or a negative error number; it will be passed to kthread_stop().
474 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
476 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
477 void *data, int node,
478 const char namefmt[],
481 struct task_struct *task;
484 va_start(args, namefmt);
485 task = __kthread_create_on_node(threadfn, data, node, namefmt, args);
490 EXPORT_SYMBOL(kthread_create_on_node);
492 static void __kthread_bind_mask(struct task_struct *p, const struct cpumask *mask, unsigned int state)
496 if (!wait_task_inactive(p, state)) {
501 /* It's safe because the task is inactive. */
502 raw_spin_lock_irqsave(&p->pi_lock, flags);
503 do_set_cpus_allowed(p, mask);
504 p->flags |= PF_NO_SETAFFINITY;
505 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
508 static void __kthread_bind(struct task_struct *p, unsigned int cpu, unsigned int state)
510 __kthread_bind_mask(p, cpumask_of(cpu), state);
513 void kthread_bind_mask(struct task_struct *p, const struct cpumask *mask)
515 __kthread_bind_mask(p, mask, TASK_UNINTERRUPTIBLE);
519 * kthread_bind - bind a just-created kthread to a cpu.
520 * @p: thread created by kthread_create().
521 * @cpu: cpu (might not be online, must be possible) for @k to run on.
523 * Description: This function is equivalent to set_cpus_allowed(),
524 * except that @cpu doesn't need to be online, and the thread must be
525 * stopped (i.e., just returned from kthread_create()).
527 void kthread_bind(struct task_struct *p, unsigned int cpu)
529 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
531 EXPORT_SYMBOL(kthread_bind);
534 * kthread_create_on_cpu - Create a cpu bound kthread
535 * @threadfn: the function to run until signal_pending(current).
536 * @data: data ptr for @threadfn.
537 * @cpu: The cpu on which the thread should be bound,
538 * @namefmt: printf-style name for the thread. Format is restricted
539 * to "name.*%u". Code fills in cpu number.
541 * Description: This helper function creates and names a kernel thread
543 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
544 void *data, unsigned int cpu,
547 struct task_struct *p;
549 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
553 kthread_bind(p, cpu);
554 /* CPU hotplug need to bind once again when unparking the thread. */
555 to_kthread(p)->cpu = cpu;
558 EXPORT_SYMBOL(kthread_create_on_cpu);
560 void kthread_set_per_cpu(struct task_struct *k, int cpu)
562 struct kthread *kthread = to_kthread(k);
566 WARN_ON_ONCE(!(k->flags & PF_NO_SETAFFINITY));
569 clear_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
574 set_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
577 bool kthread_is_per_cpu(struct task_struct *p)
579 struct kthread *kthread = __to_kthread(p);
583 return test_bit(KTHREAD_IS_PER_CPU, &kthread->flags);
587 * kthread_unpark - unpark a thread created by kthread_create().
588 * @k: thread created by kthread_create().
590 * Sets kthread_should_park() for @k to return false, wakes it, and
591 * waits for it to return. If the thread is marked percpu then its
592 * bound to the cpu again.
594 void kthread_unpark(struct task_struct *k)
596 struct kthread *kthread = to_kthread(k);
599 * Newly created kthread was parked when the CPU was offline.
600 * The binding was lost and we need to set it again.
602 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
603 __kthread_bind(k, kthread->cpu, TASK_PARKED);
605 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
607 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
609 wake_up_state(k, TASK_PARKED);
611 EXPORT_SYMBOL_GPL(kthread_unpark);
614 * kthread_park - park a thread created by kthread_create().
615 * @k: thread created by kthread_create().
617 * Sets kthread_should_park() for @k to return true, wakes it, and
618 * waits for it to return. This can also be called after kthread_create()
619 * instead of calling wake_up_process(): the thread will park without
620 * calling threadfn().
622 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
623 * If called by the kthread itself just the park bit is set.
625 int kthread_park(struct task_struct *k)
627 struct kthread *kthread = to_kthread(k);
629 if (WARN_ON(k->flags & PF_EXITING))
632 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK, &kthread->flags)))
635 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
639 * Wait for __kthread_parkme() to complete(), this means we
640 * _will_ have TASK_PARKED and are about to call schedule().
642 wait_for_completion(&kthread->parked);
644 * Now wait for that schedule() to complete and the task to
647 WARN_ON_ONCE(!wait_task_inactive(k, TASK_PARKED));
652 EXPORT_SYMBOL_GPL(kthread_park);
655 * kthread_stop - stop a thread created by kthread_create().
656 * @k: thread created by kthread_create().
658 * Sets kthread_should_stop() for @k to return true, wakes it, and
659 * waits for it to exit. This can also be called after kthread_create()
660 * instead of calling wake_up_process(): the thread will exit without
661 * calling threadfn().
663 * If threadfn() may call kthread_exit() itself, the caller must ensure
664 * task_struct can't go away.
666 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
669 int kthread_stop(struct task_struct *k)
671 struct kthread *kthread;
674 trace_sched_kthread_stop(k);
677 kthread = to_kthread(k);
678 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
681 wait_for_completion(&kthread->exited);
682 ret = kthread->result;
685 trace_sched_kthread_stop_ret(ret);
688 EXPORT_SYMBOL(kthread_stop);
690 int kthreadd(void *unused)
692 struct task_struct *tsk = current;
694 /* Setup a clean context for our children to inherit. */
695 set_task_comm(tsk, "kthreadd");
697 set_cpus_allowed_ptr(tsk, housekeeping_cpumask(HK_FLAG_KTHREAD));
698 set_mems_allowed(node_states[N_MEMORY]);
700 current->flags |= PF_NOFREEZE;
701 cgroup_init_kthreadd();
704 set_current_state(TASK_INTERRUPTIBLE);
705 if (list_empty(&kthread_create_list))
707 __set_current_state(TASK_RUNNING);
709 spin_lock(&kthread_create_lock);
710 while (!list_empty(&kthread_create_list)) {
711 struct kthread_create_info *create;
713 create = list_entry(kthread_create_list.next,
714 struct kthread_create_info, list);
715 list_del_init(&create->list);
716 spin_unlock(&kthread_create_lock);
718 create_kthread(create);
720 spin_lock(&kthread_create_lock);
722 spin_unlock(&kthread_create_lock);
728 void __kthread_init_worker(struct kthread_worker *worker,
730 struct lock_class_key *key)
732 memset(worker, 0, sizeof(struct kthread_worker));
733 raw_spin_lock_init(&worker->lock);
734 lockdep_set_class_and_name(&worker->lock, key, name);
735 INIT_LIST_HEAD(&worker->work_list);
736 INIT_LIST_HEAD(&worker->delayed_work_list);
738 EXPORT_SYMBOL_GPL(__kthread_init_worker);
741 * kthread_worker_fn - kthread function to process kthread_worker
742 * @worker_ptr: pointer to initialized kthread_worker
744 * This function implements the main cycle of kthread worker. It processes
745 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
748 * The works are not allowed to keep any locks, disable preemption or interrupts
749 * when they finish. There is defined a safe point for freezing when one work
750 * finishes and before a new one is started.
752 * Also the works must not be handled by more than one worker at the same time,
753 * see also kthread_queue_work().
755 int kthread_worker_fn(void *worker_ptr)
757 struct kthread_worker *worker = worker_ptr;
758 struct kthread_work *work;
761 * FIXME: Update the check and remove the assignment when all kthread
762 * worker users are created using kthread_create_worker*() functions.
764 WARN_ON(worker->task && worker->task != current);
765 worker->task = current;
767 if (worker->flags & KTW_FREEZABLE)
771 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
773 if (kthread_should_stop()) {
774 __set_current_state(TASK_RUNNING);
775 raw_spin_lock_irq(&worker->lock);
777 raw_spin_unlock_irq(&worker->lock);
782 raw_spin_lock_irq(&worker->lock);
783 if (!list_empty(&worker->work_list)) {
784 work = list_first_entry(&worker->work_list,
785 struct kthread_work, node);
786 list_del_init(&work->node);
788 worker->current_work = work;
789 raw_spin_unlock_irq(&worker->lock);
792 kthread_work_func_t func = work->func;
793 __set_current_state(TASK_RUNNING);
794 trace_sched_kthread_work_execute_start(work);
797 * Avoid dereferencing work after this point. The trace
798 * event only cares about the address.
800 trace_sched_kthread_work_execute_end(work, func);
801 } else if (!freezing(current))
808 EXPORT_SYMBOL_GPL(kthread_worker_fn);
810 static __printf(3, 0) struct kthread_worker *
811 __kthread_create_worker(int cpu, unsigned int flags,
812 const char namefmt[], va_list args)
814 struct kthread_worker *worker;
815 struct task_struct *task;
816 int node = NUMA_NO_NODE;
818 worker = kzalloc(sizeof(*worker), GFP_KERNEL);
820 return ERR_PTR(-ENOMEM);
822 kthread_init_worker(worker);
825 node = cpu_to_node(cpu);
827 task = __kthread_create_on_node(kthread_worker_fn, worker,
828 node, namefmt, args);
833 kthread_bind(task, cpu);
835 worker->flags = flags;
837 wake_up_process(task);
842 return ERR_CAST(task);
846 * kthread_create_worker - create a kthread worker
847 * @flags: flags modifying the default behavior of the worker
848 * @namefmt: printf-style name for the kthread worker (task).
850 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
851 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
852 * when the worker was SIGKILLed.
854 struct kthread_worker *
855 kthread_create_worker(unsigned int flags, const char namefmt[], ...)
857 struct kthread_worker *worker;
860 va_start(args, namefmt);
861 worker = __kthread_create_worker(-1, flags, namefmt, args);
866 EXPORT_SYMBOL(kthread_create_worker);
869 * kthread_create_worker_on_cpu - create a kthread worker and bind it
870 * to a given CPU and the associated NUMA node.
872 * @flags: flags modifying the default behavior of the worker
873 * @namefmt: printf-style name for the kthread worker (task).
875 * Use a valid CPU number if you want to bind the kthread worker
876 * to the given CPU and the associated NUMA node.
878 * A good practice is to add the cpu number also into the worker name.
879 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
882 * The kthread worker API is simple and generic. It just provides a way
883 * to create, use, and destroy workers.
885 * It is up to the API user how to handle CPU hotplug. They have to decide
886 * how to handle pending work items, prevent queuing new ones, and
887 * restore the functionality when the CPU goes off and on. There are a
890 * - CPU affinity gets lost when it is scheduled on an offline CPU.
892 * - The worker might not exist when the CPU was off when the user
893 * created the workers.
895 * Good practice is to implement two CPU hotplug callbacks and to
896 * destroy/create the worker when the CPU goes down/up.
899 * The pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
900 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
901 * when the worker was SIGKILLed.
903 struct kthread_worker *
904 kthread_create_worker_on_cpu(int cpu, unsigned int flags,
905 const char namefmt[], ...)
907 struct kthread_worker *worker;
910 va_start(args, namefmt);
911 worker = __kthread_create_worker(cpu, flags, namefmt, args);
916 EXPORT_SYMBOL(kthread_create_worker_on_cpu);
919 * Returns true when the work could not be queued at the moment.
920 * It happens when it is already pending in a worker list
921 * or when it is being cancelled.
923 static inline bool queuing_blocked(struct kthread_worker *worker,
924 struct kthread_work *work)
926 lockdep_assert_held(&worker->lock);
928 return !list_empty(&work->node) || work->canceling;
931 static void kthread_insert_work_sanity_check(struct kthread_worker *worker,
932 struct kthread_work *work)
934 lockdep_assert_held(&worker->lock);
935 WARN_ON_ONCE(!list_empty(&work->node));
936 /* Do not use a work with >1 worker, see kthread_queue_work() */
937 WARN_ON_ONCE(work->worker && work->worker != worker);
940 /* insert @work before @pos in @worker */
941 static void kthread_insert_work(struct kthread_worker *worker,
942 struct kthread_work *work,
943 struct list_head *pos)
945 kthread_insert_work_sanity_check(worker, work);
947 trace_sched_kthread_work_queue_work(worker, work);
949 list_add_tail(&work->node, pos);
950 work->worker = worker;
951 if (!worker->current_work && likely(worker->task))
952 wake_up_process(worker->task);
956 * kthread_queue_work - queue a kthread_work
957 * @worker: target kthread_worker
958 * @work: kthread_work to queue
960 * Queue @work to work processor @task for async execution. @task
961 * must have been created with kthread_worker_create(). Returns %true
962 * if @work was successfully queued, %false if it was already pending.
964 * Reinitialize the work if it needs to be used by another worker.
965 * For example, when the worker was stopped and started again.
967 bool kthread_queue_work(struct kthread_worker *worker,
968 struct kthread_work *work)
973 raw_spin_lock_irqsave(&worker->lock, flags);
974 if (!queuing_blocked(worker, work)) {
975 kthread_insert_work(worker, work, &worker->work_list);
978 raw_spin_unlock_irqrestore(&worker->lock, flags);
981 EXPORT_SYMBOL_GPL(kthread_queue_work);
984 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
985 * delayed work when the timer expires.
986 * @t: pointer to the expired timer
988 * The format of the function is defined by struct timer_list.
989 * It should have been called from irqsafe timer with irq already off.
991 void kthread_delayed_work_timer_fn(struct timer_list *t)
993 struct kthread_delayed_work *dwork = from_timer(dwork, t, timer);
994 struct kthread_work *work = &dwork->work;
995 struct kthread_worker *worker = work->worker;
999 * This might happen when a pending work is reinitialized.
1000 * It means that it is used a wrong way.
1002 if (WARN_ON_ONCE(!worker))
1005 raw_spin_lock_irqsave(&worker->lock, flags);
1006 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1007 WARN_ON_ONCE(work->worker != worker);
1009 /* Move the work from worker->delayed_work_list. */
1010 WARN_ON_ONCE(list_empty(&work->node));
1011 list_del_init(&work->node);
1012 if (!work->canceling)
1013 kthread_insert_work(worker, work, &worker->work_list);
1015 raw_spin_unlock_irqrestore(&worker->lock, flags);
1017 EXPORT_SYMBOL(kthread_delayed_work_timer_fn);
1019 static void __kthread_queue_delayed_work(struct kthread_worker *worker,
1020 struct kthread_delayed_work *dwork,
1021 unsigned long delay)
1023 struct timer_list *timer = &dwork->timer;
1024 struct kthread_work *work = &dwork->work;
1026 WARN_ON_FUNCTION_MISMATCH(timer->function,
1027 kthread_delayed_work_timer_fn);
1030 * If @delay is 0, queue @dwork->work immediately. This is for
1031 * both optimization and correctness. The earliest @timer can
1032 * expire is on the closest next tick and delayed_work users depend
1033 * on that there's no such delay when @delay is 0.
1036 kthread_insert_work(worker, work, &worker->work_list);
1040 /* Be paranoid and try to detect possible races already now. */
1041 kthread_insert_work_sanity_check(worker, work);
1043 list_add(&work->node, &worker->delayed_work_list);
1044 work->worker = worker;
1045 timer->expires = jiffies + delay;
1050 * kthread_queue_delayed_work - queue the associated kthread work
1052 * @worker: target kthread_worker
1053 * @dwork: kthread_delayed_work to queue
1054 * @delay: number of jiffies to wait before queuing
1056 * If the work has not been pending it starts a timer that will queue
1057 * the work after the given @delay. If @delay is zero, it queues the
1060 * Return: %false if the @work has already been pending. It means that
1061 * either the timer was running or the work was queued. It returns %true
1064 bool kthread_queue_delayed_work(struct kthread_worker *worker,
1065 struct kthread_delayed_work *dwork,
1066 unsigned long delay)
1068 struct kthread_work *work = &dwork->work;
1069 unsigned long flags;
1072 raw_spin_lock_irqsave(&worker->lock, flags);
1074 if (!queuing_blocked(worker, work)) {
1075 __kthread_queue_delayed_work(worker, dwork, delay);
1079 raw_spin_unlock_irqrestore(&worker->lock, flags);
1082 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work);
1084 struct kthread_flush_work {
1085 struct kthread_work work;
1086 struct completion done;
1089 static void kthread_flush_work_fn(struct kthread_work *work)
1091 struct kthread_flush_work *fwork =
1092 container_of(work, struct kthread_flush_work, work);
1093 complete(&fwork->done);
1097 * kthread_flush_work - flush a kthread_work
1098 * @work: work to flush
1100 * If @work is queued or executing, wait for it to finish execution.
1102 void kthread_flush_work(struct kthread_work *work)
1104 struct kthread_flush_work fwork = {
1105 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1106 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1108 struct kthread_worker *worker;
1111 worker = work->worker;
1115 raw_spin_lock_irq(&worker->lock);
1116 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1117 WARN_ON_ONCE(work->worker != worker);
1119 if (!list_empty(&work->node))
1120 kthread_insert_work(worker, &fwork.work, work->node.next);
1121 else if (worker->current_work == work)
1122 kthread_insert_work(worker, &fwork.work,
1123 worker->work_list.next);
1127 raw_spin_unlock_irq(&worker->lock);
1130 wait_for_completion(&fwork.done);
1132 EXPORT_SYMBOL_GPL(kthread_flush_work);
1135 * Make sure that the timer is neither set nor running and could
1136 * not manipulate the work list_head any longer.
1138 * The function is called under worker->lock. The lock is temporary
1139 * released but the timer can't be set again in the meantime.
1141 static void kthread_cancel_delayed_work_timer(struct kthread_work *work,
1142 unsigned long *flags)
1144 struct kthread_delayed_work *dwork =
1145 container_of(work, struct kthread_delayed_work, work);
1146 struct kthread_worker *worker = work->worker;
1149 * del_timer_sync() must be called to make sure that the timer
1150 * callback is not running. The lock must be temporary released
1151 * to avoid a deadlock with the callback. In the meantime,
1152 * any queuing is blocked by setting the canceling counter.
1155 raw_spin_unlock_irqrestore(&worker->lock, *flags);
1156 del_timer_sync(&dwork->timer);
1157 raw_spin_lock_irqsave(&worker->lock, *flags);
1162 * This function removes the work from the worker queue.
1164 * It is called under worker->lock. The caller must make sure that
1165 * the timer used by delayed work is not running, e.g. by calling
1166 * kthread_cancel_delayed_work_timer().
1168 * The work might still be in use when this function finishes. See the
1169 * current_work proceed by the worker.
1171 * Return: %true if @work was pending and successfully canceled,
1172 * %false if @work was not pending
1174 static bool __kthread_cancel_work(struct kthread_work *work)
1177 * Try to remove the work from a worker list. It might either
1178 * be from worker->work_list or from worker->delayed_work_list.
1180 if (!list_empty(&work->node)) {
1181 list_del_init(&work->node);
1189 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1190 * @worker: kthread worker to use
1191 * @dwork: kthread delayed work to queue
1192 * @delay: number of jiffies to wait before queuing
1194 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1195 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1196 * @work is guaranteed to be queued immediately.
1198 * Return: %false if @dwork was idle and queued, %true otherwise.
1200 * A special case is when the work is being canceled in parallel.
1201 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1202 * or yet another kthread_mod_delayed_work() call. We let the other command
1203 * win and return %true here. The return value can be used for reference
1204 * counting and the number of queued works stays the same. Anyway, the caller
1205 * is supposed to synchronize these operations a reasonable way.
1207 * This function is safe to call from any context including IRQ handler.
1208 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1211 bool kthread_mod_delayed_work(struct kthread_worker *worker,
1212 struct kthread_delayed_work *dwork,
1213 unsigned long delay)
1215 struct kthread_work *work = &dwork->work;
1216 unsigned long flags;
1219 raw_spin_lock_irqsave(&worker->lock, flags);
1221 /* Do not bother with canceling when never queued. */
1222 if (!work->worker) {
1227 /* Work must not be used with >1 worker, see kthread_queue_work() */
1228 WARN_ON_ONCE(work->worker != worker);
1231 * Temporary cancel the work but do not fight with another command
1232 * that is canceling the work as well.
1234 * It is a bit tricky because of possible races with another
1235 * mod_delayed_work() and cancel_delayed_work() callers.
1237 * The timer must be canceled first because worker->lock is released
1238 * when doing so. But the work can be removed from the queue (list)
1239 * only when it can be queued again so that the return value can
1240 * be used for reference counting.
1242 kthread_cancel_delayed_work_timer(work, &flags);
1243 if (work->canceling) {
1244 /* The number of works in the queue does not change. */
1248 ret = __kthread_cancel_work(work);
1251 __kthread_queue_delayed_work(worker, dwork, delay);
1253 raw_spin_unlock_irqrestore(&worker->lock, flags);
1256 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work);
1258 static bool __kthread_cancel_work_sync(struct kthread_work *work, bool is_dwork)
1260 struct kthread_worker *worker = work->worker;
1261 unsigned long flags;
1267 raw_spin_lock_irqsave(&worker->lock, flags);
1268 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1269 WARN_ON_ONCE(work->worker != worker);
1272 kthread_cancel_delayed_work_timer(work, &flags);
1274 ret = __kthread_cancel_work(work);
1276 if (worker->current_work != work)
1280 * The work is in progress and we need to wait with the lock released.
1281 * In the meantime, block any queuing by setting the canceling counter.
1284 raw_spin_unlock_irqrestore(&worker->lock, flags);
1285 kthread_flush_work(work);
1286 raw_spin_lock_irqsave(&worker->lock, flags);
1290 raw_spin_unlock_irqrestore(&worker->lock, flags);
1296 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1297 * @work: the kthread work to cancel
1299 * Cancel @work and wait for its execution to finish. This function
1300 * can be used even if the work re-queues itself. On return from this
1301 * function, @work is guaranteed to be not pending or executing on any CPU.
1303 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1304 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1306 * The caller must ensure that the worker on which @work was last
1307 * queued can't be destroyed before this function returns.
1309 * Return: %true if @work was pending, %false otherwise.
1311 bool kthread_cancel_work_sync(struct kthread_work *work)
1313 return __kthread_cancel_work_sync(work, false);
1315 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync);
1318 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1319 * wait for it to finish.
1320 * @dwork: the kthread delayed work to cancel
1322 * This is kthread_cancel_work_sync() for delayed works.
1324 * Return: %true if @dwork was pending, %false otherwise.
1326 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *dwork)
1328 return __kthread_cancel_work_sync(&dwork->work, true);
1330 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync);
1333 * kthread_flush_worker - flush all current works on a kthread_worker
1334 * @worker: worker to flush
1336 * Wait until all currently executing or pending works on @worker are
1339 void kthread_flush_worker(struct kthread_worker *worker)
1341 struct kthread_flush_work fwork = {
1342 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
1343 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
1346 kthread_queue_work(worker, &fwork.work);
1347 wait_for_completion(&fwork.done);
1349 EXPORT_SYMBOL_GPL(kthread_flush_worker);
1352 * kthread_destroy_worker - destroy a kthread worker
1353 * @worker: worker to be destroyed
1355 * Flush and destroy @worker. The simple flush is enough because the kthread
1356 * worker API is used only in trivial scenarios. There are no multi-step state
1359 void kthread_destroy_worker(struct kthread_worker *worker)
1361 struct task_struct *task;
1363 task = worker->task;
1367 kthread_flush_worker(worker);
1369 WARN_ON(!list_empty(&worker->work_list));
1372 EXPORT_SYMBOL(kthread_destroy_worker);
1375 * kthread_use_mm - make the calling kthread operate on an address space
1376 * @mm: address space to operate on
1378 void kthread_use_mm(struct mm_struct *mm)
1380 struct mm_struct *active_mm;
1381 struct task_struct *tsk = current;
1383 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1384 WARN_ON_ONCE(tsk->mm);
1387 /* Hold off tlb flush IPIs while switching mm's */
1388 local_irq_disable();
1389 active_mm = tsk->active_mm;
1390 if (active_mm != mm) {
1392 tsk->active_mm = mm;
1395 membarrier_update_current_mm(mm);
1396 switch_mm_irqs_off(active_mm, mm, tsk);
1399 #ifdef finish_arch_post_lock_switch
1400 finish_arch_post_lock_switch();
1404 * When a kthread starts operating on an address space, the loop
1405 * in membarrier_{private,global}_expedited() may not observe
1406 * that tsk->mm, and not issue an IPI. Membarrier requires a
1407 * memory barrier after storing to tsk->mm, before accessing
1408 * user-space memory. A full memory barrier for membarrier
1409 * {PRIVATE,GLOBAL}_EXPEDITED is implicitly provided by
1410 * mmdrop(), or explicitly with smp_mb().
1412 if (active_mm != mm)
1417 to_kthread(tsk)->oldfs = force_uaccess_begin();
1419 EXPORT_SYMBOL_GPL(kthread_use_mm);
1422 * kthread_unuse_mm - reverse the effect of kthread_use_mm()
1423 * @mm: address space to operate on
1425 void kthread_unuse_mm(struct mm_struct *mm)
1427 struct task_struct *tsk = current;
1429 WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
1430 WARN_ON_ONCE(!tsk->mm);
1432 force_uaccess_end(to_kthread(tsk)->oldfs);
1436 * When a kthread stops operating on an address space, the loop
1437 * in membarrier_{private,global}_expedited() may not observe
1438 * that tsk->mm, and not issue an IPI. Membarrier requires a
1439 * memory barrier after accessing user-space memory, before
1442 smp_mb__after_spinlock();
1444 local_irq_disable();
1446 membarrier_update_current_mm(NULL);
1447 /* active_mm is still 'mm' */
1448 enter_lazy_tlb(mm, tsk);
1452 EXPORT_SYMBOL_GPL(kthread_unuse_mm);
1454 #ifdef CONFIG_BLK_CGROUP
1456 * kthread_associate_blkcg - associate blkcg to current kthread
1457 * @css: the cgroup info
1459 * Current thread must be a kthread. The thread is running jobs on behalf of
1460 * other threads. In some cases, we expect the jobs attach cgroup info of
1461 * original threads instead of that of current thread. This function stores
1462 * original thread's cgroup info in current kthread context for later
1465 void kthread_associate_blkcg(struct cgroup_subsys_state *css)
1467 struct kthread *kthread;
1469 if (!(current->flags & PF_KTHREAD))
1471 kthread = to_kthread(current);
1475 if (kthread->blkcg_css) {
1476 css_put(kthread->blkcg_css);
1477 kthread->blkcg_css = NULL;
1481 kthread->blkcg_css = css;
1484 EXPORT_SYMBOL(kthread_associate_blkcg);
1487 * kthread_blkcg - get associated blkcg css of current kthread
1489 * Current thread must be a kthread.
1491 struct cgroup_subsys_state *kthread_blkcg(void)
1493 struct kthread *kthread;
1495 if (current->flags & PF_KTHREAD) {
1496 kthread = to_kthread(current);
1498 return kthread->blkcg_css;
1502 EXPORT_SYMBOL(kthread_blkcg);