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