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