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