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