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