xref: /freebsd/sys/kern/kern_fork.c (revision 8865286b9cc53fcc8e2623d4e5c4a10ab1e1f244)
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/malloc.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/resourcevar.h>
54 #include <sys/syscall.h>
55 #include <sys/vnode.h>
56 #include <sys/acct.h>
57 #include <sys/ktr.h>
58 #include <sys/ktrace.h>
59 #include <sys/kthread.h>
60 #include <sys/unistd.h>
61 #include <sys/jail.h>
62 
63 #include <vm/vm.h>
64 #include <sys/lock.h>
65 #include <vm/pmap.h>
66 #include <vm/vm_map.h>
67 #include <vm/vm_extern.h>
68 #include <vm/vm_zone.h>
69 
70 #include <sys/vmmeter.h>
71 #include <sys/user.h>
72 
73 static MALLOC_DEFINE(M_ATFORK, "atfork", "atfork callback");
74 
75 static int	fast_vfork = 1;
76 SYSCTL_INT(_kern, OID_AUTO, fast_vfork, CTLFLAG_RW, &fast_vfork, 0,
77     "flag to indicate whether we have a fast vfork()");
78 
79 /*
80  * These are the stuctures used to create a callout list for things to do
81  * when forking a process
82  */
83 struct forklist {
84 	forklist_fn function;
85 	TAILQ_ENTRY(forklist) next;
86 };
87 
88 TAILQ_HEAD(forklist_head, forklist);
89 static struct forklist_head fork_list = TAILQ_HEAD_INITIALIZER(fork_list);
90 
91 #ifndef _SYS_SYSPROTO_H_
92 struct fork_args {
93 	int     dummy;
94 };
95 #endif
96 
97 /* ARGSUSED */
98 int
99 fork(p, uap)
100 	struct proc *p;
101 	struct fork_args *uap;
102 {
103 	int error;
104 	struct proc *p2;
105 
106 	error = fork1(p, RFFDG | RFPROC, &p2);
107 	if (error == 0) {
108 		p->p_retval[0] = p2->p_pid;
109 		p->p_retval[1] = 0;
110 	}
111 	return error;
112 }
113 
114 /* ARGSUSED */
115 int
116 vfork(p, uap)
117 	struct proc *p;
118 	struct vfork_args *uap;
119 {
120 	int error;
121 	struct proc *p2;
122 
123 	error = fork1(p, RFFDG | RFPROC | RFPPWAIT | RFMEM, &p2);
124 	if (error == 0) {
125 		p->p_retval[0] = p2->p_pid;
126 		p->p_retval[1] = 0;
127 	}
128 	return error;
129 }
130 
131 int
132 rfork(p, uap)
133 	struct proc *p;
134 	struct rfork_args *uap;
135 {
136 	int error;
137 	struct proc *p2;
138 
139 	/* mask kernel only flags out of the user flags */
140 	error = fork1(p, uap->flags & ~RFKERNELONLY, &p2);
141 	if (error == 0) {
142 		p->p_retval[0] = p2 ? p2->p_pid : 0;
143 		p->p_retval[1] = 0;
144 	}
145 	return error;
146 }
147 
148 
149 int	nprocs = 1;				/* process 0 */
150 static int nextpid = 0;
151 
152 /*
153  * Random component to nextpid generation.  We mix in a random factor to make
154  * it a little harder to predict.  We sanity check the modulus value to avoid
155  * doing it in critical paths.  Don't let it be too small or we pointlessly
156  * waste randomness entropy, and don't let it be impossibly large.  Using a
157  * modulus that is too big causes a LOT more process table scans and slows
158  * down fork processing as the pidchecked caching is defeated.
159  */
160 static int randompid = 0;
161 
162 static int
163 sysctl_kern_randompid(SYSCTL_HANDLER_ARGS)
164 {
165 	int error, pid;
166 
167 	pid = randompid;
168 	error = sysctl_handle_int(oidp, &pid, 0, req);
169 	if (error || !req->newptr)
170 		return (error);
171 	if (pid < 0 || pid > PID_MAX - 100)	/* out of range */
172 		pid = PID_MAX - 100;
173 	else if (pid < 2)			/* NOP */
174 		pid = 0;
175 	else if (pid < 100)			/* Make it reasonable */
176 		pid = 100;
177 	randompid = pid;
178 	return (error);
179 }
180 
181 SYSCTL_PROC(_kern, OID_AUTO, randompid, CTLTYPE_INT|CTLFLAG_RW,
182     0, 0, sysctl_kern_randompid, "I", "Random PID modulus");
183 
184 int
185 fork1(p1, flags, procp)
186 	struct proc *p1;			/* parent proc */
187 	int flags;
188 	struct proc **procp;			/* child proc */
189 {
190 	struct proc *p2, *pptr;
191 	uid_t uid;
192 	struct proc *newproc;
193 	int trypid;
194 	int ok;
195 	static int pidchecked = 0;
196 	struct forklist *ep;
197 
198 	/* Can't copy and clear */
199 	if ((flags & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
200 		return (EINVAL);
201 
202 	/*
203 	 * Here we don't create a new process, but we divorce
204 	 * certain parts of a process from itself.
205 	 */
206 	if ((flags & RFPROC) == 0) {
207 
208 		vm_fork(p1, 0, flags);
209 
210 		/*
211 		 * Close all file descriptors.
212 		 */
213 		if (flags & RFCFDG) {
214 			struct filedesc *fdtmp;
215 			fdtmp = fdinit(p1);
216 			fdfree(p1);
217 			p1->p_fd = fdtmp;
218 		}
219 
220 		/*
221 		 * Unshare file descriptors (from parent.)
222 		 */
223 		if (flags & RFFDG) {
224 			if (p1->p_fd->fd_refcnt > 1) {
225 				struct filedesc *newfd;
226 				newfd = fdcopy(p1);
227 				fdfree(p1);
228 				p1->p_fd = newfd;
229 			}
230 		}
231 		*procp = NULL;
232 		return (0);
233 	}
234 
235 	/*
236 	 * Although process entries are dynamically created, we still keep
237 	 * a global limit on the maximum number we will create.  Don't allow
238 	 * a nonprivileged user to use the last process; don't let root
239 	 * exceed the limit. The variable nprocs is the current number of
240 	 * processes, maxproc is the limit.
241 	 */
242 	uid = p1->p_cred->p_ruid;
243 	if ((nprocs >= maxproc - 1 && uid != 0) || nprocs >= maxproc) {
244 		tablefull("proc");
245 		return (EAGAIN);
246 	}
247 	/*
248 	 * Increment the nprocs resource before blocking can occur.  There
249 	 * are hard-limits as to the number of processes that can run.
250 	 */
251 	nprocs++;
252 
253 	/*
254 	 * Increment the count of procs running with this uid. Don't allow
255 	 * a nonprivileged user to exceed their current limit.
256 	 */
257 	ok = chgproccnt(p1->p_cred->p_uidinfo, 1,
258 		(uid != 0) ? p1->p_rlimit[RLIMIT_NPROC].rlim_cur : 0);
259 	if (!ok) {
260 		/*
261 		 * Back out the process count
262 		 */
263 		nprocs--;
264 		return (EAGAIN);
265 	}
266 
267 	/* Allocate new proc. */
268 	newproc = zalloc(proc_zone);
269 
270 	/*
271 	 * Setup linkage for kernel based threading
272 	 */
273 	if((flags & RFTHREAD) != 0) {
274 		newproc->p_peers = p1->p_peers;
275 		p1->p_peers = newproc;
276 		newproc->p_leader = p1->p_leader;
277 	} else {
278 		newproc->p_peers = NULL;
279 		newproc->p_leader = newproc;
280 	}
281 
282 	newproc->p_vmspace = NULL;
283 
284 	/*
285 	 * Find an unused process ID.  We remember a range of unused IDs
286 	 * ready to use (from nextpid+1 through pidchecked-1).
287 	 *
288 	 * If RFHIGHPID is set (used during system boot), do not allocate
289 	 * low-numbered pids.
290 	 */
291 	ALLPROC_LOCK(AP_EXCLUSIVE);
292 	trypid = nextpid + 1;
293 	if (flags & RFHIGHPID) {
294 		if (trypid < 10) {
295 			trypid = 10;
296 		}
297 	} else {
298 		if (randompid)
299 			trypid += arc4random() % randompid;
300 	}
301 retry:
302 	/*
303 	 * If the process ID prototype has wrapped around,
304 	 * restart somewhat above 0, as the low-numbered procs
305 	 * tend to include daemons that don't exit.
306 	 */
307 	if (trypid >= PID_MAX) {
308 		trypid = trypid % PID_MAX;
309 		if (trypid < 100)
310 			trypid += 100;
311 		pidchecked = 0;
312 	}
313 	if (trypid >= pidchecked) {
314 		int doingzomb = 0;
315 
316 		pidchecked = PID_MAX;
317 		/*
318 		 * Scan the active and zombie procs to check whether this pid
319 		 * is in use.  Remember the lowest pid that's greater
320 		 * than trypid, so we can avoid checking for a while.
321 		 */
322 		p2 = LIST_FIRST(&allproc);
323 again:
324 		for (; p2 != NULL; p2 = LIST_NEXT(p2, p_list)) {
325 			while (p2->p_pid == trypid ||
326 			    p2->p_pgrp->pg_id == trypid ||
327 			    p2->p_session->s_sid == trypid) {
328 				trypid++;
329 				if (trypid >= pidchecked)
330 					goto retry;
331 			}
332 			if (p2->p_pid > trypid && pidchecked > p2->p_pid)
333 				pidchecked = p2->p_pid;
334 			if (p2->p_pgrp->pg_id > trypid &&
335 			    pidchecked > p2->p_pgrp->pg_id)
336 				pidchecked = p2->p_pgrp->pg_id;
337 			if (p2->p_session->s_sid > trypid &&
338 			    pidchecked > p2->p_session->s_sid)
339 				pidchecked = p2->p_session->s_sid;
340 		}
341 		if (!doingzomb) {
342 			doingzomb = 1;
343 			p2 = LIST_FIRST(&zombproc);
344 			goto again;
345 		}
346 	}
347 
348 	/*
349 	 * RFHIGHPID does not mess with the nextpid counter during boot.
350 	 */
351 	if (flags & RFHIGHPID)
352 		pidchecked = 0;
353 	else
354 		nextpid = trypid;
355 
356 	p2 = newproc;
357 	p2->p_intr_nesting_level = 0;
358 	p2->p_stat = SIDL;			/* protect against others */
359 	p2->p_pid = trypid;
360 	LIST_INSERT_HEAD(&allproc, p2, p_list);
361 	LIST_INSERT_HEAD(PIDHASH(p2->p_pid), p2, p_hash);
362 	ALLPROC_LOCK(AP_RELEASE);
363 
364 	/*
365 	 * Make a proc table entry for the new process.
366 	 * Start by zeroing the section of proc that is zero-initialized,
367 	 * then copy the section that is copied directly from the parent.
368 	 */
369 	bzero(&p2->p_startzero,
370 	    (unsigned) ((caddr_t)&p2->p_endzero - (caddr_t)&p2->p_startzero));
371 	bcopy(&p1->p_startcopy, &p2->p_startcopy,
372 	    (unsigned) ((caddr_t)&p2->p_endcopy - (caddr_t)&p2->p_startcopy));
373 
374 	mtx_init(&p2->p_mtx, "process lock", MTX_DEF);
375 	p2->p_aioinfo = NULL;
376 
377 	/*
378 	 * Duplicate sub-structures as needed.
379 	 * Increase reference counts on shared objects.
380 	 * The p_stats and p_sigacts substructs are set in vm_fork.
381 	 */
382 	p2->p_flag = 0;
383 	mtx_enter(&sched_lock, MTX_SPIN);
384 	p2->p_sflag = PS_INMEM;
385 	if (p1->p_sflag & PS_PROFIL)
386 		startprofclock(p2);
387 	mtx_exit(&sched_lock, MTX_SPIN);
388 	MALLOC(p2->p_cred, struct pcred *, sizeof(struct pcred),
389 	    M_SUBPROC, M_WAITOK);
390 	bcopy(p1->p_cred, p2->p_cred, sizeof(*p2->p_cred));
391 	p2->p_cred->p_refcnt = 1;
392 	crhold(p1->p_ucred);
393 	uihold(p1->p_cred->p_uidinfo);
394 
395 	if (p2->p_prison) {
396 		p2->p_prison->pr_ref++;
397 		p2->p_flag |= P_JAILED;
398 	}
399 
400 	if (p2->p_args)
401 		p2->p_args->ar_ref++;
402 
403 	if (flags & RFSIGSHARE) {
404 		p2->p_procsig = p1->p_procsig;
405 		p2->p_procsig->ps_refcnt++;
406 		if (p1->p_sigacts == &p1->p_addr->u_sigacts) {
407 			struct sigacts *newsigacts;
408 			int s;
409 
410 			/* Create the shared sigacts structure */
411 			MALLOC(newsigacts, struct sigacts *,
412 			    sizeof(struct sigacts), M_SUBPROC, M_WAITOK);
413 			s = splhigh();
414 			/*
415 			 * Set p_sigacts to the new shared structure.
416 			 * Note that this is updating p1->p_sigacts at the
417 			 * same time, since p_sigacts is just a pointer to
418 			 * the shared p_procsig->ps_sigacts.
419 			 */
420 			p2->p_sigacts  = newsigacts;
421 			bcopy(&p1->p_addr->u_sigacts, p2->p_sigacts,
422 			    sizeof(*p2->p_sigacts));
423 			*p2->p_sigacts = p1->p_addr->u_sigacts;
424 			splx(s);
425 		}
426 	} else {
427 		MALLOC(p2->p_procsig, struct procsig *, sizeof(struct procsig),
428 		    M_SUBPROC, M_WAITOK);
429 		bcopy(p1->p_procsig, p2->p_procsig, sizeof(*p2->p_procsig));
430 		p2->p_procsig->ps_refcnt = 1;
431 		p2->p_sigacts = NULL;	/* finished in vm_fork() */
432 	}
433 	if (flags & RFLINUXTHPN)
434 	        p2->p_sigparent = SIGUSR1;
435 	else
436 	        p2->p_sigparent = SIGCHLD;
437 
438 	/* bump references to the text vnode (for procfs) */
439 	p2->p_textvp = p1->p_textvp;
440 	if (p2->p_textvp)
441 		VREF(p2->p_textvp);
442 
443 	if (flags & RFCFDG)
444 		p2->p_fd = fdinit(p1);
445 	else if (flags & RFFDG)
446 		p2->p_fd = fdcopy(p1);
447 	else
448 		p2->p_fd = fdshare(p1);
449 
450 	/*
451 	 * If p_limit is still copy-on-write, bump refcnt,
452 	 * otherwise get a copy that won't be modified.
453 	 * (If PL_SHAREMOD is clear, the structure is shared
454 	 * copy-on-write.)
455 	 */
456 	if (p1->p_limit->p_lflags & PL_SHAREMOD)
457 		p2->p_limit = limcopy(p1->p_limit);
458 	else {
459 		p2->p_limit = p1->p_limit;
460 		p2->p_limit->p_refcnt++;
461 	}
462 
463 	/*
464 	 * Preserve some more flags in subprocess.  P_PROFIL has already
465 	 * been preserved.
466 	 */
467 	p2->p_flag |= p1->p_flag & P_SUGID;
468 	if (p1->p_session->s_ttyvp != NULL && p1->p_flag & P_CONTROLT)
469 		p2->p_flag |= P_CONTROLT;
470 	if (flags & RFPPWAIT)
471 		p2->p_flag |= P_PPWAIT;
472 
473 	LIST_INSERT_AFTER(p1, p2, p_pglist);
474 
475 	/*
476 	 * Attach the new process to its parent.
477 	 *
478 	 * If RFNOWAIT is set, the newly created process becomes a child
479 	 * of init.  This effectively disassociates the child from the
480 	 * parent.
481 	 */
482 	if (flags & RFNOWAIT)
483 		pptr = initproc;
484 	else
485 		pptr = p1;
486 	PROCTREE_LOCK(PT_EXCLUSIVE);
487 	p2->p_pptr = pptr;
488 	LIST_INSERT_HEAD(&pptr->p_children, p2, p_sibling);
489 	PROCTREE_LOCK(PT_RELEASE);
490 	LIST_INIT(&p2->p_children);
491 	LIST_INIT(&p2->p_heldmtx);
492 	LIST_INIT(&p2->p_contested);
493 
494 	callout_init(&p2->p_itcallout, 0);
495 	callout_init(&p2->p_slpcallout, 1);
496 
497 #ifdef KTRACE
498 	/*
499 	 * Copy traceflag and tracefile if enabled.
500 	 * If not inherited, these were zeroed above.
501 	 */
502 	if (p1->p_traceflag&KTRFAC_INHERIT) {
503 		p2->p_traceflag = p1->p_traceflag;
504 		if ((p2->p_tracep = p1->p_tracep) != NULL)
505 			VREF(p2->p_tracep);
506 	}
507 #endif
508 
509 	/*
510 	 * set priority of child to be that of parent
511 	 */
512 	p2->p_estcpu = p1->p_estcpu;
513 
514 	/*
515 	 * This begins the section where we must prevent the parent
516 	 * from being swapped.
517 	 */
518 	PHOLD(p1);
519 
520 	/*
521 	 * Finish creating the child process.  It will return via a different
522 	 * execution path later.  (ie: directly into user mode)
523 	 */
524 	vm_fork(p1, p2, flags);
525 
526 	if (flags == (RFFDG | RFPROC)) {
527 		cnt.v_forks++;
528 		cnt.v_forkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
529 	} else if (flags == (RFFDG | RFPROC | RFPPWAIT | RFMEM)) {
530 		cnt.v_vforks++;
531 		cnt.v_vforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
532 	} else if (p1 == &proc0) {
533 		cnt.v_kthreads++;
534 		cnt.v_kthreadpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
535 	} else {
536 		cnt.v_rforks++;
537 		cnt.v_rforkpages += p2->p_vmspace->vm_dsize + p2->p_vmspace->vm_ssize;
538 	}
539 
540 	/*
541 	 * Both processes are set up, now check if any loadable modules want
542 	 * to adjust anything.
543 	 *   What if they have an error? XXX
544 	 */
545 	TAILQ_FOREACH(ep, &fork_list, next) {
546 		(*ep->function)(p1, p2, flags);
547 	}
548 
549 	/*
550 	 * If RFSTOPPED not requested, make child runnable and add to
551 	 * run queue.
552 	 */
553 	microtime(&(p2->p_stats->p_start));
554 	p2->p_acflag = AFORK;
555 	if ((flags & RFSTOPPED) == 0) {
556 		splhigh();
557 		mtx_enter(&sched_lock, MTX_SPIN);
558 		p2->p_stat = SRUN;
559 		setrunqueue(p2);
560 		mtx_exit(&sched_lock, MTX_SPIN);
561 		spl0();
562 	}
563 
564 	/*
565 	 * Now can be swapped.
566 	 */
567 	PRELE(p1);
568 
569 	/*
570 	 * tell any interested parties about the new process
571 	 */
572 	KNOTE(&p1->p_klist, NOTE_FORK | p2->p_pid);
573 
574 	/*
575 	 * Preserve synchronization semantics of vfork.  If waiting for
576 	 * child to exec or exit, set P_PPWAIT on child, and sleep on our
577 	 * proc (in case of exit).
578 	 */
579 	while (p2->p_flag & P_PPWAIT)
580 		tsleep(p1, PWAIT, "ppwait", 0);
581 
582 	/*
583 	 * Return child proc pointer to parent.
584 	 */
585 	*procp = p2;
586 	return (0);
587 }
588 
589 /*
590  * The next two functionms are general routines to handle adding/deleting
591  * items on the fork callout list.
592  *
593  * at_fork():
594  * Take the arguments given and put them onto the fork callout list,
595  * However first make sure that it's not already there.
596  * Returns 0 on success or a standard error number.
597  */
598 
599 int
600 at_fork(function)
601 	forklist_fn function;
602 {
603 	struct forklist *ep;
604 
605 #ifdef INVARIANTS
606 	/* let the programmer know if he's been stupid */
607 	if (rm_at_fork(function))
608 		printf("WARNING: fork callout entry (%p) already present\n",
609 		    function);
610 #endif
611 	ep = malloc(sizeof(*ep), M_ATFORK, M_NOWAIT);
612 	if (ep == NULL)
613 		return (ENOMEM);
614 	ep->function = function;
615 	TAILQ_INSERT_TAIL(&fork_list, ep, next);
616 	return (0);
617 }
618 
619 /*
620  * Scan the exit callout list for the given item and remove it..
621  * Returns the number of items removed (0 or 1)
622  */
623 
624 int
625 rm_at_fork(function)
626 	forklist_fn function;
627 {
628 	struct forklist *ep;
629 
630 	TAILQ_FOREACH(ep, &fork_list, next) {
631 		if (ep->function == function) {
632 			TAILQ_REMOVE(&fork_list, ep, next);
633 			free(ep, M_ATFORK);
634 			return(1);
635 		}
636 	}
637 	return (0);
638 }
639 
640 /*
641  * Handle the return of a child process from fork1().  This function
642  * is called from the MD fork_trampoline() entry point.
643  */
644 void
645 fork_exit(callout, arg, frame)
646 	void (*callout)(void *, struct trapframe *);
647 	void *arg;
648 	struct trapframe *frame;
649 {
650 	struct proc *p;
651 
652 	mtx_exit(&sched_lock, MTX_SPIN);
653 	/*
654 	 * XXX: We really shouldn't have to do this.
655 	 */
656 	enable_intr();
657 
658 #ifdef SMP
659 	if (PCPU_GET(switchtime.tv_sec) == 0)
660 		microuptime(PCPU_PTR(switchtime));
661 	PCPU_SET(switchticks, ticks);
662 #endif
663 
664 	/*
665 	 * cpu_set_fork_handler intercepts this function call to
666          * have this call a non-return function to stay in kernel mode.
667          * initproc has its own fork handler, but it does return.
668          */
669 	callout(arg, frame);
670 
671 	/*
672 	 * Check if a kernel thread misbehaved and returned from its main
673 	 * function.
674 	 */
675 	p = CURPROC;
676 	if (p->p_flag & P_KTHREAD) {
677 		mtx_enter(&Giant, MTX_DEF);
678 		printf("Kernel thread \"%s\" (pid %d) exited prematurely.\n",
679 		    p->p_comm, p->p_pid);
680 		kthread_exit(0);
681 	}
682 	mtx_assert(&Giant, MA_NOTOWNED);
683 }
684 
685 /*
686  * Simplified back end of syscall(), used when returning from fork()
687  * directly into user mode.  Giant is not held on entry, and must not
688  * be held on return.  This function is passed in to fork_exit() as the
689  * first parameter and is called when returning to a new userland process.
690  */
691 void
692 fork_return(p, frame)
693 	struct proc *p;
694 	struct trapframe *frame;
695 {
696 
697 	userret(p, frame, 0);
698 #ifdef KTRACE
699 	if (KTRPOINT(p, KTR_SYSRET)) {
700 		if (!mtx_owned(&Giant))
701 			mtx_enter(&Giant, MTX_DEF);
702 		ktrsysret(p->p_tracep, SYS_fork, 0, 0);
703 	}
704 #endif
705 	if (mtx_owned(&Giant))
706 		mtx_exit(&Giant, MTX_DEF);
707 	mtx_assert(&Giant, MA_NOTOWNED);
708 }
709