xref: /netbsd-src/sys/kern/kern_exit.c (revision 8e6ab8837d8d6b9198e67c1c445300b483e2f304)
1 /*	$NetBSD: kern_exit.c,v 1.118 2003/07/17 18:16:58 fvdl 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.118 2003/07/17 18:16:58 fvdl 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 
183 		l->l_flag &= ~L_SA;
184 #if 0
185 		p->p_flag &= ~P_SA;
186 #endif
187 		sa = 1;
188 	}
189 
190 #ifdef PGINPROF
191 	vmsizmon();
192 #endif
193 	if (p->p_flag & P_PROFIL)
194 		stopprofclock(p);
195 	p->p_ru = pool_get(&rusage_pool, PR_WAITOK);
196 	/*
197 	 * If parent is waiting for us to exit or exec, P_PPWAIT is set; we
198 	 * wake up the parent early to avoid deadlock.
199 	 */
200 	if (p->p_flag & P_PPWAIT) {
201 		p->p_flag &= ~P_PPWAIT;
202 		wakeup((caddr_t)p->p_pptr);
203 	}
204 	sigfillset(&p->p_sigctx.ps_sigignore);
205 	sigemptyset(&p->p_sigctx.ps_siglist);
206 	p->p_sigctx.ps_sigcheck = 0;
207 	timers_free(p, TIMERS_ALL);
208 
209 	if (sa || (p->p_nlwps > 1))
210 		exit_lwps(l);
211 
212 #if defined(__HAVE_RAS)
213 	ras_purgeall(p);
214 #endif
215 
216 	/*
217 	 * Close open files and release open-file table.
218 	 * This may block!
219 	 */
220 	fdfree(p);
221 	cwdfree(p);
222 
223 	doexithooks(p);
224 
225 	if (SESS_LEADER(p)) {
226 		struct session *sp = p->p_session;
227 
228 		if (sp->s_ttyvp) {
229 			/*
230 			 * Controlling process.
231 			 * Signal foreground pgrp,
232 			 * drain controlling terminal
233 			 * and revoke access to controlling terminal.
234 			 */
235 			if (sp->s_ttyp->t_session == sp) {
236 				if (sp->s_ttyp->t_pgrp)
237 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
238 				(void) ttywait(sp->s_ttyp);
239 				/*
240 				 * The tty could have been revoked
241 				 * if we blocked.
242 				 */
243 				if (sp->s_ttyvp)
244 					VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
245 			}
246 			if (sp->s_ttyvp)
247 				vrele(sp->s_ttyvp);
248 			sp->s_ttyvp = NULL;
249 			/*
250 			 * s_ttyp is not zero'd; we use this to indicate
251 			 * that the session once had a controlling terminal.
252 			 * (for logging and informational purposes)
253 			 */
254 		}
255 		sp->s_leader = NULL;
256 	}
257 	fixjobc(p, p->p_pgrp, 0);
258 	(void)acct_process(p);
259 #ifdef KTRACE
260 	/*
261 	 * release trace file
262 	 */
263 	ktrderef(p);
264 #endif
265 #ifdef SYSTRACE
266 	systrace_sys_exit(p);
267 #endif
268 	/*
269 	 * If emulation has process exit hook, call it now.
270 	 */
271 	if (p->p_emul->e_proc_exit)
272 		(*p->p_emul->e_proc_exit)(p);
273 
274 	/*
275 	 * Give orphaned children to init(8).
276 	 */
277 	q = LIST_FIRST(&p->p_children);
278 	if (q)		/* only need this if any child is S_ZOMB */
279 		wakeup((caddr_t)initproc);
280 	for (; q != 0; q = nq) {
281 		nq = LIST_NEXT(q, p_sibling);
282 
283 		/*
284 		 * Traced processes are killed since their existence
285 		 * means someone is screwing up. Since we reset the
286 		 * trace flags, the logic in sys_wait4() would not be
287 		 * triggered to reparent the process to its
288 		 * original parent, so we must do this here.
289 		 */
290 		if (q->p_flag & P_TRACED) {
291 			if (q->p_opptr != q->p_pptr) {
292 				struct proc *t = q->p_opptr;
293 				proc_reparent(q, t ? t : initproc);
294 				q->p_opptr = NULL;
295 			} else
296 				proc_reparent(q, initproc);
297 			q->p_flag &= ~(P_TRACED|P_WAITED|P_FSTRACE);
298 			psignal(q, SIGKILL);
299 		} else {
300 			proc_reparent(q, initproc);
301 		}
302 	}
303 
304 	/*
305 	 * Reset p_opptr pointer of all former children which got
306 	 * traced by another process and were reparented. We reset
307 	 * it to NULL here; the trace detach code then reparents
308 	 * the child to initproc. We only check allproc list, since
309 	 * eventual former children on zombproc list won't reference
310 	 * p_opptr anymore.
311 	 */
312 	if (p->p_flag & P_CHTRACED) {
313 		struct proc *t;
314 
315 		proclist_lock_read();
316 
317 		LIST_FOREACH(t, &allproc, p_list) {
318 			if (t->p_opptr == p)
319 				t->p_opptr = NULL;
320 		}
321 
322 		proclist_unlock_read();
323 	}
324 
325 	/*
326 	 * Save exit status and final rusage info, adding in child rusage
327 	 * info and self times.
328 	 * In order to pick up the time for the current execution, we must
329 	 * do this before unlinking the lwp from l_list.
330 	 */
331 	p->p_xstat = rv;
332 	*p->p_ru = p->p_stats->p_ru;
333 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
334 	ruadd(p->p_ru, &p->p_stats->p_cru);
335 
336 	/*
337 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
338 	 */
339 
340 	/*
341 	 * Move proc from allproc to zombproc, but do not yet
342 	 * wake up the reaper.  We will put the proc on the
343 	 * deadproc list later (using the p_dead member), and
344 	 * wake up the reaper when we do.
345 	 * Changing the state to SDEAD stops it being found by pfind().
346 	 */
347 	s = proclist_lock_write();
348 	p->p_stat = SDEAD;
349 	p->p_nrlwps--;
350 	l->l_stat = SDEAD;
351 	LIST_REMOVE(p, p_list);
352 	LIST_INSERT_HEAD(&zombproc, p, p_list);
353 	LIST_REMOVE(l, l_list);
354 	l->l_flag |= L_DETACHED;
355 	proclist_unlock_write(s);
356 
357 	/*
358 	 * Notify interested parties of our demise.
359 	 */
360 	KNOTE(&p->p_klist, NOTE_EXIT);
361 
362 #if PERFCTRS
363 	/*
364 	 * Save final PMC information in parent process & clean up.
365 	 */
366 	if (PMC_ENABLED(p)) {
367 		pmc_save_context(p);
368 		pmc_accumulate(p->p_pptr, p);
369 		pmc_process_exit(p);
370 	}
371 #endif
372 
373 	/*
374 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
375 	 * flag set, notify init instead (and hope it will handle
376 	 * this situation).
377 	 */
378 	if (p->p_pptr->p_flag & P_NOCLDWAIT) {
379 		struct proc *pp = p->p_pptr;
380 		proc_reparent(p, initproc);
381 		/*
382 		 * If this was the last child of our parent, notify
383 		 * parent, so in case he was wait(2)ing, he will
384 		 * continue.
385 		 */
386 		if (LIST_FIRST(&pp->p_children) == NULL)
387 			wakeup((caddr_t)pp);
388 	}
389 
390 	/*
391 	 * Release the process's signal state.
392 	 */
393 	sigactsfree(p);
394 
395 	/*
396 	 * Clear curlwp after we've done all operations
397 	 * that could block, and before tearing down the rest
398 	 * of the process state that might be used from clock, etc.
399 	 * Also, can't clear curlwp while we're still runnable,
400 	 * as we're not on a run queue (we are current, just not
401 	 * a proper proc any longer!).
402 	 *
403 	 * Other substructures are freed from wait().
404 	 */
405 	curlwp = NULL;
406 	limfree(p->p_limit);
407 	pstatsfree(p->p_stats);
408 	p->p_limit = NULL;
409 
410 	/* This process no longer needs to hold the kernel lock. */
411 	KERNEL_PROC_UNLOCK(l);
412 
413 	/*
414 	 * Finally, call machine-dependent code to switch to a new
415 	 * context (possibly the idle context).  Once we are no longer
416 	 * using the dead process's vmspace and stack, exit2() will be
417 	 * called to schedule those resources to be released by the
418 	 * reaper thread.
419 	 *
420 	 * Note that cpu_exit() will end with a call equivalent to
421 	 * cpu_switch(), finishing our execution (pun intended).
422 	 */
423 
424 	cpu_exit(l, 1);
425 }
426 
427 void
428 exit_lwps(struct lwp *l)
429 {
430 	struct proc *p;
431 	struct lwp *l2;
432 	int s, error;
433 	lwpid_t		waited;
434 
435 	p = l->l_proc;
436 
437 	/* XXX SMP
438 	 * This would be the right place to IPI any LWPs running on
439 	 * other processors so that they can notice the userret exit hook.
440 	 */
441 	p->p_userret = lwp_exit_hook;
442 	p->p_userret_arg = NULL;
443 
444 	/*
445 	 * Make SA-cached LWPs normal process runnable LWPs so that
446 	 * they'll also self-destruct.
447 	 */
448 	if (p->p_sa && p->p_sa->sa_ncached > 0) {
449 		DPRINTF(("exit_lwps: Making cached LWPs of %d runnable: ",
450 		    p->p_pid));
451 		SCHED_LOCK(s);
452 		while ((l2 = sa_getcachelwp(p)) != 0) {
453 			l2->l_priority = l2->l_usrpri;
454 			setrunnable(l2);
455 			DPRINTF(("%d ", l2->l_lid));
456 		}
457 		DPRINTF(("\n"));
458 		SCHED_UNLOCK(s);
459 	}
460 
461 	/*
462 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
463 	 * LWPs, make detached LWPs undetached (so we can wait for
464 	 * them) and then wait for everyone else to finish.
465 	 */
466 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
467 #if 0
468 		l2->l_flag &= ~(L_DETACHED|L_SA);
469 #endif
470 		l2->l_flag &= ~(L_DETACHED);
471 
472 		if(l2->l_flag & L_SA_WANTS_VP)
473 		{
474 			wakeup(l2);
475 		}
476 
477 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & L_SINTR)) ||
478 		    l2->l_stat == LSSUSPENDED || l2->l_stat == LSSTOP) {
479 			SCHED_LOCK(s);
480 			setrunnable(l2);
481 			SCHED_UNLOCK(s);
482 			DPRINTF(("exit_lwps: Made %d.%d runnable\n",
483 			    p->p_pid, l2->l_lid));
484 		}
485 	}
486 
487 
488 	while (p->p_nlwps > 1) {
489 		DPRINTF(("exit_lwps: waiting for %d LWPs (%d runnable, %d zombies)\n",
490 		    p->p_nlwps, p->p_nrlwps, p->p_nzlwps));
491 		error = lwp_wait1(l, 0, &waited, LWPWAIT_EXITCONTROL);
492 		if (error)
493 			panic("exit_lwps: lwp_wait1 failed with error %d\n",
494 			    error);
495 		DPRINTF(("exit_lwps: Got LWP %d from lwp_wait1()\n", waited));
496 	}
497 
498 	p->p_userret = NULL;
499 }
500 
501 /* Wrapper function for use in p_userret */
502 static void
503 lwp_exit_hook(struct lwp *l, void *arg)
504 {
505 	KERNEL_PROC_LOCK(l);
506 	lwp_exit(l);
507 }
508 
509 /*
510  * We are called from cpu_exit() once it is safe to schedule the
511  * dead process's resources to be freed (i.e., once we've switched to
512  * the idle PCB for the current CPU).
513  *
514  * NOTE: One must be careful with locking in this routine.  It's
515  * called from a critical section in machine-dependent code, so
516  * we should refrain from changing any interrupt state.
517  *
518  * We lock the deadproc list (a spin lock), place the proc on that
519  * list (using the p_dead member), and wake up the reaper.
520  */
521 void
522 exit2(struct lwp *l)
523 {
524 	struct proc *p = l->l_proc;
525 
526 	simple_lock(&deadproc_slock);
527 	SLIST_INSERT_HEAD(&deadprocs, p, p_dead);
528 	simple_unlock(&deadproc_slock);
529 
530 	/* lwp_exit2() will wake up deadproc for us. */
531 	lwp_exit2(l);
532 }
533 
534 /*
535  * Process reaper.  This is run by a kernel thread to free the resources
536  * of a dead process.  Once the resources are free, the process becomes
537  * a zombie, and the parent is allowed to read the undead's status.
538  */
539 void
540 reaper(void *arg)
541 {
542 	struct proc *p;
543 	struct lwp *l;
544 
545 	KERNEL_PROC_UNLOCK(curlwp);
546 
547 	for (;;) {
548 		simple_lock(&deadproc_slock);
549 		p = SLIST_FIRST(&deadprocs);
550 		l = LIST_FIRST(&deadlwp);
551 		if (p == NULL && l == NULL) {
552 			/* No work for us; go to sleep until someone exits. */
553 			(void) ltsleep(&deadprocs, PVM|PNORELOCK,
554 			    "reaper", 0, &deadproc_slock);
555 			continue;
556 		}
557 
558 		if (l != NULL ) {
559 			p = l->l_proc;
560 
561 			/* Remove lwp from the deadlwp list. */
562 			LIST_REMOVE(l, l_list);
563 			simple_unlock(&deadproc_slock);
564 			KERNEL_PROC_LOCK(curlwp);
565 
566 			/*
567 			 * Give machine-dependent code a chance to free any
568 			 * resources it couldn't free while still running on
569 			 * that process's context.  This must be done before
570 			 * uvm_lwp_exit(), in case these resources are in the
571 			 * PCB.
572 			 */
573 			cpu_wait(l);
574 
575 			/*
576 			 * Free the VM resources we're still holding on to.
577 			 */
578 			uvm_lwp_exit(l);
579 
580 			l->l_stat = LSZOMB;
581 			if (l->l_flag & L_DETACHED) {
582 				/* Nobody waits for detached LWPs. */
583 				LIST_REMOVE(l, l_sibling);
584 				p->p_nlwps--;
585 				pool_put(&lwp_pool, l);
586 			} else {
587 				p->p_nzlwps++;
588 				wakeup((caddr_t)&p->p_nlwps);
589 			}
590 			/* XXXNJW where should this be with respect to
591 			 * the wakeup() above? */
592 			KERNEL_PROC_UNLOCK(curlwp);
593 		} else {
594 			/* Remove proc from the deadproc list. */
595 			SLIST_REMOVE_HEAD(&deadprocs, p_dead);
596 			simple_unlock(&deadproc_slock);
597 			KERNEL_PROC_LOCK(curlwp);
598 
599 			/*
600 			 * Free the VM resources we're still holding on to.
601 			 * We must do this from a valid thread because doing
602 			 * so may block.
603 			 */
604 			uvm_proc_exit(p);
605 
606 			/* Process is now a true zombie. */
607 			p->p_stat = SZOMB;
608 
609 			/* Wake up the parent so it can get exit status. */
610 			if ((p->p_flag & P_FSTRACE) == 0 && p->p_exitsig != 0)
611 				psignal(p->p_pptr, P_EXITSIG(p));
612 			KERNEL_PROC_UNLOCK(curlwp);
613 			wakeup((caddr_t)p->p_pptr);
614 		}
615 	}
616 }
617 
618 int
619 sys_wait4(struct lwp *l, void *v, register_t *retval)
620 {
621 	struct sys_wait4_args /* {
622 		syscallarg(int)			pid;
623 		syscallarg(int *)		status;
624 		syscallarg(int)			options;
625 		syscallarg(struct rusage *)	rusage;
626 	} */ *uap = v;
627 	struct proc	*child, *parent;
628 	int		status, error;
629 
630 	parent = l->l_proc;
631 
632 	if (SCARG(uap, pid) == 0)
633 		SCARG(uap, pid) = -parent->p_pgid;
634 	if (SCARG(uap, options) & ~(WUNTRACED|WNOHANG|WALTSIG|WALLSIG))
635 		return (EINVAL);
636 
637 	error = find_stopped_child(parent, SCARG(uap,pid), SCARG(uap,options),
638 				&child);
639 	if (error != 0)
640 		return error;
641 	if (child == NULL) {
642 		*retval = 0;
643 		return 0;
644 	}
645 
646 	retval[0] = child->p_pid;
647 
648 	if (child->p_stat == SZOMB) {
649 		if (SCARG(uap, status)) {
650 			status = child->p_xstat;	/* convert to int */
651 			error = copyout((caddr_t)&status,
652 					(caddr_t)SCARG(uap, status),
653 					sizeof(status));
654 			if (error)
655 				return (error);
656 		}
657 		if (SCARG(uap, rusage)) {
658 			error = copyout((caddr_t)child->p_ru,
659 				    (caddr_t)SCARG(uap, rusage),
660 				    sizeof(struct rusage));
661 			if (error)
662 				return (error);
663 		}
664 
665 		proc_free(child);
666 		return 0;
667 	}
668 
669 	/* child state must be SSTOP */
670 	if (SCARG(uap, status)) {
671 		status = W_STOPCODE(child->p_xstat);
672 		return copyout((caddr_t)&status,
673 				(caddr_t)SCARG(uap, status),
674 				sizeof(status));
675 	}
676 	return 0;
677 }
678 
679 /*
680  * Scan list of child processes for a child process that has stopped or
681  * exited.  Used by sys_wait4 and 'compat' equivalents.
682  */
683 int
684 find_stopped_child(struct proc *parent, pid_t pid, int options,
685 	struct proc **child_p)
686 {
687 	struct proc *child;
688 	int c_found, error;
689 
690 	 for (;;) {
691 		c_found = 0;
692 		LIST_FOREACH(child, &parent->p_children, p_sibling) {
693 			if (pid != WAIT_ANY &&
694 			    child->p_pid != pid &&
695 			    child->p_pgid != -pid)
696 				continue;
697 			/*
698 			 * Wait for processes with p_exitsig != SIGCHLD
699 			 * processes only if WALTSIG is set; wait for
700 			 * processes with p_exitsig == SIGCHLD only
701 			 * if WALTSIG is clear.
702 			 */
703 			if (((options & WALLSIG) == 0) &&
704 			    (options & WALTSIG ? child->p_exitsig == SIGCHLD
705 						: P_EXITSIG(child) != SIGCHLD))
706 				continue;
707 
708 			c_found = 1;
709 			if (child->p_stat == SZOMB &&
710 			    (options & WNOZOMBIE) == 0) {
711 				*child_p = child;
712 				return 0;
713 			}
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 				*child_p = child;
721 				return 0;
722 			}
723 		}
724 		if (c_found == 0)
725 			return ECHILD;
726 		if (options & WNOHANG) {
727 			*child_p = NULL;
728 			return 0;
729 		}
730 		error = tsleep((caddr_t)parent, PWAIT | PCATCH, "wait", 0);
731 		if (error != 0)
732 			return error;
733 	}
734 }
735 
736 /*
737  * Free a process after parent has taken all the state info.
738  */
739 void
740 proc_free(struct proc *p)
741 {
742 	struct proc *parent = p->p_pptr;
743 	int s;
744 
745 	/*
746 	 * If we got the child via ptrace(2) or procfs, and
747 	 * the parent is different (meaning the process was
748 	 * attached, rather than run as a child), then we need
749 	 * to give it back to the old parent, and send the
750 	 * parent the exit signal.  The rest of the cleanup
751 	 * will be done when the old parent waits on the child.
752 	 */
753 	if ((p->p_flag & P_TRACED) && p->p_opptr != parent){
754 		parent = p->p_opptr;
755 		if (parent == NULL)
756 			parent = initproc;
757 		proc_reparent(p, parent);
758 		p->p_opptr = NULL;
759 		p->p_flag &= ~(P_TRACED|P_WAITED|P_FSTRACE);
760 		if (p->p_exitsig != 0)
761 			psignal(parent, P_EXITSIG(p));
762 		wakeup((caddr_t)parent);
763 		return;
764 	}
765 
766 	scheduler_wait_hook(parent, p);
767 	p->p_xstat = 0;
768 
769 	ruadd(&parent->p_stats->p_cru, p->p_ru);
770 
771 	/*
772 	 * At this point we are going to start freeing the final resources.
773 	 * If anyone tries to access the proc structure after here they
774 	 * will get a shock - bits are missing.
775 	 * Attempt to make it hard!
776 	 */
777 
778 	p->p_stat = SIDL;		/* not even a zombie any more */
779 
780 	pool_put(&rusage_pool, p->p_ru);
781 
782 	/*
783 	 * Finally finished with old proc entry.
784 	 * Unlink it from its process group and free it.
785 	 */
786 	leavepgrp(p);
787 
788 	s = proclist_lock_write();
789 	LIST_REMOVE(p, p_list);	/* off zombproc */
790 	LIST_REMOVE(p, p_sibling);
791 	proclist_unlock_write(s);
792 
793 	/*
794 	 * Decrement the count of procs running with this uid.
795 	 */
796 	(void)chgproccnt(p->p_cred->p_ruid, -1);
797 
798 	/*
799 	 * Free up credentials.
800 	 */
801 	if (--p->p_cred->p_refcnt == 0) {
802 		crfree(p->p_cred->pc_ucred);
803 		pool_put(&pcred_pool, p->p_cred);
804 	}
805 
806 	/*
807 	 * Release reference to text vnode
808 	 */
809 	if (p->p_textvp)
810 		vrele(p->p_textvp);
811 
812 	/*
813 	 * Release any SA state
814 	 */
815 	if (p->p_sa) {
816 		free(p->p_sa->sa_stacks, M_SA);
817 		pool_put(&sadata_pool, p->p_sa);
818 	}
819 
820 	/* Free proc structure and let pid be reallocated */
821 	proc_free_mem(p);
822 }
823 
824 /*
825  * make process 'parent' the new parent of process 'child'.
826  */
827 void
828 proc_reparent(struct proc *child, struct proc *parent)
829 {
830 
831 	if (child->p_pptr == parent)
832 		return;
833 
834 	if (parent == initproc)
835 		child->p_exitsig = SIGCHLD;
836 
837 	LIST_REMOVE(child, p_sibling);
838 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
839 	child->p_pptr = parent;
840 }
841