1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel thread helper functions.
3 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
5 * Creation is done via kthreadd, so that we get a clean environment
6 * even if we're invoked from userspace (think modprobe, hotplug cpu,
9 #include <uapi/linux/sched/types.h>
10 #include <linux/sched.h>
11 #include <linux/sched/task.h>
12 #include <linux/kthread.h>
13 #include <linux/completion.h>
14 #include <linux/err.h>
15 #include <linux/cgroup.h>
16 #include <linux/cpuset.h>
17 #include <linux/unistd.h>
18 #include <linux/file.h>
19 #include <linux/export.h>
20 #include <linux/mutex.h>
21 #include <linux/slab.h>
22 #include <linux/freezer.h>
23 #include <linux/ptrace.h>
24 #include <linux/uaccess.h>
25 #include <linux/numa.h>
26 #include <trace/events/sched.h>
28 static DEFINE_SPINLOCK(kthread_create_lock
);
29 static LIST_HEAD(kthread_create_list
);
30 struct task_struct
*kthreadd_task
;
32 struct kthread_create_info
34 /* Information passed to kthread() from kthreadd. */
35 int (*threadfn
)(void *data
);
39 /* Result passed back to kthread_create() from kthreadd. */
40 struct task_struct
*result
;
41 struct completion
*done
;
43 struct list_head list
;
50 struct completion parked
;
51 struct completion exited
;
52 #ifdef CONFIG_BLK_CGROUP
53 struct cgroup_subsys_state
*blkcg_css
;
58 KTHREAD_IS_PER_CPU
= 0,
63 static inline void set_kthread_struct(void *kthread
)
66 * We abuse ->set_child_tid to avoid the new member and because it
67 * can't be wrongly copied by copy_process(). We also rely on fact
68 * that the caller can't exec, so PF_KTHREAD can't be cleared.
70 current
->set_child_tid
= (__force
void __user
*)kthread
;
73 static inline struct kthread
*to_kthread(struct task_struct
*k
)
75 WARN_ON(!(k
->flags
& PF_KTHREAD
));
76 return (__force
void *)k
->set_child_tid
;
79 void free_kthread_struct(struct task_struct
*k
)
81 struct kthread
*kthread
;
84 * Can be NULL if this kthread was created by kernel_thread()
85 * or if kmalloc() in kthread() failed.
87 kthread
= to_kthread(k
);
88 #ifdef CONFIG_BLK_CGROUP
89 WARN_ON_ONCE(kthread
&& kthread
->blkcg_css
);
95 * kthread_should_stop - should this kthread return now?
97 * When someone calls kthread_stop() on your kthread, it will be woken
98 * and this will return true. You should then return, and your return
99 * value will be passed through to kthread_stop().
101 bool kthread_should_stop(void)
103 return test_bit(KTHREAD_SHOULD_STOP
, &to_kthread(current
)->flags
);
105 EXPORT_SYMBOL(kthread_should_stop
);
107 bool __kthread_should_park(struct task_struct
*k
)
109 return test_bit(KTHREAD_SHOULD_PARK
, &to_kthread(k
)->flags
);
111 EXPORT_SYMBOL_GPL(__kthread_should_park
);
114 * kthread_should_park - should this kthread park now?
116 * When someone calls kthread_park() on your kthread, it will be woken
117 * and this will return true. You should then do the necessary
118 * cleanup and call kthread_parkme()
120 * Similar to kthread_should_stop(), but this keeps the thread alive
121 * and in a park position. kthread_unpark() "restarts" the thread and
122 * calls the thread function again.
124 bool kthread_should_park(void)
126 return __kthread_should_park(current
);
128 EXPORT_SYMBOL_GPL(kthread_should_park
);
131 * kthread_freezable_should_stop - should this freezable kthread return now?
132 * @was_frozen: optional out parameter, indicates whether %current was frozen
134 * kthread_should_stop() for freezable kthreads, which will enter
135 * refrigerator if necessary. This function is safe from kthread_stop() /
136 * freezer deadlock and freezable kthreads should use this function instead
137 * of calling try_to_freeze() directly.
139 bool kthread_freezable_should_stop(bool *was_frozen
)
145 if (unlikely(freezing(current
)))
146 frozen
= __refrigerator(true);
149 *was_frozen
= frozen
;
151 return kthread_should_stop();
153 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop
);
156 * kthread_data - return data value specified on kthread creation
157 * @task: kthread task in question
159 * Return the data value specified when kthread @task was created.
160 * The caller is responsible for ensuring the validity of @task when
161 * calling this function.
163 void *kthread_data(struct task_struct
*task
)
165 return to_kthread(task
)->data
;
169 * kthread_probe_data - speculative version of kthread_data()
170 * @task: possible kthread task in question
172 * @task could be a kthread task. Return the data value specified when it
173 * was created if accessible. If @task isn't a kthread task or its data is
174 * inaccessible for any reason, %NULL is returned. This function requires
175 * that @task itself is safe to dereference.
177 void *kthread_probe_data(struct task_struct
*task
)
179 struct kthread
*kthread
= to_kthread(task
);
182 probe_kernel_read(&data
, &kthread
->data
, sizeof(data
));
186 static void __kthread_parkme(struct kthread
*self
)
190 * TASK_PARKED is a special state; we must serialize against
191 * possible pending wakeups to avoid store-store collisions on
194 * Such a collision might possibly result in the task state
195 * changin from TASK_PARKED and us failing the
196 * wait_task_inactive() in kthread_park().
198 set_special_state(TASK_PARKED
);
199 if (!test_bit(KTHREAD_SHOULD_PARK
, &self
->flags
))
202 complete(&self
->parked
);
205 __set_current_state(TASK_RUNNING
);
208 void kthread_parkme(void)
210 __kthread_parkme(to_kthread(current
));
212 EXPORT_SYMBOL_GPL(kthread_parkme
);
214 static int kthread(void *_create
)
216 /* Copy data: it's on kthread's stack */
217 struct kthread_create_info
*create
= _create
;
218 int (*threadfn
)(void *data
) = create
->threadfn
;
219 void *data
= create
->data
;
220 struct completion
*done
;
221 struct kthread
*self
;
224 self
= kzalloc(sizeof(*self
), GFP_KERNEL
);
225 set_kthread_struct(self
);
227 /* If user was SIGKILLed, I release the structure. */
228 done
= xchg(&create
->done
, NULL
);
235 create
->result
= ERR_PTR(-ENOMEM
);
241 init_completion(&self
->exited
);
242 init_completion(&self
->parked
);
243 current
->vfork_done
= &self
->exited
;
245 /* OK, tell user we're spawned, wait for stop or wakeup */
246 __set_current_state(TASK_UNINTERRUPTIBLE
);
247 create
->result
= current
;
252 if (!test_bit(KTHREAD_SHOULD_STOP
, &self
->flags
)) {
253 cgroup_kthread_ready();
254 __kthread_parkme(self
);
255 ret
= threadfn(data
);
260 /* called from do_fork() to get node information for about to be created task */
261 int tsk_fork_get_node(struct task_struct
*tsk
)
264 if (tsk
== kthreadd_task
)
265 return tsk
->pref_node_fork
;
270 static void create_kthread(struct kthread_create_info
*create
)
275 current
->pref_node_fork
= create
->node
;
277 /* We want our own signal handler (we take no signals by default). */
278 pid
= kernel_thread(kthread
, create
, CLONE_FS
| CLONE_FILES
| SIGCHLD
);
280 /* If user was SIGKILLed, I release the structure. */
281 struct completion
*done
= xchg(&create
->done
, NULL
);
287 create
->result
= ERR_PTR(pid
);
292 static __printf(4, 0)
293 struct task_struct
*__kthread_create_on_node(int (*threadfn
)(void *data
),
294 void *data
, int node
,
295 const char namefmt
[],
298 DECLARE_COMPLETION_ONSTACK(done
);
299 struct task_struct
*task
;
300 struct kthread_create_info
*create
= kmalloc(sizeof(*create
),
304 return ERR_PTR(-ENOMEM
);
305 create
->threadfn
= threadfn
;
308 create
->done
= &done
;
310 spin_lock(&kthread_create_lock
);
311 list_add_tail(&create
->list
, &kthread_create_list
);
312 spin_unlock(&kthread_create_lock
);
314 wake_up_process(kthreadd_task
);
316 * Wait for completion in killable state, for I might be chosen by
317 * the OOM killer while kthreadd is trying to allocate memory for
320 if (unlikely(wait_for_completion_killable(&done
))) {
324 * I got SIGKILL, but wait for 10 more seconds for completion
325 * unless chosen by the OOM killer. This delay is there as a
326 * workaround for boot failure caused by SIGKILL upon device
327 * driver initialization timeout.
329 while (i
++ < 10 && !test_tsk_thread_flag(current
, TIF_MEMDIE
))
330 if (wait_for_completion_timeout(&done
, HZ
))
333 * If I was SIGKILLed before kthreadd (or new kernel thread)
334 * calls complete(), leave the cleanup of this structure to
337 if (xchg(&create
->done
, NULL
))
338 return ERR_PTR(-EINTR
);
340 * kthreadd (or new kernel thread) will call complete()
343 wait_for_completion(&done
);
346 task
= create
->result
;
348 static const struct sched_param param
= { .sched_priority
= 0 };
349 char name
[TASK_COMM_LEN
];
352 * task is already visible to other tasks, so updating
353 * COMM must be protected.
355 vsnprintf(name
, sizeof(name
), namefmt
, args
);
356 set_task_comm(task
, name
);
358 * root may have changed our (kthreadd's) priority or CPU mask.
359 * The kernel thread should not inherit these properties.
361 sched_setscheduler_nocheck(task
, SCHED_NORMAL
, ¶m
);
362 set_cpus_allowed_ptr(task
, cpu_all_mask
);
369 * kthread_create_on_node - create a kthread.
370 * @threadfn: the function to run until signal_pending(current).
371 * @data: data ptr for @threadfn.
372 * @node: task and thread structures for the thread are allocated on this node
373 * @namefmt: printf-style name for the thread.
375 * Description: This helper function creates and names a kernel
376 * thread. The thread will be stopped: use wake_up_process() to start
377 * it. See also kthread_run(). The new thread has SCHED_NORMAL policy and
378 * is affine to all CPUs.
380 * If thread is going to be bound on a particular cpu, give its node
381 * in @node, to get NUMA affinity for kthread stack, or else give NUMA_NO_NODE.
382 * When woken, the thread will run @threadfn() with @data as its
383 * argument. @threadfn() can either call do_exit() directly if it is a
384 * standalone thread for which no one will call kthread_stop(), or
385 * return when 'kthread_should_stop()' is true (which means
386 * kthread_stop() has been called). The return value should be zero
387 * or a negative error number; it will be passed to kthread_stop().
389 * Returns a task_struct or ERR_PTR(-ENOMEM) or ERR_PTR(-EINTR).
391 struct task_struct
*kthread_create_on_node(int (*threadfn
)(void *data
),
392 void *data
, int node
,
393 const char namefmt
[],
396 struct task_struct
*task
;
399 va_start(args
, namefmt
);
400 task
= __kthread_create_on_node(threadfn
, data
, node
, namefmt
, args
);
405 EXPORT_SYMBOL(kthread_create_on_node
);
407 static void __kthread_bind_mask(struct task_struct
*p
, const struct cpumask
*mask
, long state
)
411 if (!wait_task_inactive(p
, state
)) {
416 /* It's safe because the task is inactive. */
417 raw_spin_lock_irqsave(&p
->pi_lock
, flags
);
418 do_set_cpus_allowed(p
, mask
);
419 p
->flags
|= PF_NO_SETAFFINITY
;
420 raw_spin_unlock_irqrestore(&p
->pi_lock
, flags
);
423 static void __kthread_bind(struct task_struct
*p
, unsigned int cpu
, long state
)
425 __kthread_bind_mask(p
, cpumask_of(cpu
), state
);
428 void kthread_bind_mask(struct task_struct
*p
, const struct cpumask
*mask
)
430 __kthread_bind_mask(p
, mask
, TASK_UNINTERRUPTIBLE
);
434 * kthread_bind - bind a just-created kthread to a cpu.
435 * @p: thread created by kthread_create().
436 * @cpu: cpu (might not be online, must be possible) for @k to run on.
438 * Description: This function is equivalent to set_cpus_allowed(),
439 * except that @cpu doesn't need to be online, and the thread must be
440 * stopped (i.e., just returned from kthread_create()).
442 void kthread_bind(struct task_struct
*p
, unsigned int cpu
)
444 __kthread_bind(p
, cpu
, TASK_UNINTERRUPTIBLE
);
446 EXPORT_SYMBOL(kthread_bind
);
449 * kthread_create_on_cpu - Create a cpu bound kthread
450 * @threadfn: the function to run until signal_pending(current).
451 * @data: data ptr for @threadfn.
452 * @cpu: The cpu on which the thread should be bound,
453 * @namefmt: printf-style name for the thread. Format is restricted
454 * to "name.*%u". Code fills in cpu number.
456 * Description: This helper function creates and names a kernel thread
457 * The thread will be woken and put into park mode.
459 struct task_struct
*kthread_create_on_cpu(int (*threadfn
)(void *data
),
460 void *data
, unsigned int cpu
,
463 struct task_struct
*p
;
465 p
= kthread_create_on_node(threadfn
, data
, cpu_to_node(cpu
), namefmt
,
469 kthread_bind(p
, cpu
);
470 /* CPU hotplug need to bind once again when unparking the thread. */
471 set_bit(KTHREAD_IS_PER_CPU
, &to_kthread(p
)->flags
);
472 to_kthread(p
)->cpu
= cpu
;
477 * kthread_unpark - unpark a thread created by kthread_create().
478 * @k: thread created by kthread_create().
480 * Sets kthread_should_park() for @k to return false, wakes it, and
481 * waits for it to return. If the thread is marked percpu then its
482 * bound to the cpu again.
484 void kthread_unpark(struct task_struct
*k
)
486 struct kthread
*kthread
= to_kthread(k
);
489 * Newly created kthread was parked when the CPU was offline.
490 * The binding was lost and we need to set it again.
492 if (test_bit(KTHREAD_IS_PER_CPU
, &kthread
->flags
))
493 __kthread_bind(k
, kthread
->cpu
, TASK_PARKED
);
495 clear_bit(KTHREAD_SHOULD_PARK
, &kthread
->flags
);
497 * __kthread_parkme() will either see !SHOULD_PARK or get the wakeup.
499 wake_up_state(k
, TASK_PARKED
);
501 EXPORT_SYMBOL_GPL(kthread_unpark
);
504 * kthread_park - park a thread created by kthread_create().
505 * @k: thread created by kthread_create().
507 * Sets kthread_should_park() for @k to return true, wakes it, and
508 * waits for it to return. This can also be called after kthread_create()
509 * instead of calling wake_up_process(): the thread will park without
510 * calling threadfn().
512 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
513 * If called by the kthread itself just the park bit is set.
515 int kthread_park(struct task_struct
*k
)
517 struct kthread
*kthread
= to_kthread(k
);
519 if (WARN_ON(k
->flags
& PF_EXITING
))
522 if (WARN_ON_ONCE(test_bit(KTHREAD_SHOULD_PARK
, &kthread
->flags
)))
525 set_bit(KTHREAD_SHOULD_PARK
, &kthread
->flags
);
529 * Wait for __kthread_parkme() to complete(), this means we
530 * _will_ have TASK_PARKED and are about to call schedule().
532 wait_for_completion(&kthread
->parked
);
534 * Now wait for that schedule() to complete and the task to
537 WARN_ON_ONCE(!wait_task_inactive(k
, TASK_PARKED
));
542 EXPORT_SYMBOL_GPL(kthread_park
);
545 * kthread_stop - stop a thread created by kthread_create().
546 * @k: thread created by kthread_create().
548 * Sets kthread_should_stop() for @k to return true, wakes it, and
549 * waits for it to exit. This can also be called after kthread_create()
550 * instead of calling wake_up_process(): the thread will exit without
551 * calling threadfn().
553 * If threadfn() may call do_exit() itself, the caller must ensure
554 * task_struct can't go away.
556 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
559 int kthread_stop(struct task_struct
*k
)
561 struct kthread
*kthread
;
564 trace_sched_kthread_stop(k
);
567 kthread
= to_kthread(k
);
568 set_bit(KTHREAD_SHOULD_STOP
, &kthread
->flags
);
571 wait_for_completion(&kthread
->exited
);
575 trace_sched_kthread_stop_ret(ret
);
578 EXPORT_SYMBOL(kthread_stop
);
580 int kthreadd(void *unused
)
582 struct task_struct
*tsk
= current
;
584 /* Setup a clean context for our children to inherit. */
585 set_task_comm(tsk
, "kthreadd");
587 set_cpus_allowed_ptr(tsk
, cpu_all_mask
);
588 set_mems_allowed(node_states
[N_MEMORY
]);
590 current
->flags
|= PF_NOFREEZE
;
591 cgroup_init_kthreadd();
594 set_current_state(TASK_INTERRUPTIBLE
);
595 if (list_empty(&kthread_create_list
))
597 __set_current_state(TASK_RUNNING
);
599 spin_lock(&kthread_create_lock
);
600 while (!list_empty(&kthread_create_list
)) {
601 struct kthread_create_info
*create
;
603 create
= list_entry(kthread_create_list
.next
,
604 struct kthread_create_info
, list
);
605 list_del_init(&create
->list
);
606 spin_unlock(&kthread_create_lock
);
608 create_kthread(create
);
610 spin_lock(&kthread_create_lock
);
612 spin_unlock(&kthread_create_lock
);
618 void __kthread_init_worker(struct kthread_worker
*worker
,
620 struct lock_class_key
*key
)
622 memset(worker
, 0, sizeof(struct kthread_worker
));
623 raw_spin_lock_init(&worker
->lock
);
624 lockdep_set_class_and_name(&worker
->lock
, key
, name
);
625 INIT_LIST_HEAD(&worker
->work_list
);
626 INIT_LIST_HEAD(&worker
->delayed_work_list
);
628 EXPORT_SYMBOL_GPL(__kthread_init_worker
);
631 * kthread_worker_fn - kthread function to process kthread_worker
632 * @worker_ptr: pointer to initialized kthread_worker
634 * This function implements the main cycle of kthread worker. It processes
635 * work_list until it is stopped with kthread_stop(). It sleeps when the queue
638 * The works are not allowed to keep any locks, disable preemption or interrupts
639 * when they finish. There is defined a safe point for freezing when one work
640 * finishes and before a new one is started.
642 * Also the works must not be handled by more than one worker at the same time,
643 * see also kthread_queue_work().
645 int kthread_worker_fn(void *worker_ptr
)
647 struct kthread_worker
*worker
= worker_ptr
;
648 struct kthread_work
*work
;
651 * FIXME: Update the check and remove the assignment when all kthread
652 * worker users are created using kthread_create_worker*() functions.
654 WARN_ON(worker
->task
&& worker
->task
!= current
);
655 worker
->task
= current
;
657 if (worker
->flags
& KTW_FREEZABLE
)
661 set_current_state(TASK_INTERRUPTIBLE
); /* mb paired w/ kthread_stop */
663 if (kthread_should_stop()) {
664 __set_current_state(TASK_RUNNING
);
665 raw_spin_lock_irq(&worker
->lock
);
667 raw_spin_unlock_irq(&worker
->lock
);
672 raw_spin_lock_irq(&worker
->lock
);
673 if (!list_empty(&worker
->work_list
)) {
674 work
= list_first_entry(&worker
->work_list
,
675 struct kthread_work
, node
);
676 list_del_init(&work
->node
);
678 worker
->current_work
= work
;
679 raw_spin_unlock_irq(&worker
->lock
);
682 __set_current_state(TASK_RUNNING
);
684 } else if (!freezing(current
))
691 EXPORT_SYMBOL_GPL(kthread_worker_fn
);
693 static __printf(3, 0) struct kthread_worker
*
694 __kthread_create_worker(int cpu
, unsigned int flags
,
695 const char namefmt
[], va_list args
)
697 struct kthread_worker
*worker
;
698 struct task_struct
*task
;
699 int node
= NUMA_NO_NODE
;
701 worker
= kzalloc(sizeof(*worker
), GFP_KERNEL
);
703 return ERR_PTR(-ENOMEM
);
705 kthread_init_worker(worker
);
708 node
= cpu_to_node(cpu
);
710 task
= __kthread_create_on_node(kthread_worker_fn
, worker
,
711 node
, namefmt
, args
);
716 kthread_bind(task
, cpu
);
718 worker
->flags
= flags
;
720 wake_up_process(task
);
725 return ERR_CAST(task
);
729 * kthread_create_worker - create a kthread worker
730 * @flags: flags modifying the default behavior of the worker
731 * @namefmt: printf-style name for the kthread worker (task).
733 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
734 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
735 * when the worker was SIGKILLed.
737 struct kthread_worker
*
738 kthread_create_worker(unsigned int flags
, const char namefmt
[], ...)
740 struct kthread_worker
*worker
;
743 va_start(args
, namefmt
);
744 worker
= __kthread_create_worker(-1, flags
, namefmt
, args
);
749 EXPORT_SYMBOL(kthread_create_worker
);
752 * kthread_create_worker_on_cpu - create a kthread worker and bind it
753 * it to a given CPU and the associated NUMA node.
755 * @flags: flags modifying the default behavior of the worker
756 * @namefmt: printf-style name for the kthread worker (task).
758 * Use a valid CPU number if you want to bind the kthread worker
759 * to the given CPU and the associated NUMA node.
761 * A good practice is to add the cpu number also into the worker name.
762 * For example, use kthread_create_worker_on_cpu(cpu, "helper/%d", cpu).
764 * Returns a pointer to the allocated worker on success, ERR_PTR(-ENOMEM)
765 * when the needed structures could not get allocated, and ERR_PTR(-EINTR)
766 * when the worker was SIGKILLed.
768 struct kthread_worker
*
769 kthread_create_worker_on_cpu(int cpu
, unsigned int flags
,
770 const char namefmt
[], ...)
772 struct kthread_worker
*worker
;
775 va_start(args
, namefmt
);
776 worker
= __kthread_create_worker(cpu
, flags
, namefmt
, args
);
781 EXPORT_SYMBOL(kthread_create_worker_on_cpu
);
784 * Returns true when the work could not be queued at the moment.
785 * It happens when it is already pending in a worker list
786 * or when it is being cancelled.
788 static inline bool queuing_blocked(struct kthread_worker
*worker
,
789 struct kthread_work
*work
)
791 lockdep_assert_held(&worker
->lock
);
793 return !list_empty(&work
->node
) || work
->canceling
;
796 static void kthread_insert_work_sanity_check(struct kthread_worker
*worker
,
797 struct kthread_work
*work
)
799 lockdep_assert_held(&worker
->lock
);
800 WARN_ON_ONCE(!list_empty(&work
->node
));
801 /* Do not use a work with >1 worker, see kthread_queue_work() */
802 WARN_ON_ONCE(work
->worker
&& work
->worker
!= worker
);
805 /* insert @work before @pos in @worker */
806 static void kthread_insert_work(struct kthread_worker
*worker
,
807 struct kthread_work
*work
,
808 struct list_head
*pos
)
810 kthread_insert_work_sanity_check(worker
, work
);
812 list_add_tail(&work
->node
, pos
);
813 work
->worker
= worker
;
814 if (!worker
->current_work
&& likely(worker
->task
))
815 wake_up_process(worker
->task
);
819 * kthread_queue_work - queue a kthread_work
820 * @worker: target kthread_worker
821 * @work: kthread_work to queue
823 * Queue @work to work processor @task for async execution. @task
824 * must have been created with kthread_worker_create(). Returns %true
825 * if @work was successfully queued, %false if it was already pending.
827 * Reinitialize the work if it needs to be used by another worker.
828 * For example, when the worker was stopped and started again.
830 bool kthread_queue_work(struct kthread_worker
*worker
,
831 struct kthread_work
*work
)
836 raw_spin_lock_irqsave(&worker
->lock
, flags
);
837 if (!queuing_blocked(worker
, work
)) {
838 kthread_insert_work(worker
, work
, &worker
->work_list
);
841 raw_spin_unlock_irqrestore(&worker
->lock
, flags
);
844 EXPORT_SYMBOL_GPL(kthread_queue_work
);
847 * kthread_delayed_work_timer_fn - callback that queues the associated kthread
848 * delayed work when the timer expires.
849 * @t: pointer to the expired timer
851 * The format of the function is defined by struct timer_list.
852 * It should have been called from irqsafe timer with irq already off.
854 void kthread_delayed_work_timer_fn(struct timer_list
*t
)
856 struct kthread_delayed_work
*dwork
= from_timer(dwork
, t
, timer
);
857 struct kthread_work
*work
= &dwork
->work
;
858 struct kthread_worker
*worker
= work
->worker
;
862 * This might happen when a pending work is reinitialized.
863 * It means that it is used a wrong way.
865 if (WARN_ON_ONCE(!worker
))
868 raw_spin_lock_irqsave(&worker
->lock
, flags
);
869 /* Work must not be used with >1 worker, see kthread_queue_work(). */
870 WARN_ON_ONCE(work
->worker
!= worker
);
872 /* Move the work from worker->delayed_work_list. */
873 WARN_ON_ONCE(list_empty(&work
->node
));
874 list_del_init(&work
->node
);
875 kthread_insert_work(worker
, work
, &worker
->work_list
);
877 raw_spin_unlock_irqrestore(&worker
->lock
, flags
);
879 EXPORT_SYMBOL(kthread_delayed_work_timer_fn
);
881 void __kthread_queue_delayed_work(struct kthread_worker
*worker
,
882 struct kthread_delayed_work
*dwork
,
885 struct timer_list
*timer
= &dwork
->timer
;
886 struct kthread_work
*work
= &dwork
->work
;
888 WARN_ON_ONCE(timer
->function
!= kthread_delayed_work_timer_fn
);
891 * If @delay is 0, queue @dwork->work immediately. This is for
892 * both optimization and correctness. The earliest @timer can
893 * expire is on the closest next tick and delayed_work users depend
894 * on that there's no such delay when @delay is 0.
897 kthread_insert_work(worker
, work
, &worker
->work_list
);
901 /* Be paranoid and try to detect possible races already now. */
902 kthread_insert_work_sanity_check(worker
, work
);
904 list_add(&work
->node
, &worker
->delayed_work_list
);
905 work
->worker
= worker
;
906 timer
->expires
= jiffies
+ delay
;
911 * kthread_queue_delayed_work - queue the associated kthread work
913 * @worker: target kthread_worker
914 * @dwork: kthread_delayed_work to queue
915 * @delay: number of jiffies to wait before queuing
917 * If the work has not been pending it starts a timer that will queue
918 * the work after the given @delay. If @delay is zero, it queues the
921 * Return: %false if the @work has already been pending. It means that
922 * either the timer was running or the work was queued. It returns %true
925 bool kthread_queue_delayed_work(struct kthread_worker
*worker
,
926 struct kthread_delayed_work
*dwork
,
929 struct kthread_work
*work
= &dwork
->work
;
933 raw_spin_lock_irqsave(&worker
->lock
, flags
);
935 if (!queuing_blocked(worker
, work
)) {
936 __kthread_queue_delayed_work(worker
, dwork
, delay
);
940 raw_spin_unlock_irqrestore(&worker
->lock
, flags
);
943 EXPORT_SYMBOL_GPL(kthread_queue_delayed_work
);
945 struct kthread_flush_work
{
946 struct kthread_work work
;
947 struct completion done
;
950 static void kthread_flush_work_fn(struct kthread_work
*work
)
952 struct kthread_flush_work
*fwork
=
953 container_of(work
, struct kthread_flush_work
, work
);
954 complete(&fwork
->done
);
958 * kthread_flush_work - flush a kthread_work
959 * @work: work to flush
961 * If @work is queued or executing, wait for it to finish execution.
963 void kthread_flush_work(struct kthread_work
*work
)
965 struct kthread_flush_work fwork
= {
966 KTHREAD_WORK_INIT(fwork
.work
, kthread_flush_work_fn
),
967 COMPLETION_INITIALIZER_ONSTACK(fwork
.done
),
969 struct kthread_worker
*worker
;
972 worker
= work
->worker
;
976 raw_spin_lock_irq(&worker
->lock
);
977 /* Work must not be used with >1 worker, see kthread_queue_work(). */
978 WARN_ON_ONCE(work
->worker
!= worker
);
980 if (!list_empty(&work
->node
))
981 kthread_insert_work(worker
, &fwork
.work
, work
->node
.next
);
982 else if (worker
->current_work
== work
)
983 kthread_insert_work(worker
, &fwork
.work
,
984 worker
->work_list
.next
);
988 raw_spin_unlock_irq(&worker
->lock
);
991 wait_for_completion(&fwork
.done
);
993 EXPORT_SYMBOL_GPL(kthread_flush_work
);
996 * This function removes the work from the worker queue. Also it makes sure
997 * that it won't get queued later via the delayed work's timer.
999 * The work might still be in use when this function finishes. See the
1000 * current_work proceed by the worker.
1002 * Return: %true if @work was pending and successfully canceled,
1003 * %false if @work was not pending
1005 static bool __kthread_cancel_work(struct kthread_work
*work
, bool is_dwork
,
1006 unsigned long *flags
)
1008 /* Try to cancel the timer if exists. */
1010 struct kthread_delayed_work
*dwork
=
1011 container_of(work
, struct kthread_delayed_work
, work
);
1012 struct kthread_worker
*worker
= work
->worker
;
1015 * del_timer_sync() must be called to make sure that the timer
1016 * callback is not running. The lock must be temporary released
1017 * to avoid a deadlock with the callback. In the meantime,
1018 * any queuing is blocked by setting the canceling counter.
1021 raw_spin_unlock_irqrestore(&worker
->lock
, *flags
);
1022 del_timer_sync(&dwork
->timer
);
1023 raw_spin_lock_irqsave(&worker
->lock
, *flags
);
1028 * Try to remove the work from a worker list. It might either
1029 * be from worker->work_list or from worker->delayed_work_list.
1031 if (!list_empty(&work
->node
)) {
1032 list_del_init(&work
->node
);
1040 * kthread_mod_delayed_work - modify delay of or queue a kthread delayed work
1041 * @worker: kthread worker to use
1042 * @dwork: kthread delayed work to queue
1043 * @delay: number of jiffies to wait before queuing
1045 * If @dwork is idle, equivalent to kthread_queue_delayed_work(). Otherwise,
1046 * modify @dwork's timer so that it expires after @delay. If @delay is zero,
1047 * @work is guaranteed to be queued immediately.
1049 * Return: %true if @dwork was pending and its timer was modified,
1052 * A special case is when the work is being canceled in parallel.
1053 * It might be caused either by the real kthread_cancel_delayed_work_sync()
1054 * or yet another kthread_mod_delayed_work() call. We let the other command
1055 * win and return %false here. The caller is supposed to synchronize these
1056 * operations a reasonable way.
1058 * This function is safe to call from any context including IRQ handler.
1059 * See __kthread_cancel_work() and kthread_delayed_work_timer_fn()
1062 bool kthread_mod_delayed_work(struct kthread_worker
*worker
,
1063 struct kthread_delayed_work
*dwork
,
1064 unsigned long delay
)
1066 struct kthread_work
*work
= &dwork
->work
;
1067 unsigned long flags
;
1070 raw_spin_lock_irqsave(&worker
->lock
, flags
);
1072 /* Do not bother with canceling when never queued. */
1076 /* Work must not be used with >1 worker, see kthread_queue_work() */
1077 WARN_ON_ONCE(work
->worker
!= worker
);
1079 /* Do not fight with another command that is canceling this work. */
1080 if (work
->canceling
)
1083 ret
= __kthread_cancel_work(work
, true, &flags
);
1085 __kthread_queue_delayed_work(worker
, dwork
, delay
);
1087 raw_spin_unlock_irqrestore(&worker
->lock
, flags
);
1090 EXPORT_SYMBOL_GPL(kthread_mod_delayed_work
);
1092 static bool __kthread_cancel_work_sync(struct kthread_work
*work
, bool is_dwork
)
1094 struct kthread_worker
*worker
= work
->worker
;
1095 unsigned long flags
;
1101 raw_spin_lock_irqsave(&worker
->lock
, flags
);
1102 /* Work must not be used with >1 worker, see kthread_queue_work(). */
1103 WARN_ON_ONCE(work
->worker
!= worker
);
1105 ret
= __kthread_cancel_work(work
, is_dwork
, &flags
);
1107 if (worker
->current_work
!= work
)
1111 * The work is in progress and we need to wait with the lock released.
1112 * In the meantime, block any queuing by setting the canceling counter.
1115 raw_spin_unlock_irqrestore(&worker
->lock
, flags
);
1116 kthread_flush_work(work
);
1117 raw_spin_lock_irqsave(&worker
->lock
, flags
);
1121 raw_spin_unlock_irqrestore(&worker
->lock
, flags
);
1127 * kthread_cancel_work_sync - cancel a kthread work and wait for it to finish
1128 * @work: the kthread work to cancel
1130 * Cancel @work and wait for its execution to finish. This function
1131 * can be used even if the work re-queues itself. On return from this
1132 * function, @work is guaranteed to be not pending or executing on any CPU.
1134 * kthread_cancel_work_sync(&delayed_work->work) must not be used for
1135 * delayed_work's. Use kthread_cancel_delayed_work_sync() instead.
1137 * The caller must ensure that the worker on which @work was last
1138 * queued can't be destroyed before this function returns.
1140 * Return: %true if @work was pending, %false otherwise.
1142 bool kthread_cancel_work_sync(struct kthread_work
*work
)
1144 return __kthread_cancel_work_sync(work
, false);
1146 EXPORT_SYMBOL_GPL(kthread_cancel_work_sync
);
1149 * kthread_cancel_delayed_work_sync - cancel a kthread delayed work and
1150 * wait for it to finish.
1151 * @dwork: the kthread delayed work to cancel
1153 * This is kthread_cancel_work_sync() for delayed works.
1155 * Return: %true if @dwork was pending, %false otherwise.
1157 bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work
*dwork
)
1159 return __kthread_cancel_work_sync(&dwork
->work
, true);
1161 EXPORT_SYMBOL_GPL(kthread_cancel_delayed_work_sync
);
1164 * kthread_flush_worker - flush all current works on a kthread_worker
1165 * @worker: worker to flush
1167 * Wait until all currently executing or pending works on @worker are
1170 void kthread_flush_worker(struct kthread_worker
*worker
)
1172 struct kthread_flush_work fwork
= {
1173 KTHREAD_WORK_INIT(fwork
.work
, kthread_flush_work_fn
),
1174 COMPLETION_INITIALIZER_ONSTACK(fwork
.done
),
1177 kthread_queue_work(worker
, &fwork
.work
);
1178 wait_for_completion(&fwork
.done
);
1180 EXPORT_SYMBOL_GPL(kthread_flush_worker
);
1183 * kthread_destroy_worker - destroy a kthread worker
1184 * @worker: worker to be destroyed
1186 * Flush and destroy @worker. The simple flush is enough because the kthread
1187 * worker API is used only in trivial scenarios. There are no multi-step state
1190 void kthread_destroy_worker(struct kthread_worker
*worker
)
1192 struct task_struct
*task
;
1194 task
= worker
->task
;
1198 kthread_flush_worker(worker
);
1200 WARN_ON(!list_empty(&worker
->work_list
));
1203 EXPORT_SYMBOL(kthread_destroy_worker
);
1205 #ifdef CONFIG_BLK_CGROUP
1207 * kthread_associate_blkcg - associate blkcg to current kthread
1208 * @css: the cgroup info
1210 * Current thread must be a kthread. The thread is running jobs on behalf of
1211 * other threads. In some cases, we expect the jobs attach cgroup info of
1212 * original threads instead of that of current thread. This function stores
1213 * original thread's cgroup info in current kthread context for later
1216 void kthread_associate_blkcg(struct cgroup_subsys_state
*css
)
1218 struct kthread
*kthread
;
1220 if (!(current
->flags
& PF_KTHREAD
))
1222 kthread
= to_kthread(current
);
1226 if (kthread
->blkcg_css
) {
1227 css_put(kthread
->blkcg_css
);
1228 kthread
->blkcg_css
= NULL
;
1232 kthread
->blkcg_css
= css
;
1235 EXPORT_SYMBOL(kthread_associate_blkcg
);
1238 * kthread_blkcg - get associated blkcg css of current kthread
1240 * Current thread must be a kthread.
1242 struct cgroup_subsys_state
*kthread_blkcg(void)
1244 struct kthread
*kthread
;
1246 if (current
->flags
& PF_KTHREAD
) {
1247 kthread
= to_kthread(current
);
1249 return kthread
->blkcg_css
;
1253 EXPORT_SYMBOL(kthread_blkcg
);