xref: /netbsd-src/sys/kern/kern_exit.c (revision de2138164cd16145ee5fd4d0aef1e8f952c1a9fb)
1 /*	$NetBSD: kern_exit.c,v 1.168 2007/02/22 06:34:43 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 1999, 2006, 2007 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, and by Andrew Doran.
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.168 2007/02/22 06:34:43 thorpej 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/tty.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/kernel.h>
91 #include <sys/proc.h>
92 #include <sys/buf.h>
93 #include <sys/wait.h>
94 #include <sys/file.h>
95 #include <sys/vnode.h>
96 #include <sys/syslog.h>
97 #include <sys/malloc.h>
98 #include <sys/pool.h>
99 #include <sys/resourcevar.h>
100 #if defined(PERFCTRS)
101 #include <sys/pmc.h>
102 #endif
103 #include <sys/ptrace.h>
104 #include <sys/acct.h>
105 #include <sys/filedesc.h>
106 #include <sys/ras.h>
107 #include <sys/signalvar.h>
108 #include <sys/sched.h>
109 #include <sys/mount.h>
110 #include <sys/syscallargs.h>
111 #include <sys/systrace.h>
112 #include <sys/kauth.h>
113 #include <sys/sleepq.h>
114 #include <sys/lockdebug.h>
115 #include <sys/ktrace.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 /*
131  * Fill in the appropriate signal information, and signal the parent.
132  */
133 static void
134 exit_psignal(struct proc *p, struct proc *pp, ksiginfo_t *ksi)
135 {
136 
137 	KSI_INIT(ksi);
138 	if ((ksi->ksi_signo = P_EXITSIG(p)) == SIGCHLD) {
139 		if (WIFSIGNALED(p->p_xstat)) {
140 			if (WCOREDUMP(p->p_xstat))
141 				ksi->ksi_code = CLD_DUMPED;
142 			else
143 				ksi->ksi_code = CLD_KILLED;
144 		} else {
145 			ksi->ksi_code = CLD_EXITED;
146 		}
147 	}
148 	/*
149 	 * We fill those in, even for non-SIGCHLD.
150 	 * It's safe to access p->p_cred unlocked here.
151 	 */
152 	ksi->ksi_pid = p->p_pid;
153 	ksi->ksi_uid = kauth_cred_geteuid(p->p_cred);
154 	ksi->ksi_status = p->p_xstat;
155 	/* XXX: is this still valid? */
156 	ksi->ksi_utime = p->p_ru->ru_utime.tv_sec;
157 	ksi->ksi_stime = p->p_ru->ru_stime.tv_sec;
158 }
159 
160 /*
161  * exit --
162  *	Death of process.
163  */
164 int
165 sys_exit(struct lwp *l, void *v, register_t *retval)
166 {
167 	struct sys_exit_args /* {
168 		syscallarg(int)	rval;
169 	} */ *uap = v;
170 	struct proc *p = l->l_proc;
171 
172 	/* Don't call exit1() multiple times in the same process. */
173 	mutex_enter(&p->p_smutex);
174 	if (p->p_sflag & PS_WEXIT) {
175 		mutex_exit(&p->p_smutex);
176 		lwp_exit(l);
177 	}
178 
179 	/* exit1() will release the mutex. */
180 	exit1(l, W_EXITCODE(SCARG(uap, rval), 0));
181 	/* NOTREACHED */
182 	return (0);
183 }
184 
185 /*
186  * Exit: deallocate address space and other resources, change proc state
187  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
188  * status and rusage for wait().  Check for child processes and orphan them.
189  *
190  * Must be called with p->p_smutex held.  Does not return.
191  */
192 void
193 exit1(struct lwp *l, int rv)
194 {
195 	struct proc	*p, *q, *nq;
196 	int		s;
197 	ksiginfo_t	ksi;
198 	ksiginfoq_t	kq;
199 	int		wakeinit;
200 
201 	p = l->l_proc;
202 
203 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
204 
205 	if (__predict_false(p == initproc))
206 		panic("init died (signal %d, exit %d)",
207 		    WTERMSIG(rv), WEXITSTATUS(rv));
208 
209 	p->p_sflag |= PS_WEXIT;
210 
211 	/*
212 	 * Force all other LWPs to exit before we do.  Only then can we
213 	 * begin to tear down the rest of the process state.
214 	 */
215 	if (p->p_nlwps > 1)
216 		exit_lwps(l);
217 
218 	ksiginfo_queue_init(&kq);
219 
220 	/*
221 	 * If we have been asked to stop on exit, do so now.
222 	 */
223 	if (p->p_sflag & PS_STOPEXIT) {
224 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
225 		sigclearall(p, &contsigmask, &kq);
226 		p->p_waited = 0;
227 		mb_write();
228 		p->p_stat = SSTOP;
229 		lwp_lock(l);
230 		p->p_nrlwps--;
231 		l->l_stat = LSSTOP;
232 		mutex_exit(&p->p_smutex);
233 		mi_switch(l, NULL);
234 		KERNEL_LOCK(l->l_biglocks, l);
235 	} else
236 		mutex_exit(&p->p_smutex);
237 
238 	/*
239 	 * Drain all remaining references that procfs, ptrace and others may
240 	 * have on the process.
241 	 */
242 	mutex_enter(&p->p_mutex);
243 	proc_drainrefs(p);
244 	mutex_exit(&p->p_mutex);
245 
246 	/*
247 	 * Bin any remaining signals and mark the process as dying so it will
248 	 * not be found for, e.g. signals.
249 	 */
250 	mutex_enter(&p->p_smutex);
251 	sigfillset(&p->p_sigctx.ps_sigignore);
252 	sigclearall(p, NULL, &kq);
253 	p->p_stat = SDYING;
254 	mutex_exit(&p->p_smutex);
255 	ksiginfo_queue_drain(&kq);
256 
257 	DPRINTF(("exit1: %d.%d exiting.\n", p->p_pid, l->l_lid));
258 
259 #ifdef PGINPROF
260 	vmsizmon();
261 #endif
262 	p->p_ru = pool_get(&rusage_pool, PR_WAITOK);
263 	timers_free(p, TIMERS_ALL);
264 #if defined(__HAVE_RAS)
265 	ras_purgeall(p);
266 #endif
267 
268 	/*
269 	 * Close open files, release open-file table and free signal
270 	 * actions.  This may block!
271 	 */
272 	fdfree(l);
273 	cwdfree(p->p_cwdi);
274 	p->p_cwdi = NULL;
275 	doexithooks(p);
276 	sigactsfree(p->p_sigacts);
277 
278 	/*
279 	 * Write out accounting data.
280 	 */
281 	(void)acct_process(l);
282 
283 #ifdef KTRACE
284 	/*
285 	 * Release trace file.
286 	 */
287 	if (p->p_tracep != NULL) {
288 		mutex_enter(&ktrace_mutex);
289 		ktrderef(p);
290 		mutex_exit(&ktrace_mutex);
291 	}
292 #endif
293 #ifdef SYSTRACE
294 	systrace_sys_exit(p);
295 #endif
296 
297 	/*
298 	 * If emulation has process exit hook, call it now.
299 	 * Set the exit status now so that the exit hook has
300 	 * an opportunity to tweak it (COMPAT_LINUX requires
301 	 * this for thread group emulation)
302 	 */
303 	p->p_xstat = rv;
304 	if (p->p_emul->e_proc_exit)
305 		(*p->p_emul->e_proc_exit)(p);
306 
307 	/*
308 	 * Finalize the last LWP's specificdata, as well as the
309 	 * specificdata for the proc itself.
310 	 */
311 	lwp_finispecific(l);
312 	proc_finispecific(p);
313 
314 	/* Collect child u-areas. */
315 	uvm_uarea_drain(false);
316 
317 	/*
318 	 * Free the VM resources we're still holding on to.
319 	 * We must do this from a valid thread because doing
320 	 * so may block. This frees vmspace, which we don't
321 	 * need anymore. The only remaining lwp is the one
322 	 * we run at this moment, nothing runs in userland
323 	 * anymore.
324 	 */
325 	uvm_proc_exit(p);
326 
327 	/*
328 	 * Stop profiling.
329 	 */
330 	if ((p->p_stflag & PST_PROFIL) != 0) {
331 		mutex_spin_enter(&p->p_stmutex);
332 		stopprofclock(p);
333 		mutex_spin_exit(&p->p_stmutex);
334 	}
335 
336 	/*
337 	 * If parent is waiting for us to exit or exec, P_PPWAIT is set; we
338 	 * wake up the parent early to avoid deadlock.  We can do this once
339 	 * the VM resources are released.
340 	 */
341 	rw_enter(&proclist_lock, RW_WRITER);
342 
343 	mutex_enter(&p->p_smutex);
344 	if (p->p_sflag & PS_PPWAIT) {
345 		p->p_sflag &= ~PS_PPWAIT;
346 		cv_wakeup(&p->p_pptr->p_waitcv); /* XXXSMP */
347 	}
348 	mutex_exit(&p->p_smutex);
349 
350 	if (SESS_LEADER(p)) {
351 		struct vnode *vprele = NULL, *vprevoke = NULL;
352 		struct session *sp = p->p_session;
353 		struct tty *tp;
354 
355 		if (sp->s_ttyvp) {
356 			/*
357 			 * Controlling process.
358 			 * Signal foreground pgrp,
359 			 * drain controlling terminal
360 			 * and revoke access to controlling terminal.
361 			 */
362 			tp = sp->s_ttyp;
363 			s = spltty();
364 			TTY_LOCK(tp);
365 			if (tp->t_session == sp) {
366 				if (tp->t_pgrp) {
367 					mutex_enter(&proclist_mutex);
368 					pgsignal(tp->t_pgrp, SIGHUP, 1);
369 					mutex_exit(&proclist_mutex);
370 				}
371 				/* we can't guarantee the revoke will do this */
372 				tp->t_pgrp = NULL;
373 				tp->t_session = NULL;
374 				TTY_UNLOCK(tp);
375 				splx(s);
376 				SESSRELE(sp);
377 				rw_exit(&proclist_lock);
378 				(void) ttywait(tp);
379 				rw_enter(&proclist_lock, RW_WRITER);
380 
381 				/*
382 				 * The tty could have been revoked
383 				 * if we blocked.
384 				 */
385 				vprevoke = sp->s_ttyvp;
386 			} else {
387 				TTY_UNLOCK(tp);
388 				splx(s);
389 			}
390 			vprele = sp->s_ttyvp;
391 			sp->s_ttyvp = NULL;
392 			/*
393 			 * s_ttyp is not zero'd; we use this to indicate
394 			 * that the session once had a controlling terminal.
395 			 * (for logging and informational purposes)
396 			 */
397 		}
398 		sp->s_leader = NULL;
399 
400 		if (vprevoke != NULL || vprele != NULL) {
401 			rw_exit(&proclist_lock);
402 			if (vprevoke != NULL)
403 				VOP_REVOKE(vprevoke, REVOKEALL);
404 			if (vprele != NULL)
405 				vrele(vprele);
406 			rw_enter(&proclist_lock, RW_WRITER);
407 		}
408 	}
409 	mutex_enter(&proclist_mutex);
410 	fixjobc(p, p->p_pgrp, 0);
411 	mutex_exit(&proclist_mutex);
412 
413 	/*
414 	 * Notify interested parties of our demise.
415 	 */
416 	KNOTE(&p->p_klist, NOTE_EXIT);
417 
418 #if PERFCTRS
419 	/*
420 	 * Save final PMC information in parent process & clean up.
421 	 */
422 	if (PMC_ENABLED(p)) {
423 		pmc_save_context(p);
424 		pmc_accumulate(p->p_pptr, p);
425 		pmc_process_exit(p);
426 	}
427 #endif
428 
429 	/*
430 	 * Reset p_opptr pointer of all former children which got
431 	 * traced by another process and were reparented. We reset
432 	 * it to NULL here; the trace detach code then reparents
433 	 * the child to initproc. We only check allproc list, since
434 	 * eventual former children on zombproc list won't reference
435 	 * p_opptr anymore.
436 	 */
437 	if (p->p_slflag & PSL_CHTRACED) {
438 		PROCLIST_FOREACH(q, &allproc) {
439 			if (q->p_opptr == p)
440 				q->p_opptr = NULL;
441 		}
442 	}
443 
444 	/*
445 	 * Give orphaned children to init(8).
446 	 */
447 	q = LIST_FIRST(&p->p_children);
448 	wakeinit = (q != NULL);
449 	for (; q != NULL; q = nq) {
450 		nq = LIST_NEXT(q, p_sibling);
451 
452 		/*
453 		 * Traced processes are killed since their existence
454 		 * means someone is screwing up. Since we reset the
455 		 * trace flags, the logic in sys_wait4() would not be
456 		 * triggered to reparent the process to its
457 		 * original parent, so we must do this here.
458 		 */
459 		if (q->p_slflag & PSL_TRACED) {
460 			mutex_enter(&p->p_smutex);
461 			q->p_slflag &= ~(PSL_TRACED|PSL_FSTRACE|PSL_SYSCALL);
462 			mutex_exit(&p->p_smutex);
463 			if (q->p_opptr != q->p_pptr) {
464 				struct proc *t = q->p_opptr;
465 				proc_reparent(q, t ? t : initproc);
466 				q->p_opptr = NULL;
467 			} else
468 				proc_reparent(q, initproc);
469 			killproc(q, "orphaned traced process");
470 		} else
471 			proc_reparent(q, initproc);
472 	}
473 
474 	/*
475 	 * Move proc from allproc to zombproc, it's now nearly ready to be
476 	 * collected by parent.
477 	 */
478 	mutex_enter(&proclist_mutex);
479 	LIST_REMOVE(l, l_list);
480 	LIST_REMOVE(p, p_list);
481 	LIST_INSERT_HEAD(&zombproc, p, p_list);
482 
483 	/*
484 	 * Mark the process as dead.  We must do this before we signal
485 	 * the parent.
486 	 */
487 	p->p_stat = SDEAD;
488 
489 	/* Put in front of parent's sibling list for parent to collect it */
490 	q = p->p_pptr;
491 	q->p_nstopchild++;
492 	if (LIST_FIRST(&q->p_children) != p) {
493 		/* Put child where it can be found quickly */
494 		LIST_REMOVE(p, p_sibling);
495 		LIST_INSERT_HEAD(&q->p_children, p, p_sibling);
496 	}
497 	mutex_exit(&proclist_mutex);
498 
499 	/*
500 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
501 	 * flag set, notify init instead (and hope it will handle
502 	 * this situation).
503 	 */
504 	mutex_enter(&q->p_mutex);
505 	if (q->p_flag & (PK_NOCLDWAIT|PK_CLDSIGIGN)) {
506 		proc_reparent(p, initproc);
507 		wakeinit = 1;
508 
509 		/*
510 		 * If this was the last child of our parent, notify
511 		 * parent, so in case he was wait(2)ing, he will
512 		 * continue.
513 		 */
514 		if (LIST_FIRST(&q->p_children) == NULL)
515 			cv_wakeup(&q->p_waitcv);	/* XXXSMP */
516 	}
517 	mutex_exit(&q->p_mutex);
518 
519 	/* Reload parent pointer, since p may have been reparented above */
520 	q = p->p_pptr;
521 
522 	if ((p->p_slflag & PSL_FSTRACE) == 0 && p->p_exitsig != 0) {
523 		exit_psignal(p, q, &ksi);
524 		mutex_enter(&proclist_mutex);
525 		kpsignal(q, &ksi, NULL);
526 		mutex_exit(&proclist_mutex);
527 	}
528 
529 	/*
530 	 * Save final rusage info, adding in child rusage info and self
531 	 * times.  It's OK to call caclru() unlocked here.
532 	 */
533 	*p->p_ru = p->p_stats->p_ru;
534 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL, NULL);
535 	ruadd(p->p_ru, &p->p_stats->p_cru);
536 
537 	if (wakeinit)
538 		cv_wakeup(&initproc->p_waitcv);	/* XXXSMP */
539 
540 	/*
541 	 * Remaining lwp resources will be freed in lwp_exit2() once we've
542 	 * switch to idle context; at that point, we will be marked as a
543 	 * full blown zombie.
544 	 *
545 	 * XXXSMP disable preemption.
546 	 */
547 	mutex_enter(&p->p_smutex);
548 	lwp_drainrefs(l);
549 	lwp_lock(l);
550 	l->l_prflag &= ~LPR_DETACHED;
551 	l->l_stat = LSZOMB;
552 	lwp_unlock(l);
553 	KASSERT(curlwp == l);
554 	KASSERT(p->p_nrlwps == 1);
555 	KASSERT(p->p_nlwps == 1);
556 	p->p_stat = SZOMB;
557 	p->p_nrlwps--;
558 	p->p_nzlwps++;
559 	p->p_ndlwps = 0;
560 	mutex_exit(&p->p_smutex);
561 
562 	/*
563 	 * Signal the parent to collect us, and drop the proclist lock.
564 	 */
565 	rw_exit(&proclist_lock);
566 
567 	/* Verify that we hold no locks other than the kernel lock. */
568 #ifdef MULTIPROCESSOR
569 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
570 #else
571 	LOCKDEBUG_BARRIER(NULL, 0);
572 #endif
573 
574 	/*
575 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
576 	 */
577 
578 	/*
579 	 * Give machine-dependent code a chance to free any MD LWP
580 	 * resources.  This must be done before uvm_lwp_exit(), in
581 	 * case these resources are in the PCB.
582 	 */
583 #ifndef __NO_CPU_LWP_FREE
584 	cpu_lwp_free(l, 1);
585 #endif
586 	pmap_deactivate(l);
587 
588 	/* This process no longer needs to hold the kernel lock. */
589 #ifdef notyet
590 	/* XXXSMP hold in lwp_userret() */
591 	KERNEL_UNLOCK_LAST(l);
592 #else
593 	KERNEL_UNLOCK_ALL(l, NULL);
594 #endif
595 
596 	/*
597 	 * Finally, call machine-dependent code to switch to a new
598 	 * context (possibly the idle context).  Once we are no longer
599 	 * using the dead lwp's stack, lwp_exit2() will be called.
600 	 *
601 	 * Note that cpu_exit() will end with a call equivalent to
602 	 * cpu_switch(), finishing our execution (pun intended).
603 	 */
604 	uvmexp.swtch++;	/* XXXSMP unlocked */
605 	cv_wakeup(&p->p_pptr->p_waitcv);	/* XXXSMP */
606 	cpu_exit(l);
607 }
608 
609 void
610 exit_lwps(struct lwp *l)
611 {
612 	struct proc *p;
613 	struct lwp *l2;
614 	int error;
615 	lwpid_t waited;
616 #if defined(MULTIPROCESSOR)
617 	int nlocks;
618 #endif
619 
620 	KERNEL_UNLOCK_ALL(l, &nlocks);
621 
622 	p = l->l_proc;
623 
624  retry:
625 	/*
626 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
627 	 * LWPs and then wait for everyone else to finish.
628 	 */
629 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
630 		if (l2 == l)
631 			continue;
632 		lwp_lock(l2);
633 		l2->l_flag |= LW_WEXIT;
634 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & LW_SINTR)) ||
635 		    l2->l_stat == LSSUSPENDED || l2->l_stat == LSSTOP) {
636 		    	/* setrunnable() will release the lock. */
637 			setrunnable(l2);
638 			DPRINTF(("exit_lwps: Made %d.%d runnable\n",
639 			    p->p_pid, l2->l_lid));
640 			continue;
641 		}
642 		lwp_unlock(l2);
643 	}
644 	while (p->p_nlwps > 1) {
645 		DPRINTF(("exit_lwps: waiting for %d LWPs (%d zombies)\n",
646 		    p->p_nlwps, p->p_nzlwps));
647 		error = lwp_wait1(l, 0, &waited, LWPWAIT_EXITCONTROL);
648 		if (p->p_nlwps == 1)
649 			break;
650 		if (error == EDEADLK) {
651 			/*
652 			 * LWPs can get suspended/slept behind us.
653 			 * (eg. sa_setwoken)
654 			 * kick them again and retry.
655 			 */
656 			goto retry;
657 		}
658 		if (error)
659 			panic("exit_lwps: lwp_wait1 failed with error %d",
660 			    error);
661 		DPRINTF(("exit_lwps: Got LWP %d from lwp_wait1()\n", waited));
662 	}
663 
664 	KERNEL_LOCK(nlocks, l);
665 }
666 
667 int
668 sys_wait4(struct lwp *l, void *v, register_t *retval)
669 {
670 	struct sys_wait4_args /* {
671 		syscallarg(int)			pid;
672 		syscallarg(int *)		status;
673 		syscallarg(int)			options;
674 		syscallarg(struct rusage *)	rusage;
675 	} */ *uap = v;
676 	struct proc	*child, *parent;
677 	int		status, error;
678 	struct rusage	ru;
679 
680 	parent = l->l_proc;
681 
682 	if (SCARG(uap, pid) == 0)
683 		SCARG(uap, pid) = -parent->p_pgid;
684 	if (SCARG(uap, options) & ~(WUNTRACED|WNOHANG|WALTSIG|WALLSIG))
685 		return (EINVAL);
686 
687 	rw_enter(&proclist_lock, RW_WRITER);
688 
689 	error = find_stopped_child(parent, SCARG(uap,pid), SCARG(uap,options),
690 	    &child, &status);
691 	if (error != 0) {
692 		rw_exit(&proclist_lock);
693 		return error;
694 	}
695 	if (child == NULL) {
696 		rw_exit(&proclist_lock);
697 		*retval = 0;
698 		return 0;
699 	}
700 
701 	retval[0] = child->p_pid;
702 
703 	if (P_ZOMBIE(child)) {
704 		KERNEL_LOCK(1, l);		/* XXXSMP */
705 		/* proc_free() will release the proclist_lock. */
706 		proc_free(child, (SCARG(uap, rusage) == NULL ? NULL : &ru));
707 		KERNEL_UNLOCK_ONE(l);		/* XXXSMP */
708 
709 		if (SCARG(uap, rusage))
710 			error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
711 		if (error == 0 && SCARG(uap, status))
712 			error = copyout(&status, SCARG(uap, status),
713 			    sizeof(status));
714 
715 		return error;
716 	}
717 
718 	rw_exit(&proclist_lock);
719 
720 	/* Child state must have been SSTOP. */
721 	if (SCARG(uap, status)) {
722 		status = W_STOPCODE(status);
723 		return copyout(&status, SCARG(uap, status), sizeof(status));
724 	}
725 
726 	return 0;
727 }
728 
729 /*
730  * Scan list of child processes for a child process that has stopped or
731  * exited.  Used by sys_wait4 and 'compat' equivalents.
732  *
733  * Must be called with the proclist_lock write held, and may release
734  * while waiting.
735  */
736 int
737 find_stopped_child(struct proc *parent, pid_t pid, int options,
738 		   struct proc **child_p, int *status_p)
739 {
740 	struct proc *child, *dead;
741 	int error;
742 
743 	LOCK_ASSERT(rw_write_held(&proclist_lock));
744 
745 	for (;;) {
746 		error = ECHILD;
747 		dead = NULL;
748 
749 		mutex_enter(&proclist_mutex);
750 		LIST_FOREACH(child, &parent->p_children, p_sibling) {
751 			if (pid >= 0) {
752 				if (child->p_pid != pid) {
753 					child = p_find(pid, PFIND_ZOMBIE |
754 					    PFIND_LOCKED);
755 					if (child == NULL ||
756 					    child->p_pptr != parent) {
757 						child = NULL;
758 						break;
759 					}
760 				}
761 			} else if (pid != WAIT_ANY && child->p_pgid != -pid) {
762 				/* Child not in correct pgrp */
763 				continue;
764 			}
765 
766 			/*
767 			 * Wait for processes with p_exitsig != SIGCHLD
768 			 * processes only if WALTSIG is set; wait for
769 			 * processes with p_exitsig == SIGCHLD only
770 			 * if WALTSIG is clear.
771 			 */
772 			if (((options & WALLSIG) == 0) &&
773 			    (options & WALTSIG ? child->p_exitsig == SIGCHLD
774 						: P_EXITSIG(child) != SIGCHLD)){
775 				if (child->p_pid == pid) {
776 					child = NULL;
777 					break;
778 				}
779 				continue;
780 			}
781 
782 			error = 0;
783 			if ((options & WNOZOMBIE) == 0) {
784 				if (child->p_stat == SZOMB)
785 					break;
786 				if (child->p_stat == SDEAD) {
787 					/*
788 					 * We may occasionally arrive here
789 					 * after receiving a signal, but
790 					 * immediatley before the child
791 					 * process is zombified.  The wait
792 					 * will be short, so avoid returning
793 					 * to userspace.
794 					 */
795 					dead = child;
796 				}
797 			}
798 
799 			if (child->p_stat == SSTOP &&
800 			    child->p_waited == 0 &&
801 			    (child->p_slflag & PSL_TRACED ||
802 			    options & WUNTRACED)) {
803 				if ((options & WNOWAIT) == 0) {
804 					child->p_waited = 1;
805 					parent->p_nstopchild--;
806 				}
807 				break;
808 			}
809 			if (parent->p_nstopchild == 0 || child->p_pid == pid) {
810 				child = NULL;
811 				break;
812 			}
813 		}
814 
815 		if (child != NULL || error != 0 ||
816 		    ((options & WNOHANG) != 0 && dead == NULL)) {
817 		    	if (child != NULL)
818 			    	*status_p = child->p_xstat;
819 			mutex_exit(&proclist_mutex);
820 			*child_p = child;
821 			return error;
822 		}
823 
824 		/*
825 		 * Wait for another child process to stop.
826 		 */
827 		rw_exit(&proclist_lock);
828 		error = cv_wait_sig(&parent->p_waitcv, &proclist_mutex);
829 		mutex_exit(&proclist_mutex);
830 		rw_enter(&proclist_lock, RW_WRITER);
831 
832 		if (error != 0)
833 			return error;
834 	}
835 }
836 
837 /*
838  * Free a process after parent has taken all the state info.  Must be called
839  * with the proclist lock write held, and will release before returning.
840  *
841  * *ru is returned to the caller, and must be freed by the caller.
842  */
843 void
844 proc_free(struct proc *p, struct rusage *caller_ru)
845 {
846 	struct plimit *plim;
847 	struct pstats *pstats;
848 	struct rusage *ru;
849 	struct proc *parent;
850 	struct lwp *l;
851 	ksiginfo_t ksi;
852 	kauth_cred_t cred;
853 	struct vnode *vp;
854 	uid_t uid;
855 
856 	LOCK_ASSERT(rw_write_held(&proclist_lock));
857 
858 	KASSERT(p->p_nlwps == 1);
859 	KASSERT(p->p_nzlwps == 1);
860 	KASSERT(p->p_nrlwps == 0);
861 	KASSERT(p->p_stat == SZOMB);
862 
863 	if (caller_ru != NULL)
864 		memcpy(caller_ru, p->p_ru, sizeof(*caller_ru));
865 
866 	/*
867 	 * If we got the child via ptrace(2) or procfs, and
868 	 * the parent is different (meaning the process was
869 	 * attached, rather than run as a child), then we need
870 	 * to give it back to the old parent, and send the
871 	 * parent the exit signal.  The rest of the cleanup
872 	 * will be done when the old parent waits on the child.
873 	 */
874 	if ((p->p_slflag & PSL_TRACED) != 0) {
875 		parent = p->p_pptr;
876 		if (p->p_opptr != parent){
877 			mutex_enter(&p->p_smutex);
878 			p->p_slflag &= ~(PSL_TRACED|PSL_FSTRACE|PSL_SYSCALL);
879 			mutex_exit(&p->p_smutex);
880 			parent = p->p_opptr;
881 			if (parent == NULL)
882 				parent = initproc;
883 			proc_reparent(p, parent);
884 			p->p_opptr = NULL;
885 			if (p->p_exitsig != 0) {
886 				exit_psignal(p, parent, &ksi);
887 				mutex_enter(&proclist_mutex);
888 				kpsignal(parent, &ksi, NULL);
889 				mutex_exit(&proclist_mutex);
890 			}
891 			cv_wakeup(&parent->p_waitcv);	/* XXXSMP */
892 			rw_exit(&proclist_lock);
893 			return;
894 		}
895 	}
896 
897 	/*
898 	 * Finally finished with old proc entry.  Unlink it from its process
899 	 * group.
900 	 */
901 	leavepgrp(p);
902 
903 	parent = p->p_pptr;
904 	scheduler_wait_hook(parent, p);
905 	ruadd(&parent->p_stats->p_cru, p->p_ru);
906 	p->p_xstat = 0;
907 
908 	/*
909 	 * At this point we are going to start freeing the final resources.
910 	 * If anyone tries to access the proc structure after here they will
911 	 * get a shock - bits are missing.  Attempt to make it hard!  We
912 	 * don't bother with any further locking past this point.
913 	 */
914 	mutex_enter(&proclist_mutex);
915 	p->p_stat = SIDL;		/* not even a zombie any more */
916 	LIST_REMOVE(p, p_list);	/* off zombproc */
917 	parent = p->p_pptr;
918 	p->p_pptr->p_nstopchild--;
919 	mutex_exit(&proclist_mutex);
920 	LIST_REMOVE(p, p_sibling);
921 
922 	uid = kauth_cred_getuid(p->p_cred);
923 	vp = p->p_textvp;
924 	cred = p->p_cred;
925 	ru = p->p_ru;
926 
927 	l = LIST_FIRST(&p->p_lwps);
928 
929 #ifdef MULTIPROCESSOR
930 	/*
931 	 * If the last remaining LWP is still on the CPU (unlikely), then
932 	 * spin until it has switched away.  We need to release all locks
933 	 * to avoid deadlock against interrupt handlers on the target CPU.
934 	 */
935 	if (l->l_cpu->ci_curlwp == l) {
936 		int count;
937 		rw_exit(&proclist_lock);
938 		KERNEL_UNLOCK_ALL(l, &count);
939 		while (l->l_cpu->ci_curlwp == l)
940 			SPINLOCK_BACKOFF_HOOK;
941 		KERNEL_LOCK(count, l);
942 		rw_enter(&proclist_lock, RW_WRITER);
943 	}
944 #endif
945 
946 	mutex_destroy(&p->p_rasmutex);
947 	mutex_destroy(&p->p_mutex);
948 	mutex_destroy(&p->p_stmutex);
949 	mutex_destroy(&p->p_smutex);
950 	cv_destroy(&p->p_waitcv);
951 	cv_destroy(&p->p_lwpcv);
952 	cv_destroy(&p->p_refcv);
953 
954 	/*
955 	 * Delay release until after dropping the proclist lock.
956 	 */
957 	plim = p->p_limit;
958 	pstats = p->p_stats;
959 
960 	/*
961 	 * Free the proc structure and let pid be reallocated.  This will
962 	 * release the proclist_lock.
963 	 */
964 	proc_free_mem(p);
965 
966 	/*
967 	 * Decrement the count of procs running with this uid.
968 	 */
969 	(void)chgproccnt(uid, -1);
970 
971 	/*
972 	 * Release substructures.
973 	 */
974 	limfree(plim);
975 	pstatsfree(pstats);
976 	kauth_cred_free(cred);
977 	kauth_cred_free(l->l_cred);
978 
979 	/*
980 	 * Release reference to text vnode
981 	 */
982 	if (vp)
983 		vrele(vp);
984 
985 	/*
986 	 * Free the last LWP's resources.
987 	 */
988 	lwp_free(l, 0, 1);
989 
990 	/*
991 	 * Collect child u-areas.
992 	 */
993 	uvm_uarea_drain(false);
994 	pool_put(&rusage_pool, ru);
995 }
996 
997 /*
998  * make process 'parent' the new parent of process 'child'.
999  *
1000  * Must be called with proclist_lock write locked held.
1001  */
1002 void
1003 proc_reparent(struct proc *child, struct proc *parent)
1004 {
1005 
1006 	LOCK_ASSERT(rw_write_held(&proclist_lock));
1007 
1008 	if (child->p_pptr == parent)
1009 		return;
1010 
1011 	mutex_enter(&proclist_mutex);
1012 	if (child->p_stat == SZOMB ||
1013 	    (child->p_stat == SSTOP && !child->p_waited)) {
1014 		child->p_pptr->p_nstopchild--;
1015 		parent->p_nstopchild++;
1016 	}
1017 	mutex_exit(&proclist_mutex);
1018 	if (parent == initproc)
1019 		child->p_exitsig = SIGCHLD;
1020 
1021 	LIST_REMOVE(child, p_sibling);
1022 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1023 	child->p_pptr = parent;
1024 }
1025