Home | History | Annotate | Line # | Download | only in kern
kern_exit.c revision 1.213
      1 /*	$NetBSD: kern_exit.c,v 1.213 2008/10/15 06:51:20 wrstuden Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999, 2006, 2007, 2008 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, and by Andrew Doran.
     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  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  * (c) UNIX System Laboratories, Inc.
     37  * All or some portions of this file are derived from material licensed
     38  * to the University of California by American Telephone and Telegraph
     39  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     40  * the permission of UNIX System Laboratories, Inc.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. Neither the name of the University nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  *
     66  *	@(#)kern_exit.c	8.10 (Berkeley) 2/23/95
     67  */
     68 
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: kern_exit.c,v 1.213 2008/10/15 06:51:20 wrstuden Exp $");
     71 
     72 #include "opt_ktrace.h"
     73 #include "opt_perfctrs.h"
     74 #include "opt_sa.h"
     75 #include "opt_sysv.h"
     76 
     77 #include <sys/param.h>
     78 #include <sys/aio.h>
     79 #include <sys/systm.h>
     80 #include <sys/ioctl.h>
     81 #include <sys/tty.h>
     82 #include <sys/time.h>
     83 #include <sys/resource.h>
     84 #include <sys/kernel.h>
     85 #include <sys/proc.h>
     86 #include <sys/buf.h>
     87 #include <sys/wait.h>
     88 #include <sys/file.h>
     89 #include <sys/vnode.h>
     90 #include <sys/syslog.h>
     91 #include <sys/malloc.h>
     92 #include <sys/pool.h>
     93 #include <sys/uidinfo.h>
     94 #if defined(PERFCTRS)
     95 #include <sys/pmc.h>
     96 #endif
     97 #include <sys/ptrace.h>
     98 #include <sys/acct.h>
     99 #include <sys/filedesc.h>
    100 #include <sys/ras.h>
    101 #include <sys/signalvar.h>
    102 #include <sys/sched.h>
    103 #include <sys/sa.h>
    104 #include <sys/savar.h>
    105 #include <sys/mount.h>
    106 #include <sys/syscallargs.h>
    107 #include <sys/kauth.h>
    108 #include <sys/sleepq.h>
    109 #include <sys/lockdebug.h>
    110 #include <sys/ktrace.h>
    111 #include <sys/cpu.h>
    112 #include <sys/lwpctl.h>
    113 #include <sys/atomic.h>
    114 
    115 #include <uvm/uvm_extern.h>
    116 
    117 #define DEBUG_EXIT
    118 
    119 #ifdef DEBUG_EXIT
    120 int debug_exit = 0;
    121 #define DPRINTF(x) if (debug_exit) printf x
    122 #else
    123 #define DPRINTF(x)
    124 #endif
    125 
    126 static int find_stopped_child(struct proc *, pid_t, int, struct proc **, int *);
    127 static void proc_free(struct proc *, struct rusage *);
    128 
    129 /*
    130  * Fill in the appropriate signal information, and signal the parent.
    131  */
    132 static void
    133 exit_psignal(struct proc *p, struct proc *pp, ksiginfo_t *ksi)
    134 {
    135 
    136 	KSI_INIT(ksi);
    137 	if ((ksi->ksi_signo = P_EXITSIG(p)) == SIGCHLD) {
    138 		if (WIFSIGNALED(p->p_xstat)) {
    139 			if (WCOREDUMP(p->p_xstat))
    140 				ksi->ksi_code = CLD_DUMPED;
    141 			else
    142 				ksi->ksi_code = CLD_KILLED;
    143 		} else {
    144 			ksi->ksi_code = CLD_EXITED;
    145 		}
    146 	}
    147 	/*
    148 	 * We fill those in, even for non-SIGCHLD.
    149 	 * It's safe to access p->p_cred unlocked here.
    150 	 */
    151 	ksi->ksi_pid = p->p_pid;
    152 	ksi->ksi_uid = kauth_cred_geteuid(p->p_cred);
    153 	ksi->ksi_status = p->p_xstat;
    154 	/* XXX: is this still valid? */
    155 	ksi->ksi_utime = p->p_stats->p_ru.ru_utime.tv_sec;
    156 	ksi->ksi_stime = p->p_stats->p_ru.ru_stime.tv_sec;
    157 }
    158 
    159 /*
    160  * exit --
    161  *	Death of process.
    162  */
    163 int
    164 sys_exit(struct lwp *l, const struct sys_exit_args *uap, register_t *retval)
    165 {
    166 	/* {
    167 		syscallarg(int)	rval;
    168 	} */
    169 	struct proc *p = l->l_proc;
    170 
    171 	/* Don't call exit1() multiple times in the same process. */
    172 	mutex_enter(p->p_lock);
    173 	if (p->p_sflag & PS_WEXIT) {
    174 		mutex_exit(p->p_lock);
    175 		lwp_exit(l);
    176 	}
    177 
    178 	/* exit1() will release the mutex. */
    179 	exit1(l, W_EXITCODE(SCARG(uap, rval), 0));
    180 	/* NOTREACHED */
    181 	return (0);
    182 }
    183 
    184 /*
    185  * Exit: deallocate address space and other resources, change proc state
    186  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
    187  * status and rusage for wait().  Check for child processes and orphan them.
    188  *
    189  * Must be called with p->p_lock held.  Does not return.
    190  */
    191 void
    192 exit1(struct lwp *l, int rv)
    193 {
    194 	struct proc	*p, *q, *nq;
    195 	struct pgrp	*pgrp;
    196 	ksiginfo_t	ksi;
    197 	ksiginfoq_t	kq;
    198 	int		wakeinit, sa;
    199 
    200 	p = l->l_proc;
    201 
    202 	KASSERT(mutex_owned(p->p_lock));
    203 
    204 	if (__predict_false(p == initproc))
    205 		panic("init died (signal %d, exit %d)",
    206 		    WTERMSIG(rv), WEXITSTATUS(rv));
    207 
    208 	/*
    209 	 * Disable scheduler activation upcalls.  We're trying to get out of
    210 	 * here.
    211 	 */
    212 	sa = 0;
    213 #ifdef KERN_SA
    214 	if ((p->p_sa != NULL)) {
    215 		l->l_pflag |= LP_SA_NOBLOCK;
    216 		sa = 1;
    217 	}
    218 #endif
    219 
    220 	p->p_sflag |= PS_WEXIT;
    221 
    222 	/*
    223 	 * Force all other LWPs to exit before we do.  Only then can we
    224 	 * begin to tear down the rest of the process state.
    225 	 */
    226 	if (sa || p->p_nlwps > 1)
    227 		exit_lwps(l);
    228 
    229 	ksiginfo_queue_init(&kq);
    230 
    231 	/*
    232 	 * If we have been asked to stop on exit, do so now.
    233 	 */
    234 	if (__predict_false(p->p_sflag & PS_STOPEXIT)) {
    235 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
    236 		sigclearall(p, &contsigmask, &kq);
    237 		p->p_waited = 0;
    238 		membar_producer();
    239 		p->p_stat = SSTOP;
    240 		lwp_lock(l);
    241 		p->p_nrlwps--;
    242 		l->l_stat = LSSTOP;
    243 		mutex_exit(p->p_lock);
    244 		mi_switch(l);
    245 		KERNEL_LOCK(l->l_biglocks, l);
    246 		mutex_enter(p->p_lock);
    247 	}
    248 
    249 	/*
    250 	 * Bin any remaining signals and mark the process as dying so it will
    251 	 * not be found for, e.g. signals.
    252 	 */
    253 	sigfillset(&p->p_sigctx.ps_sigignore);
    254 	sigclearall(p, NULL, &kq);
    255 	p->p_stat = SDYING;
    256 	mutex_exit(p->p_lock);
    257 	ksiginfo_queue_drain(&kq);
    258 
    259 	/* Destroy any lwpctl info. */
    260 	if (p->p_lwpctl != NULL)
    261 		lwp_ctl_exit();
    262 
    263 	/* Destroy all AIO works */
    264 	aio_exit(p, p->p_aio);
    265 
    266 	/*
    267 	 * Drain all remaining references that procfs, ptrace and others may
    268 	 * have on the process.
    269 	 */
    270 	rw_enter(&p->p_reflock, RW_WRITER);
    271 
    272 	DPRINTF(("exit1: %d.%d exiting.\n", p->p_pid, l->l_lid));
    273 
    274 	timers_free(p, TIMERS_ALL);
    275 #if defined(__HAVE_RAS)
    276 	ras_purgeall();
    277 #endif
    278 
    279 	/*
    280 	 * Close open files, release open-file table and free signal
    281 	 * actions.  This may block!
    282 	 */
    283 	fd_free();
    284 	cwdfree(p->p_cwdi);
    285 	p->p_cwdi = NULL;
    286 	doexithooks(p);
    287 	sigactsfree(p->p_sigacts);
    288 
    289 	/*
    290 	 * Write out accounting data.
    291 	 */
    292 	(void)acct_process(l);
    293 
    294 #ifdef KTRACE
    295 	/*
    296 	 * Release trace file.
    297 	 */
    298 	if (p->p_tracep != NULL) {
    299 		mutex_enter(&ktrace_lock);
    300 		ktrderef(p);
    301 		mutex_exit(&ktrace_lock);
    302 	}
    303 #endif
    304 
    305 	/*
    306 	 * If emulation has process exit hook, call it now.
    307 	 * Set the exit status now so that the exit hook has
    308 	 * an opportunity to tweak it (COMPAT_LINUX requires
    309 	 * this for thread group emulation)
    310 	 */
    311 	p->p_xstat = rv;
    312 	if (p->p_emul->e_proc_exit)
    313 		(*p->p_emul->e_proc_exit)(p);
    314 
    315 	/*
    316 	 * Free the VM resources we're still holding on to.
    317 	 * We must do this from a valid thread because doing
    318 	 * so may block. This frees vmspace, which we don't
    319 	 * need anymore. The only remaining lwp is the one
    320 	 * we run at this moment, nothing runs in userland
    321 	 * anymore.
    322 	 */
    323 	uvm_proc_exit(p);
    324 
    325 	/*
    326 	 * Stop profiling.
    327 	 */
    328 	if (__predict_false((p->p_stflag & PST_PROFIL) != 0)) {
    329 		mutex_spin_enter(&p->p_stmutex);
    330 		stopprofclock(p);
    331 		mutex_spin_exit(&p->p_stmutex);
    332 	}
    333 
    334 	/*
    335 	 * If parent is waiting for us to exit or exec, P_PPWAIT is set; we
    336 	 * wake up the parent early to avoid deadlock.  We can do this once
    337 	 * the VM resources are released.
    338 	 */
    339 	mutex_enter(proc_lock);
    340 	if (p->p_lflag & PL_PPWAIT) {
    341 		p->p_lflag &= ~PL_PPWAIT;
    342 		cv_broadcast(&p->p_pptr->p_waitcv);
    343 	}
    344 
    345 	if (SESS_LEADER(p)) {
    346 		struct vnode *vprele = NULL, *vprevoke = NULL;
    347 		struct session *sp = p->p_session;
    348 		struct tty *tp;
    349 
    350 		if (sp->s_ttyvp) {
    351 			/*
    352 			 * Controlling process.
    353 			 * Signal foreground pgrp,
    354 			 * drain controlling terminal
    355 			 * and revoke access to controlling terminal.
    356 			 */
    357 			tp = sp->s_ttyp;
    358 			mutex_spin_enter(&tty_lock);
    359 			if (tp->t_session == sp) {
    360 				/* we can't guarantee the revoke will do this */
    361 				pgrp = tp->t_pgrp;
    362 				tp->t_pgrp = NULL;
    363 				tp->t_session = NULL;
    364 				mutex_spin_exit(&tty_lock);
    365 				if (pgrp != NULL) {
    366 					pgsignal(pgrp, SIGHUP, 1);
    367 				}
    368 				mutex_exit(proc_lock);
    369 				(void) ttywait(tp);
    370 				mutex_enter(proc_lock);
    371 
    372 				/* The tty could have been revoked. */
    373 				vprevoke = sp->s_ttyvp;
    374 			} else
    375 				mutex_spin_exit(&tty_lock);
    376 			vprele = sp->s_ttyvp;
    377 			sp->s_ttyvp = NULL;
    378 			/*
    379 			 * s_ttyp is not zero'd; we use this to indicate
    380 			 * that the session once had a controlling terminal.
    381 			 * (for logging and informational purposes)
    382 			 */
    383 		}
    384 		sp->s_leader = NULL;
    385 
    386 		if (vprevoke != NULL || vprele != NULL) {
    387 			if (vprevoke != NULL) {
    388 				SESSRELE(sp);
    389 				mutex_exit(proc_lock);
    390 				VOP_REVOKE(vprevoke, REVOKEALL);
    391 			} else
    392 				mutex_exit(proc_lock);
    393 			if (vprele != NULL)
    394 				vrele(vprele);
    395 			mutex_enter(proc_lock);
    396 		}
    397 	}
    398 	fixjobc(p, p->p_pgrp, 0);
    399 
    400 	/*
    401 	 * Finalize the last LWP's specificdata, as well as the
    402 	 * specificdata for the proc itself.
    403 	 */
    404 	lwp_finispecific(l);
    405 	proc_finispecific(p);
    406 
    407 	/*
    408 	 * Notify interested parties of our demise.
    409 	 */
    410 	KNOTE(&p->p_klist, NOTE_EXIT);
    411 
    412 #if PERFCTRS
    413 	/*
    414 	 * Save final PMC information in parent process & clean up.
    415 	 */
    416 	if (PMC_ENABLED(p)) {
    417 		pmc_save_context(p);
    418 		pmc_accumulate(p->p_pptr, p);
    419 		pmc_process_exit(p);
    420 	}
    421 #endif
    422 
    423 	/*
    424 	 * Reset p_opptr pointer of all former children which got
    425 	 * traced by another process and were reparented. We reset
    426 	 * it to NULL here; the trace detach code then reparents
    427 	 * the child to initproc. We only check allproc list, since
    428 	 * eventual former children on zombproc list won't reference
    429 	 * p_opptr anymore.
    430 	 */
    431 	if (__predict_false(p->p_slflag & PSL_CHTRACED)) {
    432 		PROCLIST_FOREACH(q, &allproc) {
    433 			if ((q->p_flag & PK_MARKER) != 0)
    434 				continue;
    435 			if (q->p_opptr == p)
    436 				q->p_opptr = NULL;
    437 		}
    438 	}
    439 
    440 	/*
    441 	 * Give orphaned children to init(8).
    442 	 */
    443 	q = LIST_FIRST(&p->p_children);
    444 	wakeinit = (q != NULL);
    445 	for (; q != NULL; q = nq) {
    446 		nq = LIST_NEXT(q, p_sibling);
    447 
    448 		/*
    449 		 * Traced processes are killed since their existence
    450 		 * means someone is screwing up. Since we reset the
    451 		 * trace flags, the logic in sys_wait4() would not be
    452 		 * triggered to reparent the process to its
    453 		 * original parent, so we must do this here.
    454 		 */
    455 		if (__predict_false(q->p_slflag & PSL_TRACED)) {
    456 			mutex_enter(p->p_lock);
    457 			q->p_slflag &= ~(PSL_TRACED|PSL_FSTRACE|PSL_SYSCALL);
    458 			mutex_exit(p->p_lock);
    459 			if (q->p_opptr != q->p_pptr) {
    460 				struct proc *t = q->p_opptr;
    461 				proc_reparent(q, t ? t : initproc);
    462 				q->p_opptr = NULL;
    463 			} else
    464 				proc_reparent(q, initproc);
    465 			killproc(q, "orphaned traced process");
    466 		} else
    467 			proc_reparent(q, initproc);
    468 	}
    469 
    470 	/*
    471 	 * Move proc from allproc to zombproc, it's now nearly ready to be
    472 	 * collected by parent.
    473 	 */
    474 	LIST_REMOVE(l, l_list);
    475 	LIST_REMOVE(p, p_list);
    476 	LIST_INSERT_HEAD(&zombproc, p, p_list);
    477 
    478 	/*
    479 	 * Mark the process as dead.  We must do this before we signal
    480 	 * the parent.
    481 	 */
    482 	p->p_stat = SDEAD;
    483 
    484 	/* Put in front of parent's sibling list for parent to collect it */
    485 	q = p->p_pptr;
    486 	q->p_nstopchild++;
    487 	if (LIST_FIRST(&q->p_children) != p) {
    488 		/* Put child where it can be found quickly */
    489 		LIST_REMOVE(p, p_sibling);
    490 		LIST_INSERT_HEAD(&q->p_children, p, p_sibling);
    491 	}
    492 
    493 	/*
    494 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
    495 	 * flag set, notify init instead (and hope it will handle
    496 	 * this situation).
    497 	 */
    498 	if (q->p_flag & (PK_NOCLDWAIT|PK_CLDSIGIGN)) {
    499 		proc_reparent(p, initproc);
    500 		wakeinit = 1;
    501 
    502 		/*
    503 		 * If this was the last child of our parent, notify
    504 		 * parent, so in case he was wait(2)ing, he will
    505 		 * continue.
    506 		 */
    507 		if (LIST_FIRST(&q->p_children) == NULL)
    508 			cv_broadcast(&q->p_waitcv);
    509 	}
    510 
    511 	/* Reload parent pointer, since p may have been reparented above */
    512 	q = p->p_pptr;
    513 
    514 	if (__predict_false((p->p_slflag & PSL_FSTRACE) == 0 && p->p_exitsig != 0)) {
    515 		exit_psignal(p, q, &ksi);
    516 		kpsignal(q, &ksi, NULL);
    517 	}
    518 
    519 	/* Calculate the final rusage info.  */
    520 	calcru(p, &p->p_stats->p_ru.ru_utime, &p->p_stats->p_ru.ru_stime,
    521 	    NULL, NULL);
    522 
    523 	if (wakeinit)
    524 		cv_broadcast(&initproc->p_waitcv);
    525 
    526 	callout_destroy(&l->l_timeout_ch);
    527 
    528 	/*
    529 	 * Remaining lwp resources will be freed in lwp_exit2() once we've
    530 	 * switch to idle context; at that point, we will be marked as a
    531 	 * full blown zombie.
    532 	 */
    533 	mutex_enter(p->p_lock);
    534 	lwp_drainrefs(l);
    535 	lwp_lock(l);
    536 	l->l_prflag &= ~LPR_DETACHED;
    537 	l->l_stat = LSZOMB;
    538 	lwp_unlock(l);
    539 	KASSERT(curlwp == l);
    540 	KASSERT(p->p_nrlwps == 1);
    541 	KASSERT(p->p_nlwps == 1);
    542 	p->p_stat = SZOMB;
    543 	p->p_nrlwps--;
    544 	p->p_nzlwps++;
    545 	p->p_ndlwps = 0;
    546 	mutex_exit(p->p_lock);
    547 
    548 	/*
    549 	 * Signal the parent to collect us, and drop the proclist lock.
    550 	 * Drop debugger/procfs lock; no new references can be gained.
    551 	 */
    552 	cv_broadcast(&p->p_pptr->p_waitcv);
    553 	mutex_exit(proc_lock);
    554 	rw_exit(&p->p_reflock);
    555 
    556 	/* Verify that we hold no locks other than the kernel lock. */
    557 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
    558 
    559 	/*
    560 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
    561 	 */
    562 
    563 	/*
    564 	 * Give machine-dependent code a chance to free any MD LWP
    565 	 * resources.  This must be done before uvm_lwp_exit(), in
    566 	 * case these resources are in the PCB.
    567 	 */
    568 #ifndef __NO_CPU_LWP_FREE
    569 	cpu_lwp_free(l, 1);
    570 #endif
    571 	pmap_deactivate(l);
    572 
    573 	/* This process no longer needs to hold the kernel lock. */
    574 #ifdef notyet
    575 	/* XXXSMP hold in lwp_userret() */
    576 	KERNEL_UNLOCK_LAST(l);
    577 #else
    578 	KERNEL_UNLOCK_ALL(l, NULL);
    579 #endif
    580 
    581 	lwp_exit_switchaway(l);
    582 }
    583 
    584 void
    585 exit_lwps(struct lwp *l)
    586 {
    587 	struct proc *p;
    588 	struct lwp *l2;
    589 	int error;
    590 	lwpid_t waited;
    591 	int nlocks;
    592 
    593 	KERNEL_UNLOCK_ALL(l, &nlocks);
    594 
    595 	p = l->l_proc;
    596 	KASSERT(mutex_owned(p->p_lock));
    597 
    598 #if 0
    599 	if (p->p_sa != NULL) {
    600 		SLIST_FOREACH(vp, &p->p_sa->sa_vps, savp_next) {
    601 			/*
    602 			 * Make SA-cached LWPs normal process runnable
    603 			 * LWPs so that they'll also self-destruct.
    604 			 */
    605 			DPRINTF(("exit_lwps: Making cached LWPs of %d on "
    606 			    "VP %d runnable: ", p->p_pid, vp->savp_id));
    607 			while ((l2 = sa_getcachelwp(p, vp)) != 0) {
    608 				lwp_lock(l2);
    609 				l2->l_flag = (l2->l_flag & ~LW_SA) | LW_WEXIT;
    610 				l2->l_priority = MAXPRI_USER; /* XXX WRS needs thought */
    611 
    612 				/* setrunnable() will release the mutex. */
    613 				setrunnable(l2);
    614 				DPRINTF(("%d ", l2->l_lid));
    615 			}
    616 			DPRINTF(("\n"));
    617 
    618 			/*
    619 			 * Clear wokenq, the LWPs on the queue will
    620 			 * run below. Workes as these threads are still
    621 			 * on the p_lwps list (even though they are no longer
    622 			 * counted).
    623 			 */
    624 			TAILQ_INIT(&vp->savp_woken);
    625 		}
    626 	}
    627 #endif
    628 
    629  retry:
    630 	/*
    631 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
    632 	 * LWPs and then wait for everyone else to finish.
    633 	 */
    634 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    635 		if (l2 == l)
    636 			continue;
    637 		lwp_lock(l2);
    638 		l2->l_flag &= ~LW_SA;
    639 		l2->l_flag |= LW_WEXIT;
    640 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & LW_SINTR)) ||
    641 		    l2->l_stat == LSSUSPENDED || l2->l_stat == LSSTOP) {
    642 		    	/* setrunnable() will release the lock. */
    643 			setrunnable(l2);
    644 			DPRINTF(("exit_lwps: Made %d.%d runnable\n",
    645 			    p->p_pid, l2->l_lid));
    646 			continue;
    647 		}
    648 		lwp_unlock(l2);
    649 	}
    650 	while (p->p_nlwps > 1) {
    651 		DPRINTF(("exit_lwps: waiting for %d LWPs (%d zombies)\n",
    652 		    p->p_nlwps, p->p_nzlwps));
    653 		error = lwp_wait1(l, 0, &waited, LWPWAIT_EXITCONTROL);
    654 		if (p->p_nlwps == 1)
    655 			break;
    656 		if (error == EDEADLK) {
    657 			/*
    658 			 * LWPs can get suspended/slept behind us.
    659 			 * (eg. sa_setwoken)
    660 			 * kick them again and retry.
    661 			 */
    662 			goto retry;
    663 		}
    664 		if (error)
    665 			panic("exit_lwps: lwp_wait1 failed with error %d",
    666 			    error);
    667 		DPRINTF(("exit_lwps: Got LWP %d from lwp_wait1()\n", waited));
    668 	}
    669 
    670 	KERNEL_LOCK(nlocks, l);
    671 	KASSERT(p->p_nlwps == 1);
    672 }
    673 
    674 int
    675 do_sys_wait(struct lwp *l, int *pid, int *status, int options,
    676     struct rusage *ru, int *was_zombie)
    677 {
    678 	struct proc	*child;
    679 	int		error;
    680 
    681 	mutex_enter(proc_lock);
    682 	error = find_stopped_child(l->l_proc, *pid, options, &child, status);
    683 
    684 	if (child == NULL) {
    685 		mutex_exit(proc_lock);
    686 		*pid = 0;
    687 		return error;
    688 	}
    689 
    690 	*pid = child->p_pid;
    691 
    692 	if (child->p_stat == SZOMB) {
    693 		/* proc_free() will release the proc_lock. */
    694 		*was_zombie = 1;
    695 		if (options & WNOWAIT)
    696 			mutex_exit(proc_lock);
    697 		else {
    698 			proc_free(child, ru);
    699 		}
    700 	} else {
    701 		/* Child state must have been SSTOP. */
    702 		*was_zombie = 0;
    703 		mutex_exit(proc_lock);
    704 		*status = W_STOPCODE(*status);
    705 	}
    706 
    707 	return 0;
    708 }
    709 
    710 int
    711 sys_wait4(struct lwp *l, const struct sys_wait4_args *uap, register_t *retval)
    712 {
    713 	/* {
    714 		syscallarg(int)			pid;
    715 		syscallarg(int *)		status;
    716 		syscallarg(int)			options;
    717 		syscallarg(struct rusage *)	rusage;
    718 	} */
    719 	int		status, error;
    720 	int		was_zombie;
    721 	struct rusage	ru;
    722 	int pid = SCARG(uap, pid);
    723 
    724 	error = do_sys_wait(l, &pid, &status, SCARG(uap, options),
    725 	    SCARG(uap, rusage) != NULL ? &ru : NULL, &was_zombie);
    726 
    727 	retval[0] = pid;
    728 	if (pid == 0)
    729 		return error;
    730 
    731 	if (SCARG(uap, rusage))
    732 		error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
    733 
    734 	if (error == 0 && SCARG(uap, status))
    735 		error = copyout(&status, SCARG(uap, status), sizeof(status));
    736 
    737 	return error;
    738 }
    739 
    740 /*
    741  * Scan list of child processes for a child process that has stopped or
    742  * exited.  Used by sys_wait4 and 'compat' equivalents.
    743  *
    744  * Must be called with the proc_lock held, and may release while waiting.
    745  */
    746 static int
    747 find_stopped_child(struct proc *parent, pid_t pid, int options,
    748 		   struct proc **child_p, int *status_p)
    749 {
    750 	struct proc *child, *dead;
    751 	int error;
    752 
    753 	KASSERT(mutex_owned(proc_lock));
    754 
    755 	if (options & ~(WUNTRACED|WNOHANG|WALTSIG|WALLSIG)
    756 	    && !(options & WOPTSCHECKED)) {
    757 		*child_p = NULL;
    758 		return EINVAL;
    759 	}
    760 
    761 	if (pid == 0 && !(options & WOPTSCHECKED))
    762 		pid = -parent->p_pgid;
    763 
    764 	for (;;) {
    765 		error = ECHILD;
    766 		dead = NULL;
    767 
    768 		LIST_FOREACH(child, &parent->p_children, p_sibling) {
    769 			if (pid >= 0) {
    770 				if (child->p_pid != pid) {
    771 					child = p_find(pid, PFIND_ZOMBIE |
    772 					    PFIND_LOCKED);
    773 					if (child == NULL ||
    774 					    child->p_pptr != parent) {
    775 						child = NULL;
    776 						break;
    777 					}
    778 				}
    779 			} else if (pid != WAIT_ANY && child->p_pgid != -pid) {
    780 				/* Child not in correct pgrp */
    781 				continue;
    782 			}
    783 
    784 			/*
    785 			 * Wait for processes with p_exitsig != SIGCHLD
    786 			 * processes only if WALTSIG is set; wait for
    787 			 * processes with p_exitsig == SIGCHLD only
    788 			 * if WALTSIG is clear.
    789 			 */
    790 			if (((options & WALLSIG) == 0) &&
    791 			    (options & WALTSIG ? child->p_exitsig == SIGCHLD
    792 						: P_EXITSIG(child) != SIGCHLD)){
    793 				if (child->p_pid == pid) {
    794 					child = NULL;
    795 					break;
    796 				}
    797 				continue;
    798 			}
    799 
    800 			error = 0;
    801 			if ((options & WNOZOMBIE) == 0) {
    802 				if (child->p_stat == SZOMB)
    803 					break;
    804 				if (child->p_stat == SDEAD) {
    805 					/*
    806 					 * We may occasionally arrive here
    807 					 * after receiving a signal, but
    808 					 * immediatley before the child
    809 					 * process is zombified.  The wait
    810 					 * will be short, so avoid returning
    811 					 * to userspace.
    812 					 */
    813 					dead = child;
    814 				}
    815 			}
    816 
    817 			if (child->p_stat == SSTOP &&
    818 			    child->p_waited == 0 &&
    819 			    (child->p_slflag & PSL_TRACED ||
    820 			    options & WUNTRACED)) {
    821 				if ((options & WNOWAIT) == 0) {
    822 					child->p_waited = 1;
    823 					parent->p_nstopchild--;
    824 				}
    825 				break;
    826 			}
    827 			if (parent->p_nstopchild == 0 || child->p_pid == pid) {
    828 				child = NULL;
    829 				break;
    830 			}
    831 		}
    832 
    833 		if (child != NULL || error != 0 ||
    834 		    ((options & WNOHANG) != 0 && dead == NULL)) {
    835 		    	if (child != NULL) {
    836 			    	*status_p = child->p_xstat;
    837 			}
    838 			*child_p = child;
    839 			return error;
    840 		}
    841 
    842 		/*
    843 		 * Wait for another child process to stop.
    844 		 */
    845 		error = cv_wait_sig(&parent->p_waitcv, proc_lock);
    846 
    847 		if (error != 0) {
    848 			*child_p = NULL;
    849 			return error;
    850 		}
    851 	}
    852 }
    853 
    854 /*
    855  * Free a process after parent has taken all the state info.  Must be called
    856  * with the proclist lock held, and will release before returning.
    857  *
    858  * *ru is returned to the caller, and must be freed by the caller.
    859  */
    860 static void
    861 proc_free(struct proc *p, struct rusage *ru)
    862 {
    863 	struct proc *parent;
    864 	struct lwp *l;
    865 	ksiginfo_t ksi;
    866 	kauth_cred_t cred1, cred2;
    867 	uid_t uid;
    868 
    869 	KASSERT(mutex_owned(proc_lock));
    870 	KASSERT(p->p_nlwps == 1);
    871 	KASSERT(p->p_nzlwps == 1);
    872 	KASSERT(p->p_nrlwps == 0);
    873 	KASSERT(p->p_stat == SZOMB);
    874 
    875 	/*
    876 	 * If we got the child via ptrace(2) or procfs, and
    877 	 * the parent is different (meaning the process was
    878 	 * attached, rather than run as a child), then we need
    879 	 * to give it back to the old parent, and send the
    880 	 * parent the exit signal.  The rest of the cleanup
    881 	 * will be done when the old parent waits on the child.
    882 	 */
    883 	if ((p->p_slflag & PSL_TRACED) != 0) {
    884 		parent = p->p_pptr;
    885 		if (p->p_opptr != parent){
    886 			mutex_enter(p->p_lock);
    887 			p->p_slflag &= ~(PSL_TRACED|PSL_FSTRACE|PSL_SYSCALL);
    888 			mutex_exit(p->p_lock);
    889 			parent = p->p_opptr;
    890 			if (parent == NULL)
    891 				parent = initproc;
    892 			proc_reparent(p, parent);
    893 			p->p_opptr = NULL;
    894 			if (p->p_exitsig != 0) {
    895 				exit_psignal(p, parent, &ksi);
    896 				kpsignal(parent, &ksi, NULL);
    897 			}
    898 			cv_broadcast(&parent->p_waitcv);
    899 			mutex_exit(proc_lock);
    900 			return;
    901 		}
    902 	}
    903 
    904 	/*
    905 	 * Finally finished with old proc entry.  Unlink it from its process
    906 	 * group.
    907 	 */
    908 	leavepgrp(p);
    909 
    910 	parent = p->p_pptr;
    911 	sched_proc_exit(parent, p);
    912 
    913 	/*
    914 	 * Add child times of exiting process onto its own times.
    915 	 * This cannot be done any earlier else it might get done twice.
    916 	 */
    917 	l = LIST_FIRST(&p->p_lwps);
    918 	p->p_stats->p_ru.ru_nvcsw += (l->l_ncsw - l->l_nivcsw);
    919 	p->p_stats->p_ru.ru_nivcsw += l->l_nivcsw;
    920 	ruadd(&p->p_stats->p_ru, &l->l_ru);
    921 	ruadd(&p->p_stats->p_ru, &p->p_stats->p_cru);
    922 	ruadd(&parent->p_stats->p_cru, &p->p_stats->p_ru);
    923 	if (ru != NULL)
    924 		*ru = p->p_stats->p_ru;
    925 	p->p_xstat = 0;
    926 
    927 	/* Release any SA state. */
    928 #ifdef KERN_SA
    929 	if (p->p_sa)
    930 		sa_release(p);
    931 #endif
    932 
    933 	/*
    934 	 * At this point we are going to start freeing the final resources.
    935 	 * If anyone tries to access the proc structure after here they will
    936 	 * get a shock - bits are missing.  Attempt to make it hard!  We
    937 	 * don't bother with any further locking past this point.
    938 	 */
    939 	p->p_stat = SIDL;		/* not even a zombie any more */
    940 	LIST_REMOVE(p, p_list);	/* off zombproc */
    941 	parent = p->p_pptr;
    942 	p->p_pptr->p_nstopchild--;
    943 	LIST_REMOVE(p, p_sibling);
    944 
    945 	/*
    946 	 * Let pid be reallocated.
    947 	 */
    948 	proc_free_pid(p);
    949 	mutex_exit(proc_lock);
    950 
    951 	/*
    952 	 * Delay release until after lwp_free.
    953 	 */
    954 	cred2 = l->l_cred;
    955 
    956 	/*
    957 	 * Free the last LWP's resources.
    958 	 *
    959 	 * lwp_free ensures the LWP is no longer running on another CPU.
    960 	 */
    961 	lwp_free(l, false, true);
    962 
    963 	/*
    964 	 * Now no one except us can reach the process p.
    965 	 */
    966 
    967 	/*
    968 	 * Decrement the count of procs running with this uid.
    969 	 */
    970 	cred1 = p->p_cred;
    971 	uid = kauth_cred_getuid(cred1);
    972 	(void)chgproccnt(uid, -1);
    973 
    974 	/*
    975 	 * Release substructures.
    976 	 */
    977 
    978 	limfree(p->p_limit);
    979 	pstatsfree(p->p_stats);
    980 	kauth_cred_free(cred1);
    981 	kauth_cred_free(cred2);
    982 
    983 	/*
    984 	 * Release reference to text vnode
    985 	 */
    986 	if (p->p_textvp)
    987 		vrele(p->p_textvp);
    988 
    989 	mutex_destroy(&p->p_auxlock);
    990 	mutex_obj_free(p->p_lock);
    991 	mutex_destroy(&p->p_stmutex);
    992 	cv_destroy(&p->p_waitcv);
    993 	cv_destroy(&p->p_lwpcv);
    994 	rw_destroy(&p->p_reflock);
    995 
    996 	proc_free_mem(p);
    997 }
    998 
    999 /*
   1000  * make process 'parent' the new parent of process 'child'.
   1001  *
   1002  * Must be called with proc_lock held.
   1003  */
   1004 void
   1005 proc_reparent(struct proc *child, struct proc *parent)
   1006 {
   1007 
   1008 	KASSERT(mutex_owned(proc_lock));
   1009 
   1010 	if (child->p_pptr == parent)
   1011 		return;
   1012 
   1013 	if (child->p_stat == SZOMB ||
   1014 	    (child->p_stat == SSTOP && !child->p_waited)) {
   1015 		child->p_pptr->p_nstopchild--;
   1016 		parent->p_nstopchild++;
   1017 	}
   1018 	if (parent == initproc)
   1019 		child->p_exitsig = SIGCHLD;
   1020 
   1021 	LIST_REMOVE(child, p_sibling);
   1022 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
   1023 	child->p_pptr = parent;
   1024 	child->p_ppid = parent->p_pid;
   1025 }
   1026