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