xref: /freebsd/sys/kern/kern_kthread.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 #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/sysent.h>
41 #include <sys/sx.h>
42 #include <sys/umtxvar.h>
43 #include <sys/unistd.h>
44 #include <sys/wait.h>
45 #include <sys/sched.h>
46 #include <sys/tslog.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_flags2 = FR2_KPROC;
97 	fr.fr_pages = pages;
98 	fr.fr_procp = &p2;
99 	error = fork1(&thread0, &fr);
100 	if (error)
101 		return error;
102 
103 	/* save a global descriptor, if desired */
104 	if (newpp != NULL)
105 		*newpp = p2;
106 
107 	/* set up arg0 for 'ps', et al */
108 	va_start(ap, fmt);
109 	vsnprintf(p2->p_comm, sizeof(p2->p_comm), fmt, ap);
110 	va_end(ap);
111 	td = FIRST_THREAD_IN_PROC(p2);
112 	va_start(ap, fmt);
113 	vsnprintf(td->td_name, sizeof(td->td_name), fmt, ap);
114 	va_end(ap);
115 #ifdef KTR
116 	sched_clear_tdname(td);
117 #endif
118 	TSTHREAD(td, td->td_name);
119 #ifdef HWPMC_HOOKS
120 	if (PMC_SYSTEM_SAMPLING_ACTIVE()) {
121 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_PROC_CREATE_LOG, p2);
122 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_CREATE_LOG, NULL);
123 	}
124 #endif
125 
126 	/* call the processes' main()... */
127 	cpu_fork_kthread_handler(td, func, arg);
128 
129 	/* Avoid inheriting affinity from a random parent. */
130 	cpuset_kernthread(td);
131 	thread_lock(td);
132 	TD_SET_CAN_RUN(td);
133 	sched_prio(td, PVM);
134 	sched_user_prio(td, PUSER);
135 
136 	/* Delay putting it on the run queue until now. */
137 	if (!(flags & RFSTOPPED))
138 		sched_add(td, SRQ_BORING);
139 	else
140 		thread_unlock(td);
141 
142 	return 0;
143 }
144 
145 void
146 kproc_exit(int ecode)
147 {
148 	struct thread *td;
149 	struct proc *p;
150 
151 	td = curthread;
152 	p = td->td_proc;
153 
154 	/*
155 	 * Reparent curthread from proc0 to init so that the zombie
156 	 * is harvested.
157 	 */
158 	sx_xlock(&proctree_lock);
159 	PROC_LOCK(p);
160 	proc_reparent(p, initproc, true);
161 	PROC_UNLOCK(p);
162 	sx_xunlock(&proctree_lock);
163 
164 	/*
165 	 * Wakeup anyone waiting for us to exit.
166 	 */
167 	wakeup(p);
168 
169 	/* Buh-bye! */
170 	exit1(td, ecode, 0);
171 }
172 
173 /*
174  * Advise a kernel process to suspend (or resume) in its main loop.
175  * Participation is voluntary.
176  */
177 int
178 kproc_suspend(struct proc *p, int timo)
179 {
180 	/*
181 	 * Make sure this is indeed a system process and we can safely
182 	 * use the p_siglist field.
183 	 */
184 	PROC_LOCK(p);
185 	if ((p->p_flag & P_KPROC) == 0) {
186 		PROC_UNLOCK(p);
187 		return (EINVAL);
188 	}
189 	SIGADDSET(p->p_siglist, SIGSTOP);
190 	wakeup(p);
191 	return msleep(&p->p_siglist, &p->p_mtx, PPAUSE | PDROP, "suspkp", timo);
192 }
193 
194 int
195 kproc_resume(struct proc *p)
196 {
197 	/*
198 	 * Make sure this is indeed a system process and we can safely
199 	 * use the p_siglist field.
200 	 */
201 	PROC_LOCK(p);
202 	if ((p->p_flag & P_KPROC) == 0) {
203 		PROC_UNLOCK(p);
204 		return (EINVAL);
205 	}
206 	SIGDELSET(p->p_siglist, SIGSTOP);
207 	PROC_UNLOCK(p);
208 	wakeup(&p->p_siglist);
209 	return (0);
210 }
211 
212 void
213 kproc_suspend_check(struct proc *p)
214 {
215 	PROC_LOCK(p);
216 	while (SIGISMEMBER(p->p_siglist, SIGSTOP)) {
217 		wakeup(&p->p_siglist);
218 		msleep(&p->p_siglist, &p->p_mtx, PPAUSE, "kpsusp", 0);
219 	}
220 	PROC_UNLOCK(p);
221 }
222 
223 /*
224  * Start a kernel thread.
225  *
226  * This function is used to start "internal" daemons and intended
227  * to be called from SYSINIT().
228  */
229 
230 void
231 kthread_start(const void *udata)
232 {
233 	const struct kthread_desc	*kp = udata;
234 	int error;
235 
236 	error = kthread_add((void (*)(void *))kp->func, NULL,
237 		    NULL, kp->global_threadpp, 0, 0, "%s", kp->arg0);
238 	if (error)
239 		panic("kthread_start: %s: error %d", kp->arg0, error);
240 }
241 
242 /*
243  * Create a kernel thread.  It shares its address space
244  * with proc0 - ie: kernel only.
245  *
246  * func is the function to start.
247  * arg is the parameter to pass to function on first startup.
248  * newtdp is the return value pointing to the thread's struct thread.
249  *  ** XXX fix this --> flags are flags to fork1 (in unistd.h)
250  * fmt and following will be *printf'd into (*newtd)->td_name (for ps, etc.).
251  */
252 int
253 kthread_add(void (*func)(void *), void *arg, struct proc *p,
254     struct thread **newtdp, int flags, int pages, const char *fmt, ...)
255 {
256 	va_list ap;
257 	struct thread *newtd, *oldtd;
258 
259 	if (!proc0.p_stats)
260 		panic("kthread_add called too soon");
261 
262 	/* If no process supplied, put it on proc0 */
263 	if (p == NULL)
264 		p = &proc0;
265 
266 	/* Initialize our new td  */
267 	newtd = thread_alloc(pages);
268 	if (newtd == NULL)
269 		return (ENOMEM);
270 
271 	PROC_LOCK(p);
272 	oldtd = FIRST_THREAD_IN_PROC(p);
273 
274 	bzero(&newtd->td_startzero,
275 	    __rangeof(struct thread, td_startzero, td_endzero));
276 	bcopy(&oldtd->td_startcopy, &newtd->td_startcopy,
277 	    __rangeof(struct thread, td_startcopy, td_endcopy));
278 
279 	/* set up arg0 for 'ps', et al */
280 	va_start(ap, fmt);
281 	vsnprintf(newtd->td_name, sizeof(newtd->td_name), fmt, ap);
282 	va_end(ap);
283 
284 	TSTHREAD(newtd, newtd->td_name);
285 
286 	newtd->td_proc = p;  /* needed for cpu_copy_thread */
287 	newtd->td_pflags |= TDP_KTHREAD;
288 
289 	/* might be further optimized for kthread */
290 	cpu_copy_thread(newtd, oldtd);
291 
292 	/* put the designated function(arg) as the resume context */
293 	cpu_fork_kthread_handler(newtd, func, arg);
294 
295 	thread_cow_get_proc(newtd, p);
296 
297 	/* This code is similar to thread_create() in kern_thr.c. */
298 	p->p_flag |= P_HADTHREADS;
299 	thread_link(newtd, p);
300 	thread_lock(oldtd);
301 	/* let the scheduler know about these things. */
302 	sched_fork_thread(oldtd, newtd);
303 	TD_SET_CAN_RUN(newtd);
304 	thread_unlock(oldtd);
305 	PROC_UNLOCK(p);
306 
307 	tidhash_add(newtd);
308 
309 	/* Avoid inheriting affinity from a random parent. */
310 	cpuset_kernthread(newtd);
311 #ifdef HWPMC_HOOKS
312 	if (PMC_SYSTEM_SAMPLING_ACTIVE())
313 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_CREATE_LOG, NULL);
314 #endif
315 	/* Delay putting it on the run queue until now. */
316 	if (!(flags & RFSTOPPED)) {
317 		thread_lock(newtd);
318 		sched_add(newtd, SRQ_BORING);
319 	}
320 	if (newtdp)
321 		*newtdp = newtd;
322 	return 0;
323 }
324 
325 void
326 kthread_exit(void)
327 {
328 	struct proc *p;
329 	struct thread *td;
330 
331 	td = curthread;
332 	p = td->td_proc;
333 
334 #ifdef HWPMC_HOOKS
335 	if (PMC_SYSTEM_SAMPLING_ACTIVE())
336 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
337 #endif
338 	/* A module may be waiting for us to exit. */
339 	wakeup(td);
340 
341 	/*
342 	 * The last exiting thread in a kernel process must tear down
343 	 * the whole process.
344 	 */
345 	PROC_LOCK(p);
346 	if (p->p_numthreads == 1) {
347 		PROC_UNLOCK(p);
348 		kproc_exit(0);
349 	}
350 
351 	if (p->p_sysent->sv_ontdexit != NULL)
352 		p->p_sysent->sv_ontdexit(td);
353 
354 	tidhash_remove(td);
355 	umtx_thread_exit(td);
356 	tdsigcleanup(td);
357 	PROC_SLOCK(p);
358 	thread_exit();
359 }
360 
361 /*
362  * Advise a kernel process to suspend (or resume) in its main loop.
363  * Participation is voluntary.
364  */
365 int
366 kthread_suspend(struct thread *td, int timo)
367 {
368 	struct proc *p;
369 
370 	p = td->td_proc;
371 
372 	/*
373 	 * td_pflags should not be read by any thread other than
374 	 * curthread, but as long as this flag is invariant during the
375 	 * thread's lifetime, it is OK to check its state.
376 	 */
377 	if ((td->td_pflags & TDP_KTHREAD) == 0)
378 		return (EINVAL);
379 
380 	/*
381 	 * The caller of the primitive should have already checked that the
382 	 * thread is up and running, thus not being blocked by other
383 	 * conditions.
384 	 */
385 	PROC_LOCK(p);
386 	thread_lock(td);
387 	td->td_flags |= TDF_KTH_SUSP;
388 	thread_unlock(td);
389 	return (msleep(&td->td_flags, &p->p_mtx, PPAUSE | PDROP, "suspkt",
390 	    timo));
391 }
392 
393 /*
394  * Resume a thread previously put asleep with kthread_suspend().
395  */
396 int
397 kthread_resume(struct thread *td)
398 {
399 	struct proc *p;
400 
401 	p = td->td_proc;
402 
403 	/*
404 	 * td_pflags should not be read by any thread other than
405 	 * curthread, but as long as this flag is invariant during the
406 	 * thread's lifetime, it is OK to check its state.
407 	 */
408 	if ((td->td_pflags & TDP_KTHREAD) == 0)
409 		return (EINVAL);
410 
411 	PROC_LOCK(p);
412 	thread_lock(td);
413 	td->td_flags &= ~TDF_KTH_SUSP;
414 	thread_unlock(td);
415 	wakeup(&td->td_flags);
416 	PROC_UNLOCK(p);
417 	return (0);
418 }
419 
420 /*
421  * Used by the thread to poll as to whether it should yield/sleep
422  * and notify the caller that is has happened.
423  */
424 void
425 kthread_suspend_check(void)
426 {
427 	struct proc *p;
428 	struct thread *td;
429 
430 	td = curthread;
431 	p = td->td_proc;
432 
433 	if ((td->td_pflags & TDP_KTHREAD) == 0)
434 		panic("%s: curthread is not a valid kthread", __func__);
435 
436 	/*
437 	 * Setting the TDF_KTH_SUSP flag is protected by process lock.
438 	 *
439 	 * Do an unlocked read first to avoid serializing with all other threads
440 	 * in the common case of not suspending.
441 	 */
442 	if ((td->td_flags & TDF_KTH_SUSP) == 0)
443 		return;
444 	PROC_LOCK(p);
445 	while ((td->td_flags & TDF_KTH_SUSP) != 0) {
446 		wakeup(&td->td_flags);
447 		msleep(&td->td_flags, &p->p_mtx, PPAUSE, "ktsusp", 0);
448 	}
449 	PROC_UNLOCK(p);
450 }
451 
452 int
453 kproc_kthread_add(void (*func)(void *), void *arg,
454             struct proc **procptr, struct thread **tdptr,
455             int flags, int pages, const char *procname, const char *fmt, ...)
456 {
457 	int error;
458 	va_list ap;
459 	char buf[100];
460 	struct thread *td;
461 
462 	if (*procptr == NULL) {
463 		error = kproc_create(func, arg,
464 		    	procptr, flags, pages, "%s", procname);
465 		if (error)
466 			return (error);
467 		td = FIRST_THREAD_IN_PROC(*procptr);
468 		if (tdptr)
469 			*tdptr = td;
470 		va_start(ap, fmt);
471 		vsnprintf(td->td_name, sizeof(td->td_name), fmt, ap);
472 		va_end(ap);
473 #ifdef KTR
474 		sched_clear_tdname(td);
475 #endif
476 		return (0);
477 	}
478 	va_start(ap, fmt);
479 	vsnprintf(buf, sizeof(buf), fmt, ap);
480 	va_end(ap);
481 	error = kthread_add(func, arg, *procptr,
482 		    tdptr, flags, pages, "%s", buf);
483 	return (error);
484 }
485