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