xref: /freebsd/sys/kern/kern_kthread.c (revision a0dd79dbdf917a8fbe2762d668f05a7c9f682b22)
1 /*-
2  * Copyright (c) 1999 Peter Wemm <peter@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/cpuset.h>
33 #include <sys/kthread.h>
34 #include <sys/lock.h>
35 #include <sys/mutex.h>
36 #include <sys/proc.h>
37 #include <sys/resourcevar.h>
38 #include <sys/rwlock.h>
39 #include <sys/signalvar.h>
40 #include <sys/sx.h>
41 #include <sys/unistd.h>
42 #include <sys/wait.h>
43 #include <sys/sched.h>
44 #include <vm/vm.h>
45 #include <vm/vm_extern.h>
46 
47 #include <machine/stdarg.h>
48 
49 /*
50  * Start a kernel process.  This is called after a fork() call in
51  * mi_startup() in the file kern/init_main.c.
52  *
53  * This function is used to start "internal" daemons and intended
54  * to be called from SYSINIT().
55  */
56 void
57 kproc_start(udata)
58 	const void *udata;
59 {
60 	const struct kproc_desc	*kp = udata;
61 	int error;
62 
63 	error = kproc_create((void (*)(void *))kp->func, NULL,
64 		    kp->global_procpp, 0, 0, "%s", kp->arg0);
65 	if (error)
66 		panic("kproc_start: %s: error %d", kp->arg0, error);
67 }
68 
69 /*
70  * Create a kernel process/thread/whatever.  It shares its address space
71  * with proc0 - ie: kernel only.
72  *
73  * func is the function to start.
74  * arg is the parameter to pass to function on first startup.
75  * newpp is the return value pointing to the thread's struct proc.
76  * flags are flags to fork1 (in unistd.h)
77  * fmt and following will be *printf'd into (*newpp)->p_comm (for ps, etc.).
78  */
79 int
80 kproc_create(void (*func)(void *), void *arg,
81     struct proc **newpp, int flags, int pages, const char *fmt, ...)
82 {
83 	int error;
84 	va_list ap;
85 	struct thread *td;
86 	struct proc *p2;
87 
88 	if (!proc0.p_stats)
89 		panic("kproc_create called too soon");
90 
91 	error = fork1(&thread0, RFMEM | RFFDG | RFPROC | RFSTOPPED | flags,
92 	    pages, &p2, NULL, 0);
93 	if (error)
94 		return error;
95 
96 	/* save a global descriptor, if desired */
97 	if (newpp != NULL)
98 		*newpp = p2;
99 
100 	/* this is a non-swapped system process */
101 	PROC_LOCK(p2);
102 	td = FIRST_THREAD_IN_PROC(p2);
103 	p2->p_flag |= P_SYSTEM | P_KTHREAD;
104 	td->td_pflags |= TDP_KTHREAD;
105 	mtx_lock(&p2->p_sigacts->ps_mtx);
106 	p2->p_sigacts->ps_flag |= PS_NOCLDWAIT;
107 	mtx_unlock(&p2->p_sigacts->ps_mtx);
108 	PROC_UNLOCK(p2);
109 
110 	/* set up arg0 for 'ps', et al */
111 	va_start(ap, fmt);
112 	vsnprintf(p2->p_comm, sizeof(p2->p_comm), fmt, ap);
113 	va_end(ap);
114 	/* set up arg0 for 'ps', et al */
115 	va_start(ap, fmt);
116 	vsnprintf(td->td_name, sizeof(td->td_name), fmt, ap);
117 	va_end(ap);
118 
119 	/* call the processes' main()... */
120 	cpu_set_fork_handler(td, func, arg);
121 
122 	/* Avoid inheriting affinity from a random parent. */
123 	cpuset_setthread(td->td_tid, cpuset_root);
124 	thread_lock(td);
125 	TD_SET_CAN_RUN(td);
126 	sched_prio(td, PVM);
127 	sched_user_prio(td, PUSER);
128 
129 	/* Delay putting it on the run queue until now. */
130 	if (!(flags & RFSTOPPED))
131 		sched_add(td, SRQ_BORING);
132 	thread_unlock(td);
133 
134 	return 0;
135 }
136 
137 void
138 kproc_exit(int ecode)
139 {
140 	struct thread *td;
141 	struct proc *p;
142 
143 	td = curthread;
144 	p = td->td_proc;
145 
146 	/*
147 	 * Reparent curthread from proc0 to init so that the zombie
148 	 * is harvested.
149 	 */
150 	sx_xlock(&proctree_lock);
151 	PROC_LOCK(p);
152 	proc_reparent(p, initproc);
153 	PROC_UNLOCK(p);
154 	sx_xunlock(&proctree_lock);
155 
156 	/*
157 	 * Wakeup anyone waiting for us to exit.
158 	 */
159 	wakeup(p);
160 
161 	/* Buh-bye! */
162 	exit1(td, W_EXITCODE(ecode, 0));
163 }
164 
165 /*
166  * Advise a kernel process to suspend (or resume) in its main loop.
167  * Participation is voluntary.
168  */
169 int
170 kproc_suspend(struct proc *p, int timo)
171 {
172 	/*
173 	 * Make sure this is indeed a system process and we can safely
174 	 * use the p_siglist field.
175 	 */
176 	PROC_LOCK(p);
177 	if ((p->p_flag & P_KTHREAD) == 0) {
178 		PROC_UNLOCK(p);
179 		return (EINVAL);
180 	}
181 	SIGADDSET(p->p_siglist, SIGSTOP);
182 	wakeup(p);
183 	return msleep(&p->p_siglist, &p->p_mtx, PPAUSE | PDROP, "suspkp", timo);
184 }
185 
186 int
187 kproc_resume(struct proc *p)
188 {
189 	/*
190 	 * Make sure this is indeed a system process and we can safely
191 	 * use the p_siglist field.
192 	 */
193 	PROC_LOCK(p);
194 	if ((p->p_flag & P_KTHREAD) == 0) {
195 		PROC_UNLOCK(p);
196 		return (EINVAL);
197 	}
198 	SIGDELSET(p->p_siglist, SIGSTOP);
199 	PROC_UNLOCK(p);
200 	wakeup(&p->p_siglist);
201 	return (0);
202 }
203 
204 void
205 kproc_suspend_check(struct proc *p)
206 {
207 	PROC_LOCK(p);
208 	while (SIGISMEMBER(p->p_siglist, SIGSTOP)) {
209 		wakeup(&p->p_siglist);
210 		msleep(&p->p_siglist, &p->p_mtx, PPAUSE, "kpsusp", 0);
211 	}
212 	PROC_UNLOCK(p);
213 }
214 
215 
216 /*
217  * Start a kernel thread.
218  *
219  * This function is used to start "internal" daemons and intended
220  * to be called from SYSINIT().
221  */
222 
223 void
224 kthread_start(udata)
225 	const void *udata;
226 {
227 	const struct kthread_desc	*kp = udata;
228 	int error;
229 
230 	error = kthread_add((void (*)(void *))kp->func, NULL,
231 		    NULL, kp->global_threadpp, 0, 0, "%s", kp->arg0);
232 	if (error)
233 		panic("kthread_start: %s: error %d", kp->arg0, error);
234 }
235 
236 /*
237  * Create a kernel thread.  It shares its address space
238  * with proc0 - ie: kernel only.
239  *
240  * func is the function to start.
241  * arg is the parameter to pass to function on first startup.
242  * newtdp is the return value pointing to the thread's struct thread.
243  *  ** XXX fix this --> flags are flags to fork1 (in unistd.h)
244  * fmt and following will be *printf'd into (*newtd)->td_name (for ps, etc.).
245  */
246 int
247 kthread_add(void (*func)(void *), void *arg, struct proc *p,
248     struct thread **newtdp, int flags, int pages, const char *fmt, ...)
249 {
250 	va_list ap;
251 	struct thread *newtd, *oldtd;
252 
253 	if (!proc0.p_stats)
254 		panic("kthread_add called too soon");
255 
256 	/* If no process supplied, put it on proc0 */
257 	if (p == NULL) {
258 		p = &proc0;
259 		oldtd = &thread0;
260 	} else {
261 		oldtd = FIRST_THREAD_IN_PROC(p);
262 	}
263 
264 	/* Initialize our new td  */
265 	newtd = thread_alloc(pages);
266 	if (newtd == NULL)
267 		return (ENOMEM);
268 
269 	bzero(&newtd->td_startzero,
270 	    __rangeof(struct thread, td_startzero, td_endzero));
271 /* XXX check if we should zero. */
272 	bcopy(&oldtd->td_startcopy, &newtd->td_startcopy,
273 	    __rangeof(struct thread, td_startcopy, td_endcopy));
274 
275 	/* set up arg0 for 'ps', et al */
276 	va_start(ap, fmt);
277 	vsnprintf(newtd->td_name, sizeof(newtd->td_name), fmt, ap);
278 	va_end(ap);
279 
280 	newtd->td_proc = p;  /* needed for cpu_set_upcall */
281 
282 	/* XXX optimise this probably? */
283 	/* On x86 (and probably the others too) it is way too full of junk */
284 	/* Needs a better name */
285 	cpu_set_upcall(newtd, oldtd);
286 	/* put the designated function(arg) as the resume context */
287 	cpu_set_fork_handler(newtd, func, arg);
288 
289 	newtd->td_pflags |= TDP_KTHREAD;
290 	newtd->td_ucred = crhold(p->p_ucred);
291 
292 	/* this code almost the same as create_thread() in kern_thr.c */
293 	PROC_LOCK(p);
294 	p->p_flag |= P_HADTHREADS;
295 	newtd->td_sigmask = oldtd->td_sigmask; /* XXX dubious */
296 	thread_link(newtd, p);
297 	thread_lock(oldtd);
298 	/* let the scheduler know about these things. */
299 	sched_fork_thread(oldtd, newtd);
300 	TD_SET_CAN_RUN(newtd);
301 	thread_unlock(oldtd);
302 	PROC_UNLOCK(p);
303 
304 	tidhash_add(newtd);
305 
306 	/* Avoid inheriting affinity from a random parent. */
307 	cpuset_setthread(newtd->td_tid, cpuset_root);
308 
309 	/* Delay putting it on the run queue until now. */
310 	if (!(flags & RFSTOPPED)) {
311 		thread_lock(newtd);
312 		sched_add(newtd, SRQ_BORING);
313 		thread_unlock(newtd);
314 	}
315 	if (newtdp)
316 		*newtdp = newtd;
317 	return 0;
318 }
319 
320 void
321 kthread_exit(void)
322 {
323 	struct proc *p;
324 
325 	p = curthread->td_proc;
326 
327 	/* A module may be waiting for us to exit. */
328 	wakeup(curthread);
329 
330 	/*
331 	 * The last exiting thread in a kernel process must tear down
332 	 * the whole process.
333 	 */
334 	rw_wlock(&tidhash_lock);
335 	PROC_LOCK(p);
336 	if (p->p_numthreads == 1) {
337 		PROC_UNLOCK(p);
338 		rw_wunlock(&tidhash_lock);
339 		kproc_exit(0);
340 	}
341 	LIST_REMOVE(curthread, td_hash);
342 	rw_wunlock(&tidhash_lock);
343 	PROC_SLOCK(p);
344 	thread_exit();
345 }
346 
347 /*
348  * Advise a kernel process to suspend (or resume) in its main loop.
349  * Participation is voluntary.
350  */
351 int
352 kthread_suspend(struct thread *td, int timo)
353 {
354 	struct proc *p;
355 
356 	p = td->td_proc;
357 
358 	/*
359 	 * td_pflags should not be read by any thread other than
360 	 * curthread, but as long as this flag is invariant during the
361 	 * thread's lifetime, it is OK to check its state.
362 	 */
363 	if ((td->td_pflags & TDP_KTHREAD) == 0)
364 		return (EINVAL);
365 
366 	/*
367 	 * The caller of the primitive should have already checked that the
368 	 * thread is up and running, thus not being blocked by other
369 	 * conditions.
370 	 */
371 	PROC_LOCK(p);
372 	thread_lock(td);
373 	td->td_flags |= TDF_KTH_SUSP;
374 	thread_unlock(td);
375 	return (msleep(&td->td_flags, &p->p_mtx, PPAUSE | PDROP, "suspkt",
376 	    timo));
377 }
378 
379 /*
380  * Resume a thread previously put asleep with kthread_suspend().
381  */
382 int
383 kthread_resume(struct thread *td)
384 {
385 	struct proc *p;
386 
387 	p = td->td_proc;
388 
389 	/*
390 	 * td_pflags should not be read by any thread other than
391 	 * curthread, but as long as this flag is invariant during the
392 	 * thread's lifetime, it is OK to check its state.
393 	 */
394 	if ((td->td_pflags & TDP_KTHREAD) == 0)
395 		return (EINVAL);
396 
397 	PROC_LOCK(p);
398 	thread_lock(td);
399 	td->td_flags &= ~TDF_KTH_SUSP;
400 	thread_unlock(td);
401 	wakeup(&td->td_flags);
402 	PROC_UNLOCK(p);
403 	return (0);
404 }
405 
406 /*
407  * Used by the thread to poll as to whether it should yield/sleep
408  * and notify the caller that is has happened.
409  */
410 void
411 kthread_suspend_check()
412 {
413 	struct proc *p;
414 	struct thread *td;
415 
416 	td = curthread;
417 	p = td->td_proc;
418 
419 	if ((td->td_pflags & TDP_KTHREAD) == 0)
420 		panic("%s: curthread is not a valid kthread", __func__);
421 
422 	/*
423 	 * As long as the double-lock protection is used when accessing the
424 	 * TDF_KTH_SUSP flag, synchronizing the read operation via proc mutex
425 	 * is fine.
426 	 */
427 	PROC_LOCK(p);
428 	while (td->td_flags & TDF_KTH_SUSP) {
429 		wakeup(&td->td_flags);
430 		msleep(&td->td_flags, &p->p_mtx, PPAUSE, "ktsusp", 0);
431 	}
432 	PROC_UNLOCK(p);
433 }
434 
435 int
436 kproc_kthread_add(void (*func)(void *), void *arg,
437             struct proc **procptr, struct thread **tdptr,
438             int flags, int pages, const char *procname, const char *fmt, ...)
439 {
440 	int error;
441 	va_list ap;
442 	char buf[100];
443 	struct thread *td;
444 
445 	if (*procptr == 0) {
446 		error = kproc_create(func, arg,
447 		    	procptr, flags, pages, "%s", procname);
448 		if (error)
449 			return (error);
450 		td = FIRST_THREAD_IN_PROC(*procptr);
451 		if (tdptr)
452 			*tdptr = td;
453 		va_start(ap, fmt);
454 		vsnprintf(td->td_name, sizeof(td->td_name), fmt, ap);
455 		va_end(ap);
456 		return (0);
457 	}
458 	va_start(ap, fmt);
459 	vsnprintf(buf, sizeof(buf), fmt, ap);
460 	va_end(ap);
461 	error = kthread_add(func, arg, *procptr,
462 		    tdptr, flags, pages, "%s", buf);
463 	return (error);
464 }
465