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