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/export.h>
16 #include <linux/mutex.h>
17 #include <linux/slab.h>
18 #include <linux/freezer.h>
19 #include <linux/ptrace.h>
20 #include <linux/uaccess.h>
21 #include <linux/preempt.h>
22 #include <trace/events/sched.h>
24 static DEFINE_SPINLOCK(kthread_create_lock);
25 static LIST_HEAD(kthread_create_list);
26 struct task_struct *kthreadd_task;
28 struct kthread_create_info
30 /* Information passed to kthread() from kthreadd. */
31 int (*threadfn)(void *data);
35 /* Result passed back to kthread_create() from kthreadd. */
36 struct task_struct *result;
37 struct completion done;
39 struct list_head list;
46 struct completion parked;
47 struct completion exited;
51 KTHREAD_IS_PER_CPU = 0,
57 #define __to_kthread(vfork) \
58 container_of(vfork, struct kthread, exited)
60 static inline struct kthread *to_kthread(struct task_struct *k)
62 return __to_kthread(k->vfork_done);
65 static struct kthread *to_live_kthread(struct task_struct *k)
67 struct completion *vfork = ACCESS_ONCE(k->vfork_done);
69 return __to_kthread(vfork);
74 * kthread_should_stop - should this kthread return now?
76 * When someone calls kthread_stop() on your kthread, it will be woken
77 * and this will return true. You should then return, and your return
78 * value will be passed through to kthread_stop().
80 bool kthread_should_stop(void)
82 return test_bit(KTHREAD_SHOULD_STOP, &to_kthread(current)->flags);
84 EXPORT_SYMBOL(kthread_should_stop);
87 * kthread_should_park - should this kthread park now?
89 * When someone calls kthread_park() on your kthread, it will be woken
90 * and this will return true. You should then do the necessary
91 * cleanup and call kthread_parkme()
93 * Similar to kthread_should_stop(), but this keeps the thread alive
94 * and in a park position. kthread_unpark() "restarts" the thread and
95 * calls the thread function again.
97 bool kthread_should_park(void)
99 return test_bit(KTHREAD_SHOULD_PARK, &to_kthread(current)->flags);
103 * kthread_freezable_should_stop - should this freezable kthread return now?
104 * @was_frozen: optional out parameter, indicates whether %current was frozen
106 * kthread_should_stop() for freezable kthreads, which will enter
107 * refrigerator if necessary. This function is safe from kthread_stop() /
108 * freezer deadlock and freezable kthreads should use this function instead
109 * of calling try_to_freeze() directly.
111 bool kthread_freezable_should_stop(bool *was_frozen)
117 if (unlikely(freezing(current)))
118 frozen = __refrigerator(true);
121 *was_frozen = frozen;
123 return kthread_should_stop();
125 EXPORT_SYMBOL_GPL(kthread_freezable_should_stop);
128 * kthread_data - return data value specified on kthread creation
129 * @task: kthread task in question
131 * Return the data value specified when kthread @task was created.
132 * The caller is responsible for ensuring the validity of @task when
133 * calling this function.
135 void *kthread_data(struct task_struct *task)
137 return to_kthread(task)->data;
141 * probe_kthread_data - speculative version of kthread_data()
142 * @task: possible kthread task in question
144 * @task could be a kthread task. Return the data value specified when it
145 * was created if accessible. If @task isn't a kthread task or its data is
146 * inaccessible for any reason, %NULL is returned. This function requires
147 * that @task itself is safe to dereference.
149 void *probe_kthread_data(struct task_struct *task)
151 struct kthread *kthread = to_kthread(task);
154 probe_kernel_read(&data, &kthread->data, sizeof(data));
158 static void __kthread_parkme(struct kthread *self)
160 __set_current_state(TASK_PARKED);
161 while (test_bit(KTHREAD_SHOULD_PARK, &self->flags)) {
162 if (!test_and_set_bit(KTHREAD_IS_PARKED, &self->flags))
163 complete(&self->parked);
165 __set_current_state(TASK_PARKED);
167 clear_bit(KTHREAD_IS_PARKED, &self->flags);
168 __set_current_state(TASK_RUNNING);
171 void kthread_parkme(void)
173 __kthread_parkme(to_kthread(current));
176 static int kthread(void *_create)
178 /* Copy data: it's on kthread's stack */
179 struct kthread_create_info *create = _create;
180 int (*threadfn)(void *data) = create->threadfn;
181 void *data = create->data;
187 init_completion(&self.exited);
188 init_completion(&self.parked);
189 current->vfork_done = &self.exited;
191 /* OK, tell user we're spawned, wait for stop or wakeup */
192 __set_current_state(TASK_UNINTERRUPTIBLE);
193 create->result = current;
196 * Disable preemption so we enter TASK_UNINTERRUPTIBLE after
197 * complete() instead of possibly being preempted. This speeds
198 * up clients that do a kthread_bind() directly after
202 complete(&create->done);
203 preempt_enable_no_resched();
209 if (!test_bit(KTHREAD_SHOULD_STOP, &self.flags)) {
210 __kthread_parkme(&self);
211 ret = threadfn(data);
213 /* we can't just return, we must preserve "self" on stack */
217 /* called from do_fork() to get node information for about to be created task */
218 int tsk_fork_get_node(struct task_struct *tsk)
221 if (tsk == kthreadd_task)
222 return tsk->pref_node_fork;
224 return numa_node_id();
227 static void create_kthread(struct kthread_create_info *create)
232 current->pref_node_fork = create->node;
234 /* We want our own signal handler (we take no signals by default). */
235 pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
237 create->result = ERR_PTR(pid);
238 complete(&create->done);
243 * kthread_create_on_node - create a kthread.
244 * @threadfn: the function to run until signal_pending(current).
245 * @data: data ptr for @threadfn.
246 * @node: memory node number.
247 * @namefmt: printf-style name for the thread.
249 * Description: This helper function creates and names a kernel
250 * thread. The thread will be stopped: use wake_up_process() to start
251 * it. See also kthread_run().
253 * If thread is going to be bound on a particular cpu, give its node
254 * in @node, to get NUMA affinity for kthread stack, or else give -1.
255 * When woken, the thread will run @threadfn() with @data as its
256 * argument. @threadfn() can either call do_exit() directly if it is a
257 * standalone thread for which no one will call kthread_stop(), or
258 * return when 'kthread_should_stop()' is true (which means
259 * kthread_stop() has been called). The return value should be zero
260 * or a negative error number; it will be passed to kthread_stop().
262 * Returns a task_struct or ERR_PTR(-ENOMEM).
264 struct task_struct *kthread_create_on_node(int (*threadfn)(void *data),
265 void *data, int node,
266 const char namefmt[],
269 struct kthread_create_info create;
271 create.threadfn = threadfn;
274 init_completion(&create.done);
276 spin_lock(&kthread_create_lock);
277 list_add_tail(&create.list, &kthread_create_list);
278 spin_unlock(&kthread_create_lock);
280 wake_up_process(kthreadd_task);
281 wait_for_completion(&create.done);
283 if (!IS_ERR(create.result)) {
284 static const struct sched_param param = { .sched_priority = 0 };
287 va_start(args, namefmt);
288 vsnprintf(create.result->comm, sizeof(create.result->comm),
292 * root may have changed our (kthreadd's) priority or CPU mask.
293 * The kernel thread should not inherit these properties.
295 sched_setscheduler_nocheck(create.result, SCHED_NORMAL, ¶m);
296 set_cpus_allowed_ptr(create.result, cpu_all_mask);
298 return create.result;
300 EXPORT_SYMBOL(kthread_create_on_node);
302 static void __kthread_bind(struct task_struct *p, unsigned int cpu, long state)
304 /* Must have done schedule() in kthread() before we set_task_cpu */
305 if (!wait_task_inactive(p, state)) {
309 /* It's safe because the task is inactive. */
310 do_set_cpus_allowed(p, cpumask_of(cpu));
311 p->flags |= PF_NO_SETAFFINITY;
315 * kthread_bind - bind a just-created kthread to a cpu.
316 * @p: thread created by kthread_create().
317 * @cpu: cpu (might not be online, must be possible) for @k to run on.
319 * Description: This function is equivalent to set_cpus_allowed(),
320 * except that @cpu doesn't need to be online, and the thread must be
321 * stopped (i.e., just returned from kthread_create()).
323 void kthread_bind(struct task_struct *p, unsigned int cpu)
325 __kthread_bind(p, cpu, TASK_UNINTERRUPTIBLE);
327 EXPORT_SYMBOL(kthread_bind);
330 * kthread_create_on_cpu - Create a cpu bound kthread
331 * @threadfn: the function to run until signal_pending(current).
332 * @data: data ptr for @threadfn.
333 * @cpu: The cpu on which the thread should be bound,
334 * @namefmt: printf-style name for the thread. Format is restricted
335 * to "name.*%u". Code fills in cpu number.
337 * Description: This helper function creates and names a kernel thread
338 * The thread will be woken and put into park mode.
340 struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
341 void *data, unsigned int cpu,
344 struct task_struct *p;
346 p = kthread_create_on_node(threadfn, data, cpu_to_node(cpu), namefmt,
350 set_bit(KTHREAD_IS_PER_CPU, &to_kthread(p)->flags);
351 to_kthread(p)->cpu = cpu;
352 /* Park the thread to get it out of TASK_UNINTERRUPTIBLE state */
357 static void __kthread_unpark(struct task_struct *k, struct kthread *kthread)
359 clear_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
361 * We clear the IS_PARKED bit here as we don't wait
362 * until the task has left the park code. So if we'd
363 * park before that happens we'd see the IS_PARKED bit
364 * which might be about to be cleared.
366 if (test_and_clear_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
367 if (test_bit(KTHREAD_IS_PER_CPU, &kthread->flags))
368 __kthread_bind(k, kthread->cpu, TASK_PARKED);
369 wake_up_state(k, TASK_PARKED);
374 * kthread_unpark - unpark a thread created by kthread_create().
375 * @k: thread created by kthread_create().
377 * Sets kthread_should_park() for @k to return false, wakes it, and
378 * waits for it to return. If the thread is marked percpu then its
379 * bound to the cpu again.
381 void kthread_unpark(struct task_struct *k)
383 struct kthread *kthread = to_live_kthread(k);
386 __kthread_unpark(k, kthread);
390 * kthread_park - park a thread created by kthread_create().
391 * @k: thread created by kthread_create().
393 * Sets kthread_should_park() for @k to return true, wakes it, and
394 * waits for it to return. This can also be called after kthread_create()
395 * instead of calling wake_up_process(): the thread will park without
396 * calling threadfn().
398 * Returns 0 if the thread is parked, -ENOSYS if the thread exited.
399 * If called by the kthread itself just the park bit is set.
401 int kthread_park(struct task_struct *k)
403 struct kthread *kthread = to_live_kthread(k);
407 if (!test_bit(KTHREAD_IS_PARKED, &kthread->flags)) {
408 set_bit(KTHREAD_SHOULD_PARK, &kthread->flags);
411 wait_for_completion(&kthread->parked);
420 * kthread_stop - stop a thread created by kthread_create().
421 * @k: thread created by kthread_create().
423 * Sets kthread_should_stop() for @k to return true, wakes it, and
424 * waits for it to exit. This can also be called after kthread_create()
425 * instead of calling wake_up_process(): the thread will exit without
426 * calling threadfn().
428 * If threadfn() may call do_exit() itself, the caller must ensure
429 * task_struct can't go away.
431 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
434 int kthread_stop(struct task_struct *k)
436 struct kthread *kthread;
439 trace_sched_kthread_stop(k);
442 kthread = to_live_kthread(k);
444 set_bit(KTHREAD_SHOULD_STOP, &kthread->flags);
445 __kthread_unpark(k, kthread);
447 wait_for_completion(&kthread->exited);
452 trace_sched_kthread_stop_ret(ret);
455 EXPORT_SYMBOL(kthread_stop);
457 int kthreadd(void *unused)
459 struct task_struct *tsk = current;
461 /* Setup a clean context for our children to inherit. */
462 set_task_comm(tsk, "kthreadd");
464 set_cpus_allowed_ptr(tsk, cpu_all_mask);
465 set_mems_allowed(node_states[N_MEMORY]);
467 current->flags |= PF_NOFREEZE;
470 set_current_state(TASK_INTERRUPTIBLE);
471 if (list_empty(&kthread_create_list))
473 __set_current_state(TASK_RUNNING);
475 spin_lock(&kthread_create_lock);
476 while (!list_empty(&kthread_create_list)) {
477 struct kthread_create_info *create;
479 create = list_entry(kthread_create_list.next,
480 struct kthread_create_info, list);
481 list_del_init(&create->list);
482 spin_unlock(&kthread_create_lock);
484 create_kthread(create);
486 spin_lock(&kthread_create_lock);
488 spin_unlock(&kthread_create_lock);
494 void __init_kthread_worker(struct kthread_worker *worker,
496 struct lock_class_key *key)
498 spin_lock_init(&worker->lock);
499 lockdep_set_class_and_name(&worker->lock, key, name);
500 INIT_LIST_HEAD(&worker->work_list);
503 EXPORT_SYMBOL_GPL(__init_kthread_worker);
506 * kthread_worker_fn - kthread function to process kthread_worker
507 * @worker_ptr: pointer to initialized kthread_worker
509 * This function can be used as @threadfn to kthread_create() or
510 * kthread_run() with @worker_ptr argument pointing to an initialized
511 * kthread_worker. The started kthread will process work_list until
512 * the it is stopped with kthread_stop(). A kthread can also call
513 * this function directly after extra initialization.
515 * Different kthreads can be used for the same kthread_worker as long
516 * as there's only one kthread attached to it at any given time. A
517 * kthread_worker without an attached kthread simply collects queued
520 int kthread_worker_fn(void *worker_ptr)
522 struct kthread_worker *worker = worker_ptr;
523 struct kthread_work *work;
525 WARN_ON(worker->task);
526 worker->task = current;
528 set_current_state(TASK_INTERRUPTIBLE); /* mb paired w/ kthread_stop */
530 if (kthread_should_stop()) {
531 __set_current_state(TASK_RUNNING);
532 spin_lock_irq(&worker->lock);
534 spin_unlock_irq(&worker->lock);
539 spin_lock_irq(&worker->lock);
540 if (!list_empty(&worker->work_list)) {
541 work = list_first_entry(&worker->work_list,
542 struct kthread_work, node);
543 list_del_init(&work->node);
545 worker->current_work = work;
546 spin_unlock_irq(&worker->lock);
549 __set_current_state(TASK_RUNNING);
551 } else if (!freezing(current))
557 EXPORT_SYMBOL_GPL(kthread_worker_fn);
559 /* insert @work before @pos in @worker */
560 static void insert_kthread_work(struct kthread_worker *worker,
561 struct kthread_work *work,
562 struct list_head *pos)
564 lockdep_assert_held(&worker->lock);
566 list_add_tail(&work->node, pos);
567 work->worker = worker;
568 if (likely(worker->task))
569 wake_up_process(worker->task);
573 * queue_kthread_work - queue a kthread_work
574 * @worker: target kthread_worker
575 * @work: kthread_work to queue
577 * Queue @work to work processor @task for async execution. @task
578 * must have been created with kthread_worker_create(). Returns %true
579 * if @work was successfully queued, %false if it was already pending.
581 bool queue_kthread_work(struct kthread_worker *worker,
582 struct kthread_work *work)
587 spin_lock_irqsave(&worker->lock, flags);
588 if (list_empty(&work->node)) {
589 insert_kthread_work(worker, work, &worker->work_list);
592 spin_unlock_irqrestore(&worker->lock, flags);
595 EXPORT_SYMBOL_GPL(queue_kthread_work);
597 struct kthread_flush_work {
598 struct kthread_work work;
599 struct completion done;
602 static void kthread_flush_work_fn(struct kthread_work *work)
604 struct kthread_flush_work *fwork =
605 container_of(work, struct kthread_flush_work, work);
606 complete(&fwork->done);
610 * flush_kthread_work - flush a kthread_work
611 * @work: work to flush
613 * If @work is queued or executing, wait for it to finish execution.
615 void flush_kthread_work(struct kthread_work *work)
617 struct kthread_flush_work fwork = {
618 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
619 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
621 struct kthread_worker *worker;
625 worker = work->worker;
629 spin_lock_irq(&worker->lock);
630 if (work->worker != worker) {
631 spin_unlock_irq(&worker->lock);
635 if (!list_empty(&work->node))
636 insert_kthread_work(worker, &fwork.work, work->node.next);
637 else if (worker->current_work == work)
638 insert_kthread_work(worker, &fwork.work, worker->work_list.next);
642 spin_unlock_irq(&worker->lock);
645 wait_for_completion(&fwork.done);
647 EXPORT_SYMBOL_GPL(flush_kthread_work);
650 * flush_kthread_worker - flush all current works on a kthread_worker
651 * @worker: worker to flush
653 * Wait until all currently executing or pending works on @worker are
656 void flush_kthread_worker(struct kthread_worker *worker)
658 struct kthread_flush_work fwork = {
659 KTHREAD_WORK_INIT(fwork.work, kthread_flush_work_fn),
660 COMPLETION_INITIALIZER_ONSTACK(fwork.done),
663 queue_kthread_work(worker, &fwork.work);
664 wait_for_completion(&fwork.done);
666 EXPORT_SYMBOL_GPL(flush_kthread_worker);