xref: /netbsd-src/sys/kern/kern_exit.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: kern_exit.c,v 1.273 2018/11/29 12:37:22 maxv Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 1999, 2006, 2007, 2008 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  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1989, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  * (c) UNIX System Laboratories, Inc.
37  * All or some portions of this file are derived from material licensed
38  * to the University of California by American Telephone and Telegraph
39  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
40  * the permission of UNIX System Laboratories, Inc.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)kern_exit.c	8.10 (Berkeley) 2/23/95
67  */
68 
69 #include <sys/cdefs.h>
70 __KERNEL_RCSID(0, "$NetBSD: kern_exit.c,v 1.273 2018/11/29 12:37:22 maxv Exp $");
71 
72 #include "opt_ktrace.h"
73 #include "opt_dtrace.h"
74 #include "opt_sysv.h"
75 
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/ioctl.h>
79 #include <sys/tty.h>
80 #include <sys/time.h>
81 #include <sys/resource.h>
82 #include <sys/kernel.h>
83 #include <sys/proc.h>
84 #include <sys/buf.h>
85 #include <sys/wait.h>
86 #include <sys/file.h>
87 #include <sys/vnode.h>
88 #include <sys/syslog.h>
89 #include <sys/pool.h>
90 #include <sys/uidinfo.h>
91 #include <sys/ptrace.h>
92 #include <sys/acct.h>
93 #include <sys/filedesc.h>
94 #include <sys/ras.h>
95 #include <sys/signalvar.h>
96 #include <sys/sched.h>
97 #include <sys/mount.h>
98 #include <sys/syscallargs.h>
99 #include <sys/kauth.h>
100 #include <sys/sleepq.h>
101 #include <sys/lockdebug.h>
102 #include <sys/ktrace.h>
103 #include <sys/cpu.h>
104 #include <sys/lwpctl.h>
105 #include <sys/atomic.h>
106 #include <sys/sdt.h>
107 
108 #include <uvm/uvm_extern.h>
109 
110 #ifdef DEBUG_EXIT
111 int debug_exit = 0;
112 #define DPRINTF(x) if (debug_exit) printf x
113 #else
114 #define DPRINTF(x)
115 #endif
116 
117 static int find_stopped_child(struct proc *, idtype_t, id_t, int,
118     struct proc **, struct wrusage *, siginfo_t *);
119 static void proc_free(struct proc *, struct wrusage *);
120 
121 /*
122  * DTrace SDT provider definitions
123  */
124 SDT_PROVIDER_DECLARE(proc);
125 SDT_PROBE_DEFINE1(proc, kernel, , exit, "int");
126 
127 /*
128  * Fill in the appropriate signal information, and signal the parent.
129  */
130 /* XXX noclone works around a gcc 4.5 bug on arm */
131 static void __noclone
132 exit_psignal(struct proc *p, struct proc *pp, ksiginfo_t *ksi)
133 {
134 
135 	KSI_INIT(ksi);
136 	if ((ksi->ksi_signo = P_EXITSIG(p)) == SIGCHLD) {
137 		if (p->p_xsig) {
138 			if (p->p_sflag & PS_COREDUMP)
139 				ksi->ksi_code = CLD_DUMPED;
140 			else
141 				ksi->ksi_code = CLD_KILLED;
142 			ksi->ksi_status = p->p_xsig;
143 		} else {
144 			ksi->ksi_code = CLD_EXITED;
145 			ksi->ksi_status = p->p_xexit;
146 		}
147 	} else {
148 		ksi->ksi_code = SI_USER;
149 		ksi->ksi_status = p->p_xsig;
150 	}
151 	/*
152 	 * We fill those in, even for non-SIGCHLD.
153 	 * It's safe to access p->p_cred unlocked here.
154 	 */
155 	ksi->ksi_pid = p->p_pid;
156 	ksi->ksi_uid = kauth_cred_geteuid(p->p_cred);
157 	/* XXX: is this still valid? */
158 	ksi->ksi_utime = p->p_stats->p_ru.ru_utime.tv_sec;
159 	ksi->ksi_stime = p->p_stats->p_ru.ru_stime.tv_sec;
160 }
161 
162 /*
163  * exit --
164  *	Death of process.
165  */
166 int
167 sys_exit(struct lwp *l, const struct sys_exit_args *uap, register_t *retval)
168 {
169 	/* {
170 		syscallarg(int)	rval;
171 	} */
172 	struct proc *p = l->l_proc;
173 
174 	/* Don't call exit1() multiple times in the same process. */
175 	mutex_enter(p->p_lock);
176 	if (p->p_sflag & PS_WEXIT) {
177 		mutex_exit(p->p_lock);
178 		lwp_exit(l);
179 	}
180 
181 	/* exit1() will release the mutex. */
182 	exit1(l, SCARG(uap, rval), 0);
183 	/* NOTREACHED */
184 	return (0);
185 }
186 
187 /*
188  * Exit: deallocate address space and other resources, change proc state
189  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
190  * status and rusage for wait().  Check for child processes and orphan them.
191  *
192  * Must be called with p->p_lock held.  Does not return.
193  */
194 void
195 exit1(struct lwp *l, int exitcode, int signo)
196 {
197 	struct proc	*p, *child, *next_child, *old_parent, *new_parent;
198 	struct pgrp	*pgrp;
199 	ksiginfo_t	ksi;
200 	ksiginfoq_t	kq;
201 	int		wakeinit;
202 
203 	p = l->l_proc;
204 
205 	KASSERT(mutex_owned(p->p_lock));
206 	KASSERT(p->p_vmspace != NULL);
207 
208 	if (__predict_false(p == initproc)) {
209 		panic("init died (signal %d, exit %d)", signo, exitcode);
210 	}
211 
212 	p->p_sflag |= PS_WEXIT;
213 
214 	/*
215 	 * Force all other LWPs to exit before we do.  Only then can we
216 	 * begin to tear down the rest of the process state.
217 	 */
218 	if (p->p_nlwps > 1) {
219 		exit_lwps(l);
220 	}
221 
222 	ksiginfo_queue_init(&kq);
223 
224 	/*
225 	 * If we have been asked to stop on exit, do so now.
226 	 */
227 	if (__predict_false(p->p_sflag & PS_STOPEXIT)) {
228 		KERNEL_UNLOCK_ALL(l, &l->l_biglocks);
229 		sigclearall(p, &contsigmask, &kq);
230 
231 		if (!mutex_tryenter(proc_lock)) {
232 			mutex_exit(p->p_lock);
233 			mutex_enter(proc_lock);
234 			mutex_enter(p->p_lock);
235 		}
236 		p->p_waited = 0;
237 		p->p_pptr->p_nstopchild++;
238 		p->p_stat = SSTOP;
239 		mutex_exit(proc_lock);
240 		lwp_lock(l);
241 		p->p_nrlwps--;
242 		l->l_stat = LSSTOP;
243 		lwp_unlock(l);
244 		mutex_exit(p->p_lock);
245 		lwp_lock(l);
246 		mi_switch(l);
247 		KERNEL_LOCK(l->l_biglocks, l);
248 		mutex_enter(p->p_lock);
249 	}
250 
251 	/*
252 	 * Bin any remaining signals and mark the process as dying so it will
253 	 * not be found for, e.g. signals.
254 	 */
255 	sigfillset(&p->p_sigctx.ps_sigignore);
256 	sigclearall(p, NULL, &kq);
257 	p->p_stat = SDYING;
258 	mutex_exit(p->p_lock);
259 	ksiginfo_queue_drain(&kq);
260 
261 	/* Destroy any lwpctl info. */
262 	if (p->p_lwpctl != NULL)
263 		lwp_ctl_exit();
264 
265 	/*
266 	 * Drain all remaining references that procfs, ptrace and others may
267 	 * have on the process.
268 	 */
269 	rw_enter(&p->p_reflock, RW_WRITER);
270 
271 	DPRINTF(("%s: %d.%d exiting.\n", __func__, p->p_pid, l->l_lid));
272 
273 	timers_free(p, TIMERS_ALL);
274 #if defined(__HAVE_RAS)
275 	ras_purgeall();
276 #endif
277 
278 	/*
279 	 * Close open files, release open-file table and free signal
280 	 * actions.  This may block!
281 	 */
282 	fd_free();
283 	cwdfree(p->p_cwdi);
284 	p->p_cwdi = NULL;
285 	doexithooks(p);
286 	sigactsfree(p->p_sigacts);
287 
288 	/*
289 	 * Write out accounting data.
290 	 */
291 	(void)acct_process(l);
292 
293 #ifdef KTRACE
294 	/*
295 	 * Release trace file.
296 	 */
297 	if (p->p_tracep != NULL) {
298 		mutex_enter(&ktrace_lock);
299 		ktrderef(p);
300 		mutex_exit(&ktrace_lock);
301 	}
302 #endif
303 
304 	p->p_xexit = exitcode;
305 	p->p_xsig = signo;
306 
307 	/*
308 	 * If emulation has process exit hook, call it now.
309 	 * Set the exit status now so that the exit hook has
310 	 * an opportunity to tweak it (COMPAT_LINUX requires
311 	 * this for thread group emulation)
312 	 */
313 	if (p->p_emul->e_proc_exit)
314 		(*p->p_emul->e_proc_exit)(p);
315 
316 	/*
317 	 * Free the VM resources we're still holding on to.
318 	 * We must do this from a valid thread because doing
319 	 * so may block. This frees vmspace, which we don't
320 	 * need anymore. The only remaining lwp is the one
321 	 * we run at this moment, nothing runs in userland
322 	 * anymore.
323 	 */
324 	ruspace(p);	/* Update our vm resource use */
325 	uvm_proc_exit(p);
326 
327 	/*
328 	 * Stop profiling.
329 	 */
330 	if (__predict_false((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, PL_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 	mutex_enter(proc_lock);
342 	if (p->p_lflag & PL_PPWAIT) {
343 		l->l_lwpctl = NULL; /* was on loan from blocked parent */
344 		p->p_lflag &= ~PL_PPWAIT;
345 		cv_broadcast(&p->p_pptr->p_waitcv);
346 	}
347 
348 	if (SESS_LEADER(p)) {
349 		struct vnode *vprele = NULL, *vprevoke = NULL;
350 		struct session *sp = p->p_session;
351 		struct tty *tp;
352 
353 		if (sp->s_ttyvp) {
354 			/*
355 			 * Controlling process.
356 			 * Signal foreground pgrp,
357 			 * drain controlling terminal
358 			 * and revoke access to controlling terminal.
359 			 */
360 			tp = sp->s_ttyp;
361 			mutex_spin_enter(&tty_lock);
362 			if (tp->t_session == sp) {
363 				/* we can't guarantee the revoke will do this */
364 				pgrp = tp->t_pgrp;
365 				tp->t_pgrp = NULL;
366 				tp->t_session = NULL;
367 				mutex_spin_exit(&tty_lock);
368 				if (pgrp != NULL) {
369 					pgsignal(pgrp, SIGHUP, 1);
370 				}
371 				mutex_exit(proc_lock);
372 				(void) ttywait(tp);
373 				mutex_enter(proc_lock);
374 
375 				/* The tty could have been revoked. */
376 				vprevoke = sp->s_ttyvp;
377 			} else
378 				mutex_spin_exit(&tty_lock);
379 			vprele = sp->s_ttyvp;
380 			sp->s_ttyvp = NULL;
381 			/*
382 			 * s_ttyp is not zero'd; we use this to indicate
383 			 * that the session once had a controlling terminal.
384 			 * (for logging and informational purposes)
385 			 */
386 		}
387 		sp->s_leader = NULL;
388 
389 		if (vprevoke != NULL || vprele != NULL) {
390 			if (vprevoke != NULL) {
391 				/* Releases proc_lock. */
392 				proc_sessrele(sp);
393 				VOP_REVOKE(vprevoke, REVOKEALL);
394 			} else
395 				mutex_exit(proc_lock);
396 			if (vprele != NULL)
397 				vrele(vprele);
398 			mutex_enter(proc_lock);
399 		}
400 	}
401 	fixjobc(p, p->p_pgrp, 0);
402 
403 	/*
404 	 * Finalize the last LWP's specificdata, as well as the
405 	 * specificdata for the proc itself.
406 	 */
407 	lwp_finispecific(l);
408 	proc_finispecific(p);
409 
410 	/*
411 	 * Notify interested parties of our demise.
412 	 */
413 	KNOTE(&p->p_klist, NOTE_EXIT);
414 
415 	SDT_PROBE(proc, kernel, , exit,
416 		((p->p_sflag & PS_COREDUMP) ? CLD_DUMPED :
417 		 (p->p_xsig ? CLD_KILLED : CLD_EXITED)),
418 		0,0,0,0);
419 
420 	/*
421 	 * Reset p_opptr pointer of all former children which got
422 	 * traced by another process and were reparented. We reset
423 	 * it to NULL here; the trace detach code then reparents
424 	 * the child to initproc. We only check allproc list, since
425 	 * eventual former children on zombproc list won't reference
426 	 * p_opptr anymore.
427 	 */
428 	if (__predict_false(p->p_slflag & PSL_CHTRACED)) {
429 		struct proc *q;
430 		PROCLIST_FOREACH(q, &allproc) {
431 			if (q->p_opptr == p)
432 				q->p_opptr = NULL;
433 		}
434 		PROCLIST_FOREACH(q, &zombproc) {
435 			if (q->p_opptr == p)
436 				q->p_opptr = NULL;
437 		}
438 	}
439 
440 	/*
441 	 * Give orphaned children to init(8).
442 	 */
443 	child = LIST_FIRST(&p->p_children);
444 	wakeinit = (child != NULL);
445 	for (; child != NULL; child = next_child) {
446 		next_child = LIST_NEXT(child, p_sibling);
447 
448 		/*
449 		 * Traced processes are killed since their existence
450 		 * means someone is screwing up. Since we reset the
451 		 * trace flags, the logic in sys_wait4() would not be
452 		 * triggered to reparent the process to its
453 		 * original parent, so we must do this here.
454 		 */
455 		if (__predict_false(child->p_slflag & PSL_TRACED)) {
456 			mutex_enter(p->p_lock);
457 			child->p_slflag &=
458 			    ~(PSL_TRACED|PSL_SYSCALL);
459 			mutex_exit(p->p_lock);
460 			if (child->p_opptr != child->p_pptr) {
461 				struct proc *t = child->p_opptr;
462 				proc_reparent(child, t ? t : initproc);
463 				child->p_opptr = NULL;
464 			} else
465 				proc_reparent(child, initproc);
466 			killproc(child, "orphaned traced process");
467 		} else
468 			proc_reparent(child, initproc);
469 	}
470 
471 	/*
472 	 * Move proc from allproc to zombproc, it's now nearly ready to be
473 	 * collected by parent.
474 	 */
475 	LIST_REMOVE(l, l_list);
476 	LIST_REMOVE(p, p_list);
477 	LIST_INSERT_HEAD(&zombproc, p, p_list);
478 
479 	/*
480 	 * Mark the process as dead.  We must do this before we signal
481 	 * the parent.
482 	 */
483 	p->p_stat = SDEAD;
484 
485 	/* Put in front of parent's sibling list for parent to collect it */
486 	old_parent = p->p_pptr;
487 	old_parent->p_nstopchild++;
488 	if (LIST_FIRST(&old_parent->p_children) != p) {
489 		/* Put child where it can be found quickly */
490 		LIST_REMOVE(p, p_sibling);
491 		LIST_INSERT_HEAD(&old_parent->p_children, p, p_sibling);
492 	}
493 
494 	/*
495 	 * Notify parent that we're gone.  If parent has the P_NOCLDWAIT
496 	 * flag set, notify init instead (and hope it will handle
497 	 * this situation).
498 	 */
499 	if (old_parent->p_flag & (PK_NOCLDWAIT|PK_CLDSIGIGN)) {
500 		proc_reparent(p, initproc);
501 		wakeinit = 1;
502 
503 		/*
504 		 * If this was the last child of our parent, notify
505 		 * parent, so in case he was wait(2)ing, he will
506 		 * continue.
507 		 */
508 		if (LIST_FIRST(&old_parent->p_children) == NULL)
509 			cv_broadcast(&old_parent->p_waitcv);
510 	}
511 
512 	/* Reload parent pointer, since p may have been reparented above */
513 	new_parent = p->p_pptr;
514 
515 	if (__predict_false(p->p_exitsig != 0)) {
516 		exit_psignal(p, new_parent, &ksi);
517 		kpsignal(new_parent, &ksi, NULL);
518 	}
519 
520 	/* Calculate the final rusage info.  */
521 	calcru(p, &p->p_stats->p_ru.ru_utime, &p->p_stats->p_ru.ru_stime,
522 	    NULL, NULL);
523 
524 	if (wakeinit)
525 		cv_broadcast(&initproc->p_waitcv);
526 
527 	callout_destroy(&l->l_timeout_ch);
528 
529 	/*
530 	 * Release any PCU resources before becoming a zombie.
531 	 */
532 	pcu_discard_all(l);
533 
534 	mutex_enter(p->p_lock);
535 	/* Free the linux lwp id */
536 	if ((l->l_pflag & LP_PIDLID) != 0 && l->l_lid != p->p_pid)
537 		proc_free_pid(l->l_lid);
538 	lwp_drainrefs(l);
539 	lwp_lock(l);
540 	l->l_prflag &= ~LPR_DETACHED;
541 	l->l_stat = LSZOMB;
542 	lwp_unlock(l);
543 	KASSERT(curlwp == l);
544 	KASSERT(p->p_nrlwps == 1);
545 	KASSERT(p->p_nlwps == 1);
546 	p->p_stat = SZOMB;
547 	p->p_nrlwps--;
548 	p->p_nzlwps++;
549 	p->p_ndlwps = 0;
550 	mutex_exit(p->p_lock);
551 
552 	/*
553 	 * Signal the parent to collect us, and drop the proclist lock.
554 	 * Drop debugger/procfs lock; no new references can be gained.
555 	 */
556 	cv_broadcast(&p->p_pptr->p_waitcv);
557 	rw_exit(&p->p_reflock);
558 	mutex_exit(proc_lock);
559 
560 	/* Verify that we hold no locks other than the kernel lock. */
561 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
562 
563 	/*
564 	 * NOTE: WE ARE NO LONGER ALLOWED TO SLEEP!
565 	 */
566 
567 	/*
568 	 * Give machine-dependent code a chance to free any MD LWP
569 	 * resources.  This must be done before uvm_lwp_exit(), in
570 	 * case these resources are in the PCB.
571 	 */
572 	cpu_lwp_free(l, 1);
573 
574 	pmap_deactivate(l);
575 
576 	/* This process no longer needs to hold the kernel lock. */
577 #ifdef notyet
578 	/* XXXSMP hold in lwp_userret() */
579 	KERNEL_UNLOCK_LAST(l);
580 #else
581 	KERNEL_UNLOCK_ALL(l, NULL);
582 #endif
583 
584 	lwp_exit_switchaway(l);
585 }
586 
587 void
588 exit_lwps(struct lwp *l)
589 {
590 	proc_t *p = l->l_proc;
591 	lwp_t *l2;
592 	int nlocks;
593 
594 	KERNEL_UNLOCK_ALL(l, &nlocks);
595 retry:
596 	KASSERT(mutex_owned(p->p_lock));
597 
598 	/*
599 	 * Interrupt LWPs in interruptable sleep, unsuspend suspended
600 	 * LWPs and then wait for everyone else to finish.
601 	 */
602 	LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
603 		if (l2 == l)
604 			continue;
605 		lwp_lock(l2);
606 		l2->l_flag |= LW_WEXIT;
607 		if ((l2->l_stat == LSSLEEP && (l2->l_flag & LW_SINTR)) ||
608 		    l2->l_stat == LSSUSPENDED || l2->l_stat == LSSTOP) {
609 		    	/* setrunnable() will release the lock. */
610 			setrunnable(l2);
611 			continue;
612 		}
613 		lwp_unlock(l2);
614 	}
615 
616 	/*
617 	 * Wait for every LWP to exit.  Note: LWPs can get suspended/slept
618 	 * behind us or there may even be new LWPs created.  Therefore, a
619 	 * full retry is required on error.
620 	 */
621 	while (p->p_nlwps > 1) {
622 		if (lwp_wait(l, 0, NULL, true)) {
623 			goto retry;
624 		}
625 	}
626 
627 	KERNEL_LOCK(nlocks, l);
628 	KASSERT(p->p_nlwps == 1);
629 }
630 
631 int
632 do_sys_waitid(idtype_t idtype, id_t id, int *pid, int *status, int options,
633     struct wrusage *wru, siginfo_t *si)
634 {
635 	proc_t *child;
636 	int error;
637 
638 
639 	if (wru != NULL)
640 		memset(wru, 0, sizeof(*wru));
641 	if (si != NULL)
642 		memset(si, 0, sizeof(*si));
643 
644 	mutex_enter(proc_lock);
645 	error = find_stopped_child(curproc, idtype, id, options, &child,
646 	    wru, si);
647 	if (child == NULL) {
648 		mutex_exit(proc_lock);
649 		*pid = 0;
650 		*status = 0;
651 		return error;
652 	}
653 	*pid = child->p_pid;
654 
655 	if (child->p_stat == SZOMB) {
656 		/* Child is exiting */
657 		*status = P_WAITSTATUS(child);
658 		/* proc_free() will release the proc_lock. */
659 		if (options & WNOWAIT) {
660 			mutex_exit(proc_lock);
661 		} else {
662 			proc_free(child, wru);
663 		}
664 	} else {
665 		/* Don't mark SIGCONT if we are being stopped */
666 		*status = (child->p_xsig == SIGCONT && child->p_stat != SSTOP) ?
667 		    W_CONTCODE() : W_STOPCODE(child->p_xsig);
668 		mutex_exit(proc_lock);
669 	}
670 	return 0;
671 }
672 
673 int
674 do_sys_wait(int *pid, int *status, int options, struct rusage *ru)
675 {
676 	idtype_t idtype;
677 	id_t id;
678 	int ret;
679 	struct wrusage wru;
680 
681 	/*
682 	 * Translate the special pid values into the (idtype, pid)
683 	 * pair for wait6. The WAIT_MYPGRP case is handled by
684 	 * find_stopped_child() on its own.
685 	 */
686 	if (*pid == WAIT_ANY) {
687 		idtype = P_ALL;
688 		id = 0;
689 	} else if (*pid < 0) {
690 		idtype = P_PGID;
691 		id = (id_t)-*pid;
692 	} else {
693 		idtype = P_PID;
694 		id = (id_t)*pid;
695 	}
696 	options |= WEXITED | WTRAPPED;
697 	ret = do_sys_waitid(idtype, id, pid, status, options, ru ? &wru : NULL,
698 	    NULL);
699 	if (ru)
700 		*ru = wru.wru_self;
701 	return ret;
702 }
703 
704 int
705 sys___wait450(struct lwp *l, const struct sys___wait450_args *uap,
706     register_t *retval)
707 {
708 	/* {
709 		syscallarg(int)			pid;
710 		syscallarg(int *)		status;
711 		syscallarg(int)			options;
712 		syscallarg(struct rusage *)	rusage;
713 	} */
714 	int error, status, pid = SCARG(uap, pid);
715 	struct rusage ru;
716 
717 	error = do_sys_wait(&pid, &status, SCARG(uap, options),
718 	    SCARG(uap, rusage) != NULL ? &ru : NULL);
719 
720 	retval[0] = pid;
721 	if (pid == 0) {
722 		return error;
723 	}
724 	if (SCARG(uap, status)) {
725 		error = copyout(&status, SCARG(uap, status), sizeof(status));
726 	}
727 	if (SCARG(uap, rusage) && error == 0) {
728 		error = copyout(&ru, SCARG(uap, rusage), sizeof(ru));
729 	}
730 	return error;
731 }
732 
733 int
734 sys_wait6(struct lwp *l, const struct sys_wait6_args *uap, register_t *retval)
735 {
736 	/* {
737 		syscallarg(idtype_t)		idtype;
738 		syscallarg(id_t)		id;
739 		syscallarg(int *)		status;
740 		syscallarg(int)			options;
741 		syscallarg(struct wrusage *)	wru;
742 		syscallarg(siginfo_t *)		si;
743 	} */
744 	struct wrusage wru, *wrup;
745 	siginfo_t si, *sip;
746 	idtype_t idtype;
747 	int pid;
748 	id_t id;
749 	int error, status;
750 
751 	idtype = SCARG(uap, idtype);
752 	id = SCARG(uap, id);
753 
754 	if (SCARG(uap, wru) != NULL)
755 		wrup = &wru;
756 	else
757 		wrup = NULL;
758 
759 	if (SCARG(uap, info) != NULL)
760 		sip = &si;
761 	else
762 		sip = NULL;
763 
764 	/*
765 	 *  We expect all callers of wait6() to know about WEXITED and
766 	 *  WTRAPPED.
767 	 */
768 	error = do_sys_waitid(idtype, id, &pid, &status, SCARG(uap, options),
769 	    wrup, sip);
770 
771 	retval[0] = pid; 	/* tell userland who it was */
772 
773 #if 0
774 	/*
775 	 * should we copyout if there was no process, hence no useful data?
776 	 * We don't for an old sytle wait4() (etc) but I believe
777 	 * FreeBSD does for wait6(), so a tossup...  Go with FreeBSD for now.
778 	 */
779 	if (pid == 0)
780 		return error;
781 #endif
782 
783 	if (SCARG(uap, status) != NULL && error == 0)
784 		error = copyout(&status, SCARG(uap, status), sizeof(status));
785 	if (SCARG(uap, wru) != NULL && error == 0)
786 		error = copyout(&wru, SCARG(uap, wru), sizeof(wru));
787 	if (SCARG(uap, info) != NULL && error == 0)
788 		error = copyout(&si, SCARG(uap, info), sizeof(si));
789 	return error;
790 }
791 
792 
793 /*
794  * Find a process that matches the provided criteria, and fill siginfo
795  * and resources if found.
796  * Returns:
797  *	-1: 	Not found, abort early
798  *	 0:	Not matched
799  *	 1:	Matched, there might be more matches
800  *	 2:	This is the only match
801  */
802 static int
803 match_process(const struct proc *pp, struct proc **q, idtype_t idtype, id_t id,
804     int options, struct wrusage *wrusage, siginfo_t *siginfo)
805 {
806 	struct rusage *rup;
807 	struct proc *p = *q;
808 	int rv = 1;
809 
810 	mutex_enter(p->p_lock);
811 	switch (idtype) {
812 	case P_ALL:
813 		break;
814 	case P_PID:
815 		if (p->p_pid != (pid_t)id) {
816 			mutex_exit(p->p_lock);
817 			p = *q = proc_find_raw((pid_t)id);
818 			if (p == NULL || p->p_stat == SIDL || p->p_pptr != pp) {
819 				*q = NULL;
820 				return -1;
821 			}
822 			mutex_enter(p->p_lock);
823 		}
824 		rv++;
825 		break;
826 	case P_PGID:
827 		if (p->p_pgid != (pid_t)id)
828 			goto out;
829 		break;
830 	case P_SID:
831 		if (p->p_session->s_sid != (pid_t)id)
832 			goto out;
833 		break;
834 	case P_UID:
835 		if (kauth_cred_geteuid(p->p_cred) != (uid_t)id)
836 			goto out;
837 		break;
838 	case P_GID:
839 		if (kauth_cred_getegid(p->p_cred) != (gid_t)id)
840 			goto out;
841 		break;
842 	case P_CID:
843 	case P_PSETID:
844 	case P_CPUID:
845 		/* XXX: Implement me */
846 	default:
847 	out:
848 		mutex_exit(p->p_lock);
849 		return 0;
850 	}
851 
852 	if ((options & WEXITED) == 0 && p->p_stat == SZOMB)
853 		goto out;
854 
855 	if (siginfo != NULL) {
856 		siginfo->si_errno = 0;
857 
858 		/*
859 		 * SUSv4 requires that the si_signo value is always
860 		 * SIGCHLD. Obey it despite the rfork(2) interface
861 		 * allows to request other signal for child exit
862 		 * notification.
863 		 */
864 		siginfo->si_signo = SIGCHLD;
865 
866 		/*
867 		 *  This is still a rough estimate.  We will fix the
868 		 *  cases TRAPPED, STOPPED, and CONTINUED later.
869 		 */
870 		if (p->p_sflag & PS_COREDUMP) {
871 			siginfo->si_code = CLD_DUMPED;
872 			siginfo->si_status = p->p_xsig;
873 		} else if (p->p_xsig) {
874 			siginfo->si_code = CLD_KILLED;
875 			siginfo->si_status = p->p_xsig;
876 		} else {
877 			siginfo->si_code = CLD_EXITED;
878 			siginfo->si_status = p->p_xexit;
879 		}
880 
881 		siginfo->si_pid = p->p_pid;
882 		siginfo->si_uid = kauth_cred_geteuid(p->p_cred);
883 		siginfo->si_utime = p->p_stats->p_ru.ru_utime.tv_sec;
884 		siginfo->si_stime = p->p_stats->p_ru.ru_stime.tv_sec;
885 	}
886 
887 	/*
888 	 * There should be no reason to limit resources usage info to
889 	 * exited processes only.  A snapshot about any resources used
890 	 * by a stopped process may be exactly what is needed.
891 	 */
892 	if (wrusage != NULL) {
893 		rup = &wrusage->wru_self;
894 		*rup = p->p_stats->p_ru;
895 		calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
896 
897 		rup = &wrusage->wru_children;
898 		*rup = p->p_stats->p_cru;
899 		calcru(p, &rup->ru_utime, &rup->ru_stime, NULL, NULL);
900 	}
901 
902 	mutex_exit(p->p_lock);
903 	return rv;
904 }
905 
906 /*
907  * Determine if there are existing processes being debugged
908  * that used to be (and sometime later will be again) children
909  * of a specific parent (while matching wait criteria)
910  */
911 static bool
912 debugged_child_exists(idtype_t idtype, id_t id, int options, siginfo_t *si,
913     const struct proc *parent)
914 {
915 	struct proc *pp;
916 
917 	/*
918 	 * If we are searching for a specific pid, we can optimise a little
919 	 */
920 	if (idtype == P_PID) {
921 		/*
922 		 * Check the specific process to see if its real parent is us
923 		 */
924 		pp = proc_find_raw((pid_t)id);
925 		if (pp != NULL && pp->p_stat != SIDL && pp->p_opptr == parent) {
926 			/*
927 			 * using P_ALL here avoids match_process() doing the
928 			 * same work that we just did, but incorrectly for
929 			 * this scenario.
930 			 */
931 			if (match_process(parent, &pp, P_ALL, id, options,
932 			    NULL, si))
933 				return true;
934 		}
935 		return false;
936 	}
937 
938 	/*
939 	 * For the hard cases, just look everywhere to see if some
940 	 * stolen (reparented) process is really our lost child.
941 	 * Then check if that process could satisfy the wait conditions.
942 	 */
943 
944 	/*
945 	 * XXX inefficient, but hopefully fairly rare.
946 	 * XXX should really use a list of reparented processes.
947 	 */
948 	PROCLIST_FOREACH(pp, &allproc) {
949 		if (pp->p_stat == SIDL)		/* XXX impossible ?? */
950 			continue;
951 		if (pp->p_opptr == parent &&
952 		    match_process(parent, &pp, idtype, id, options, NULL, si))
953 			return true;
954 	}
955 	PROCLIST_FOREACH(pp, &zombproc) {
956 		if (pp->p_stat == SIDL)		/* XXX impossible ?? */
957 			continue;
958 		if (pp->p_opptr == parent &&
959 		    match_process(parent, &pp, idtype, id, options, NULL, si))
960 			return true;
961 	}
962 
963 	return false;
964 }
965 
966 /*
967  * Scan list of child processes for a child process that has stopped or
968  * exited.  Used by sys_wait4 and 'compat' equivalents.
969  *
970  * Must be called with the proc_lock held, and may release while waiting.
971  */
972 static int
973 find_stopped_child(struct proc *parent, idtype_t idtype, id_t id, int options,
974     struct proc **child_p, struct wrusage *wru, siginfo_t *si)
975 {
976 	struct proc *child, *dead;
977 	int error;
978 
979 	KASSERT(mutex_owned(proc_lock));
980 
981 	if (options & ~WALLOPTS) {
982 		*child_p = NULL;
983 		return EINVAL;
984 	}
985 
986 	if ((options & WSELECTOPTS) == 0) {
987 		/*
988 		 * We will be unable to find any matching processes,
989 		 * because there are no known events to look for.
990 		 * Prefer to return error instead of blocking
991 		 * indefinitely.
992 		 */
993 		*child_p = NULL;
994 		return EINVAL;
995 	}
996 
997 	if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
998 		mutex_enter(parent->p_lock);
999 		id = (id_t)parent->p_pgid;
1000 		mutex_exit(parent->p_lock);
1001 		idtype = P_PGID;
1002 	}
1003 
1004 	for (;;) {
1005 		error = ECHILD;
1006 		dead = NULL;
1007 
1008 		LIST_FOREACH(child, &parent->p_children, p_sibling) {
1009 			int rv = match_process(parent, &child, idtype, id,
1010 			    options, wru, si);
1011 			if (rv == -1)
1012 				break;
1013 			if (rv == 0)
1014 				continue;
1015 
1016 			/*
1017 			 * Wait for processes with p_exitsig != SIGCHLD
1018 			 * processes only if WALTSIG is set; wait for
1019 			 * processes with p_exitsig == SIGCHLD only
1020 			 * if WALTSIG is clear.
1021 			 */
1022 			if (((options & WALLSIG) == 0) &&
1023 			    (options & WALTSIG ? child->p_exitsig == SIGCHLD
1024 						: P_EXITSIG(child) != SIGCHLD)){
1025 				if (rv == 2) {
1026 					child = NULL;
1027 					break;
1028 				}
1029 				continue;
1030 			}
1031 
1032 			error = 0;
1033 			if ((options & WNOZOMBIE) == 0) {
1034 				if (child->p_stat == SZOMB)
1035 					break;
1036 				if (child->p_stat == SDEAD) {
1037 					/*
1038 					 * We may occasionally arrive here
1039 					 * after receiving a signal, but
1040 					 * immediately before the child
1041 					 * process is zombified.  The wait
1042 					 * will be short, so avoid returning
1043 					 * to userspace.
1044 					 */
1045 					dead = child;
1046 				}
1047 			}
1048 
1049 			if ((options & WCONTINUED) != 0 &&
1050 			    child->p_xsig == SIGCONT &&
1051 			    (child->p_sflag & PS_CONTINUED)) {
1052 				if ((options & WNOWAIT) == 0) {
1053 					child->p_sflag &= ~PS_CONTINUED;
1054 					child->p_waited = 1;
1055 					parent->p_nstopchild--;
1056 				}
1057 				if (si) {
1058 					si->si_status = child->p_xsig;
1059 					si->si_code = CLD_CONTINUED;
1060 				}
1061 				break;
1062 			}
1063 
1064 			if ((options & (WTRAPPED|WSTOPPED)) != 0 &&
1065 			    child->p_stat == SSTOP &&
1066 			    child->p_waited == 0 &&
1067 			    ((child->p_slflag & PSL_TRACED) ||
1068 			    options & (WUNTRACED|WSTOPPED))) {
1069 				if ((options & WNOWAIT) == 0) {
1070 					child->p_waited = 1;
1071 					parent->p_nstopchild--;
1072 				}
1073 				if (si) {
1074 					si->si_status = child->p_xsig;
1075 					si->si_code =
1076 					    (child->p_slflag & PSL_TRACED) ?
1077 					    CLD_TRAPPED : CLD_STOPPED;
1078 				}
1079 				break;
1080 			}
1081 			if (parent->p_nstopchild == 0 || rv == 2) {
1082 				child = NULL;
1083 				break;
1084 			}
1085 		}
1086 
1087 		/*
1088 		 * If we found nothing, but we are the bereaved parent
1089 		 * of a stolen child, look and see if that child (or
1090 		 * one of them) meets our search criteria.   If so, then
1091 		 * we cannot succeed, but we can hang (wait...),
1092 		 * or if WNOHANG, return 0 instead of ECHILD
1093 		 */
1094 		if (child == NULL && error == ECHILD &&
1095 		    (parent->p_slflag & PSL_CHTRACED) &&
1096 		    debugged_child_exists(idtype, id, options, si, parent))
1097 			error = 0;
1098 
1099 		if (child != NULL || error != 0 ||
1100 		    ((options & WNOHANG) != 0 && dead == NULL)) {
1101 			*child_p = child;
1102 			return error;
1103 		}
1104 
1105 		/*
1106 		 * Wait for another child process to stop.
1107 		 */
1108 		error = cv_wait_sig(&parent->p_waitcv, proc_lock);
1109 
1110 		if (error != 0) {
1111 			*child_p = NULL;
1112 			return error;
1113 		}
1114 	}
1115 }
1116 
1117 /*
1118  * Free a process after parent has taken all the state info.  Must be called
1119  * with the proclist lock held, and will release before returning.
1120  *
1121  * *ru is returned to the caller, and must be freed by the caller.
1122  */
1123 static void
1124 proc_free(struct proc *p, struct wrusage *wru)
1125 {
1126 	struct proc *parent = p->p_pptr;
1127 	struct lwp *l;
1128 	ksiginfo_t ksi;
1129 	kauth_cred_t cred1, cred2;
1130 	uid_t uid;
1131 
1132 	KASSERT(mutex_owned(proc_lock));
1133 	KASSERT(p->p_nlwps == 1);
1134 	KASSERT(p->p_nzlwps == 1);
1135 	KASSERT(p->p_nrlwps == 0);
1136 	KASSERT(p->p_stat == SZOMB);
1137 
1138 	/*
1139 	 * If we got the child via ptrace(2) or procfs, and
1140 	 * the parent is different (meaning the process was
1141 	 * attached, rather than run as a child), then we need
1142 	 * to give it back to the old parent, and send the
1143 	 * parent the exit signal.  The rest of the cleanup
1144 	 * will be done when the old parent waits on the child.
1145 	 */
1146 	if ((p->p_slflag & PSL_TRACED) != 0 && p->p_opptr != parent) {
1147 		mutex_enter(p->p_lock);
1148 		p->p_slflag &= ~(PSL_TRACED|PSL_SYSCALL);
1149 		mutex_exit(p->p_lock);
1150 		parent = (p->p_opptr == NULL) ? initproc : p->p_opptr;
1151 		proc_reparent(p, parent);
1152 		p->p_opptr = NULL;
1153 		if (p->p_exitsig != 0) {
1154 			exit_psignal(p, parent, &ksi);
1155 			kpsignal(parent, &ksi, NULL);
1156 		}
1157 		cv_broadcast(&parent->p_waitcv);
1158 		mutex_exit(proc_lock);
1159 		return;
1160 	}
1161 
1162 	sched_proc_exit(parent, p);
1163 
1164 	/*
1165 	 * Add child times of exiting process onto its own times.
1166 	 * This cannot be done any earlier else it might get done twice.
1167 	 */
1168 	l = LIST_FIRST(&p->p_lwps);
1169 	p->p_stats->p_ru.ru_nvcsw += (l->l_ncsw - l->l_nivcsw);
1170 	p->p_stats->p_ru.ru_nivcsw += l->l_nivcsw;
1171 	ruadd(&p->p_stats->p_ru, &l->l_ru);
1172 	ruadd(&p->p_stats->p_ru, &p->p_stats->p_cru);
1173 	ruadd(&parent->p_stats->p_cru, &p->p_stats->p_ru);
1174 	if (wru != NULL) {
1175 		wru->wru_self = p->p_stats->p_ru;
1176 		wru->wru_children = p->p_stats->p_cru;
1177 	}
1178 	p->p_xsig = 0;
1179 	p->p_xexit = 0;
1180 
1181 	/*
1182 	 * At this point we are going to start freeing the final resources.
1183 	 * If anyone tries to access the proc structure after here they will
1184 	 * get a shock - bits are missing.  Attempt to make it hard!  We
1185 	 * don't bother with any further locking past this point.
1186 	 */
1187 	p->p_stat = SIDL;		/* not even a zombie any more */
1188 	LIST_REMOVE(p, p_list);	/* off zombproc */
1189 	parent->p_nstopchild--;
1190 	LIST_REMOVE(p, p_sibling);
1191 
1192 	/*
1193 	 * Let pid be reallocated.
1194 	 */
1195 	proc_free_pid(p->p_pid);
1196 
1197 	/*
1198 	 * Unlink process from its process group.
1199 	 * Releases the proc_lock.
1200 	 */
1201 	proc_leavepgrp(p);
1202 
1203 	/*
1204 	 * Delay release until after lwp_free.
1205 	 */
1206 	cred2 = l->l_cred;
1207 
1208 	/*
1209 	 * Free the last LWP's resources.
1210 	 *
1211 	 * lwp_free ensures the LWP is no longer running on another CPU.
1212 	 */
1213 	lwp_free(l, false, true);
1214 
1215 	/*
1216 	 * Now no one except us can reach the process p.
1217 	 */
1218 
1219 	/*
1220 	 * Decrement the count of procs running with this uid.
1221 	 */
1222 	cred1 = p->p_cred;
1223 	uid = kauth_cred_getuid(cred1);
1224 	(void)chgproccnt(uid, -1);
1225 
1226 	/*
1227 	 * Release substructures.
1228 	 */
1229 
1230 	lim_free(p->p_limit);
1231 	pstatsfree(p->p_stats);
1232 	kauth_cred_free(cred1);
1233 	kauth_cred_free(cred2);
1234 
1235 	/*
1236 	 * Release reference to text vnode
1237 	 */
1238 	if (p->p_textvp)
1239 		vrele(p->p_textvp);
1240 	kmem_strfree(p->p_path);
1241 
1242 	mutex_destroy(&p->p_auxlock);
1243 	mutex_obj_free(p->p_lock);
1244 	mutex_destroy(&p->p_stmutex);
1245 	cv_destroy(&p->p_waitcv);
1246 	cv_destroy(&p->p_lwpcv);
1247 	rw_destroy(&p->p_reflock);
1248 
1249 	proc_free_mem(p);
1250 }
1251 
1252 /*
1253  * Change the parent of a process for tracing purposes.
1254  */
1255 void
1256 proc_changeparent(struct proc *t, struct proc *p)
1257 {
1258 	SET(t->p_slflag, PSL_TRACED);
1259 	t->p_opptr = t->p_pptr;
1260 	if (t->p_pptr == p)
1261 		return;
1262 	struct proc *parent = t->p_pptr;
1263 
1264 	if (parent->p_lock < t->p_lock) {
1265 		if (!mutex_tryenter(parent->p_lock)) {
1266 			mutex_exit(t->p_lock);
1267 			mutex_enter(parent->p_lock);
1268 			mutex_enter(t->p_lock);
1269 		}
1270 	} else if (parent->p_lock > t->p_lock) {
1271 		mutex_enter(parent->p_lock);
1272 	}
1273 	parent->p_slflag |= PSL_CHTRACED;
1274 	proc_reparent(t, p);
1275 	if (parent->p_lock != t->p_lock)
1276 		mutex_exit(parent->p_lock);
1277 }
1278 
1279 /*
1280  * make process 'parent' the new parent of process 'child'.
1281  *
1282  * Must be called with proc_lock held.
1283  */
1284 void
1285 proc_reparent(struct proc *child, struct proc *parent)
1286 {
1287 
1288 	KASSERT(mutex_owned(proc_lock));
1289 
1290 	if (child->p_pptr == parent)
1291 		return;
1292 
1293 	if (child->p_stat == SZOMB || child->p_stat == SDEAD ||
1294 	    (child->p_stat == SSTOP && !child->p_waited)) {
1295 		child->p_pptr->p_nstopchild--;
1296 		parent->p_nstopchild++;
1297 	}
1298 	if (parent == initproc) {
1299 		child->p_exitsig = SIGCHLD;
1300 		child->p_ppid = parent->p_pid;
1301 	}
1302 
1303 	LIST_REMOVE(child, p_sibling);
1304 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1305 	child->p_pptr = parent;
1306 }
1307