xref: /freebsd/sys/kern/kern_fork.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_fork.c	8.6 (Berkeley) 4/8/94
39  * $FreeBSD$
40  */
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/filedesc.h>
48 #include <sys/kernel.h>
49 #include <sys/sysctl.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/resourcevar.h>
55 #include <sys/syscall.h>
56 #include <sys/vnode.h>
57 #include <sys/acct.h>
58 #include <sys/ktr.h>
59 #include <sys/ktrace.h>
60 #include <sys/kthread.h>
61 #include <sys/unistd.h>
62 #include <sys/jail.h>
63 #include <sys/sx.h>
64 
65 #include <vm/vm.h>
66 #include <vm/pmap.h>
67 #include <vm/vm_map.h>
68 #include <vm/vm_extern.h>
69 #include <vm/vm_zone.h>
70 
71 #include <sys/vmmeter.h>
72 #include <sys/user.h>
73 
74 static MALLOC_DEFINE(M_ATFORK, "atfork", "atfork callback");
75 
76 static int	fast_vfork = 1;
77 SYSCTL_INT(_kern, OID_AUTO, fast_vfork, CTLFLAG_RW, &fast_vfork, 0,
78     "flag to indicate whether we have a fast vfork()");
79 
80 /*
81  * These are the stuctures used to create a callout list for things to do
82  * when forking a process
83  */
84 struct forklist {
85 	forklist_fn function;
86 	TAILQ_ENTRY(forklist) next;
87 };
88 
89 static struct sx fork_list_lock;
90 
91 TAILQ_HEAD(forklist_head, forklist);
92 static struct forklist_head fork_list = TAILQ_HEAD_INITIALIZER(fork_list);
93 
94 #ifndef _SYS_SYSPROTO_H_
95 struct fork_args {
96 	int     dummy;
97 };
98 #endif
99 
100 static void
101 init_fork_list(void *data __unused)
102 {
103 
104 	sx_init(&fork_list_lock, "fork list");
105 }
106 SYSINIT(fork_list, SI_SUB_INTRINSIC, SI_ORDER_ANY, init_fork_list, NULL);
107 
108 /* ARGSUSED */
109 int
110 fork(p, uap)
111 	struct proc *p;
112 	struct fork_args *uap;
113 {
114 	int error;
115 	struct proc *p2;
116 
117 	error = fork1(p, RFFDG | RFPROC, &p2);
118 	if (error == 0) {
119 		p->p_retval[0] = p2->p_pid;
120 		p->p_retval[1] = 0;
121 	}
122 	return error;
123 }
124 
125 /* ARGSUSED */
126 int
127 vfork(p, uap)
128 	struct proc *p;
129 	struct vfork_args *uap;
130 {
131 	int error;
132 	struct proc *p2;
133 
134 	error = fork1(p, RFFDG | RFPROC | RFPPWAIT | RFMEM, &p2);
135 	if (error == 0) {
136 		p->p_retval[0] = p2->p_pid;
137 		p->p_retval[1] = 0;
138 	}
139 	return error;
140 }
141 
142 int
143 rfork(p, uap)
144 	struct proc *p;
145 	struct rfork_args *uap;
146 {
147 	int error;
148 	struct proc *p2;
149 
150 	/* mask kernel only flags out of the user flags */
151 	error = fork1(p, uap->flags & ~RFKERNELONLY, &p2);
152 	if (error == 0) {
153 		p->p_retval[0] = p2 ? p2->p_pid : 0;
154 		p->p_retval[1] = 0;
155 	}
156 	return error;
157 }
158 
159 
160 int	nprocs = 1;				/* process 0 */
161 int	lastpid = 0;
162 SYSCTL_INT(_kern, OID_AUTO, lastpid, CTLFLAG_RD, &lastpid, 0,
163     "Last used PID");
164 
165 /*
166  * Random component to lastpid generation.  We mix in a random factor to make
167  * it a little harder to predict.  We sanity check the modulus value to avoid
168  * doing it in critical paths.  Don't let it be too small or we pointlessly
169  * waste randomness entropy, and don't let it be impossibly large.  Using a
170  * modulus that is too big causes a LOT more process table scans and slows
171  * down fork processing as the pidchecked caching is defeated.
172  */
173 static int randompid = 0;
174 
175 static int
176 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
177 {
178 	int error, pid;
179 
180 	pid = randompid;
181 	error = sysctl_handle_int(oidp, &pid, 0, req);
182 	if (error || !req->newptr)
183 		return (error);
184 	if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
185 		pid = PID_MAX - 100;
186 	else if (pid < 2)			/* NOP */
187 		pid = 0;
188 	else if (pid < 100)			/* Make it reasonable */
189 		pid = 100;
190 	randompid = pid;
191 	return (error);
192 }
193 
194 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
195     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
196 
197 int
198 fork1(p1, flags, procp)
199 	struct proc *p1;			/* parent proc */
200 	int flags;
201 	struct proc **procp;			/* child proc */
202 {
203 	struct proc *p2, *pptr;
204 	uid_t uid;
205 	struct proc *newproc;
206 	int trypid;
207 	int ok;
208 	static int pidchecked = 0;
209 	struct forklist *ep;
210 	struct filedesc *fd;
211 
212 	/* Can't copy and clear */
213 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
214 		return (EINVAL);
215 
216 	/*
217 	 * Here we don't create a new process, but we divorce
218 	 * certain parts of a process from itself.
219 	 */
220 	if ((flags & RFPROC) == 0) {
221 
222 		vm_fork(p1, 0, flags);
223 		mtx_assert(&vm_mtx, MA_NOTOWNED);
224 
225 		/*
226 		 * Close all file descriptors.
227 		 */
228 		if (flags & RFCFDG) {
229 			struct filedesc *fdtmp;
230 			fdtmp = fdinit(p1);
231 			PROC_LOCK(p1);
232 			fdfree(p1);
233 			p1->p_fd = fdtmp;
234 			PROC_UNLOCK(p1);
235 		}
236 
237 		/*
238 		 * Unshare file descriptors (from parent.)
239 		 */
240 		if (flags & RFFDG) {
241 			if (p1->p_fd->fd_refcnt > 1) {
242 				struct filedesc *newfd;
243 				newfd = fdcopy(p1);
244 				PROC_LOCK(p1);
245 				fdfree(p1);
246 				p1->p_fd = newfd;
247 				PROC_UNLOCK(p1);
248 			}
249 		}
250 		*procp = NULL;
251 		return (0);
252 	}
253 
254 	/*
255 	 * Although process entries are dynamically created, we still keep
256 	 * a global limit on the maximum number we will create.  Don't allow
257 	 * a nonprivileged user to use the last process; don't let root
258 	 * exceed the limit. The variable nprocs is the current number of
259 	 * processes, maxproc is the limit.
260 	 */
261 	uid = p1->p_ucred->cr_ruid;
262 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
263 		tablefull("proc");
264 		return (EAGAIN);
265 	}
266 	/*
267 	 * Increment the nprocs resource before blocking can occur.  There
268 	 * are hard-limits as to the number of processes that can run.
269 	 */
270 	nprocs++;
271 
272 	/*
273 	 * Increment the count of procs running with this uid. Don't allow
274 	 * a nonprivileged user to exceed their current limit.
275 	 */
276 	ok = chgproccnt(p1->p_ucred->cr_ruidinfo, 1,
277 		(uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
278 	if (!ok) {
279 		/*
280 		 * Back out the process count
281 		 */
282 		nprocs--;
283 		return (EAGAIN);
284 	}
285 
286 	/* Allocate new proc. */
287 	newproc = zalloc(proc_zone);
288 
289 	/*
290 	 * Setup linkage for kernel based threading
291 	 */
292 	if((flags & RFTHREAD) != 0) {
293 		newproc->p_peers = p1->p_peers;
294 		p1->p_peers = newproc;
295 		newproc->p_leader = p1->p_leader;
296 	} else {
297 		newproc->p_peers = NULL;
298 		newproc->p_leader = newproc;
299 	}
300 
301 	newproc->p_vmspace = NULL;
302 
303 	/*
304 	 * Find an unused process ID.  We remember a range of unused IDs
305 	 * ready to use (from lastpid+1 through pidchecked-1).
306 	 *
307 	 * If RFHIGHPID is set (used during system boot), do not allocate
308 	 * low-numbered pids.
309 	 */
310 	sx_xlock(&allproc_lock);
311 	trypid = lastpid + 1;
312 	if (flags & RFHIGHPID) {
313 		if (trypid < 10) {
314 			trypid = 10;
315 		}
316 	} else {
317 		if (randompid)
318 			trypid += arc4random() % randompid;
319 	}
320 retry:
321 	/*
322 	 * If the process ID prototype has wrapped around,
323 	 * restart somewhat above 0, as the low-numbered procs
324 	 * tend to include daemons that don't exit.
325 	 */
326 	if (trypid >= PID_MAX) {
327 		trypid = trypid % PID_MAX;
328 		if (trypid < 100)
329 			trypid += 100;
330 		pidchecked = 0;
331 	}
332 	if (trypid >= pidchecked) {
333 		int doingzomb = 0;
334 
335 		pidchecked = PID_MAX;
336 		/*
337 		 * Scan the active and zombie procs to check whether this pid
338 		 * is in use.  Remember the lowest pid that's greater
339 		 * than trypid, so we can avoid checking for a while.
340 		 */
341 		p2 = LIST_FIRST(&allproc);
342 again:
343 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
344 			while (p2->p_pid == trypid ||
345 			    p2->p_pgrp->pg_id == trypid ||
346 			    p2->p_session->s_sid == trypid) {
347 				trypid++;
348 				if (trypid >= pidchecked)
349 					goto retry;
350 			}
351 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
352 				pidchecked = p2->p_pid;
353 			if (p2->p_pgrp->pg_id > trypid &&
354 			    pidchecked > p2->p_pgrp->pg_id)
355 				pidchecked = p2->p_pgrp->pg_id;
356 			if (p2->p_session->s_sid > trypid &&
357 			    pidchecked > p2->p_session->s_sid)
358 				pidchecked = p2->p_session->s_sid;
359 		}
360 		if (!doingzomb) {
361 			doingzomb = 1;
362 			p2 = LIST_FIRST(&zombproc);
363 			goto again;
364 		}
365 	}
366 
367 	/*
368 	 * RFHIGHPID does not mess with the lastpid counter during boot.
369 	 */
370 	if (flags & RFHIGHPID)
371 		pidchecked = 0;
372 	else
373 		lastpid = trypid;
374 
375 	p2 = newproc;
376 	p2->p_stat = SIDL;			/* protect against others */
377 	p2->p_pid = trypid;
378 	LIST_INSERT_HEAD(&allproc, p2, p_list);
379 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
380 	sx_xunlock(&allproc_lock);
381 
382 	/*
383 	 * Make a proc table entry for the new process.
384 	 * Start by zeroing the section of proc that is zero-initialized,
385 	 * then copy the section that is copied directly from the parent.
386 	 */
387 	bzero(&p2->p_startzero,
388 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
389 	PROC_LOCK(p1);
390 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
391 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
392 	PROC_UNLOCK(p1);
393 
394 	mtx_init(&p2->p_mtx, "process lock", MTX_DEF);
395 	PROC_LOCK(p2);
396 
397 	/*
398 	 * Duplicate sub-structures as needed.
399 	 * Increase reference counts on shared objects.
400 	 * The p_stats and p_sigacts substructs are set in vm_fork.
401 	 */
402 	p2->p_flag = 0;
403 	mtx_lock_spin(&sched_lock);
404 	p2->p_sflag = PS_INMEM;
405 	if (p1->p_sflag & PS_PROFIL)
406 		startprofclock(p2);
407 	mtx_unlock_spin(&sched_lock);
408 	/*
409 	 * We start off holding one spinlock after fork: sched_lock.
410 	 */
411 	PROC_LOCK(p1);
412 	crhold(p1->p_ucred);
413 	p2->p_ucred = p1->p_ucred;
414 
415 	if (p2->p_args)
416 		p2->p_args->ar_ref++;
417 
418 	if (flags & RFSIGSHARE) {
419 		p2->p_procsig = p1->p_procsig;
420 		p2->p_procsig->ps_refcnt++;
421 		if (p1->p_sigacts == &p1->p_addr->u_sigacts) {
422 			struct sigacts *newsigacts;
423 
424 			PROC_UNLOCK(p1);
425 			PROC_UNLOCK(p2);
426 			/* Create the shared sigacts structure */
427 			MALLOC(newsigacts, struct sigacts *,
428 			    sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
429 			PROC_LOCK(p2);
430 			PROC_LOCK(p1);
431 			/*
432 			 * Set p_sigacts to the new shared structure.
433 			 * Note that this is updating p1->p_sigacts at the
434 			 * same time, since p_sigacts is just a pointer to
435 			 * the shared p_procsig->ps_sigacts.
436 			 */
437 			p2->p_sigacts  = newsigacts;
438 			bcopy(&p1->p_addr->u_sigacts, p2->p_sigacts,
439 			    sizeof(*p2->p_sigacts));
440 			*p2->p_sigacts = p1->p_addr->u_sigacts;
441 		}
442 	} else {
443 		PROC_UNLOCK(p1);
444 		PROC_UNLOCK(p2);
445 		MALLOC(p2->p_procsig, struct procsig *, sizeof(struct procsig),
446 		    M_SUBPROC, M_WAITOK);
447 		PROC_LOCK(p2);
448 		PROC_LOCK(p1);
449 		bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
450 		p2->p_procsig->ps_refcnt = 1;
451 		p2->p_sigacts = NULL;	/* finished in vm_fork() */
452 	}
453 	if (flags & RFLINUXTHPN)
454 	        p2->p_sigparent = SIGUSR1;
455 	else
456 	        p2->p_sigparent = SIGCHLD;
457 
458 	/* bump references to the text vnode (for procfs) */
459 	p2->p_textvp = p1->p_textvp;
460 	PROC_UNLOCK(p1);
461 	PROC_UNLOCK(p2);
462 	if (p2->p_textvp)
463 		VREF(p2->p_textvp);
464 
465 	if (flags & RFCFDG)
466 		fd = fdinit(p1);
467 	else if (flags & RFFDG)
468 		fd = fdcopy(p1);
469 	else
470 		fd = fdshare(p1);
471 	PROC_LOCK(p2);
472 	p2->p_fd = fd;
473 
474 	/*
475 	 * If p_limit is still copy-on-write, bump refcnt,
476 	 * otherwise get a copy that won't be modified.
477 	 * (If PL_SHAREMOD is clear, the structure is shared
478 	 * copy-on-write.)
479 	 */
480 	PROC_LOCK(p1);
481 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
482 		p2->p_limit = limcopy(p1->p_limit);
483 	else {
484 		p2->p_limit = p1->p_limit;
485 		p2->p_limit->p_refcnt++;
486 	}
487 
488 	/*
489 	 * Preserve some more flags in subprocess.  PS_PROFIL has already
490 	 * been preserved.
491 	 */
492 	p2->p_flag |= p1->p_flag & (P_SUGID | P_ALTSTACK);
493 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
494 		p2->p_flag |= P_CONTROLT;
495 	if (flags & RFPPWAIT)
496 		p2->p_flag |= P_PPWAIT;
497 
498 	LIST_INSERT_AFTER(p1, p2, p_pglist);
499 	PROC_UNLOCK(p1);
500 	PROC_UNLOCK(p2);
501 
502 	/*
503 	 * Attach the new process to its parent.
504 	 *
505 	 * If RFNOWAIT is set, the newly created process becomes a child
506 	 * of init.  This effectively disassociates the child from the
507 	 * parent.
508 	 */
509 	if (flags & RFNOWAIT)
510 		pptr = initproc;
511 	else
512 		pptr = p1;
513 	sx_xlock(&proctree_lock);
514 	PROC_LOCK(p2);
515 	p2->p_pptr = pptr;
516 	PROC_UNLOCK(p2);
517 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
518 	sx_xunlock(&proctree_lock);
519 	PROC_LOCK(p2);
520 	LIST_INIT(&p2->p_children);
521 	LIST_INIT(&p2->p_contested);
522 
523 	callout_init(&p2->p_itcallout, 0);
524 	callout_init(&p2->p_slpcallout, 1);
525 
526 	PROC_LOCK(p1);
527 #ifdef KTRACE
528 	/*
529 	 * Copy traceflag and tracefile if enabled.
530 	 * If not inherited, these were zeroed above.
531 	 */
532 	if (p1->p_traceflag & KTRFAC_INHERIT) {
533 		p2->p_traceflag = p1->p_traceflag;
534 		if ((p2->p_tracep = p1->p_tracep) != NULL) {
535 			PROC_UNLOCK(p1);
536 			PROC_UNLOCK(p2);
537 			VREF(p2->p_tracep);
538 			PROC_LOCK(p2);
539 			PROC_LOCK(p1);
540 		}
541 	}
542 #endif
543 
544 	/*
545 	 * set priority of child to be that of parent
546 	 */
547 	mtx_lock_spin(&sched_lock);
548 	p2->p_estcpu = p1->p_estcpu;
549 	mtx_unlock_spin(&sched_lock);
550 
551 	/*
552 	 * This begins the section where we must prevent the parent
553 	 * from being swapped.
554 	 */
555 	_PHOLD(p1);
556 	PROC_UNLOCK(p1);
557 	PROC_UNLOCK(p2);
558 
559 	/*
560 	 * Finish creating the child process.  It will return via a different
561 	 * execution path later.  (ie: directly into user mode)
562 	 */
563 	vm_fork(p1, p2, flags);
564 	mtx_assert(&vm_mtx, MA_NOTOWNED);
565 
566 	if (flags == (RFFDG | RFPROC)) {
567 		cnt.v_forks++;
568 		cnt.v_forkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
569 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
570 		cnt.v_vforks++;
571 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
572 	} else if (p1 == &proc0) {
573 		cnt.v_kthreads++;
574 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
575 	} else {
576 		cnt.v_rforks++;
577 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
578 	}
579 
580 	/*
581 	 * Both processes are set up, now check if any loadable modules want
582 	 * to adjust anything.
583 	 *   What if they have an error? XXX
584 	 */
585 	sx_slock(&fork_list_lock);
586 	TAILQ_FOREACH(ep, &fork_list, next) {
587 		(*ep->function)(p1, p2, flags);
588 	}
589 	sx_sunlock(&fork_list_lock);
590 
591 	/*
592 	 * If RFSTOPPED not requested, make child runnable and add to
593 	 * run queue.
594 	 */
595 	microtime(&(p2->p_stats->p_start));
596 	p2->p_acflag = AFORK;
597 	if ((flags & RFSTOPPED) == 0) {
598 		mtx_lock_spin(&sched_lock);
599 		p2->p_stat = SRUN;
600 		setrunqueue(p2);
601 		mtx_unlock_spin(&sched_lock);
602 	}
603 
604 	/*
605 	 * Now can be swapped.
606 	 */
607 	PROC_LOCK(p1);
608 	_PRELE(p1);
609 
610 	/*
611 	 * tell any interested parties about the new process
612 	 */
613 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
614 	PROC_UNLOCK(p1);
615 
616 	/*
617 	 * Preserve synchronization semantics of vfork.  If waiting for
618 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
619 	 * proc (in case of exit).
620 	 */
621 	PROC_LOCK(p2);
622 	while (p2->p_flag & P_PPWAIT)
623 		msleep(p1, &p2->p_mtx, PWAIT, "ppwait", 0);
624 	PROC_UNLOCK(p2);
625 
626 	/*
627 	 * Return child proc pointer to parent.
628 	 */
629 	*procp = p2;
630 	return (0);
631 }
632 
633 /*
634  * The next two functionms are general routines to handle adding/deleting
635  * items on the fork callout list.
636  *
637  * at_fork():
638  * Take the arguments given and put them onto the fork callout list,
639  * However first make sure that it's not already there.
640  * Returns 0 on success or a standard error number.
641  */
642 
643 int
644 at_fork(function)
645 	forklist_fn function;
646 {
647 	struct forklist *ep;
648 
649 #ifdef INVARIANTS
650 	/* let the programmer know if he's been stupid */
651 	if (rm_at_fork(function))
652 		printf("WARNING: fork callout entry (%p) already present\n",
653 		    function);
654 #endif
655 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
656 	if (ep == NULL)
657 		return (ENOMEM);
658 	ep->function = function;
659 	sx_xlock(&fork_list_lock);
660 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
661 	sx_xunlock(&fork_list_lock);
662 	return (0);
663 }
664 
665 /*
666  * Scan the exit callout list for the given item and remove it..
667  * Returns the number of items removed (0 or 1)
668  */
669 
670 int
671 rm_at_fork(function)
672 	forklist_fn function;
673 {
674 	struct forklist *ep;
675 
676 	sx_xlock(&fork_list_lock);
677 	TAILQ_FOREACH(ep, &fork_list, next) {
678 		if (ep->function == function) {
679 			TAILQ_REMOVE(&fork_list, ep, next);
680 			sx_xunlock(&fork_list_lock);
681 			free(ep, M_ATFORK);
682 			return(1);
683 		}
684 	}
685 	sx_xunlock(&fork_list_lock);
686 	return (0);
687 }
688 
689 /*
690  * Handle the return of a child process from fork1().  This function
691  * is called from the MD fork_trampoline() entry point.
692  */
693 void
694 fork_exit(callout, arg, frame)
695 	void (*callout)(void *, struct trapframe *);
696 	void *arg;
697 	struct trapframe *frame;
698 {
699 	struct proc *p;
700 
701 	p = curproc;
702 
703 	/*
704 	 * Setup the sched_lock state so that we can release it.
705 	 */
706 	sched_lock.mtx_lock = (uintptr_t)p;
707 	sched_lock.mtx_recurse = 0;
708 	/*
709 	 * XXX: We really shouldn't have to do this.
710 	 */
711 	mtx_intr_enable(&sched_lock);
712 	mtx_unlock_spin(&sched_lock);
713 
714 #ifdef SMP
715 	if (PCPU_GET(switchtime.tv_sec) == 0)
716 		microuptime(PCPU_PTR(switchtime));
717 	PCPU_SET(switchticks, ticks);
718 #endif
719 
720 	/*
721 	 * cpu_set_fork_handler intercepts this function call to
722          * have this call a non-return function to stay in kernel mode.
723          * initproc has its own fork handler, but it does return.
724          */
725 	KASSERT(callout != NULL, ("NULL callout in fork_exit"));
726 	callout(arg, frame);
727 
728 	/*
729 	 * Check if a kernel thread misbehaved and returned from its main
730 	 * function.
731 	 */
732 	PROC_LOCK(p);
733 	if (p->p_flag & P_KTHREAD) {
734 		PROC_UNLOCK(p);
735 		mtx_lock(&Giant);
736 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
737 		    p->p_comm, p->p_pid);
738 		kthread_exit(0);
739 	}
740 	PROC_UNLOCK(p);
741 	mtx_assert(&Giant, MA_NOTOWNED);
742 }
743 
744 /*
745  * Simplified back end of syscall(), used when returning from fork()
746  * directly into user mode.  Giant is not held on entry, and must not
747  * be held on return.  This function is passed in to fork_exit() as the
748  * first parameter and is called when returning to a new userland process.
749  */
750 void
751 fork_return(p, frame)
752 	struct proc *p;
753 	struct trapframe *frame;
754 {
755 
756 	userret(p, frame, 0);
757 #ifdef KTRACE
758 	if (KTRPOINT(p, KTR_SYSRET)) {
759 		if (!mtx_owned(&Giant))
760 			mtx_lock(&Giant);
761 		ktrsysret(p->p_tracep, SYS_fork, 0, 0);
762 	}
763 #endif
764 	if (mtx_owned(&Giant))
765 		mtx_unlock(&Giant);
766 	mtx_assert(&Giant, MA_NOTOWNED);
767 }
768