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