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