xref: /linux/kernel/kthread.c (revision 363c55cae53742f3f685a1814912c6d4fda245b4)
1 /* Kernel thread helper functions.
2  *   Copyright (C) 2004 IBM Corporation, Rusty Russell.
3  *
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,
6  * etc.).
7  */
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 <trace/events/sched.h>
18 
19 #define KTHREAD_NICE_LEVEL (-5)
20 
21 static DEFINE_SPINLOCK(kthread_create_lock);
22 static LIST_HEAD(kthread_create_list);
23 struct task_struct *kthreadd_task;
24 
25 struct kthread_create_info
26 {
27 	/* Information passed to kthread() from kthreadd. */
28 	int (*threadfn)(void *data);
29 	void *data;
30 	struct completion started;
31 
32 	/* Result passed back to kthread_create() from kthreadd. */
33 	struct task_struct *result;
34 	struct completion done;
35 
36 	struct list_head list;
37 };
38 
39 struct kthread_stop_info
40 {
41 	struct task_struct *k;
42 	int err;
43 	struct completion done;
44 };
45 
46 /* Thread stopping is done by setthing this var: lock serializes
47  * multiple kthread_stop calls. */
48 static DEFINE_MUTEX(kthread_stop_lock);
49 static struct kthread_stop_info kthread_stop_info;
50 
51 /**
52  * kthread_should_stop - should this kthread return now?
53  *
54  * When someone calls kthread_stop() on your kthread, it will be woken
55  * and this will return true.  You should then return, and your return
56  * value will be passed through to kthread_stop().
57  */
58 int kthread_should_stop(void)
59 {
60 	return (kthread_stop_info.k == current);
61 }
62 EXPORT_SYMBOL(kthread_should_stop);
63 
64 static int kthread(void *_create)
65 {
66 	struct kthread_create_info *create = _create;
67 	int (*threadfn)(void *data);
68 	void *data;
69 	int ret = -EINTR;
70 
71 	/* Copy data: it's on kthread's stack */
72 	threadfn = create->threadfn;
73 	data = create->data;
74 
75 	/* OK, tell user we're spawned, wait for stop or wakeup */
76 	__set_current_state(TASK_UNINTERRUPTIBLE);
77 	create->result = current;
78 	complete(&create->started);
79 	schedule();
80 
81 	if (!kthread_should_stop())
82 		ret = threadfn(data);
83 
84 	/* It might have exited on its own, w/o kthread_stop.  Check. */
85 	if (kthread_should_stop()) {
86 		kthread_stop_info.err = ret;
87 		complete(&kthread_stop_info.done);
88 	}
89 	return 0;
90 }
91 
92 static void create_kthread(struct kthread_create_info *create)
93 {
94 	int pid;
95 
96 	/* We want our own signal handler (we take no signals by default). */
97 	pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);
98 	if (pid < 0)
99 		create->result = ERR_PTR(pid);
100 	else
101 		wait_for_completion(&create->started);
102 	complete(&create->done);
103 }
104 
105 /**
106  * kthread_create - create a kthread.
107  * @threadfn: the function to run until signal_pending(current).
108  * @data: data ptr for @threadfn.
109  * @namefmt: printf-style name for the thread.
110  *
111  * Description: This helper function creates and names a kernel
112  * thread.  The thread will be stopped: use wake_up_process() to start
113  * it.  See also kthread_run(), kthread_create_on_cpu().
114  *
115  * When woken, the thread will run @threadfn() with @data as its
116  * argument. @threadfn() can either call do_exit() directly if it is a
117  * standalone thread for which noone will call kthread_stop(), or
118  * return when 'kthread_should_stop()' is true (which means
119  * kthread_stop() has been called).  The return value should be zero
120  * or a negative error number; it will be passed to kthread_stop().
121  *
122  * Returns a task_struct or ERR_PTR(-ENOMEM).
123  */
124 struct task_struct *kthread_create(int (*threadfn)(void *data),
125 				   void *data,
126 				   const char namefmt[],
127 				   ...)
128 {
129 	struct kthread_create_info create;
130 
131 	create.threadfn = threadfn;
132 	create.data = data;
133 	init_completion(&create.started);
134 	init_completion(&create.done);
135 
136 	spin_lock(&kthread_create_lock);
137 	list_add_tail(&create.list, &kthread_create_list);
138 	spin_unlock(&kthread_create_lock);
139 
140 	wake_up_process(kthreadd_task);
141 	wait_for_completion(&create.done);
142 
143 	if (!IS_ERR(create.result)) {
144 		struct sched_param param = { .sched_priority = 0 };
145 		va_list args;
146 
147 		va_start(args, namefmt);
148 		vsnprintf(create.result->comm, sizeof(create.result->comm),
149 			  namefmt, args);
150 		va_end(args);
151 		/*
152 		 * root may have changed our (kthreadd's) priority or CPU mask.
153 		 * The kernel thread should not inherit these properties.
154 		 */
155 		sched_setscheduler_nocheck(create.result, SCHED_NORMAL, &param);
156 		set_user_nice(create.result, KTHREAD_NICE_LEVEL);
157 		set_cpus_allowed_ptr(create.result, cpu_all_mask);
158 	}
159 	return create.result;
160 }
161 EXPORT_SYMBOL(kthread_create);
162 
163 /**
164  * kthread_bind - bind a just-created kthread to a cpu.
165  * @k: thread created by kthread_create().
166  * @cpu: cpu (might not be online, must be possible) for @k to run on.
167  *
168  * Description: This function is equivalent to set_cpus_allowed(),
169  * except that @cpu doesn't need to be online, and the thread must be
170  * stopped (i.e., just returned from kthread_create()).
171  */
172 void kthread_bind(struct task_struct *k, unsigned int cpu)
173 {
174 	/* Must have done schedule() in kthread() before we set_task_cpu */
175 	if (!wait_task_inactive(k, TASK_UNINTERRUPTIBLE)) {
176 		WARN_ON(1);
177 		return;
178 	}
179 	set_task_cpu(k, cpu);
180 	k->cpus_allowed = cpumask_of_cpu(cpu);
181 	k->rt.nr_cpus_allowed = 1;
182 	k->flags |= PF_THREAD_BOUND;
183 }
184 EXPORT_SYMBOL(kthread_bind);
185 
186 /**
187  * kthread_stop - stop a thread created by kthread_create().
188  * @k: thread created by kthread_create().
189  *
190  * Sets kthread_should_stop() for @k to return true, wakes it, and
191  * waits for it to exit.  Your threadfn() must not call do_exit()
192  * itself if you use this function!  This can also be called after
193  * kthread_create() instead of calling wake_up_process(): the thread
194  * will exit without calling threadfn().
195  *
196  * Returns the result of threadfn(), or %-EINTR if wake_up_process()
197  * was never called.
198  */
199 int kthread_stop(struct task_struct *k)
200 {
201 	int ret;
202 
203 	mutex_lock(&kthread_stop_lock);
204 
205 	/* It could exit after stop_info.k set, but before wake_up_process. */
206 	get_task_struct(k);
207 
208 	trace_sched_kthread_stop(k);
209 
210 	/* Must init completion *before* thread sees kthread_stop_info.k */
211 	init_completion(&kthread_stop_info.done);
212 	smp_wmb();
213 
214 	/* Now set kthread_should_stop() to true, and wake it up. */
215 	kthread_stop_info.k = k;
216 	wake_up_process(k);
217 	put_task_struct(k);
218 
219 	/* Once it dies, reset stop ptr, gather result and we're done. */
220 	wait_for_completion(&kthread_stop_info.done);
221 	kthread_stop_info.k = NULL;
222 	ret = kthread_stop_info.err;
223 	mutex_unlock(&kthread_stop_lock);
224 
225 	trace_sched_kthread_stop_ret(ret);
226 
227 	return ret;
228 }
229 EXPORT_SYMBOL(kthread_stop);
230 
231 int kthreadd(void *unused)
232 {
233 	struct task_struct *tsk = current;
234 
235 	/* Setup a clean context for our children to inherit. */
236 	set_task_comm(tsk, "kthreadd");
237 	ignore_signals(tsk);
238 	set_user_nice(tsk, KTHREAD_NICE_LEVEL);
239 	set_cpus_allowed_ptr(tsk, cpu_all_mask);
240 	set_mems_allowed(node_possible_map);
241 
242 	current->flags |= PF_NOFREEZE | PF_FREEZER_NOSIG;
243 
244 	for (;;) {
245 		set_current_state(TASK_INTERRUPTIBLE);
246 		if (list_empty(&kthread_create_list))
247 			schedule();
248 		__set_current_state(TASK_RUNNING);
249 
250 		spin_lock(&kthread_create_lock);
251 		while (!list_empty(&kthread_create_list)) {
252 			struct kthread_create_info *create;
253 
254 			create = list_entry(kthread_create_list.next,
255 					    struct kthread_create_info, list);
256 			list_del_init(&create->list);
257 			spin_unlock(&kthread_create_lock);
258 
259 			create_kthread(create);
260 
261 			spin_lock(&kthread_create_lock);
262 		}
263 		spin_unlock(&kthread_create_lock);
264 	}
265 
266 	return 0;
267 }
268