2 * Copyright (c) 2019 François Tigeot <ftigeot@wolfpond.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice unmodified, this list of conditions, and the following
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <linux/kthread.h>
28 #include <linux/sched.h>
29 #include <linux/slab.h>
31 #include <sys/kthread.h>
34 All Linux threads/processes have an associated task_struct
35 a kthread is a pure kernel thread without userland context
39 linux_ktfn_wrapper(void *arg)
41 struct task_struct *task = arg;
43 task->kt_exitvalue = task->kt_fn(task->kt_fndata);
47 kthread_run(int (*lfn)(void *), void *data, const char *namefmt, ...)
49 struct task_struct *task;
54 task = kzalloc(sizeof(*task), GFP_KERNEL);
56 __va_start(args, namefmt);
57 ret = kthread_alloc(linux_ktfn_wrapper, task, &td, namefmt, args);
61 return ERR_PTR(-ENOMEM);
65 td->td_linux_task = task;
67 task->mm = NULL; /* kthreads have no userland address space */
70 task->kt_fndata = data;
72 /* Start the thread here */
78 #define KTHREAD_SHOULD_STOP 1
81 kthread_should_stop(void)
83 return test_bit(KTHREAD_SHOULD_STOP, ¤t->kt_flags);
87 kthread_stop(struct task_struct *ts)
89 set_bit(KTHREAD_SHOULD_STOP, &ts->kt_flags);
92 wait_for_completion(&ts->kt_exited);
94 return ts->kt_exitvalue;