Home | History | Annotate | Line # | Download | only in kern
kern_exit.c revision 1.107
      1 /*	$NetBSD: kern_exit.c,v 1.107 2003/01/18 10:06:26 thorpej Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  * (c) UNIX System Laboratories, Inc.
     44  * All or some portions of this file are derived from material licensed
     45  * to the University of California by American Telephone and Telegraph
     46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     47  * the permission of UNIX System Laboratories, Inc.
     48  *
     49  * Redistribution and use in source and binary forms, with or without
     50  * modification, are permitted provided that the following conditions
     51  * are met:
     52  * 1. Redistributions of source code must retain the above copyright
     53  *    notice, this list of conditions and the following disclaimer.
     54  * 2. Redistributions in binary form must reproduce the above copyright
     55  *    notice, this list of conditions and the following disclaimer in the
     56  *    documentation and/or other materials provided with the distribution.
     57  * 3. All advertising materials mentioning features or use of this software
     58  *    must display the following acknowledgement:
     59  *	This product includes software developed by the University of
     60  *	California, Berkeley and its contributors.
     61  * 4. Neither the name of the University nor the names of its contributors
     62  *    may be used to endorse or promote products derived from this software
     63  *    without specific prior written permission.
     64  *
     65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     75  * SUCH DAMAGE.
     76  *
     77  *	@(#)kern_exit.c	8.10 (Berkeley) 2/23/95
     78  */
     79 
     80 #include <sys/cdefs.h>
     81 __KERNEL_RCSID(0, "$NetBSD: kern_exit.c,v 1.107 2003/01/18 10:06:26 thorpej Exp $");
     82 
     83 #include "opt_ktrace.h"
     84 #include "opt_perfctrs.h"
     85 #include "opt_systrace.h"
     86 #include "opt_sysv.h"
     87 
     88 #include <sys/param.h>
     89 #include <sys/systm.h>
     90 #include <sys/ioctl.h>
     91 #include <sys/proc.h>
     92 #include <sys/tty.h>
     93 #include <sys/time.h>
     94 #include <sys/resource.h>
     95 #include <sys/kernel.h>
     96 #include <sys/ktrace.h>
     97 #include <sys/proc.h>
     98 #include <sys/buf.h>
     99 #include <sys/wait.h>
    100 #include <sys/file.h>
    101 #include <sys/vnode.h>
    102 #include <sys/syslog.h>
    103 #include <sys/malloc.h>
    104 #include <sys/pool.h>
    105 #include <sys/resourcevar.h>
    106 #if defined(PERFCTRS)
    107 #include <sys/pmc.h>
    108 #endif
    109 #include <sys/ptrace.h>
    110 #include <sys/acct.h>
    111 #include <sys/filedesc.h>
    112 #include <sys/ras.h>
    113 #include <sys/signalvar.h>
    114 #include <sys/sched.h>
    115 #include <sys/sa.h>
    116 #include <sys/savar.h>
    117 #include <sys/mount.h>
    118 #include <sys/syscallargs.h>
    119 #include <sys/systrace.h>
    120 
    121 #include <machine/cpu.h>
    122 
    123 #include <uvm/uvm_extern.h>
    124 
    125 #define DEBUG_EXIT
    126 
    127 #ifdef DEBUG_EXIT
    128 int debug_exit = 0;
    129 #define DPRINTF(x) if (debug_exit) printf x
    130 #else
    131 #define DPRINTF(x)
    132 #endif
    133 
    134 static void lwp_exit_hook(struct lwp *, void *);
    135 
    136 /*
    137  * exit --
    138  *	Death of process.
    139  */
    140 int
    141 sys_exit(struct lwp *l, void *v, register_t *retval)
    142 {
    143 	struct sys_exit_args /* {
    144 		syscallarg(int)	rval;
    145 	} */ *uap = v;
    146 
    147 	/* Don't call exit1() multiple times in the same process.*/
    148 	if (l->l_proc->p_flag & P_WEXIT)
    149 		lwp_exit(l);
    150 
    151 	exit1(l, W_EXITCODE(SCARG(uap, rval), 0));
    152 	/* NOTREACHED */
    153 	return (0);
    154 }
    155 
    156 /*
    157  * Exit: deallocate address space and other resources, change proc state
    158  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
    159  * status and rusage for wait().  Check for child processes and orphan them.
    160  */
    161 void
    162 exit1(struct lwp *l, int rv)
    163 {
    164 	struct proc	*p, *q, *nq;
    165 	int		s;
    166 
    167 	p = l->l_proc;
    168 
    169 	if (__predict_false(p == initproc))
    170 		panic("init died (signal %d, exit %d)",
    171 		    WTERMSIG(rv), WEXITSTATUS(rv));
    172 
    173 	DPRINTF(("exit1: %d.%d exiting.\n", p->p_pid, l->l_lid));
    174 	/*
    175 	 * Disable scheduler activation upcalls.
    176 	 * We're trying to get out of here.
    177 	 */
    178 	if (l->l_flag & L_SA) {
    179 		l->l_flag &= ~L_SA;
    180 		p->p_flag &= ~P_SA;
    181 	}
    182 
    183 #ifdef PGINPROF
    184 	vmsizmon();
    185 #endif
    186 	if (p->p_flag & P_PROFIL)
    187 		stopprofclock(p);
    188 	p->p_ru = pool_get(&rusage_pool, PR_WAITOK);
    189 	/*
    190 	 * If parent is waiting for us to exit or exec, P_PPWAIT is set; we
    191 	 * wake up the parent early to avoid deadlock.
    192 	 */
    193 	p->p_flag |= P_WEXIT;
    194 	if (p->p_flag & P_PPWAIT) {
    195 		p->p_flag &= ~P_PPWAIT;
    196 		wakeup((caddr_t)p->p_pptr);
    197 	}
    198 	sigfillset(&p->p_sigctx.ps_sigignore);
    199 	sigemptyset(&p->p_sigctx.ps_siglist);
    200 	p->p_sigctx.ps_sigcheck = 0;
    201 	timers_free(p, TIMERS_ALL);
    202 
    203 	if (p->p_nlwps > 1)
    204 		exit_lwps(l);
    205 
    206 #if defined(__HAVE_RAS)
    207 	ras_purgeall(p);
    208 #endif
    209 
    210 	/*
    211 	 * Close open files and release open-file table.
    212 	 * This may block!
    213 	 */
    214 	fdfree(p);
    215 	cwdfree(p);
    216 
    217 	doexithooks(p);
    218 
    219 	if (SESS_LEADER(p)) {
    220 		struct session *sp = p->p_session;
    221 
    222 		if (sp->s_ttyvp) {
    223 			/*
    224 			 * Controlling process.
    225 			 * Signal foreground pgrp,
    226 			 * drain controlling terminal
    227 			 * and revoke access to controlling terminal.
    228 			 */
    229 			if (sp->s_ttyp->t_session == sp) {
    230 				if (sp->s_ttyp->t_pgrp)
    231 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
    232 				(void) ttywait(sp->s_ttyp);
    233 				/*
    234 				 * The tty could have been revoked
    235 				 * if we blocked.
    236 				 */
    237 				if (sp->s_ttyvp)
    238 					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
    239 			}
    240 			if (sp->s_ttyvp)
    241 				vrele(sp->s_ttyvp);
    242 			sp->s_ttyvp = NULL;
    243 			/*
    244 			 * s_ttyp is not zero'd; we use this to indicate
    245 			 * that the session once had a controlling terminal.
    246 			 * (for logging and informational purposes)
    247 			 */
    248 		}
    249 		sp->s_leader = NULL;
    250 	}
    251 	fixjobc(p, p->p_pgrp, 0);
    252 	(void)acct_process(p);
    253 #ifdef KTRACE
    254 	/*
    255 	 * release trace file
    256 	 */
    257 	ktrderef(p);
    258 #endif
    259 #ifdef SYSTRACE
    260 	systrace_sys_exit(p);
    261 #endif
    262 	/*
    263 	 * If emulation has process exit hook, call it now.
    264 	 */
    265 	if (p->p_emul->e_proc_exit)
    266 		(*p->p_emul->e_proc_exit)(p);
    267 
    268 	/*
    269 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
    270 	 */
    271 	p->p_stat = SDEAD;
    272 	p->p_nrlwps--;
    273 	l->l_stat = SDEAD;
    274 
    275 	/*
    276 	 * Remove proc from pidhash chain so looking it up won't
    277 	 * work.  Move it from allproc to zombproc, but do not yet
    278 	 * wake up the reaper.  We will put the proc on the
    279 	 * deadproc list later (using the p_hash member), and
    280 	 * wake up the reaper when we do.
    281 	 */
    282 	s = proclist_lock_write();
    283 	LIST_REMOVE(p, p_hash);
    284 	LIST_REMOVE(p, p_list);
    285 	LIST_INSERT_HEAD(&zombproc, p, p_list);
    286 	LIST_REMOVE(l, l_list);
    287 	l->l_flag |= L_DETACHED;
    288 	proclist_unlock_write(s);
    289 
    290 	/*
    291 	 * Give orphaned children to init(8).
    292 	 */
    293 	q = LIST_FIRST(&p->p_children);
    294 	if (q)		/* only need this if any child is S_ZOMB */
    295 		wakeup((caddr_t)initproc);
    296 	for (; q != 0; q = nq) {
    297 		nq = LIST_NEXT(q, p_sibling);
    298 
    299 		/*
    300 		 * Traced processes are killed since their existence
    301 		 * means someone is screwing up. Since we reset the
    302 		 * trace flags, the logic in sys_wait4() would not be
    303 		 * triggered to reparent the process to its
    304 		 * original parent, so we must do this here.
    305 		 */
    306 		if (q->p_flag & P_TRACED) {
    307 			if (q->p_opptr != q->p_pptr) {
    308 				struct proc *t = q->p_opptr;
    309 				proc_reparent(q, t ? t : initproc);
    310 				q->p_opptr = NULL;
    311 			} else
    312 				proc_reparent(q, initproc);
    313 			q->p_flag &= ~(P_TRACED|P_WAITED|P_FSTRACE);
    314 			psignal(q, SIGKILL);
    315 		} else {
    316 			proc_reparent(q, initproc);
    317 		}
    318 	}
    319 
    320 	/*
    321 	 * Reset p_opptr pointer of all former children which got
    322 	 * traced by another process and were reparented. We reset
    323 	 * it to NULL here; the trace detach code then reparents
    324 	 * the child to initproc. We only check allproc list, since
    325 	 * eventual former children on zombproc list won't reference
    326 	 * p_opptr anymore.
    327 	 */
    328 	if (p->p_flag & P_CHTRACED) {
    329 		struct proc *t;
    330 
    331 		proclist_lock_read();
    332 
    333 		LIST_FOREACH(t, &allproc, p_list) {
    334 			if (t->p_opptr == p)
    335 				t->p_opptr = NULL;
    336 		}
    337 
    338 		proclist_unlock_read();
    339 	}
    340 
    341 	/*
    342 	 * Save exit status and final rusage info, adding in child rusage
    343 	 * info and self times.
    344 	 */
    345 	p->p_xstat = rv;
    346 	*p->p_ru = p->p_stats->p_ru;
    347 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
    348 	ruadd(p->p_ru, &p->p_stats->p_cru);
    349 
    350 	/*
    351 	 * Notify interested parties of our demise.
    352 	 */
    353 	KNOTE(&p->p_klist, NOTE_EXIT);
    354 
    355 #if PERFCTRS
    356 	/*
    357 	 * Save final PMC information in parent process & clean up.
    358 	 */
    359 	if (PMC_ENABLED(p)) {
    360 		pmc_save_context(p);
    361 		pmc_accumulate(p->p_pptr, p);
    362 		pmc_process_exit(p);
    363 	}
    364 #endif
    365 
    366 	/*
    367 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
    368 	 * flag set, notify init instead (and hope it will handle
    369 	 * this situation).
    370 	 */
    371 	if (p->p_pptr->p_flag & P_NOCLDWAIT) {
    372 		struct proc *pp = p->p_pptr;
    373 		proc_reparent(p, initproc);
    374 		/*
    375 		 * If this was the last child of our parent, notify
    376 		 * parent, so in case he was wait(2)ing, he will
    377 		 * continue.
    378 		 */
    379 		if (LIST_FIRST(&pp->p_children) == NULL)
    380 			wakeup((caddr_t)pp);
    381 	}
    382 
    383 	/*
    384 	 * Release the process's signal state.
    385 	 */
    386 	sigactsfree(p);
    387 
    388 	/*
    389 	 * Clear curlwp after we've done all operations
    390 	 * that could block, and before tearing down the rest
    391 	 * of the process state that might be used from clock, etc.
    392 	 * Also, can't clear curlwp while we're still runnable,
    393 	 * as we're not on a run queue (we are current, just not
    394 	 * a proper proc any longer!).
    395 	 *
    396 	 * Other substructures are freed from wait().
    397 	 */
    398 	curlwp = NULL;
    399 	limfree(p->p_limit);
    400 	pstatsfree(p->p_stats);
    401 	p->p_limit = NULL;
    402 
    403 	/* This process no longer needs to hold the kernel lock. */
    404 	KERNEL_PROC_UNLOCK(l);
    405 
    406 	/*
    407 	 * Finally, call machine-dependent code to switch to a new
    408 	 * context (possibly the idle context).  Once we are no longer
    409 	 * using the dead process's vmspace and stack, exit2() will be
    410 	 * called to schedule those resources to be released by the
    411 	 * reaper thread.
    412 	 *
    413 	 * Note that cpu_exit() will end with a call equivalent to
    414 	 * cpu_switch(), finishing our execution (pun intended).
    415 	 */
    416 
    417 	cpu_exit(l, 1);
    418 }
    419 
    420 void
    421 exit_lwps(struct lwp *l)
    422 {
    423 	struct proc *p;
    424 	struct lwp *l2;
    425 	int s, error;
    426 	lwpid_t		waited;
    427 
    428 	p = l->l_proc;
    429 
    430 	/* XXX SMP
    431 	 * This would be the right place to IPI any LWPs running on
    432 	 * other processors so that they can notice the userret exit hook.
    433 	 */
    434 	p->p_userret = lwp_exit_hook;
    435 	p->p_userret_arg = NULL;
    436 
    437 	/*
    438 	 * Make SA-cached LWPs normal process runnable LWPs so that
    439 	 * they'll also self-destruct.
    440 	 */
    441 	if (p->p_sa && p->p_sa->sa_ncached > 0) {
    442 		DPRINTF(("exit_lwps: Making cached LWPs of %d runnable: ",
    443 		    p->p_pid));
    444 		SCHED_LOCK(s);
    445 		while ((l2 = sa_getcachelwp(p)) != 0) {
    446 			l2->l_priority = l2->l_usrpri;
    447 			setrunnable(l2);
    448 			DPRINTF(("%d ", l2->l_lid));
    449 		}
    450 		DPRINTF(("\n"));
    451 		SCHED_UNLOCK(s);
    452 	}
    453 
    454 	/*
    455 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
    456 	 * LWPs, make detached LWPs undeached (so we can wait for
    457 	 * them) and then wait for everyone else to finish.
    458 	 */
    459 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    460 		l2->l_flag &= ~(L_DETACHED|L_SA);
    461 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & L_SINTR)) ||
    462 		    l2->l_stat == LSSUSPENDED) {
    463 			SCHED_LOCK(s);
    464 			setrunnable(l2);
    465 			SCHED_UNLOCK(s);
    466 			DPRINTF(("exit_lwps: Made %d.%d runnable\n",
    467 			    p->p_pid, l2->l_lid));
    468 		}
    469 	}
    470 
    471 
    472 	while (p->p_nlwps > 1) {
    473 		DPRINTF(("exit_lwps: waiting for %d LWPs (%d runnable, %d zombies)\n",
    474 		    p->p_nlwps, p->p_nrlwps, p->p_nzlwps));
    475 		error = lwp_wait1(l, 0, &waited, LWPWAIT_EXITCONTROL);
    476 		if (error)
    477 			panic("exit_lwps: lwp_wait1 failed with error %d\n",
    478 			    error);
    479 		DPRINTF(("exit_lwps: Got LWP %d from lwp_wait1()\n", waited));
    480 	}
    481 
    482 	p->p_userret = NULL;
    483 }
    484 
    485 /* Wrapper function for use in p_userret */
    486 static void
    487 lwp_exit_hook(struct lwp *l, void *arg)
    488 {
    489 	KERNEL_PROC_LOCK(l);
    490 	lwp_exit(l);
    491 }
    492 
    493 /*
    494  * We are called from cpu_exit() once it is safe to schedule the
    495  * dead process's resources to be freed (i.e., once we've switched to
    496  * the idle PCB for the current CPU).
    497  *
    498  * NOTE: One must be careful with locking in this routine.  It's
    499  * called from a critical section in machine-dependent code, so
    500  * we should refrain from changing any interrupt state.
    501  *
    502  * We lock the deadproc list (a spin lock), place the proc on that
    503  * list (using the p_hash member), and wake up the reaper.
    504  */
    505 void
    506 exit2(struct lwp *l)
    507 {
    508 	struct proc *p = l->l_proc;
    509 
    510 	simple_lock(&deadproc_slock);
    511 	LIST_INSERT_HEAD(&deadproc, p, p_hash);
    512 	simple_unlock(&deadproc_slock);
    513 
    514 	/* lwp_exit2() will wake up deadproc for us. */
    515 	lwp_exit2(l);
    516 }
    517 
    518 /*
    519  * Process reaper.  This is run by a kernel thread to free the resources
    520  * of a dead process.  Once the resources are free, the process becomes
    521  * a zombie, and the parent is allowed to read the undead's status.
    522  */
    523 void
    524 reaper(void *arg)
    525 {
    526 	struct proc *p;
    527 	struct lwp *l;
    528 
    529 	KERNEL_PROC_UNLOCK(curlwp);
    530 
    531 	for (;;) {
    532 		simple_lock(&deadproc_slock);
    533 		p = LIST_FIRST(&deadproc);
    534 		l = LIST_FIRST(&deadlwp);
    535 		if (p == NULL && l == NULL) {
    536 			/* No work for us; go to sleep until someone exits. */
    537 			(void) ltsleep(&deadproc, PVM|PNORELOCK,
    538 			    "reaper", 0, &deadproc_slock);
    539 			continue;
    540 		}
    541 
    542 		if (l != NULL ) {
    543 			p = l->l_proc;
    544 
    545 			/* Remove us from the deadlwp list. */
    546 			LIST_REMOVE(l, l_list);
    547 			simple_unlock(&deadproc_slock);
    548 			KERNEL_PROC_LOCK(curlwp);
    549 
    550 			/*
    551 			 * Give machine-dependent code a chance to free any
    552 			 * resources it couldn't free while still running on
    553 			 * that process's context.  This must be done before
    554 			 * uvm_lwp_exit(), in case these resources are in the
    555 			 * PCB.
    556 			 */
    557 			cpu_wait(l);
    558 
    559 			/*
    560 			 * Free the VM resources we're still holding on to.
    561 			 */
    562 			uvm_lwp_exit(l);
    563 
    564 			l->l_stat = LSZOMB;
    565 			if (l->l_flag & L_DETACHED) {
    566 				/* Nobody waits for detached LWPs. */
    567 				LIST_REMOVE(l, l_sibling);
    568 				p->p_nlwps--;
    569 				pool_put(&lwp_pool, l);
    570 			} else {
    571 				p->p_nzlwps++;
    572 				wakeup((caddr_t)&p->p_nlwps);
    573 			}
    574 			/* XXXNJW where should this be with respect to
    575 			 * the wakeup() above? */
    576 			KERNEL_PROC_UNLOCK(curlwp);
    577 		} else {
    578 			/* Remove us from the deadproc list. */
    579 			LIST_REMOVE(p, p_hash);
    580 			simple_unlock(&deadproc_slock);
    581 			KERNEL_PROC_LOCK(curlwp);
    582 
    583 			/*
    584 			 * Free the VM resources we're still holding on to.
    585 			 * We must do this from a valid thread because doing
    586 			 * so may block.
    587 			 */
    588 			uvm_proc_exit(p);
    589 
    590 			/* Process is now a true zombie. */
    591 			p->p_stat = SZOMB;
    592 
    593 			/* Wake up the parent so it can get exit status. */
    594 			if ((p->p_flag & P_FSTRACE) == 0 && p->p_exitsig != 0)
    595 				psignal(p->p_pptr, P_EXITSIG(p));
    596 			KERNEL_PROC_UNLOCK(curlwp);
    597 			wakeup((caddr_t)p->p_pptr);
    598 		}
    599 	}
    600 }
    601 
    602 int
    603 sys_wait4(struct lwp *l, void *v, register_t *retval)
    604 {
    605 	struct sys_wait4_args /* {
    606 		syscallarg(int)			pid;
    607 		syscallarg(int *)		status;
    608 		syscallarg(int)			options;
    609 		syscallarg(struct rusage *)	rusage;
    610 	} */ *uap = v;
    611 	struct proc	*p, *q, *t;
    612 	int		nfound, status, error, s;
    613 
    614 	q = l->l_proc;
    615 
    616 	if (SCARG(uap, pid) == 0)
    617 		SCARG(uap, pid) = -q->p_pgid;
    618 	if (SCARG(uap, options) &~ (WUNTRACED|WNOHANG|WALTSIG))
    619 		return (EINVAL);
    620 
    621  loop:
    622 	nfound = 0;
    623 	LIST_FOREACH(p, &q->p_children, p_sibling) {
    624 		if (SCARG(uap, pid) != WAIT_ANY &&
    625 		    p->p_pid != SCARG(uap, pid) &&
    626 		    p->p_pgid != -SCARG(uap, pid))
    627 			continue;
    628 		/*
    629 		 * Wait for processes with p_exitsig != SIGCHLD processes only
    630 		 * if WALTSIG is set; wait for processes with p_exitsig ==
    631 		 * SIGCHLD only if WALTSIG is clear.
    632 		 */
    633 		if (((SCARG(uap, options) & WALLSIG) == 0) &&
    634 		    ((SCARG(uap, options) & WALTSIG) ?
    635 		     (p->p_exitsig == SIGCHLD) : (P_EXITSIG(p) != SIGCHLD)))
    636 			continue;
    637 
    638 		nfound++;
    639 		if (p->p_stat == SZOMB) {
    640 			retval[0] = p->p_pid;
    641 
    642 			if (SCARG(uap, status)) {
    643 				status = p->p_xstat;	/* convert to int */
    644 				error = copyout((caddr_t)&status,
    645 						(caddr_t)SCARG(uap, status),
    646 						sizeof(status));
    647 				if (error)
    648 					return (error);
    649 			}
    650 			if (SCARG(uap, rusage) &&
    651 			    (error = copyout((caddr_t)p->p_ru,
    652 			    (caddr_t)SCARG(uap, rusage),
    653 			    sizeof(struct rusage))))
    654 				return (error);
    655 			/*
    656 			 * If we got the child via ptrace(2) or procfs, and
    657 			 * the parent is different (meaning the process was
    658 			 * attached, rather than run as a child), then we need
    659 			 * to give it back to the old parent, and send the
    660 			 * parent the exit signal.  The rest of the cleanup
    661 			 * will be done when the old parent waits on the child.
    662 			 */
    663 			if ((p->p_flag & P_TRACED) && p->p_opptr != p->p_pptr){
    664 				t = p->p_opptr;
    665 				proc_reparent(p, t ? t : initproc);
    666 				p->p_opptr = NULL;
    667 				p->p_flag &= ~(P_TRACED|P_WAITED|P_FSTRACE);
    668 				if (p->p_exitsig != 0)
    669 					psignal(p->p_pptr, P_EXITSIG(p));
    670 				wakeup((caddr_t)p->p_pptr);
    671 				return (0);
    672 			}
    673 			scheduler_wait_hook(q, p);
    674 			p->p_xstat = 0;
    675 			ruadd(&q->p_stats->p_cru, p->p_ru);
    676 			pool_put(&rusage_pool, p->p_ru);
    677 
    678 			/*
    679 			 * Finally finished with old proc entry.
    680 			 * Unlink it from its process group and free it.
    681 			 */
    682 			leavepgrp(p);
    683 
    684 			s = proclist_lock_write();
    685 			LIST_REMOVE(p, p_list);	/* off zombproc */
    686 			proclist_unlock_write(s);
    687 
    688 			LIST_REMOVE(p, p_sibling);
    689 
    690 			/*
    691 			 * Decrement the count of procs running with this uid.
    692 			 */
    693 			(void)chgproccnt(p->p_cred->p_ruid, -1);
    694 
    695 			/*
    696 			 * Free up credentials.
    697 			 */
    698 			if (--p->p_cred->p_refcnt == 0) {
    699 				crfree(p->p_cred->pc_ucred);
    700 				pool_put(&pcred_pool, p->p_cred);
    701 			}
    702 
    703 			/*
    704 			 * Release reference to text vnode
    705 			 */
    706 			if (p->p_textvp)
    707 				vrele(p->p_textvp);
    708 
    709 			/*
    710 			 * Release any SA state
    711 			 */
    712 			if (p->p_sa) {
    713 				free(p->p_sa->sa_stacks, M_SA);
    714 				pool_put(&sadata_pool, p->p_sa);
    715 			}
    716 
    717 			pool_put(&proc_pool, p);
    718 			nprocs--;
    719 			return (0);
    720 		}
    721 		if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
    722 		    (p->p_flag & P_TRACED || SCARG(uap, options) & WUNTRACED)) {
    723 			p->p_flag |= P_WAITED;
    724 			retval[0] = p->p_pid;
    725 
    726 			if (SCARG(uap, status)) {
    727 				status = W_STOPCODE(p->p_xstat);
    728 				error = copyout((caddr_t)&status,
    729 				    (caddr_t)SCARG(uap, status),
    730 				    sizeof(status));
    731 			} else
    732 				error = 0;
    733 			return (error);
    734 		}
    735 	}
    736 	if (nfound == 0)
    737 		return (ECHILD);
    738 	if (SCARG(uap, options) & WNOHANG) {
    739 		retval[0] = 0;
    740 		return (0);
    741 	}
    742 	if ((error = tsleep((caddr_t)q, PWAIT | PCATCH, "wait", 0)) != 0)
    743 		return (error);
    744 	goto loop;
    745 }
    746 
    747 /*
    748  * make process 'parent' the new parent of process 'child'.
    749  */
    750 void
    751 proc_reparent(struct proc *child, struct proc *parent)
    752 {
    753 
    754 	if (child->p_pptr == parent)
    755 		return;
    756 
    757 	if (parent == initproc)
    758 		child->p_exitsig = SIGCHLD;
    759 
    760 	LIST_REMOVE(child, p_sibling);
    761 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
    762 	child->p_pptr = parent;
    763 }
    764