Home | History | Annotate | Line # | Download | only in kern
kern_exit.c revision 1.297
      1 /*	$NetBSD: kern_exit.c,v 1.297 2023/10/04 20:48:13 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999, 2006, 2007, 2008, 2020, 2023
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
     10  * NASA Ames Research Center, and by Andrew Doran.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 
     34 /*
     35  * Copyright (c) 1982, 1986, 1989, 1991, 1993
     36  *	The Regents of the University of California.  All rights reserved.
     37  * (c) UNIX System Laboratories, Inc.
     38  * All or some portions of this file are derived from material licensed
     39  * to the University of California by American Telephone and Telegraph
     40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     41  * the permission of UNIX System Laboratories, Inc.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. Neither the name of the University nor the names of its contributors
     52  *    may be used to endorse or promote products derived from this software
     53  *    without specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  *
     67  *	@(#)kern_exit.c	8.10 (Berkeley) 2/23/95
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 __KERNEL_RCSID(0, "$NetBSD: kern_exit.c,v 1.297 2023/10/04 20:48:13 ad Exp $");
     72 
     73 #include "opt_ktrace.h"
     74 #include "opt_dtrace.h"
     75 #include "opt_sysv.h"
     76 
     77 #include <sys/param.h>
     78 #include <sys/systm.h>
     79 #include <sys/ioctl.h>
     80 #include <sys/tty.h>
     81 #include <sys/time.h>
     82 #include <sys/resource.h>
     83 #include <sys/kernel.h>
     84 #include <sys/proc.h>
     85 #include <sys/buf.h>
     86 #include <sys/wait.h>
     87 #include <sys/file.h>
     88 #include <sys/fstrans.h>
     89 #include <sys/vnode.h>
     90 #include <sys/syslog.h>
     91 #include <sys/pool.h>
     92 #include <sys/uidinfo.h>
     93 #include <sys/ptrace.h>
     94 #include <sys/acct.h>
     95 #include <sys/filedesc.h>
     96 #include <sys/ras.h>
     97 #include <sys/signalvar.h>
     98 #include <sys/sched.h>
     99 #include <sys/mount.h>
    100 #include <sys/syscallargs.h>
    101 #include <sys/kauth.h>
    102 #include <sys/sleepq.h>
    103 #include <sys/lock.h>
    104 #include <sys/lockdebug.h>
    105 #include <sys/ktrace.h>
    106 #include <sys/cpu.h>
    107 #include <sys/lwpctl.h>
    108 #include <sys/atomic.h>
    109 #include <sys/sdt.h>
    110 #include <sys/psref.h>
    111 
    112 #include <uvm/uvm_extern.h>
    113 
    114 #ifdef DEBUG_EXIT
    115 int debug_exit = 0;
    116 #define DPRINTF(x) if (debug_exit) printf x
    117 #else
    118 #define DPRINTF(x)
    119 #endif
    120 
    121 static int find_stopped_child(struct proc *, idtype_t, id_t, int,
    122     struct proc **, struct wrusage *, siginfo_t *);
    123 static void proc_free(struct proc *, struct wrusage *);
    124 
    125 /*
    126  * DTrace SDT provider definitions
    127  */
    128 SDT_PROVIDER_DECLARE(proc);
    129 SDT_PROBE_DEFINE1(proc, kernel, , exit, "int");
    130 
    131 /*
    132  * Fill in the appropriate signal information, and signal the parent.
    133  */
    134 /* XXX noclone works around a gcc 4.5 bug on arm */
    135 static void __noclone
    136 exit_psignal(struct proc *p, struct proc *pp, ksiginfo_t *ksi)
    137 {
    138 
    139 	KSI_INIT(ksi);
    140 	if ((ksi->ksi_signo = P_EXITSIG(p)) == SIGCHLD) {
    141 		if (p->p_xsig) {
    142 			if (p->p_sflag & PS_COREDUMP)
    143 				ksi->ksi_code = CLD_DUMPED;
    144 			else
    145 				ksi->ksi_code = CLD_KILLED;
    146 			ksi->ksi_status = p->p_xsig;
    147 		} else {
    148 			ksi->ksi_code = CLD_EXITED;
    149 			ksi->ksi_status = p->p_xexit;
    150 		}
    151 	} else {
    152 		ksi->ksi_code = SI_USER;
    153 		ksi->ksi_status = p->p_xsig;
    154 	}
    155 	/*
    156 	 * We fill those in, even for non-SIGCHLD.
    157 	 * It's safe to access p->p_cred unlocked here.
    158 	 */
    159 	ksi->ksi_pid = p->p_pid;
    160 	ksi->ksi_uid = kauth_cred_geteuid(p->p_cred);
    161 	/* XXX: is this still valid? */
    162 	ksi->ksi_utime = p->p_stats->p_ru.ru_utime.tv_sec;
    163 	ksi->ksi_stime = p->p_stats->p_ru.ru_stime.tv_sec;
    164 }
    165 
    166 /*
    167  * exit --
    168  *	Death of process.
    169  */
    170 int
    171 sys_exit(struct lwp *l, const struct sys_exit_args *uap, register_t *retval)
    172 {
    173 	/* {
    174 		syscallarg(int)	rval;
    175 	} */
    176 	struct proc *p = l->l_proc;
    177 
    178 	/* Don't call exit1() multiple times in the same process. */
    179 	mutex_enter(p->p_lock);
    180 	if (p->p_sflag & PS_WEXIT) {
    181 		mutex_exit(p->p_lock);
    182 		lwp_exit(l);
    183 	}
    184 
    185 	/* exit1() will release the mutex. */
    186 	exit1(l, SCARG(uap, rval), 0);
    187 	/* NOTREACHED */
    188 	return (0);
    189 }
    190 
    191 /*
    192  * Exit: deallocate address space and other resources, change proc state
    193  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
    194  * status and rusage for wait().  Check for child processes and orphan them.
    195  *
    196  * Must be called with p->p_lock held.  Does not return.
    197  */
    198 void
    199 exit1(struct lwp *l, int exitcode, int signo)
    200 {
    201 	struct proc	*p, *child, *next_child, *old_parent, *new_parent;
    202 	struct pgrp	*pgrp;
    203 	ksiginfo_t	ksi;
    204 	ksiginfoq_t	kq;
    205 	int		wakeinit;
    206 
    207 	p = l->l_proc;
    208 
    209 	/* Verify that we hold no locks other than p->p_lock. */
    210 	LOCKDEBUG_BARRIER(p->p_lock, 0);
    211 
    212 	/* XXX Temporary: something is leaking kernel_lock. */
    213 	KERNEL_UNLOCK_ALL(l, NULL);
    214 
    215 	KASSERT(mutex_owned(p->p_lock));
    216 	KASSERT(p->p_vmspace != NULL);
    217 
    218 	if (__predict_false(p == initproc)) {
    219 		panic("init died (signal %d, exit %d)", signo, exitcode);
    220 	}
    221 
    222 	p->p_sflag |= PS_WEXIT;
    223 
    224 	/*
    225 	 * Force all other LWPs to exit before we do.  Only then can we
    226 	 * begin to tear down the rest of the process state.
    227 	 */
    228 	if (p->p_nlwps > 1) {
    229 		exit_lwps(l);
    230 	}
    231 
    232 	ksiginfo_queue_init(&kq);
    233 
    234 	/*
    235 	 * If we have been asked to stop on exit, do so now.
    236 	 */
    237 	if (__predict_false(p->p_sflag & PS_STOPEXIT)) {
    238 		KASSERT(l->l_blcnt == 0);
    239 		sigclearall(p, &contsigmask, &kq);
    240 
    241 		if (!mutex_tryenter(&proc_lock)) {
    242 			mutex_exit(p->p_lock);
    243 			mutex_enter(&proc_lock);
    244 			mutex_enter(p->p_lock);
    245 		}
    246 		p->p_waited = 0;
    247 		p->p_pptr->p_nstopchild++;
    248 		p->p_stat = SSTOP;
    249 		mutex_exit(&proc_lock);
    250 		lwp_lock(l);
    251 		p->p_nrlwps--;
    252 		l->l_stat = LSSTOP;
    253 		lwp_unlock(l);
    254 		mutex_exit(p->p_lock);
    255 		lwp_lock(l);
    256 		spc_lock(l->l_cpu);
    257 		mi_switch(l);
    258 		mutex_enter(p->p_lock);
    259 	}
    260 
    261 	/*
    262 	 * Bin any remaining signals and mark the process as dying so it will
    263 	 * not be found for, e.g. signals.
    264 	 */
    265 	sigfillset(&p->p_sigctx.ps_sigignore);
    266 	sigclearall(p, NULL, &kq);
    267 	p->p_stat = SDYING;
    268 
    269 	/*
    270 	 * Perform any required thread cleanup.  Do this early so
    271 	 * anyone wanting to look us up by our global thread ID
    272 	 * will fail to find us.
    273 	 *
    274 	 * N.B. this will unlock p->p_lock on our behalf.
    275 	 */
    276 	lwp_thread_cleanup(l);
    277 
    278 	ksiginfo_queue_drain(&kq);
    279 
    280 	/* Destroy any lwpctl info. */
    281 	if (p->p_lwpctl != NULL)
    282 		lwp_ctl_exit();
    283 
    284 	/*
    285 	 * Drain all remaining references that procfs, ptrace and others may
    286 	 * have on the process.
    287 	 */
    288 	rw_enter(&p->p_reflock, RW_WRITER);
    289 
    290 	DPRINTF(("%s: %d.%d exiting.\n", __func__, p->p_pid, l->l_lid));
    291 
    292 	ptimers_free(p, TIMERS_ALL);
    293 #if defined(__HAVE_RAS)
    294 	ras_purgeall();
    295 #endif
    296 
    297 	/*
    298 	 * Close open files, release open-file table and free signal
    299 	 * actions.  This may block!
    300 	 */
    301 	fd_free();
    302 	cwdfree(p->p_cwdi);
    303 	p->p_cwdi = NULL;
    304 	doexithooks(p);
    305 	sigactsfree(p->p_sigacts);
    306 
    307 	/*
    308 	 * Write out accounting data.
    309 	 */
    310 	(void)acct_process(l);
    311 
    312 #ifdef KTRACE
    313 	/*
    314 	 * Release trace file.
    315 	 */
    316 	if (p->p_tracep != NULL) {
    317 		mutex_enter(&ktrace_lock);
    318 		ktrderef(p);
    319 		mutex_exit(&ktrace_lock);
    320 	}
    321 #endif
    322 
    323 	p->p_xexit = exitcode;
    324 	p->p_xsig = signo;
    325 
    326 	/*
    327 	 * If emulation has process exit hook, call it now.
    328 	 * Set the exit status now so that the exit hook has
    329 	 * an opportunity to tweak it (COMPAT_LINUX requires
    330 	 * this for thread group emulation)
    331 	 */
    332 	if (p->p_emul->e_proc_exit)
    333 		(*p->p_emul->e_proc_exit)(p);
    334 
    335 	/*
    336 	 * Free the VM resources we're still holding on to.
    337 	 * We must do this from a valid thread because doing
    338 	 * so may block. This frees vmspace, which we don't
    339 	 * need anymore. The only remaining lwp is the one
    340 	 * we run at this moment, nothing runs in userland
    341 	 * anymore.
    342 	 */
    343 	ruspace(p);	/* Update our vm resource use */
    344 	uvm_proc_exit(p);
    345 
    346 	/*
    347 	 * Stop profiling.
    348 	 */
    349 	if (__predict_false((p->p_stflag & PST_PROFIL) != 0)) {
    350 		mutex_spin_enter(&p->p_stmutex);
    351 		stopprofclock(p);
    352 		mutex_spin_exit(&p->p_stmutex);
    353 	}
    354 
    355 	/*
    356 	 * If parent is waiting for us to exit or exec, PL_PPWAIT is set; we
    357 	 * wake up the parent early to avoid deadlock.  We can do this once
    358 	 * the VM resources are released.
    359 	 */
    360 	mutex_enter(&proc_lock);
    361 	if (p->p_lflag & PL_PPWAIT) {
    362 		lwp_t *lp;
    363 
    364 		l->l_lwpctl = NULL; /* was on loan from blocked parent */
    365 		p->p_lflag &= ~PL_PPWAIT;
    366 
    367 		lp = p->p_vforklwp;
    368 		p->p_vforklwp = NULL;
    369 		lp->l_vforkwaiting = false;
    370 		cv_broadcast(&lp->l_waitcv);
    371 	}
    372 
    373 	if (SESS_LEADER(p)) {
    374 		struct vnode *vprele = NULL, *vprevoke = NULL;
    375 		struct session *sp = p->p_session;
    376 		struct tty *tp;
    377 
    378 		if (sp->s_ttyvp) {
    379 			/*
    380 			 * Controlling process.
    381 			 * Signal foreground pgrp,
    382 			 * drain controlling terminal
    383 			 * and revoke access to controlling terminal.
    384 			 */
    385 			tp = sp->s_ttyp;
    386 			mutex_spin_enter(&tty_lock);
    387 			if (tp->t_session == sp) {
    388 				/* we can't guarantee the revoke will do this */
    389 				pgrp = tp->t_pgrp;
    390 				tp->t_pgrp = NULL;
    391 				tp->t_session = NULL;
    392 				mutex_spin_exit(&tty_lock);
    393 				if (pgrp != NULL) {
    394 					pgsignal(pgrp, SIGHUP, 1);
    395 				}
    396 				mutex_exit(&proc_lock);
    397 				(void) ttywait(tp);
    398 				mutex_enter(&proc_lock);
    399 
    400 				/* The tty could have been revoked. */
    401 				vprevoke = sp->s_ttyvp;
    402 			} else
    403 				mutex_spin_exit(&tty_lock);
    404 			vprele = sp->s_ttyvp;
    405 			sp->s_ttyvp = NULL;
    406 			/*
    407 			 * s_ttyp is not zero'd; we use this to indicate
    408 			 * that the session once had a controlling terminal.
    409 			 * (for logging and informational purposes)
    410 			 */
    411 		}
    412 		sp->s_leader = NULL;
    413 
    414 		if (vprevoke != NULL || vprele != NULL) {
    415 			if (vprevoke != NULL) {
    416 				/* Releases proc_lock. */
    417 				proc_sessrele(sp);
    418 				VOP_REVOKE(vprevoke, REVOKEALL);
    419 			} else
    420 				mutex_exit(&proc_lock);
    421 			if (vprele != NULL)
    422 				vrele(vprele);
    423 			mutex_enter(&proc_lock);
    424 		}
    425 	}
    426 	fixjobc(p, p->p_pgrp, 0);
    427 
    428 	/* Release fstrans private data. */
    429 	fstrans_lwp_dtor(l);
    430 
    431 	/*
    432 	 * Finalize the last LWP's specificdata, as well as the
    433 	 * specificdata for the proc itself.
    434 	 */
    435 	lwp_finispecific(l);
    436 	proc_finispecific(p);
    437 
    438 	/*
    439 	 * Reset p_opptr pointer of all former children which got
    440 	 * traced by another process and were reparented. We reset
    441 	 * it to NULL here; the trace detach code then reparents
    442 	 * the child to initproc. We only check allproc list, since
    443 	 * eventual former children on zombproc list won't reference
    444 	 * p_opptr anymore.
    445 	 */
    446 	if (__predict_false(p->p_slflag & PSL_CHTRACED)) {
    447 		struct proc *q;
    448 		PROCLIST_FOREACH(q, &allproc) {
    449 			if (q->p_opptr == p)
    450 				q->p_opptr = NULL;
    451 		}
    452 		PROCLIST_FOREACH(q, &zombproc) {
    453 			if (q->p_opptr == p)
    454 				q->p_opptr = NULL;
    455 		}
    456 	}
    457 
    458 	/*
    459 	 * Give orphaned children to init(8).
    460 	 */
    461 	child = LIST_FIRST(&p->p_children);
    462 	wakeinit = (child != NULL);
    463 	for (; child != NULL; child = next_child) {
    464 		next_child = LIST_NEXT(child, p_sibling);
    465 
    466 		/*
    467 		 * Traced processes are killed since their existence
    468 		 * means someone is screwing up. Since we reset the
    469 		 * trace flags, the logic in sys_wait4() would not be
    470 		 * triggered to reparent the process to its
    471 		 * original parent, so we must do this here.
    472 		 */
    473 		if (__predict_false(child->p_slflag & PSL_TRACED)) {
    474 			mutex_enter(p->p_lock);
    475 			child->p_slflag &=
    476 			    ~(PSL_TRACED|PSL_SYSCALL);
    477 			mutex_exit(p->p_lock);
    478 			if (child->p_opptr != child->p_pptr) {
    479 				struct proc *t = child->p_opptr;
    480 				proc_reparent(child, t ? t : initproc);
    481 				child->p_opptr = NULL;
    482 			} else
    483 				proc_reparent(child, initproc);
    484 			killproc(child, "orphaned traced process");
    485 		} else
    486 			proc_reparent(child, initproc);
    487 	}
    488 
    489 	/*
    490 	 * Move proc from allproc to zombproc, it's now nearly ready to be
    491 	 * collected by parent.
    492 	 */
    493 	LIST_REMOVE(l, l_list);
    494 	LIST_REMOVE(p, p_list);
    495 	LIST_INSERT_HEAD(&zombproc, p, p_list);
    496 
    497 	/*
    498 	 * Mark the process as dead.  We must do this before we signal
    499 	 * the parent.
    500 	 */
    501 	p->p_stat = SDEAD;
    502 
    503 	/*
    504 	 * Let anyone watching this DTrace probe know what we're
    505 	 * on our way out.
    506 	 */
    507 	SDT_PROBE(proc, kernel, , exit,
    508 		((p->p_sflag & PS_COREDUMP) ? CLD_DUMPED :
    509 		 (p->p_xsig ? CLD_KILLED : CLD_EXITED)),
    510 		0,0,0,0);
    511 
    512 	/* Put in front of parent's sibling list for parent to collect it */
    513 	old_parent = p->p_pptr;
    514 	old_parent->p_nstopchild++;
    515 	if (LIST_FIRST(&old_parent->p_children) != p) {
    516 		/* Put child where it can be found quickly */
    517 		LIST_REMOVE(p, p_sibling);
    518 		LIST_INSERT_HEAD(&old_parent->p_children, p, p_sibling);
    519 	}
    520 
    521 	/*
    522 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
    523 	 * flag set, notify init instead (and hope it will handle
    524 	 * this situation).
    525 	 */
    526 	if (old_parent->p_flag & (PK_NOCLDWAIT|PK_CLDSIGIGN)) {
    527 		proc_reparent(p, initproc);
    528 		wakeinit = 1;
    529 
    530 		/*
    531 		 * If this was the last child of our parent, notify
    532 		 * parent, so in case he was wait(2)ing, he will
    533 		 * continue.
    534 		 */
    535 		if (LIST_FIRST(&old_parent->p_children) == NULL)
    536 			cv_broadcast(&old_parent->p_waitcv);
    537 	}
    538 
    539 	/* Reload parent pointer, since p may have been reparented above */
    540 	new_parent = p->p_pptr;
    541 
    542 	if (__predict_false(p->p_exitsig != 0)) {
    543 		exit_psignal(p, new_parent, &ksi);
    544 		kpsignal(new_parent, &ksi, NULL);
    545 	}
    546 
    547 	/* Calculate the final rusage info.  */
    548 	calcru(p, &p->p_stats->p_ru.ru_utime, &p->p_stats->p_ru.ru_stime,
    549 	    NULL, NULL);
    550 
    551 	if (wakeinit)
    552 		cv_broadcast(&initproc->p_waitcv);
    553 
    554 	callout_destroy(&l->l_timeout_ch);
    555 
    556 	/*
    557 	 * Release any PCU resources before becoming a zombie.
    558 	 */
    559 	pcu_discard_all(l);
    560 
    561 	mutex_enter(p->p_lock);
    562 	/*
    563 	 * Notify other processes tracking us with a knote that
    564 	 * we're exiting.
    565 	 *
    566 	 * N.B. we do this here because the process is now SDEAD,
    567 	 * and thus cannot have any more knotes attached.  Also,
    568 	 * knote_proc_exit() expects that p->p_lock is already
    569 	 * held (and will assert so).
    570 	 */
    571 	if (!SLIST_EMPTY(&p->p_klist)) {
    572 		knote_proc_exit(p);
    573 	}
    574 
    575 	/* Free the LWP ID */
    576 	proc_free_lwpid(p, l->l_lid);
    577 	lwp_drainrefs(l);
    578 	lwp_lock(l);
    579 	l->l_prflag &= ~LPR_DETACHED;
    580 	l->l_stat = LSZOMB;
    581 	lwp_unlock(l);
    582 	KASSERT(curlwp == l);
    583 	KASSERT(p->p_nrlwps == 1);
    584 	KASSERT(p->p_nlwps == 1);
    585 	p->p_stat = SZOMB;
    586 	p->p_nrlwps--;
    587 	p->p_nzlwps++;
    588 	p->p_ndlwps = 0;
    589 	mutex_exit(p->p_lock);
    590 
    591 	/*
    592 	 * Signal the parent to collect us, and drop the proclist lock.
    593 	 * Drop debugger/procfs lock; no new references can be gained.
    594 	 */
    595 	cv_broadcast(&p->p_pptr->p_waitcv);
    596 	rw_exit(&p->p_reflock);
    597 	mutex_exit(&proc_lock);
    598 
    599 	/*
    600 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
    601 	 */
    602 
    603 	/*
    604 	 * Give machine-dependent code a chance to free any MD LWP
    605 	 * resources.  This must be done before uvm_lwp_exit(), in
    606 	 * case these resources are in the PCB.
    607 	 */
    608 	cpu_lwp_free(l, 1);
    609 
    610 	/* Switch away into oblivion. */
    611 	lwp_lock(l);
    612 	spc_lock(l->l_cpu);
    613 	mi_switch(l);
    614 	panic("exit1");
    615 }
    616 
    617 void
    618 exit_lwps(struct lwp *l)
    619 {
    620 	proc_t *p = l->l_proc;
    621 	lwp_t *l2;
    622 
    623 retry:
    624 	KASSERT(mutex_owned(p->p_lock));
    625 
    626 	/*
    627 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
    628 	 * LWPs and then wait for everyone else to finish.
    629 	 */
    630 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    631 		if (l2 == l)
    632 			continue;
    633 		lwp_lock(l2);
    634 		l2->l_flag |= LW_WEXIT;
    635 		lwp_need_userret(l2);
    636 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & LW_SINTR)) ||
    637 		    l2->l_stat == LSSUSPENDED || l2->l_stat == LSSTOP) {
    638 			l2->l_flag &= ~LW_DBGSUSPEND;
    639 		    	/* setrunnable() will release the lock. */
    640 			setrunnable(l2);
    641 			continue;
    642 		}
    643 		lwp_unlock(l2);
    644 	}
    645 
    646 	/*
    647 	 * Wait for every LWP to exit.  Note: LWPs can get suspended/slept
    648 	 * behind us or there may even be new LWPs created.  Therefore, a
    649 	 * full retry is required on error.
    650 	 */
    651 	while (p->p_nlwps > 1) {
    652 		if (lwp_wait(l, 0, NULL, true)) {
    653 			goto retry;
    654 		}
    655 	}
    656 
    657 	KASSERT(p->p_nlwps == 1);
    658 }
    659 
    660 int
    661 do_sys_waitid(idtype_t idtype, id_t id, int *pid, int *status, int options,
    662     struct wrusage *wru, siginfo_t *si)
    663 {
    664 	proc_t *child;
    665 	int error;
    666 
    667 
    668 	if (wru != NULL)
    669 		memset(wru, 0, sizeof(*wru));
    670 	if (si != NULL)
    671 		memset(si, 0, sizeof(*si));
    672 
    673 	mutex_enter(&proc_lock);
    674 	error = find_stopped_child(curproc, idtype, id, options, &child,
    675 	    wru, si);
    676 	if (child == NULL) {
    677 		mutex_exit(&proc_lock);
    678 		*pid = 0;
    679 		*status = 0;
    680 		return error;
    681 	}
    682 	*pid = child->p_pid;
    683 
    684 	if (child->p_stat == SZOMB) {
    685 		/* Child is exiting */
    686 		*status = P_WAITSTATUS(child);
    687 		/* proc_free() will release the proc_lock. */
    688 		if (options & WNOWAIT) {
    689 			mutex_exit(&proc_lock);
    690 		} else {
    691 			proc_free(child, wru);
    692 		}
    693 	} else {
    694 		/* Don't mark SIGCONT if we are being stopped */
    695 		*status = (child->p_xsig == SIGCONT && child->p_stat != SSTOP) ?
    696 		    W_CONTCODE() : W_STOPCODE(child->p_xsig);
    697 		mutex_exit(&proc_lock);
    698 	}
    699 	return 0;
    700 }
    701 
    702 int
    703 do_sys_wait(int *pid, int *status, int options, struct rusage *ru)
    704 {
    705 	idtype_t idtype;
    706 	id_t id;
    707 	int ret;
    708 	struct wrusage wru;
    709 
    710 	/*
    711 	 * Translate the special pid values into the (idtype, pid)
    712 	 * pair for wait6. The WAIT_MYPGRP case is handled by
    713 	 * find_stopped_child() on its own.
    714 	 */
    715 	if (*pid == WAIT_ANY) {
    716 		idtype = P_ALL;
    717 		id = 0;
    718 	} else if (*pid < 0) {
    719 		idtype = P_PGID;
    720 		id = (id_t)-*pid;
    721 	} else {
    722 		idtype = P_PID;
    723 		id = (id_t)*pid;
    724 	}
    725 	options |= WEXITED | WTRAPPED;
    726 	ret = do_sys_waitid(idtype, id, pid, status, options, ru ? &wru : NULL,
    727 	    NULL);
    728 	if (ru)
    729 		*ru = wru.wru_self;
    730 	return ret;
    731 }
    732 
    733 int
    734 sys___wait450(struct lwp *l, const struct sys___wait450_args *uap,
    735     register_t *retval)
    736 {
    737 	/* {
    738 		syscallarg(int)			pid;
    739 		syscallarg(int *)		status;
    740 		syscallarg(int)			options;
    741 		syscallarg(struct rusage *)	rusage;
    742 	} */
    743 	int error, status, pid = SCARG(uap, pid);
    744 	struct rusage ru;
    745 
    746 	error = do_sys_wait(&pid, &status, SCARG(uap, options),
    747 	    SCARG(uap, rusage) != NULL ? &ru : NULL);
    748 
    749 	retval[0] = pid;
    750 	if (pid == 0) {
    751 		return error;
    752 	}
    753 	if (SCARG(uap, status)) {
    754 		error = copyout(&status, SCARG(uap, status), sizeof(status));
    755 	}
    756 	if (SCARG(uap, rusage) && error == 0) {
    757 		error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
    758 	}
    759 	return error;
    760 }
    761 
    762 int
    763 sys_wait6(struct lwp *l, const struct sys_wait6_args *uap, register_t *retval)
    764 {
    765 	/* {
    766 		syscallarg(idtype_t)		idtype;
    767 		syscallarg(id_t)		id;
    768 		syscallarg(int *)		status;
    769 		syscallarg(int)			options;
    770 		syscallarg(struct wrusage *)	wru;
    771 		syscallarg(siginfo_t *)		si;
    772 	} */
    773 	struct wrusage wru, *wrup;
    774 	siginfo_t si, *sip;
    775 	idtype_t idtype;
    776 	int pid;
    777 	id_t id;
    778 	int error, status;
    779 
    780 	idtype = SCARG(uap, idtype);
    781 	id = SCARG(uap, id);
    782 
    783 	if (SCARG(uap, wru) != NULL)
    784 		wrup = &wru;
    785 	else
    786 		wrup = NULL;
    787 
    788 	if (SCARG(uap, info) != NULL)
    789 		sip = &si;
    790 	else
    791 		sip = NULL;
    792 
    793 	/*
    794 	 *  We expect all callers of wait6() to know about WEXITED and
    795 	 *  WTRAPPED.
    796 	 */
    797 	error = do_sys_waitid(idtype, id, &pid, &status, SCARG(uap, options),
    798 	    wrup, sip);
    799 
    800 	retval[0] = pid; 	/* tell userland who it was */
    801 
    802 #if 0
    803 	/*
    804 	 * should we copyout if there was no process, hence no useful data?
    805 	 * We don't for an old style wait4() (etc) but I believe
    806 	 * FreeBSD does for wait6(), so a tossup...  Go with FreeBSD for now.
    807 	 */
    808 	if (pid == 0)
    809 		return error;
    810 #endif
    811 
    812 	if (SCARG(uap, status) != NULL && error == 0)
    813 		error = copyout(&status, SCARG(uap, status), sizeof(status));
    814 	if (SCARG(uap, wru) != NULL && error == 0)
    815 		error = copyout(&wru, SCARG(uap, wru), sizeof(wru));
    816 	if (SCARG(uap, info) != NULL && error == 0)
    817 		error = copyout(&si, SCARG(uap, info), sizeof(si));
    818 	return error;
    819 }
    820 
    821 
    822 /*
    823  * Find a process that matches the provided criteria, and fill siginfo
    824  * and resources if found.
    825  * Returns:
    826  *	-1: 	Not found, abort early
    827  *	 0:	Not matched
    828  *	 1:	Matched, there might be more matches
    829  *	 2:	This is the only match
    830  */
    831 static int
    832 match_process(const struct proc *pp, struct proc **q, idtype_t idtype, id_t id,
    833     int options, struct wrusage *wrusage, siginfo_t *siginfo)
    834 {
    835 	struct rusage *rup;
    836 	struct proc *p = *q;
    837 	int rv = 1;
    838 
    839 	switch (idtype) {
    840 	case P_ALL:
    841 		mutex_enter(p->p_lock);
    842 		break;
    843 	case P_PID:
    844 		if (p->p_pid != (pid_t)id) {
    845 			p = *q = proc_find_raw((pid_t)id);
    846 			if (p == NULL || p->p_stat == SIDL || p->p_pptr != pp) {
    847 				*q = NULL;
    848 				return -1;
    849 			}
    850 		}
    851 		mutex_enter(p->p_lock);
    852 		rv++;
    853 		break;
    854 	case P_PGID:
    855 		if (p->p_pgid != (pid_t)id)
    856 			return 0;
    857 		mutex_enter(p->p_lock);
    858 		break;
    859 	case P_SID:
    860 		if (p->p_session->s_sid != (pid_t)id)
    861 			return 0;
    862 		mutex_enter(p->p_lock);
    863 		break;
    864 	case P_UID:
    865 		mutex_enter(p->p_lock);
    866 		if (kauth_cred_geteuid(p->p_cred) != (uid_t)id) {
    867 			mutex_exit(p->p_lock);
    868 			return 0;
    869 		}
    870 		break;
    871 	case P_GID:
    872 		mutex_enter(p->p_lock);
    873 		if (kauth_cred_getegid(p->p_cred) != (gid_t)id) {
    874 			mutex_exit(p->p_lock);
    875 			return 0;
    876 		}
    877 		break;
    878 	case P_CID:
    879 	case P_PSETID:
    880 	case P_CPUID:
    881 		/* XXX: Implement me */
    882 	default:
    883 		return 0;
    884 	}
    885 
    886 	if ((options & WEXITED) == 0 && p->p_stat == SZOMB) {
    887 		mutex_exit(p->p_lock);
    888 		return 0;
    889 	}
    890 
    891 	if (siginfo != NULL) {
    892 		siginfo->si_errno = 0;
    893 
    894 		/*
    895 		 * SUSv4 requires that the si_signo value is always
    896 		 * SIGCHLD. Obey it despite the rfork(2) interface
    897 		 * allows to request other signal for child exit
    898 		 * notification.
    899 		 */
    900 		siginfo->si_signo = SIGCHLD;
    901 
    902 		/*
    903 		 *  This is still a rough estimate.  We will fix the
    904 		 *  cases TRAPPED, STOPPED, and CONTINUED later.
    905 		 */
    906 		if (p->p_sflag & PS_COREDUMP) {
    907 			siginfo->si_code = CLD_DUMPED;
    908 			siginfo->si_status = p->p_xsig;
    909 		} else if (p->p_xsig) {
    910 			siginfo->si_code = CLD_KILLED;
    911 			siginfo->si_status = p->p_xsig;
    912 		} else {
    913 			siginfo->si_code = CLD_EXITED;
    914 			siginfo->si_status = p->p_xexit;
    915 		}
    916 
    917 		siginfo->si_pid = p->p_pid;
    918 		siginfo->si_uid = kauth_cred_geteuid(p->p_cred);
    919 		siginfo->si_utime = p->p_stats->p_ru.ru_utime.tv_sec;
    920 		siginfo->si_stime = p->p_stats->p_ru.ru_stime.tv_sec;
    921 	}
    922 
    923 	/*
    924 	 * There should be no reason to limit resources usage info to
    925 	 * exited processes only.  A snapshot about any resources used
    926 	 * by a stopped process may be exactly what is needed.
    927 	 */
    928 	if (wrusage != NULL) {
    929 		rup = &wrusage->wru_self;
    930 		*rup = p->p_stats->p_ru;
    931 		calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
    932 
    933 		rup = &wrusage->wru_children;
    934 		*rup = p->p_stats->p_cru;
    935 		calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
    936 	}
    937 
    938 	mutex_exit(p->p_lock);
    939 	return rv;
    940 }
    941 
    942 /*
    943  * Determine if there are existing processes being debugged
    944  * that used to be (and sometime later will be again) children
    945  * of a specific parent (while matching wait criteria)
    946  */
    947 static bool
    948 debugged_child_exists(idtype_t idtype, id_t id, int options, siginfo_t *si,
    949     const struct proc *parent)
    950 {
    951 	struct proc *pp;
    952 
    953 	/*
    954 	 * If we are searching for a specific pid, we can optimise a little
    955 	 */
    956 	if (idtype == P_PID) {
    957 		/*
    958 		 * Check the specific process to see if its real parent is us
    959 		 */
    960 		pp = proc_find_raw((pid_t)id);
    961 		if (pp != NULL && pp->p_stat != SIDL && pp->p_opptr == parent) {
    962 			/*
    963 			 * using P_ALL here avoids match_process() doing the
    964 			 * same work that we just did, but incorrectly for
    965 			 * this scenario.
    966 			 */
    967 			if (match_process(parent, &pp, P_ALL, id, options,
    968 			    NULL, si))
    969 				return true;
    970 		}
    971 		return false;
    972 	}
    973 
    974 	/*
    975 	 * For the hard cases, just look everywhere to see if some
    976 	 * stolen (reparented) process is really our lost child.
    977 	 * Then check if that process could satisfy the wait conditions.
    978 	 */
    979 
    980 	/*
    981 	 * XXX inefficient, but hopefully fairly rare.
    982 	 * XXX should really use a list of reparented processes.
    983 	 */
    984 	PROCLIST_FOREACH(pp, &allproc) {
    985 		if (pp->p_stat == SIDL)		/* XXX impossible ?? */
    986 			continue;
    987 		if (pp->p_opptr == parent &&
    988 		    match_process(parent, &pp, idtype, id, options, NULL, si))
    989 			return true;
    990 	}
    991 	PROCLIST_FOREACH(pp, &zombproc) {
    992 		if (pp->p_stat == SIDL)		/* XXX impossible ?? */
    993 			continue;
    994 		if (pp->p_opptr == parent &&
    995 		    match_process(parent, &pp, idtype, id, options, NULL, si))
    996 			return true;
    997 	}
    998 
    999 	return false;
   1000 }
   1001 
   1002 /*
   1003  * Scan list of child processes for a child process that has stopped or
   1004  * exited.  Used by sys_wait4 and 'compat' equivalents.
   1005  *
   1006  * Must be called with the proc_lock held, and may release while waiting.
   1007  */
   1008 static int
   1009 find_stopped_child(struct proc *parent, idtype_t idtype, id_t id, int options,
   1010     struct proc **child_p, struct wrusage *wru, siginfo_t *si)
   1011 {
   1012 	struct proc *child, *dead;
   1013 	int error;
   1014 
   1015 	KASSERT(mutex_owned(&proc_lock));
   1016 
   1017 	if (options & ~WALLOPTS) {
   1018 		*child_p = NULL;
   1019 		return EINVAL;
   1020 	}
   1021 
   1022 	if ((options & WSELECTOPTS) == 0) {
   1023 		/*
   1024 		 * We will be unable to find any matching processes,
   1025 		 * because there are no known events to look for.
   1026 		 * Prefer to return error instead of blocking
   1027 		 * indefinitely.
   1028 		 */
   1029 		*child_p = NULL;
   1030 		return EINVAL;
   1031 	}
   1032 
   1033 	if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
   1034 		id = (id_t)parent->p_pgid;
   1035 		idtype = P_PGID;
   1036 	}
   1037 
   1038 	for (;;) {
   1039 		error = ECHILD;
   1040 		dead = NULL;
   1041 
   1042 		LIST_FOREACH(child, &parent->p_children, p_sibling) {
   1043 			int rv = match_process(parent, &child, idtype, id,
   1044 			    options, wru, si);
   1045 			if (rv == -1)
   1046 				break;
   1047 			if (rv == 0)
   1048 				continue;
   1049 
   1050 			/*
   1051 			 * Wait for processes with p_exitsig != SIGCHLD
   1052 			 * processes only if WALTSIG is set; wait for
   1053 			 * processes with p_exitsig == SIGCHLD only
   1054 			 * if WALTSIG is clear.
   1055 			 */
   1056 			if (((options & WALLSIG) == 0) &&
   1057 			    (options & WALTSIG ? child->p_exitsig == SIGCHLD
   1058 						: P_EXITSIG(child) != SIGCHLD)){
   1059 				if (rv == 2) {
   1060 					child = NULL;
   1061 					break;
   1062 				}
   1063 				continue;
   1064 			}
   1065 
   1066 			error = 0;
   1067 			if ((options & WNOZOMBIE) == 0) {
   1068 				if (child->p_stat == SZOMB)
   1069 					break;
   1070 				if (child->p_stat == SDEAD) {
   1071 					/*
   1072 					 * We may occasionally arrive here
   1073 					 * after receiving a signal, but
   1074 					 * immediately before the child
   1075 					 * process is zombified.  The wait
   1076 					 * will be short, so avoid returning
   1077 					 * to userspace.
   1078 					 */
   1079 					dead = child;
   1080 				}
   1081 			}
   1082 
   1083 			if ((options & WCONTINUED) != 0 &&
   1084 			    child->p_xsig == SIGCONT &&
   1085 			    (child->p_sflag & PS_CONTINUED)) {
   1086 				if ((options & WNOWAIT) == 0) {
   1087 					child->p_sflag &= ~PS_CONTINUED;
   1088 					child->p_waited = 1;
   1089 					parent->p_nstopchild--;
   1090 				}
   1091 				if (si) {
   1092 					si->si_status = child->p_xsig;
   1093 					si->si_code = CLD_CONTINUED;
   1094 				}
   1095 				break;
   1096 			}
   1097 
   1098 			if ((options & (WTRAPPED|WSTOPPED)) != 0 &&
   1099 			    child->p_stat == SSTOP &&
   1100 			    child->p_waited == 0 &&
   1101 			    ((child->p_slflag & PSL_TRACED) ||
   1102 			    options & (WUNTRACED|WSTOPPED))) {
   1103 				if ((options & WNOWAIT) == 0) {
   1104 					child->p_waited = 1;
   1105 					parent->p_nstopchild--;
   1106 				}
   1107 				if (si) {
   1108 					si->si_status = child->p_xsig;
   1109 					si->si_code =
   1110 					    (child->p_slflag & PSL_TRACED) ?
   1111 					    CLD_TRAPPED : CLD_STOPPED;
   1112 				}
   1113 				break;
   1114 			}
   1115 			if (parent->p_nstopchild == 0 || rv == 2) {
   1116 				child = NULL;
   1117 				break;
   1118 			}
   1119 		}
   1120 
   1121 		/*
   1122 		 * If we found nothing, but we are the bereaved parent
   1123 		 * of a stolen child, look and see if that child (or
   1124 		 * one of them) meets our search criteria.   If so, then
   1125 		 * we cannot succeed, but we can hang (wait...),
   1126 		 * or if WNOHANG, return 0 instead of ECHILD
   1127 		 */
   1128 		if (child == NULL && error == ECHILD &&
   1129 		    (parent->p_slflag & PSL_CHTRACED) &&
   1130 		    debugged_child_exists(idtype, id, options, si, parent))
   1131 			error = 0;
   1132 
   1133 		if (child != NULL || error != 0 ||
   1134 		    ((options & WNOHANG) != 0 && dead == NULL)) {
   1135 			*child_p = child;
   1136 			return error;
   1137 		}
   1138 
   1139 		/*
   1140 		 * Wait for another child process to stop.
   1141 		 */
   1142 		error = cv_wait_sig(&parent->p_waitcv, &proc_lock);
   1143 
   1144 		if (error != 0) {
   1145 			*child_p = NULL;
   1146 			return error;
   1147 		}
   1148 	}
   1149 }
   1150 
   1151 /*
   1152  * Free a process after parent has taken all the state info.  Must be called
   1153  * with the proclist lock held, and will release before returning.
   1154  *
   1155  * *ru is returned to the caller, and must be freed by the caller.
   1156  */
   1157 static void
   1158 proc_free(struct proc *p, struct wrusage *wru)
   1159 {
   1160 	struct proc *parent = p->p_pptr;
   1161 	struct lwp *l;
   1162 	ksiginfo_t ksi;
   1163 	kauth_cred_t cred1, cred2;
   1164 	uid_t uid;
   1165 
   1166 	KASSERT(mutex_owned(&proc_lock));
   1167 	KASSERT(p->p_nlwps == 1);
   1168 	KASSERT(p->p_nzlwps == 1);
   1169 	KASSERT(p->p_nrlwps == 0);
   1170 	KASSERT(p->p_stat == SZOMB);
   1171 
   1172 	/*
   1173 	 * If we got the child via ptrace(2) or procfs, and
   1174 	 * the parent is different (meaning the process was
   1175 	 * attached, rather than run as a child), then we need
   1176 	 * to give it back to the old parent, and send the
   1177 	 * parent the exit signal.  The rest of the cleanup
   1178 	 * will be done when the old parent waits on the child.
   1179 	 */
   1180 	if ((p->p_slflag & PSL_TRACED) != 0 && p->p_opptr != parent) {
   1181 		mutex_enter(p->p_lock);
   1182 		p->p_slflag &= ~(PSL_TRACED|PSL_SYSCALL);
   1183 		mutex_exit(p->p_lock);
   1184 		parent = (p->p_opptr == NULL) ? initproc : p->p_opptr;
   1185 		proc_reparent(p, parent);
   1186 		p->p_opptr = NULL;
   1187 		if (p->p_exitsig != 0) {
   1188 			exit_psignal(p, parent, &ksi);
   1189 			kpsignal(parent, &ksi, NULL);
   1190 		}
   1191 		cv_broadcast(&parent->p_waitcv);
   1192 		mutex_exit(&proc_lock);
   1193 		return;
   1194 	}
   1195 
   1196 	sched_proc_exit(parent, p);
   1197 
   1198 	/*
   1199 	 * Add child times of exiting process onto its own times.
   1200 	 * This cannot be done any earlier else it might get done twice.
   1201 	 */
   1202 	l = LIST_FIRST(&p->p_lwps);
   1203 	ruadd(&p->p_stats->p_ru, &l->l_ru);
   1204 	ruadd(&p->p_stats->p_ru, &p->p_stats->p_cru);
   1205 	ruadd(&parent->p_stats->p_cru, &p->p_stats->p_ru);
   1206 	if (wru != NULL) {
   1207 		wru->wru_self = p->p_stats->p_ru;
   1208 		wru->wru_children = p->p_stats->p_cru;
   1209 	}
   1210 	p->p_xsig = 0;
   1211 	p->p_xexit = 0;
   1212 
   1213 	/*
   1214 	 * At this point we are going to start freeing the final resources.
   1215 	 * If anyone tries to access the proc structure after here they will
   1216 	 * get a shock - bits are missing.  Attempt to make it hard!  We
   1217 	 * don't bother with any further locking past this point.
   1218 	 */
   1219 	p->p_stat = SIDL;		/* not even a zombie any more */
   1220 	LIST_REMOVE(p, p_list);	/* off zombproc */
   1221 	parent->p_nstopchild--;
   1222 	LIST_REMOVE(p, p_sibling);
   1223 
   1224 	/*
   1225 	 * Let pid be reallocated.
   1226 	 */
   1227 	proc_free_pid(p->p_pid);
   1228 	atomic_dec_uint(&nprocs);
   1229 
   1230 	/*
   1231 	 * Unlink process from its process group.
   1232 	 * Releases the proc_lock.
   1233 	 */
   1234 	proc_leavepgrp(p);
   1235 
   1236 	/*
   1237 	 * Delay release until after lwp_free.
   1238 	 */
   1239 	cred2 = l->l_cred;
   1240 
   1241 	/*
   1242 	 * Free the last LWP's resources.
   1243 	 *
   1244 	 * lwp_free ensures the LWP is no longer running on another CPU.
   1245 	 */
   1246 	lwp_free(l, false, true);
   1247 
   1248 	/*
   1249 	 * Now no one except us can reach the process p.
   1250 	 */
   1251 
   1252 	/*
   1253 	 * Decrement the count of procs running with this uid.
   1254 	 */
   1255 	cred1 = p->p_cred;
   1256 	uid = kauth_cred_getuid(cred1);
   1257 	(void)chgproccnt(uid, -1);
   1258 
   1259 	/*
   1260 	 * Release substructures.
   1261 	 */
   1262 
   1263 	lim_free(p->p_limit);
   1264 	pstatsfree(p->p_stats);
   1265 	kauth_cred_free(cred1);
   1266 	kauth_cred_free(cred2);
   1267 
   1268 	/*
   1269 	 * Release reference to text vnode
   1270 	 */
   1271 	if (p->p_textvp)
   1272 		vrele(p->p_textvp);
   1273 	kmem_strfree(p->p_path);
   1274 
   1275 	mutex_destroy(&p->p_auxlock);
   1276 	mutex_obj_free(p->p_lock);
   1277 	mutex_destroy(&p->p_stmutex);
   1278 	cv_destroy(&p->p_waitcv);
   1279 	cv_destroy(&p->p_lwpcv);
   1280 	rw_destroy(&p->p_reflock);
   1281 
   1282 	proc_free_mem(p);
   1283 }
   1284 
   1285 /*
   1286  * Change the parent of a process for tracing purposes.
   1287  */
   1288 void
   1289 proc_changeparent(struct proc *t, struct proc *p)
   1290 {
   1291 	SET(t->p_slflag, PSL_TRACED);
   1292 	t->p_opptr = t->p_pptr;
   1293 	if (t->p_pptr == p)
   1294 		return;
   1295 	struct proc *parent = t->p_pptr;
   1296 
   1297 	if (parent->p_lock < t->p_lock) {
   1298 		if (!mutex_tryenter(parent->p_lock)) {
   1299 			mutex_exit(t->p_lock);
   1300 			mutex_enter(parent->p_lock);
   1301 			mutex_enter(t->p_lock);
   1302 		}
   1303 	} else if (parent->p_lock > t->p_lock) {
   1304 		mutex_enter(parent->p_lock);
   1305 	}
   1306 	parent->p_slflag |= PSL_CHTRACED;
   1307 	proc_reparent(t, p);
   1308 	if (parent->p_lock != t->p_lock)
   1309 		mutex_exit(parent->p_lock);
   1310 }
   1311 
   1312 /*
   1313  * make process 'parent' the new parent of process 'child'.
   1314  *
   1315  * Must be called with proc_lock held.
   1316  */
   1317 void
   1318 proc_reparent(struct proc *child, struct proc *parent)
   1319 {
   1320 
   1321 	KASSERT(mutex_owned(&proc_lock));
   1322 
   1323 	if (child->p_pptr == parent)
   1324 		return;
   1325 
   1326 	if (child->p_stat == SZOMB || child->p_stat == SDEAD ||
   1327 	    (child->p_stat == SSTOP && !child->p_waited)) {
   1328 		child->p_pptr->p_nstopchild--;
   1329 		parent->p_nstopchild++;
   1330 	}
   1331 	if (parent == initproc) {
   1332 		child->p_exitsig = SIGCHLD;
   1333 		child->p_ppid = parent->p_pid;
   1334 	}
   1335 
   1336 	LIST_REMOVE(child, p_sibling);
   1337 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
   1338 	child->p_pptr = parent;
   1339 }
   1340