2 * Copyright (c) 2017 Hans Petter Selasky
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 <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <linux/kthread.h>
31 #include <linux/sched.h>
32 #include <linux/compat.h>
35 #include <sys/interrupt.h>
36 #include <sys/priority.h>
39 KTHREAD_SHOULD_STOP_MASK = (1 << 0),
40 KTHREAD_SHOULD_PARK_MASK = (1 << 1),
41 KTHREAD_IS_PARKED_MASK = (1 << 2),
45 kthread_should_stop_task(struct task_struct *task)
48 return (atomic_read(&task->kthread_flags) & KTHREAD_SHOULD_STOP_MASK);
52 kthread_should_stop(void)
55 return (atomic_read(¤t->kthread_flags) & KTHREAD_SHOULD_STOP_MASK);
59 kthread_stop(struct task_struct *task)
64 * Assume task is still alive else caller should not call
67 atomic_or(KTHREAD_SHOULD_STOP_MASK, &task->kthread_flags);
68 wake_up_process(task);
69 wait_for_completion(&task->exited);
72 * Get return code and free task structure:
74 retval = task->task_ret;
75 put_task_struct(task);
81 linux_kthread_setup_and_run(struct thread *td, linux_task_fn_t *task_fn, void *arg)
83 struct task_struct *task;
85 linux_set_current(td);
87 task = td->td_lkpi_task;
88 task->task_fn = task_fn;
89 task->task_data = arg;
92 /* make sure the scheduler priority is raised */
93 sched_prio(td, PI_SWI(SWI_NET));
94 /* put thread into run-queue */
95 sched_add(td, SRQ_BORING);
102 linux_kthread_fn(void *arg __unused)
104 struct task_struct *task = current;
106 if (kthread_should_stop_task(task) == 0)
107 task->task_ret = task->task_fn(task->task_data);
109 if (kthread_should_stop_task(task) != 0) {
110 struct thread *td = curthread;
112 /* let kthread_stop() free data */
113 td->td_lkpi_task = NULL;
115 /* wakeup kthread_stop() */
116 complete(&task->exited);