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