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