1 /* Kernel thread helper functions.
2 * Copyright (C) 2004 IBM Corporation, Rusty Russell.
4 * Creation is done via kthreadd, so that we get a clean environment
5 * even if we're invoked from userspace (think modprobe, hotplug cpu,
8 #include <linux/sched.h>
9 #include <linux/kthread.h>
10 #include <linux/completion.h>
11 #include <linux/err.h>
12 #include <linux/cpuset.h>
13 #include <linux/unistd.h>
14 #include <linux/file.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/slab.h>
18 #include <linux/freezer.h>
19 #include <trace/events/sched.h>
21 static DEFINE_SPINLOCK(kthread_create_lock);
22 static LIST_HEAD(kthread_create_list);
23 struct task_struct *kthreadd_task;
25 struct kthread_create_info
27 /* Information passed to kthread() from kthreadd. */
28 int (*threadfn)(void *data);
31 /* Result passed back to kthread_create() from kthreadd. */
32 struct task_struct *result;
33 struct completion done;
35 struct list_head list;
41 struct completion exited;
44 #define to_kthread(tsk) \
45 container_of((tsk)->vfork_done, struct kthread, exited)
48 * kthread_should_stop - should this kthread return now?
50 * When someone calls kthread_stop() on your kthread, it will be woken
51 * and this will return true. You should then return, and your return
52 * value will be passed through to kthread_stop().
54 int kthread_should_stop(void)
56 return to_kthread(current)->should_stop;
58 EXPORT_SYMBOL(kthread_should_stop);
61 * kthread_data - return data value specified on kthread creation
62 * @task: kthread task in question
64 * Return the data value specified when kthread @task was created.
65 * The caller is responsible for ensuring the validity of @task when
66 * calling this function.
68 void *kthread_data(struct task_struct *task)
70 return to_kthread(task)->data;
73 static int kthread(void *_create)
75 /* Copy data: it's on kthread's stack */
76 struct kthread_create_info *create = _create;
77 int (*threadfn)(void *data) = create->threadfn;
78 void *data = create->data;
84 init_completion(&self.exited);
85 current->vfork_done = &self.exited;
87 /* OK, tell user we're spawned, wait for stop or wakeup */
88 __set_current_state(TASK_UNINTERRUPTIBLE);
89 create->result = current;
90 complete(&create->done);
94 if (!self.should_stop)
97 /* we can't just return, we must preserve "self" on stack */
101 static void create_kthread(struct kthread_create_info *create)
105 /* We want our own signal handler (we take no signals by default). */
106 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
108 create->result = ERR_PTR(pid);
109 complete(&create->done);
114 * kthread_create - create a kthread.
115 * @threadfn: the function to run until signal_pending(current).
116 * @data: data ptr for @threadfn.
117 * @namefmt: printf-style name for the thread.
119 * Description: This helper function creates and names a kernel
120 * thread. The thread will be stopped: use wake_up_process() to start
121 * it. See also kthread_run().
123 * When woken, the thread will run @threadfn() with @data as its
124 * argument. @threadfn() can either call do_exit() directly if it is a
125 * standalone thread for which noone will call kthread_stop(), or
126 * return when 'kthread_should_stop()' is true (which means
127 * kthread_stop() has been called). The return value should be zero
128 * or a negative error number; it will be passed to kthread_stop().
130 * Returns a task_struct or ERR_PTR(-ENOMEM).
132 struct task_struct *kthread_create(int (*threadfn)(void *data),
134 const char namefmt[],
137 struct kthread_create_info create;
139 create.threadfn = threadfn;
141 init_completion(&create.done);
143 spin_lock(&kthread_create_lock);
144 list_add_tail(&create.list, &kthread_create_list);
145 spin_unlock(&kthread_create_lock);
147 wake_up_process(kthreadd_task);
148 wait_for_completion(&create.done);
150 if (!IS_ERR(create.result)) {
151 static const struct sched_param param = { .sched_priority = 0 };
154 va_start(args, namefmt);
155 vsnprintf(create.result->comm, sizeof(create.result->comm),
159 * root may have changed our (kthreadd's) priority or CPU mask.
160 * The kernel thread should not inherit these properties.
162 sched_setscheduler_nocheck(create.result, SCHED_NORMAL, ¶m);
163 set_cpus_allowed_ptr(create.result, cpu_all_mask);
165 return create.result;
167 EXPORT_SYMBOL(kthread_create);
170 * kthread_bind - bind a just-created kthread to a cpu.
171 * @p: thread created by kthread_create().
172 * @cpu: cpu (might not be online, must be possible) for @k to run on.
174 * Description: This function is equivalent to set_cpus_allowed(),
175 * except that @cpu doesn't need to be online, and the thread must be
176 * stopped (i.e., just returned from kthread_create()).
178 void kthread_bind(struct task_struct *p, unsigned int cpu)
180 /* Must have done schedule() in kthread() before we set_task_cpu */
181 if (!wait_task_inactive(p, TASK_UNINTERRUPTIBLE)) {
186 p->cpus_allowed = cpumask_of_cpu(cpu);
187 p->rt.nr_cpus_allowed = 1;
188 p->flags |= PF_THREAD_BOUND;
190 EXPORT_SYMBOL(kthread_bind);
193 * kthread_stop - stop a thread created by kthread_create().
194 * @k: thread created by kthread_create().
196 * Sets kthread_should_stop() for @k to return true, wakes it, and
197 * waits for it to exit. This can also be called after kthread_create()
198 * instead of calling wake_up_process(): the thread will exit without
199 * calling threadfn().
201 * If threadfn() may call do_exit() itself, the caller must ensure
202 * task_struct can't go away.
204 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
207 int kthread_stop(struct task_struct *k)
209 struct kthread *kthread;
212 trace_sched_kthread_stop(k);
215 kthread = to_kthread(k);
216 barrier(); /* it might have exited */
217 if (k->vfork_done != NULL) {
218 kthread->should_stop = 1;
220 wait_for_completion(&kthread->exited);
225 trace_sched_kthread_stop_ret(ret);
229 EXPORT_SYMBOL(kthread_stop);
231 int kthreadd(void *unused)
233 struct task_struct *tsk = current;
235 /* Setup a clean context for our children to inherit. */
236 set_task_comm(tsk, "kthreadd");
238 set_cpus_allowed_ptr(tsk, cpu_all_mask);
239 set_mems_allowed(node_states[N_HIGH_MEMORY]);
241 current->flags |= PF_NOFREEZE | PF_FREEZER_NOSIG;
244 set_current_state(TASK_INTERRUPTIBLE);
245 if (list_empty(&kthread_create_list))
247 __set_current_state(TASK_RUNNING);
249 spin_lock(&kthread_create_lock);
250 while (!list_empty(&kthread_create_list)) {
251 struct kthread_create_info *create;
253 create = list_entry(kthread_create_list.next,
254 struct kthread_create_info, list);
255 list_del_init(&create->list);
256 spin_unlock(&kthread_create_lock);
258 create_kthread(create);
260 spin_lock(&kthread_create_lock);
262 spin_unlock(&kthread_create_lock);
268 void __init_kthread_worker(struct kthread_worker *worker,
270 struct lock_class_key *key)
272 spin_lock_init(&worker->lock);
273 lockdep_set_class_and_name(&worker->lock, key, name);
274 INIT_LIST_HEAD(&worker->work_list);
277 EXPORT_SYMBOL_GPL(__init_kthread_worker);
280 * kthread_worker_fn - kthread function to process kthread_worker
281 * @worker_ptr: pointer to initialized kthread_worker
283 * This function can be used as @threadfn to kthread_create() or
284 * kthread_run() with @worker_ptr argument pointing to an initialized
285 * kthread_worker. The started kthread will process work_list until
286 * the it is stopped with kthread_stop(). A kthread can also call
287 * this function directly after extra initialization.
289 * Different kthreads can be used for the same kthread_worker as long
290 * as there's only one kthread attached to it at any given time. A
291 * kthread_worker without an attached kthread simply collects queued
294 int kthread_worker_fn(void *worker_ptr)
296 struct kthread_worker *worker = worker_ptr;
297 struct kthread_work *work;
299 WARN_ON(worker->task);
300 worker->task = current;
302 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
304 if (kthread_should_stop()) {
305 __set_current_state(TASK_RUNNING);
306 spin_lock_irq(&worker->lock);
308 spin_unlock_irq(&worker->lock);
313 spin_lock_irq(&worker->lock);
314 if (!list_empty(&worker->work_list)) {
315 work = list_first_entry(&worker->work_list,
316 struct kthread_work, node);
317 list_del_init(&work->node);
319 spin_unlock_irq(&worker->lock);
322 __set_current_state(TASK_RUNNING);
324 smp_wmb(); /* wmb worker-b0 paired with flush-b1 */
325 work->done_seq = work->queue_seq;
326 smp_mb(); /* mb worker-b1 paired with flush-b0 */
327 if (atomic_read(&work->flushing))
328 wake_up_all(&work->done);
329 } else if (!freezing(current))
335 EXPORT_SYMBOL_GPL(kthread_worker_fn);
338 * queue_kthread_work - queue a kthread_work
339 * @worker: target kthread_worker
340 * @work: kthread_work to queue
342 * Queue @work to work processor @task for async execution. @task
343 * must have been created with kthread_worker_create(). Returns %true
344 * if @work was successfully queued, %false if it was already pending.
346 bool queue_kthread_work(struct kthread_worker *worker,
347 struct kthread_work *work)
352 spin_lock_irqsave(&worker->lock, flags);
353 if (list_empty(&work->node)) {
354 list_add_tail(&work->node, &worker->work_list);
356 if (likely(worker->task))
357 wake_up_process(worker->task);
360 spin_unlock_irqrestore(&worker->lock, flags);
363 EXPORT_SYMBOL_GPL(queue_kthread_work);
366 * flush_kthread_work - flush a kthread_work
367 * @work: work to flush
369 * If @work is queued or executing, wait for it to finish execution.
371 void flush_kthread_work(struct kthread_work *work)
373 int seq = work->queue_seq;
375 atomic_inc(&work->flushing);
378 * mb flush-b0 paired with worker-b1, to make sure either
379 * worker sees the above increment or we see done_seq update.
381 smp_mb__after_atomic_inc();
383 /* A - B <= 0 tests whether B is in front of A regardless of overflow */
384 wait_event(work->done, seq - work->done_seq <= 0);
385 atomic_dec(&work->flushing);
388 * rmb flush-b1 paired with worker-b0, to make sure our caller
389 * sees every change made by work->func().
391 smp_mb__after_atomic_dec();
393 EXPORT_SYMBOL_GPL(flush_kthread_work);
395 struct kthread_flush_work {
396 struct kthread_work work;
397 struct completion done;
400 static void kthread_flush_work_fn(struct kthread_work *work)
402 struct kthread_flush_work *fwork =
403 container_of(work, struct kthread_flush_work, work);
404 complete(&fwork->done);
408 * flush_kthread_worker - flush all current works on a kthread_worker
409 * @worker: worker to flush
411 * Wait until all currently executing or pending works on @worker are
414 void flush_kthread_worker(struct kthread_worker *worker)
416 struct kthread_flush_work fwork = {
417 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
418 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
421 queue_kthread_work(worker, &fwork.work);
422 wait_for_completion(&fwork.done);
424 EXPORT_SYMBOL_GPL(flush_kthread_worker);