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