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