xref: /netbsd-src/sys/kern/kern_exit.c (revision 1ffa7b76c40339c17a0fb2a09fac93f287cfc046)
1 /*	$NetBSD: kern_exit.c,v 1.115 2003/03/19 11:36:33 dsl Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 1999 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.
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  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the NetBSD
22  *	Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 /*
41  * Copyright (c) 1982, 1986, 1989, 1991, 1993
42  *	The Regents of the University of California.  All rights reserved.
43  * (c) UNIX System Laboratories, Inc.
44  * All or some portions of this file are derived from material licensed
45  * to the University of California by American Telephone and Telegraph
46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
47  * the permission of UNIX System Laboratories, Inc.
48  *
49  * Redistribution and use in source and binary forms, with or without
50  * modification, are permitted provided that the following conditions
51  * are met:
52  * 1. Redistributions of source code must retain the above copyright
53  *    notice, this list of conditions and the following disclaimer.
54  * 2. Redistributions in binary form must reproduce the above copyright
55  *    notice, this list of conditions and the following disclaimer in the
56  *    documentation and/or other materials provided with the distribution.
57  * 3. All advertising materials mentioning features or use of this software
58  *    must display the following acknowledgement:
59  *	This product includes software developed by the University of
60  *	California, Berkeley and its contributors.
61  * 4. Neither the name of the University nor the names of its contributors
62  *    may be used to endorse or promote products derived from this software
63  *    without specific prior written permission.
64  *
65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75  * SUCH DAMAGE.
76  *
77  *	@(#)kern_exit.c	8.10 (Berkeley) 2/23/95
78  */
79 
80 #include <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: kern_exit.c,v 1.115 2003/03/19 11:36:33 dsl Exp $");
82 
83 #include "opt_ktrace.h"
84 #include "opt_perfctrs.h"
85 #include "opt_systrace.h"
86 #include "opt_sysv.h"
87 
88 #include <sys/param.h>
89 #include <sys/systm.h>
90 #include <sys/ioctl.h>
91 #include <sys/proc.h>
92 #include <sys/tty.h>
93 #include <sys/time.h>
94 #include <sys/resource.h>
95 #include <sys/kernel.h>
96 #include <sys/ktrace.h>
97 #include <sys/proc.h>
98 #include <sys/buf.h>
99 #include <sys/wait.h>
100 #include <sys/file.h>
101 #include <sys/vnode.h>
102 #include <sys/syslog.h>
103 #include <sys/malloc.h>
104 #include <sys/pool.h>
105 #include <sys/resourcevar.h>
106 #if defined(PERFCTRS)
107 #include <sys/pmc.h>
108 #endif
109 #include <sys/ptrace.h>
110 #include <sys/acct.h>
111 #include <sys/filedesc.h>
112 #include <sys/ras.h>
113 #include <sys/signalvar.h>
114 #include <sys/sched.h>
115 #include <sys/sa.h>
116 #include <sys/savar.h>
117 #include <sys/mount.h>
118 #include <sys/syscallargs.h>
119 #include <sys/systrace.h>
120 
121 #include <machine/cpu.h>
122 
123 #include <uvm/uvm_extern.h>
124 
125 #define DEBUG_EXIT
126 
127 #ifdef DEBUG_EXIT
128 int debug_exit = 0;
129 #define DPRINTF(x) if (debug_exit) printf x
130 #else
131 #define DPRINTF(x)
132 #endif
133 
134 static void lwp_exit_hook(struct lwp *, void *);
135 
136 /*
137  * exit --
138  *	Death of process.
139  */
140 int
141 sys_exit(struct lwp *l, void *v, register_t *retval)
142 {
143 	struct sys_exit_args /* {
144 		syscallarg(int)	rval;
145 	} */ *uap = v;
146 
147 	/* Don't call exit1() multiple times in the same process.*/
148 	if (l->l_proc->p_flag & P_WEXIT)
149 		lwp_exit(l);
150 
151 	exit1(l, W_EXITCODE(SCARG(uap, rval), 0));
152 	/* NOTREACHED */
153 	return (0);
154 }
155 
156 /*
157  * Exit: deallocate address space and other resources, change proc state
158  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
159  * status and rusage for wait().  Check for child processes and orphan them.
160  */
161 void
162 exit1(struct lwp *l, int rv)
163 {
164 	struct proc	*p, *q, *nq;
165 	int		s, sa;
166 
167 	p = l->l_proc;
168 
169 	if (__predict_false(p == initproc))
170 		panic("init died (signal %d, exit %d)",
171 		    WTERMSIG(rv), WEXITSTATUS(rv));
172 
173 	p->p_flag |= P_WEXIT;
174 
175 	DPRINTF(("exit1: %d.%d exiting.\n", p->p_pid, l->l_lid));
176 	/*
177 	 * Disable scheduler activation upcalls.
178 	 * We're trying to get out of here.
179 	 */
180 	sa = 0;
181 	if (p->p_sa != NULL) {
182 		l->l_flag &= ~L_SA;
183 		p->p_flag &= ~P_SA;
184 		sa = 1;
185 	}
186 
187 #ifdef PGINPROF
188 	vmsizmon();
189 #endif
190 	if (p->p_flag & P_PROFIL)
191 		stopprofclock(p);
192 	p->p_ru = pool_get(&rusage_pool, PR_WAITOK);
193 	/*
194 	 * If parent is waiting for us to exit or exec, P_PPWAIT is set; we
195 	 * wake up the parent early to avoid deadlock.
196 	 */
197 	if (p->p_flag & P_PPWAIT) {
198 		p->p_flag &= ~P_PPWAIT;
199 		wakeup((caddr_t)p->p_pptr);
200 	}
201 	sigfillset(&p->p_sigctx.ps_sigignore);
202 	sigemptyset(&p->p_sigctx.ps_siglist);
203 	p->p_sigctx.ps_sigcheck = 0;
204 	timers_free(p, TIMERS_ALL);
205 
206 	if (sa || (p->p_nlwps > 1))
207 		exit_lwps(l);
208 
209 #if defined(__HAVE_RAS)
210 	ras_purgeall(p);
211 #endif
212 
213 	/*
214 	 * Close open files and release open-file table.
215 	 * This may block!
216 	 */
217 	fdfree(p);
218 	cwdfree(p);
219 
220 	doexithooks(p);
221 
222 	if (SESS_LEADER(p)) {
223 		struct session *sp = p->p_session;
224 
225 		if (sp->s_ttyvp) {
226 			/*
227 			 * Controlling process.
228 			 * Signal foreground pgrp,
229 			 * drain controlling terminal
230 			 * and revoke access to controlling terminal.
231 			 */
232 			if (sp->s_ttyp->t_session == sp) {
233 				if (sp->s_ttyp->t_pgrp)
234 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
235 				(void) ttywait(sp->s_ttyp);
236 				/*
237 				 * The tty could have been revoked
238 				 * if we blocked.
239 				 */
240 				if (sp->s_ttyvp)
241 					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
242 			}
243 			if (sp->s_ttyvp)
244 				vrele(sp->s_ttyvp);
245 			sp->s_ttyvp = NULL;
246 			/*
247 			 * s_ttyp is not zero'd; we use this to indicate
248 			 * that the session once had a controlling terminal.
249 			 * (for logging and informational purposes)
250 			 */
251 		}
252 		sp->s_leader = NULL;
253 	}
254 	fixjobc(p, p->p_pgrp, 0);
255 	(void)acct_process(p);
256 #ifdef KTRACE
257 	/*
258 	 * release trace file
259 	 */
260 	ktrderef(p);
261 #endif
262 #ifdef SYSTRACE
263 	systrace_sys_exit(p);
264 #endif
265 	/*
266 	 * If emulation has process exit hook, call it now.
267 	 */
268 	if (p->p_emul->e_proc_exit)
269 		(*p->p_emul->e_proc_exit)(p);
270 
271 	/*
272 	 * Give orphaned children to init(8).
273 	 */
274 	q = LIST_FIRST(&p->p_children);
275 	if (q)		/* only need this if any child is S_ZOMB */
276 		wakeup((caddr_t)initproc);
277 	for (; q != 0; q = nq) {
278 		nq = LIST_NEXT(q, p_sibling);
279 
280 		/*
281 		 * Traced processes are killed since their existence
282 		 * means someone is screwing up. Since we reset the
283 		 * trace flags, the logic in sys_wait4() would not be
284 		 * triggered to reparent the process to its
285 		 * original parent, so we must do this here.
286 		 */
287 		if (q->p_flag & P_TRACED) {
288 			if (q->p_opptr != q->p_pptr) {
289 				struct proc *t = q->p_opptr;
290 				proc_reparent(q, t ? t : initproc);
291 				q->p_opptr = NULL;
292 			} else
293 				proc_reparent(q, initproc);
294 			q->p_flag &= ~(P_TRACED|P_WAITED|P_FSTRACE);
295 			psignal(q, SIGKILL);
296 		} else {
297 			proc_reparent(q, initproc);
298 		}
299 	}
300 
301 	/*
302 	 * Reset p_opptr pointer of all former children which got
303 	 * traced by another process and were reparented. We reset
304 	 * it to NULL here; the trace detach code then reparents
305 	 * the child to initproc. We only check allproc list, since
306 	 * eventual former children on zombproc list won't reference
307 	 * p_opptr anymore.
308 	 */
309 	if (p->p_flag & P_CHTRACED) {
310 		struct proc *t;
311 
312 		proclist_lock_read();
313 
314 		LIST_FOREACH(t, &allproc, p_list) {
315 			if (t->p_opptr == p)
316 				t->p_opptr = NULL;
317 		}
318 
319 		proclist_unlock_read();
320 	}
321 
322 	/*
323 	 * Save exit status and final rusage info, adding in child rusage
324 	 * info and self times.
325 	 * In order to pick up the time for the current execution, we must
326 	 * do this before unlinking the lwp from l_list.
327 	 */
328 	p->p_xstat = rv;
329 	*p->p_ru = p->p_stats->p_ru;
330 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
331 	ruadd(p->p_ru, &p->p_stats->p_cru);
332 
333 	/*
334 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
335 	 */
336 
337 	/*
338 	 * Move proc from allproc to zombproc, but do not yet
339 	 * wake up the reaper.  We will put the proc on the
340 	 * deadproc list later (using the p_dead member), and
341 	 * wake up the reaper when we do.
342 	 * Changing the state to SDEAD stops it being found by pfind().
343 	 */
344 	s = proclist_lock_write();
345 	p->p_stat = SDEAD;
346 	p->p_nrlwps--;
347 	l->l_stat = SDEAD;
348 	LIST_REMOVE(p, p_list);
349 	LIST_INSERT_HEAD(&zombproc, p, p_list);
350 	LIST_REMOVE(l, l_list);
351 	l->l_flag |= L_DETACHED;
352 	proclist_unlock_write(s);
353 
354 	/*
355 	 * Notify interested parties of our demise.
356 	 */
357 	KNOTE(&p->p_klist, NOTE_EXIT);
358 
359 #if PERFCTRS
360 	/*
361 	 * Save final PMC information in parent process & clean up.
362 	 */
363 	if (PMC_ENABLED(p)) {
364 		pmc_save_context(p);
365 		pmc_accumulate(p->p_pptr, p);
366 		pmc_process_exit(p);
367 	}
368 #endif
369 
370 	/*
371 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
372 	 * flag set, notify init instead (and hope it will handle
373 	 * this situation).
374 	 */
375 	if (p->p_pptr->p_flag & P_NOCLDWAIT) {
376 		struct proc *pp = p->p_pptr;
377 		proc_reparent(p, initproc);
378 		/*
379 		 * If this was the last child of our parent, notify
380 		 * parent, so in case he was wait(2)ing, he will
381 		 * continue.
382 		 */
383 		if (LIST_FIRST(&pp->p_children) == NULL)
384 			wakeup((caddr_t)pp);
385 	}
386 
387 	/*
388 	 * Release the process's signal state.
389 	 */
390 	sigactsfree(p);
391 
392 	/*
393 	 * Clear curlwp after we've done all operations
394 	 * that could block, and before tearing down the rest
395 	 * of the process state that might be used from clock, etc.
396 	 * Also, can't clear curlwp while we're still runnable,
397 	 * as we're not on a run queue (we are current, just not
398 	 * a proper proc any longer!).
399 	 *
400 	 * Other substructures are freed from wait().
401 	 */
402 	curlwp = NULL;
403 	limfree(p->p_limit);
404 	pstatsfree(p->p_stats);
405 	p->p_limit = NULL;
406 
407 	/* This process no longer needs to hold the kernel lock. */
408 	KERNEL_PROC_UNLOCK(l);
409 
410 	/*
411 	 * Finally, call machine-dependent code to switch to a new
412 	 * context (possibly the idle context).  Once we are no longer
413 	 * using the dead process's vmspace and stack, exit2() will be
414 	 * called to schedule those resources to be released by the
415 	 * reaper thread.
416 	 *
417 	 * Note that cpu_exit() will end with a call equivalent to
418 	 * cpu_switch(), finishing our execution (pun intended).
419 	 */
420 
421 	cpu_exit(l, 1);
422 }
423 
424 void
425 exit_lwps(struct lwp *l)
426 {
427 	struct proc *p;
428 	struct lwp *l2;
429 	int s, error;
430 	lwpid_t		waited;
431 
432 	p = l->l_proc;
433 
434 	/* XXX SMP
435 	 * This would be the right place to IPI any LWPs running on
436 	 * other processors so that they can notice the userret exit hook.
437 	 */
438 	p->p_userret = lwp_exit_hook;
439 	p->p_userret_arg = NULL;
440 
441 	/*
442 	 * Make SA-cached LWPs normal process runnable LWPs so that
443 	 * they'll also self-destruct.
444 	 */
445 	if (p->p_sa && p->p_sa->sa_ncached > 0) {
446 		DPRINTF(("exit_lwps: Making cached LWPs of %d runnable: ",
447 		    p->p_pid));
448 		SCHED_LOCK(s);
449 		while ((l2 = sa_getcachelwp(p)) != 0) {
450 			l2->l_priority = l2->l_usrpri;
451 			setrunnable(l2);
452 			DPRINTF(("%d ", l2->l_lid));
453 		}
454 		DPRINTF(("\n"));
455 		SCHED_UNLOCK(s);
456 	}
457 
458 	/*
459 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
460 	 * LWPs, make detached LWPs undetached (so we can wait for
461 	 * them) and then wait for everyone else to finish.
462 	 */
463 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
464 		l2->l_flag &= ~(L_DETACHED|L_SA);
465 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & L_SINTR)) ||
466 		    l2->l_stat == LSSUSPENDED) {
467 			SCHED_LOCK(s);
468 			setrunnable(l2);
469 			SCHED_UNLOCK(s);
470 			DPRINTF(("exit_lwps: Made %d.%d runnable\n",
471 			    p->p_pid, l2->l_lid));
472 		}
473 	}
474 
475 
476 	while (p->p_nlwps > 1) {
477 		DPRINTF(("exit_lwps: waiting for %d LWPs (%d runnable, %d zombies)\n",
478 		    p->p_nlwps, p->p_nrlwps, p->p_nzlwps));
479 		error = lwp_wait1(l, 0, &waited, LWPWAIT_EXITCONTROL);
480 		if (error)
481 			panic("exit_lwps: lwp_wait1 failed with error %d\n",
482 			    error);
483 		DPRINTF(("exit_lwps: Got LWP %d from lwp_wait1()\n", waited));
484 	}
485 
486 	p->p_userret = NULL;
487 }
488 
489 /* Wrapper function for use in p_userret */
490 static void
491 lwp_exit_hook(struct lwp *l, void *arg)
492 {
493 	KERNEL_PROC_LOCK(l);
494 	lwp_exit(l);
495 }
496 
497 /*
498  * We are called from cpu_exit() once it is safe to schedule the
499  * dead process's resources to be freed (i.e., once we've switched to
500  * the idle PCB for the current CPU).
501  *
502  * NOTE: One must be careful with locking in this routine.  It's
503  * called from a critical section in machine-dependent code, so
504  * we should refrain from changing any interrupt state.
505  *
506  * We lock the deadproc list (a spin lock), place the proc on that
507  * list (using the p_dead member), and wake up the reaper.
508  */
509 void
510 exit2(struct lwp *l)
511 {
512 	struct proc *p = l->l_proc;
513 
514 	simple_lock(&deadproc_slock);
515 	SLIST_INSERT_HEAD(&deadprocs, p, p_dead);
516 	simple_unlock(&deadproc_slock);
517 
518 	/* lwp_exit2() will wake up deadproc for us. */
519 	lwp_exit2(l);
520 }
521 
522 /*
523  * Process reaper.  This is run by a kernel thread to free the resources
524  * of a dead process.  Once the resources are free, the process becomes
525  * a zombie, and the parent is allowed to read the undead's status.
526  */
527 void
528 reaper(void *arg)
529 {
530 	struct proc *p;
531 	struct lwp *l;
532 
533 	KERNEL_PROC_UNLOCK(curlwp);
534 
535 	for (;;) {
536 		simple_lock(&deadproc_slock);
537 		p = SLIST_FIRST(&deadprocs);
538 		l = LIST_FIRST(&deadlwp);
539 		if (p == NULL && l == NULL) {
540 			/* No work for us; go to sleep until someone exits. */
541 			(void) ltsleep(&deadprocs, PVM|PNORELOCK,
542 			    "reaper", 0, &deadproc_slock);
543 			continue;
544 		}
545 
546 		if (l != NULL ) {
547 			p = l->l_proc;
548 
549 			/* Remove lwp from the deadlwp list. */
550 			LIST_REMOVE(l, l_list);
551 			simple_unlock(&deadproc_slock);
552 			KERNEL_PROC_LOCK(curlwp);
553 
554 			/*
555 			 * Give machine-dependent code a chance to free any
556 			 * resources it couldn't free while still running on
557 			 * that process's context.  This must be done before
558 			 * uvm_lwp_exit(), in case these resources are in the
559 			 * PCB.
560 			 */
561 			cpu_wait(l);
562 
563 			/*
564 			 * Free the VM resources we're still holding on to.
565 			 */
566 			uvm_lwp_exit(l);
567 
568 			l->l_stat = LSZOMB;
569 			if (l->l_flag & L_DETACHED) {
570 				/* Nobody waits for detached LWPs. */
571 				LIST_REMOVE(l, l_sibling);
572 				p->p_nlwps--;
573 				pool_put(&lwp_pool, l);
574 			} else {
575 				p->p_nzlwps++;
576 				wakeup((caddr_t)&p->p_nlwps);
577 			}
578 			/* XXXNJW where should this be with respect to
579 			 * the wakeup() above? */
580 			KERNEL_PROC_UNLOCK(curlwp);
581 		} else {
582 			/* Remove proc from the deadproc list. */
583 			SLIST_REMOVE_HEAD(&deadprocs, p_dead);
584 			simple_unlock(&deadproc_slock);
585 			KERNEL_PROC_LOCK(curlwp);
586 
587 			/*
588 			 * Free the VM resources we're still holding on to.
589 			 * We must do this from a valid thread because doing
590 			 * so may block.
591 			 */
592 			uvm_proc_exit(p);
593 
594 			/* Process is now a true zombie. */
595 			p->p_stat = SZOMB;
596 
597 			/* Wake up the parent so it can get exit status. */
598 			if ((p->p_flag & P_FSTRACE) == 0 && p->p_exitsig != 0)
599 				psignal(p->p_pptr, P_EXITSIG(p));
600 			KERNEL_PROC_UNLOCK(curlwp);
601 			wakeup((caddr_t)p->p_pptr);
602 		}
603 	}
604 }
605 
606 int
607 sys_wait4(struct lwp *l, void *v, register_t *retval)
608 {
609 	struct sys_wait4_args /* {
610 		syscallarg(int)			pid;
611 		syscallarg(int *)		status;
612 		syscallarg(int)			options;
613 		syscallarg(struct rusage *)	rusage;
614 	} */ *uap = v;
615 	struct proc	*child, *parent;
616 	int		status, error;
617 
618 	parent = l->l_proc;
619 
620 	if (SCARG(uap, pid) == 0)
621 		SCARG(uap, pid) = -parent->p_pgid;
622 	if (SCARG(uap, options) & ~(WUNTRACED|WNOHANG|WALTSIG|WALLSIG))
623 		return (EINVAL);
624 
625 	error = find_stopped_child(parent, SCARG(uap,pid), SCARG(uap,options),
626 				&child);
627 	if (error != 0)
628 		return error;
629 	if (child == NULL) {
630 		*retval = 0;
631 		return 0;
632 	}
633 
634 	retval[0] = child->p_pid;
635 
636 	if (child->p_stat == SZOMB) {
637 		if (SCARG(uap, status)) {
638 			status = child->p_xstat;	/* convert to int */
639 			error = copyout((caddr_t)&status,
640 					(caddr_t)SCARG(uap, status),
641 					sizeof(status));
642 			if (error)
643 				return (error);
644 		}
645 		if (SCARG(uap, rusage)) {
646 			error = copyout((caddr_t)child->p_ru,
647 				    (caddr_t)SCARG(uap, rusage),
648 				    sizeof(struct rusage));
649 			if (error)
650 				return (error);
651 		}
652 
653 		proc_free(child);
654 		return 0;
655 	}
656 
657 	/* child state must be SSTOP */
658 	if (SCARG(uap, status)) {
659 		status = W_STOPCODE(child->p_xstat);
660 		return copyout((caddr_t)&status,
661 				(caddr_t)SCARG(uap, status),
662 				sizeof(status));
663 	}
664 	return 0;
665 }
666 
667 /*
668  * Scan list of child processes for a child process that has stopped or
669  * exited.  Used by sys_wait4 and 'compat' equivalents.
670  */
671 int
672 find_stopped_child(struct proc *parent, pid_t pid, int options,
673 	struct proc **child_p)
674 {
675 	struct proc *child;
676 	int c_found, error;
677 
678 	 for (;;) {
679 		c_found = 0;
680 		LIST_FOREACH(child, &parent->p_children, p_sibling) {
681 			if (pid != WAIT_ANY &&
682 			    child->p_pid != pid &&
683 			    child->p_pgid != -pid)
684 				continue;
685 			/*
686 			 * Wait for processes with p_exitsig != SIGCHLD
687 			 * processes only if WALTSIG is set; wait for
688 			 * processes with p_exitsig == SIGCHLD only
689 			 * if WALTSIG is clear.
690 			 */
691 			if (((options & WALLSIG) == 0) &&
692 			    (options & WALTSIG ? child->p_exitsig == SIGCHLD
693 						: P_EXITSIG(child) != SIGCHLD))
694 				continue;
695 
696 			c_found = 1;
697 			if (child->p_stat == SZOMB &&
698 			    (options & WNOZOMBIE) == 0) {
699 				*child_p = child;
700 				return 0;
701 			}
702 
703 			if (child->p_stat == SSTOP &&
704 			    (child->p_flag & P_WAITED) == 0 &&
705 			    (child->p_flag & P_TRACED || options & WUNTRACED)) {
706 				if ((options & WNOWAIT) == 0)
707 					child->p_flag |= P_WAITED;
708 				*child_p = child;
709 				return 0;
710 			}
711 		}
712 		if (c_found == 0)
713 			return ECHILD;
714 		if (options & WNOHANG) {
715 			*child_p = NULL;
716 			return 0;
717 		}
718 		error = tsleep((caddr_t)parent, PWAIT | PCATCH, "wait", 0);
719 		if (error != 0)
720 			return error;
721 	}
722 }
723 
724 /*
725  * Free a process after parent has taken all the state info.
726  */
727 void
728 proc_free(struct proc *p)
729 {
730 	struct proc *parent = p->p_pptr;
731 	int s;
732 
733 	/*
734 	 * If we got the child via ptrace(2) or procfs, and
735 	 * the parent is different (meaning the process was
736 	 * attached, rather than run as a child), then we need
737 	 * to give it back to the old parent, and send the
738 	 * parent the exit signal.  The rest of the cleanup
739 	 * will be done when the old parent waits on the child.
740 	 */
741 	if ((p->p_flag & P_TRACED) && p->p_opptr != parent){
742 		parent = p->p_opptr;
743 		if (parent == NULL)
744 			parent = initproc;
745 		proc_reparent(p, parent);
746 		p->p_opptr = NULL;
747 		p->p_flag &= ~(P_TRACED|P_WAITED|P_FSTRACE);
748 		if (p->p_exitsig != 0)
749 			psignal(parent, P_EXITSIG(p));
750 		wakeup((caddr_t)parent);
751 		return;
752 	}
753 
754 	scheduler_wait_hook(parent, p);
755 	p->p_xstat = 0;
756 
757 	ruadd(&parent->p_stats->p_cru, p->p_ru);
758 
759 	/*
760 	 * At this point we are going to start freeing the final resources.
761 	 * If anyone tries to access the proc structure after here they
762 	 * will get a shock - bits are missing.
763 	 * Attempt to make it hard!
764 	 */
765 
766 	p->p_stat = SIDL;		/* not even a zombie any more */
767 
768 	pool_put(&rusage_pool, p->p_ru);
769 
770 	/*
771 	 * Finally finished with old proc entry.
772 	 * Unlink it from its process group and free it.
773 	 */
774 	leavepgrp(p);
775 
776 	s = proclist_lock_write();
777 	LIST_REMOVE(p, p_list);	/* off zombproc */
778 	LIST_REMOVE(p, p_sibling);
779 	proclist_unlock_write(s);
780 
781 	/*
782 	 * Decrement the count of procs running with this uid.
783 	 */
784 	(void)chgproccnt(p->p_cred->p_ruid, -1);
785 
786 	/*
787 	 * Free up credentials.
788 	 */
789 	if (--p->p_cred->p_refcnt == 0) {
790 		crfree(p->p_cred->pc_ucred);
791 		pool_put(&pcred_pool, p->p_cred);
792 	}
793 
794 	/*
795 	 * Release reference to text vnode
796 	 */
797 	if (p->p_textvp)
798 		vrele(p->p_textvp);
799 
800 	/*
801 	 * Release any SA state
802 	 */
803 	if (p->p_sa) {
804 		free(p->p_sa->sa_stacks, M_SA);
805 		pool_put(&sadata_pool, p->p_sa);
806 	}
807 
808 	/* Free proc structure and let pid be reallocated */
809 	proc_free_mem(p);
810 }
811 
812 /*
813  * make process 'parent' the new parent of process 'child'.
814  */
815 void
816 proc_reparent(struct proc *child, struct proc *parent)
817 {
818 
819 	if (child->p_pptr == parent)
820 		return;
821 
822 	if (parent == initproc)
823 		child->p_exitsig = SIGCHLD;
824 
825 	LIST_REMOVE(child, p_sibling);
826 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
827 	child->p_pptr = parent;
828 }
829