xref: /freebsd/sys/kern/kern_exit.c (revision cd8537910406e68d4719136a5b0cf6d23bb1b23b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_ktrace.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/capsicum.h>
48 #include <sys/eventhandler.h>
49 #include <sys/kernel.h>
50 #include <sys/ktr.h>
51 #include <sys/malloc.h>
52 #include <sys/lock.h>
53 #include <sys/mutex.h>
54 #include <sys/proc.h>
55 #include <sys/procdesc.h>
56 #include <sys/jail.h>
57 #include <sys/tty.h>
58 #include <sys/wait.h>
59 #include <sys/vmmeter.h>
60 #include <sys/vnode.h>
61 #include <sys/racct.h>
62 #include <sys/resourcevar.h>
63 #include <sys/sbuf.h>
64 #include <sys/signalvar.h>
65 #include <sys/sched.h>
66 #include <sys/sx.h>
67 #include <sys/syscallsubr.h>
68 #include <sys/syslog.h>
69 #include <sys/ptrace.h>
70 #include <sys/acct.h>		/* for acct_process() function prototype */
71 #include <sys/filedesc.h>
72 #include <sys/sdt.h>
73 #include <sys/shm.h>
74 #include <sys/sem.h>
75 #include <sys/sysent.h>
76 #include <sys/timers.h>
77 #include <sys/umtx.h>
78 #ifdef KTRACE
79 #include <sys/ktrace.h>
80 #endif
81 
82 #include <security/audit/audit.h>
83 #include <security/mac/mac_framework.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_param.h>
88 #include <vm/pmap.h>
89 #include <vm/vm_map.h>
90 #include <vm/vm_page.h>
91 #include <vm/uma.h>
92 
93 #ifdef KDTRACE_HOOKS
94 #include <sys/dtrace_bsd.h>
95 dtrace_execexit_func_t	dtrace_fasttrap_exit;
96 #endif
97 
98 SDT_PROVIDER_DECLARE(proc);
99 SDT_PROBE_DEFINE1(proc, , , exit, "int");
100 
101 struct proc *
102 proc_realparent(struct proc *child)
103 {
104 	struct proc *p, *parent;
105 
106 	sx_assert(&proctree_lock, SX_LOCKED);
107 	if ((child->p_treeflag & P_TREE_ORPHANED) == 0)
108 		return (child->p_pptr->p_pid == child->p_oppid ?
109 		    child->p_pptr : child->p_reaper);
110 	for (p = child; (p->p_treeflag & P_TREE_FIRST_ORPHAN) == 0;) {
111 		/* Cannot use LIST_PREV(), since the list head is not known. */
112 		p = __containerof(p->p_orphan.le_prev, struct proc,
113 		    p_orphan.le_next);
114 		KASSERT((p->p_treeflag & P_TREE_ORPHANED) != 0,
115 		    ("missing P_ORPHAN %p", p));
116 	}
117 	parent = __containerof(p->p_orphan.le_prev, struct proc,
118 	    p_orphans.lh_first);
119 	return (parent);
120 }
121 
122 void
123 reaper_abandon_children(struct proc *p, bool exiting)
124 {
125 	struct proc *p1, *p2, *ptmp;
126 
127 	sx_assert(&proctree_lock, SX_LOCKED);
128 	KASSERT(p != initproc, ("reaper_abandon_children for initproc"));
129 	if ((p->p_treeflag & P_TREE_REAPER) == 0)
130 		return;
131 	p1 = p->p_reaper;
132 	LIST_FOREACH_SAFE(p2, &p->p_reaplist, p_reapsibling, ptmp) {
133 		LIST_REMOVE(p2, p_reapsibling);
134 		p2->p_reaper = p1;
135 		p2->p_reapsubtree = p->p_reapsubtree;
136 		LIST_INSERT_HEAD(&p1->p_reaplist, p2, p_reapsibling);
137 		if (exiting && p2->p_pptr == p) {
138 			PROC_LOCK(p2);
139 			proc_reparent(p2, p1, true);
140 			PROC_UNLOCK(p2);
141 		}
142 	}
143 	KASSERT(LIST_EMPTY(&p->p_reaplist), ("p_reaplist not empty"));
144 	p->p_treeflag &= ~P_TREE_REAPER;
145 }
146 
147 static void
148 reaper_clear(struct proc *p)
149 {
150 	struct proc *p1;
151 	bool clear;
152 
153 	sx_assert(&proctree_lock, SX_LOCKED);
154 	LIST_REMOVE(p, p_reapsibling);
155 	if (p->p_reapsubtree == 1)
156 		return;
157 	clear = true;
158 	LIST_FOREACH(p1, &p->p_reaper->p_reaplist, p_reapsibling) {
159 		if (p1->p_reapsubtree == p->p_reapsubtree) {
160 			clear = false;
161 			break;
162 		}
163 	}
164 	if (clear)
165 		proc_id_clear(PROC_ID_REAP, p->p_reapsubtree);
166 }
167 
168 void
169 proc_clear_orphan(struct proc *p)
170 {
171 	struct proc *p1;
172 
173 	sx_assert(&proctree_lock, SA_XLOCKED);
174 	if ((p->p_treeflag & P_TREE_ORPHANED) == 0)
175 		return;
176 	if ((p->p_treeflag & P_TREE_FIRST_ORPHAN) != 0) {
177 		p1 = LIST_NEXT(p, p_orphan);
178 		if (p1 != NULL)
179 			p1->p_treeflag |= P_TREE_FIRST_ORPHAN;
180 		p->p_treeflag &= ~P_TREE_FIRST_ORPHAN;
181 	}
182 	LIST_REMOVE(p, p_orphan);
183 	p->p_treeflag &= ~P_TREE_ORPHANED;
184 }
185 
186 /*
187  * exit -- death of process.
188  */
189 void
190 sys_sys_exit(struct thread *td, struct sys_exit_args *uap)
191 {
192 
193 	exit1(td, uap->rval, 0);
194 	/* NOTREACHED */
195 }
196 
197 /*
198  * Exit: deallocate address space and other resources, change proc state to
199  * zombie, and unlink proc from allproc and parent's lists.  Save exit status
200  * and rusage for wait().  Check for child processes and orphan them.
201  */
202 void
203 exit1(struct thread *td, int rval, int signo)
204 {
205 	struct proc *p, *nq, *q, *t;
206 	struct thread *tdt;
207 	ksiginfo_t *ksi, *ksi1;
208 	int signal_parent;
209 
210 	mtx_assert(&Giant, MA_NOTOWNED);
211 	KASSERT(rval == 0 || signo == 0, ("exit1 rv %d sig %d", rval, signo));
212 
213 	p = td->td_proc;
214 	/*
215 	 * XXX in case we're rebooting we just let init die in order to
216 	 * work around an unsolved stack overflow seen very late during
217 	 * shutdown on sparc64 when the gmirror worker process exists.
218 	 * XXX what to do now that sparc64 is gone... remove if?
219 	 */
220 	if (p == initproc && rebooting == 0) {
221 		printf("init died (signal %d, exit %d)\n", signo, rval);
222 		panic("Going nowhere without my init!");
223 	}
224 
225 	/*
226 	 * Deref SU mp, since the thread does not return to userspace.
227 	 */
228 	td_softdep_cleanup(td);
229 
230 	/*
231 	 * MUST abort all other threads before proceeding past here.
232 	 */
233 	PROC_LOCK(p);
234 	/*
235 	 * First check if some other thread or external request got
236 	 * here before us.  If so, act appropriately: exit or suspend.
237 	 * We must ensure that stop requests are handled before we set
238 	 * P_WEXIT.
239 	 */
240 	thread_suspend_check(0);
241 	while (p->p_flag & P_HADTHREADS) {
242 		/*
243 		 * Kill off the other threads. This requires
244 		 * some co-operation from other parts of the kernel
245 		 * so it may not be instantaneous.  With this state set
246 		 * any thread entering the kernel from userspace will
247 		 * thread_exit() in trap().  Any thread attempting to
248 		 * sleep will return immediately with EINTR or EWOULDBLOCK
249 		 * which will hopefully force them to back out to userland
250 		 * freeing resources as they go.  Any thread attempting
251 		 * to return to userland will thread_exit() from userret().
252 		 * thread_exit() will unsuspend us when the last of the
253 		 * other threads exits.
254 		 * If there is already a thread singler after resumption,
255 		 * calling thread_single will fail; in that case, we just
256 		 * re-check all suspension request, the thread should
257 		 * either be suspended there or exit.
258 		 */
259 		if (!thread_single(p, SINGLE_EXIT))
260 			/*
261 			 * All other activity in this process is now
262 			 * stopped.  Threading support has been turned
263 			 * off.
264 			 */
265 			break;
266 		/*
267 		 * Recheck for new stop or suspend requests which
268 		 * might appear while process lock was dropped in
269 		 * thread_single().
270 		 */
271 		thread_suspend_check(0);
272 	}
273 	KASSERT(p->p_numthreads == 1,
274 	    ("exit1: proc %p exiting with %d threads", p, p->p_numthreads));
275 	racct_sub(p, RACCT_NTHR, 1);
276 
277 	/* Let event handler change exit status */
278 	p->p_xexit = rval;
279 	p->p_xsig = signo;
280 
281 	/*
282 	 * Ignore any pending request to stop due to a stop signal.
283 	 * Once P_WEXIT is set, future requests will be ignored as
284 	 * well.
285 	 */
286 	p->p_flag &= ~P_STOPPED_SIG;
287 	KASSERT(!P_SHOULDSTOP(p), ("exiting process is stopped"));
288 
289 	/* Note that we are exiting. */
290 	p->p_flag |= P_WEXIT;
291 
292 	/*
293 	 * Wait for any processes that have a hold on our vmspace to
294 	 * release their reference.
295 	 */
296 	while (p->p_lock > 0)
297 		msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
298 
299 	PROC_UNLOCK(p);
300 	/* Drain the limit callout while we don't have the proc locked */
301 	callout_drain(&p->p_limco);
302 
303 #ifdef AUDIT
304 	/*
305 	 * The Sun BSM exit token contains two components: an exit status as
306 	 * passed to exit(), and a return value to indicate what sort of exit
307 	 * it was.  The exit status is WEXITSTATUS(rv), but it's not clear
308 	 * what the return value is.
309 	 */
310 	AUDIT_ARG_EXIT(rval, 0);
311 	AUDIT_SYSCALL_EXIT(0, td);
312 #endif
313 
314 	/* Are we a task leader with peers? */
315 	if (p->p_peers != NULL && p == p->p_leader) {
316 		mtx_lock(&ppeers_lock);
317 		q = p->p_peers;
318 		while (q != NULL) {
319 			PROC_LOCK(q);
320 			kern_psignal(q, SIGKILL);
321 			PROC_UNLOCK(q);
322 			q = q->p_peers;
323 		}
324 		while (p->p_peers != NULL)
325 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
326 		mtx_unlock(&ppeers_lock);
327 	}
328 
329 	itimers_exit(p);
330 
331 	if (p->p_sysent->sv_onexit != NULL)
332 		p->p_sysent->sv_onexit(p);
333 
334 	/*
335 	 * Check if any loadable modules need anything done at process exit.
336 	 * E.g. SYSV IPC stuff.
337 	 * Event handler could change exit status.
338 	 * XXX what if one of these generates an error?
339 	 */
340 	EVENTHANDLER_DIRECT_INVOKE(process_exit, p);
341 
342 	/*
343 	 * If parent is waiting for us to exit or exec,
344 	 * P_PPWAIT is set; we will wakeup the parent below.
345 	 */
346 	PROC_LOCK(p);
347 	stopprofclock(p);
348 	p->p_ptevents = 0;
349 
350 	/*
351 	 * Stop the real interval timer.  If the handler is currently
352 	 * executing, prevent it from rearming itself and let it finish.
353 	 */
354 	if (timevalisset(&p->p_realtimer.it_value) &&
355 	    _callout_stop_safe(&p->p_itcallout, CS_EXECUTING, NULL) == 0) {
356 		timevalclear(&p->p_realtimer.it_interval);
357 		msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
358 		KASSERT(!timevalisset(&p->p_realtimer.it_value),
359 		    ("realtime timer is still armed"));
360 	}
361 
362 	PROC_UNLOCK(p);
363 
364 	umtx_thread_exit(td);
365 	seltdfini(td);
366 
367 	/*
368 	 * Reset any sigio structures pointing to us as a result of
369 	 * F_SETOWN with our pid.  The P_WEXIT flag interlocks with fsetown().
370 	 */
371 	funsetownlst(&p->p_sigiolst);
372 
373 	/*
374 	 * Close open files and release open-file table.
375 	 * This may block!
376 	 */
377 	pdescfree(td);
378 	fdescfree(td);
379 
380 	/*
381 	 * If this thread tickled GEOM, we need to wait for the giggling to
382 	 * stop before we return to userland
383 	 */
384 	if (td->td_pflags & TDP_GEOM)
385 		g_waitidle();
386 
387 	/*
388 	 * Remove ourself from our leader's peer list and wake our leader.
389 	 */
390 	if (p->p_leader->p_peers != NULL) {
391 		mtx_lock(&ppeers_lock);
392 		if (p->p_leader->p_peers != NULL) {
393 			q = p->p_leader;
394 			while (q->p_peers != p)
395 				q = q->p_peers;
396 			q->p_peers = p->p_peers;
397 			wakeup(p->p_leader);
398 		}
399 		mtx_unlock(&ppeers_lock);
400 	}
401 
402 	vmspace_exit(td);
403 	(void)acct_process(td);
404 
405 #ifdef KTRACE
406 	ktrprocexit(td);
407 #endif
408 	/*
409 	 * Release reference to text vnode
410 	 */
411 	if (p->p_textvp != NULL) {
412 		vrele(p->p_textvp);
413 		p->p_textvp = NULL;
414 	}
415 
416 	/*
417 	 * Release our limits structure.
418 	 */
419 	lim_free(p->p_limit);
420 	p->p_limit = NULL;
421 
422 	tidhash_remove(td);
423 
424 	/*
425 	 * Call machine-dependent code to release any
426 	 * machine-dependent resources other than the address space.
427 	 * The address space is released by "vmspace_exitfree(p)" in
428 	 * vm_waitproc().
429 	 */
430 	cpu_exit(td);
431 
432 	WITNESS_WARN(WARN_PANIC, NULL, "process (pid %d) exiting", p->p_pid);
433 
434 	/*
435 	 * Remove from allproc. It still sits in the hash.
436 	 */
437 	sx_xlock(&allproc_lock);
438 	LIST_REMOVE(p, p_list);
439 	sx_xunlock(&allproc_lock);
440 
441 	sx_xlock(&proctree_lock);
442 	PROC_LOCK(p);
443 	p->p_flag &= ~(P_TRACED | P_PPWAIT | P_PPTRACE);
444 	PROC_UNLOCK(p);
445 
446 	/*
447 	 * killjobc() might drop and re-acquire proctree_lock to
448 	 * revoke control tty if exiting process was a session leader.
449 	 */
450 	killjobc();
451 
452 	/*
453 	 * Reparent all children processes:
454 	 * - traced ones to the original parent (or init if we are that parent)
455 	 * - the rest to init
456 	 */
457 	q = LIST_FIRST(&p->p_children);
458 	if (q != NULL)		/* only need this if any child is S_ZOMB */
459 		wakeup(q->p_reaper);
460 	for (; q != NULL; q = nq) {
461 		nq = LIST_NEXT(q, p_sibling);
462 		ksi = ksiginfo_alloc(TRUE);
463 		PROC_LOCK(q);
464 		q->p_sigparent = SIGCHLD;
465 
466 		if ((q->p_flag & P_TRACED) == 0) {
467 			proc_reparent(q, q->p_reaper, true);
468 			if (q->p_state == PRS_ZOMBIE) {
469 				/*
470 				 * Inform reaper about the reparented
471 				 * zombie, since wait(2) has something
472 				 * new to report.  Guarantee queueing
473 				 * of the SIGCHLD signal, similar to
474 				 * the _exit() behaviour, by providing
475 				 * our ksiginfo.  Ksi is freed by the
476 				 * signal delivery.
477 				 */
478 				if (q->p_ksi == NULL) {
479 					ksi1 = NULL;
480 				} else {
481 					ksiginfo_copy(q->p_ksi, ksi);
482 					ksi->ksi_flags |= KSI_INS;
483 					ksi1 = ksi;
484 					ksi = NULL;
485 				}
486 				PROC_LOCK(q->p_reaper);
487 				pksignal(q->p_reaper, SIGCHLD, ksi1);
488 				PROC_UNLOCK(q->p_reaper);
489 			} else if (q->p_pdeathsig > 0) {
490 				/*
491 				 * The child asked to received a signal
492 				 * when we exit.
493 				 */
494 				kern_psignal(q, q->p_pdeathsig);
495 			}
496 		} else {
497 			/*
498 			 * Traced processes are killed since their existence
499 			 * means someone is screwing up.
500 			 */
501 			t = proc_realparent(q);
502 			if (t == p) {
503 				proc_reparent(q, q->p_reaper, true);
504 			} else {
505 				PROC_LOCK(t);
506 				proc_reparent(q, t, true);
507 				PROC_UNLOCK(t);
508 			}
509 			/*
510 			 * Since q was found on our children list, the
511 			 * proc_reparent() call moved q to the orphan
512 			 * list due to present P_TRACED flag. Clear
513 			 * orphan link for q now while q is locked.
514 			 */
515 			proc_clear_orphan(q);
516 			q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
517 			q->p_flag2 &= ~P2_PTRACE_FSTP;
518 			q->p_ptevents = 0;
519 			FOREACH_THREAD_IN_PROC(q, tdt) {
520 				tdt->td_dbgflags &= ~(TDB_SUSPEND | TDB_XSIG |
521 				    TDB_FSTP);
522 			}
523 			kern_psignal(q, SIGKILL);
524 		}
525 		PROC_UNLOCK(q);
526 		if (ksi != NULL)
527 			ksiginfo_free(ksi);
528 	}
529 
530 	/*
531 	 * Also get rid of our orphans.
532 	 */
533 	while ((q = LIST_FIRST(&p->p_orphans)) != NULL) {
534 		PROC_LOCK(q);
535 		KASSERT(q->p_oppid == p->p_pid,
536 		    ("orphan %p of %p has unexpected oppid %d", q, p,
537 		    q->p_oppid));
538 		q->p_oppid = q->p_reaper->p_pid;
539 
540 		/*
541 		 * If we are the real parent of this process
542 		 * but it has been reparented to a debugger, then
543 		 * check if it asked for a signal when we exit.
544 		 */
545 		if (q->p_pdeathsig > 0)
546 			kern_psignal(q, q->p_pdeathsig);
547 		CTR2(KTR_PTRACE, "exit: pid %d, clearing orphan %d", p->p_pid,
548 		    q->p_pid);
549 		proc_clear_orphan(q);
550 		PROC_UNLOCK(q);
551 	}
552 
553 #ifdef KDTRACE_HOOKS
554 	if (SDT_PROBES_ENABLED()) {
555 		int reason = CLD_EXITED;
556 		if (WCOREDUMP(signo))
557 			reason = CLD_DUMPED;
558 		else if (WIFSIGNALED(signo))
559 			reason = CLD_KILLED;
560 		SDT_PROBE1(proc, , , exit, reason);
561 	}
562 #endif
563 
564 	/* Save exit status. */
565 	PROC_LOCK(p);
566 	p->p_xthread = td;
567 
568 	if (p->p_sysent->sv_ontdexit != NULL)
569 		p->p_sysent->sv_ontdexit(td);
570 
571 #ifdef KDTRACE_HOOKS
572 	/*
573 	 * Tell the DTrace fasttrap provider about the exit if it
574 	 * has declared an interest.
575 	 */
576 	if (dtrace_fasttrap_exit)
577 		dtrace_fasttrap_exit(p);
578 #endif
579 
580 	/*
581 	 * Notify interested parties of our demise.
582 	 */
583 	KNOTE_LOCKED(p->p_klist, NOTE_EXIT);
584 
585 	/*
586 	 * If this is a process with a descriptor, we may not need to deliver
587 	 * a signal to the parent.  proctree_lock is held over
588 	 * procdesc_exit() to serialize concurrent calls to close() and
589 	 * exit().
590 	 */
591 	signal_parent = 0;
592 	if (p->p_procdesc == NULL || procdesc_exit(p)) {
593 		/*
594 		 * Notify parent that we're gone.  If parent has the
595 		 * PS_NOCLDWAIT flag set, or if the handler is set to SIG_IGN,
596 		 * notify process 1 instead (and hope it will handle this
597 		 * situation).
598 		 */
599 		PROC_LOCK(p->p_pptr);
600 		mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
601 		if (p->p_pptr->p_sigacts->ps_flag &
602 		    (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
603 			struct proc *pp;
604 
605 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
606 			pp = p->p_pptr;
607 			PROC_UNLOCK(pp);
608 			proc_reparent(p, p->p_reaper, true);
609 			p->p_sigparent = SIGCHLD;
610 			PROC_LOCK(p->p_pptr);
611 
612 			/*
613 			 * Notify parent, so in case he was wait(2)ing or
614 			 * executing waitpid(2) with our pid, he will
615 			 * continue.
616 			 */
617 			wakeup(pp);
618 		} else
619 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
620 
621 		if (p->p_pptr == p->p_reaper || p->p_pptr == initproc) {
622 			signal_parent = 1;
623 		} else if (p->p_sigparent != 0) {
624 			if (p->p_sigparent == SIGCHLD) {
625 				signal_parent = 1;
626 			} else { /* LINUX thread */
627 				signal_parent = 2;
628 			}
629 		}
630 	} else
631 		PROC_LOCK(p->p_pptr);
632 	sx_xunlock(&proctree_lock);
633 
634 	if (signal_parent == 1) {
635 		childproc_exited(p);
636 	} else if (signal_parent == 2) {
637 		kern_psignal(p->p_pptr, p->p_sigparent);
638 	}
639 
640 	/* Tell the prison that we are gone. */
641 	prison_proc_free(p->p_ucred->cr_prison);
642 
643 	/*
644 	 * The state PRS_ZOMBIE prevents other proesses from sending
645 	 * signal to the process, to avoid memory leak, we free memory
646 	 * for signal queue at the time when the state is set.
647 	 */
648 	sigqueue_flush(&p->p_sigqueue);
649 	sigqueue_flush(&td->td_sigqueue);
650 
651 	/*
652 	 * We have to wait until after acquiring all locks before
653 	 * changing p_state.  We need to avoid all possible context
654 	 * switches (including ones from blocking on a mutex) while
655 	 * marked as a zombie.  We also have to set the zombie state
656 	 * before we release the parent process' proc lock to avoid
657 	 * a lost wakeup.  So, we first call wakeup, then we grab the
658 	 * sched lock, update the state, and release the parent process'
659 	 * proc lock.
660 	 */
661 	wakeup(p->p_pptr);
662 	cv_broadcast(&p->p_pwait);
663 	sched_exit(p->p_pptr, td);
664 	PROC_SLOCK(p);
665 	p->p_state = PRS_ZOMBIE;
666 	PROC_UNLOCK(p->p_pptr);
667 
668 	/*
669 	 * Save our children's rusage information in our exit rusage.
670 	 */
671 	PROC_STATLOCK(p);
672 	ruadd(&p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
673 	PROC_STATUNLOCK(p);
674 
675 	/*
676 	 * Make sure the scheduler takes this thread out of its tables etc.
677 	 * This will also release this thread's reference to the ucred.
678 	 * Other thread parts to release include pcb bits and such.
679 	 */
680 	thread_exit();
681 }
682 
683 #ifndef _SYS_SYSPROTO_H_
684 struct abort2_args {
685 	char *why;
686 	int nargs;
687 	void **args;
688 };
689 #endif
690 
691 int
692 sys_abort2(struct thread *td, struct abort2_args *uap)
693 {
694 	struct proc *p = td->td_proc;
695 	struct sbuf *sb;
696 	void *uargs[16];
697 	int error, i, sig;
698 
699 	/*
700 	 * Do it right now so we can log either proper call of abort2(), or
701 	 * note, that invalid argument was passed. 512 is big enough to
702 	 * handle 16 arguments' descriptions with additional comments.
703 	 */
704 	sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
705 	sbuf_clear(sb);
706 	sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
707 	    p->p_comm, p->p_pid, td->td_ucred->cr_uid);
708 	/*
709 	 * Since we can't return from abort2(), send SIGKILL in cases, where
710 	 * abort2() was called improperly
711 	 */
712 	sig = SIGKILL;
713 	/* Prevent from DoSes from user-space. */
714 	if (uap->nargs < 0 || uap->nargs > 16)
715 		goto out;
716 	if (uap->nargs > 0) {
717 		if (uap->args == NULL)
718 			goto out;
719 		error = copyin(uap->args, uargs, uap->nargs * sizeof(void *));
720 		if (error != 0)
721 			goto out;
722 	}
723 	/*
724 	 * Limit size of 'reason' string to 128. Will fit even when
725 	 * maximal number of arguments was chosen to be logged.
726 	 */
727 	if (uap->why != NULL) {
728 		error = sbuf_copyin(sb, uap->why, 128);
729 		if (error < 0)
730 			goto out;
731 	} else {
732 		sbuf_printf(sb, "(null)");
733 	}
734 	if (uap->nargs > 0) {
735 		sbuf_printf(sb, "(");
736 		for (i = 0;i < uap->nargs; i++)
737 			sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
738 		sbuf_printf(sb, ")");
739 	}
740 	/*
741 	 * Final stage: arguments were proper, string has been
742 	 * successfully copied from userspace, and copying pointers
743 	 * from user-space succeed.
744 	 */
745 	sig = SIGABRT;
746 out:
747 	if (sig == SIGKILL) {
748 		sbuf_trim(sb);
749 		sbuf_printf(sb, " (Reason text inaccessible)");
750 	}
751 	sbuf_cat(sb, "\n");
752 	sbuf_finish(sb);
753 	log(LOG_INFO, "%s", sbuf_data(sb));
754 	sbuf_delete(sb);
755 	exit1(td, 0, sig);
756 	return (0);
757 }
758 
759 #ifdef COMPAT_43
760 /*
761  * The dirty work is handled by kern_wait().
762  */
763 int
764 owait(struct thread *td, struct owait_args *uap __unused)
765 {
766 	int error, status;
767 
768 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
769 	if (error == 0)
770 		td->td_retval[1] = status;
771 	return (error);
772 }
773 #endif /* COMPAT_43 */
774 
775 /*
776  * The dirty work is handled by kern_wait().
777  */
778 int
779 sys_wait4(struct thread *td, struct wait4_args *uap)
780 {
781 	struct rusage ru, *rup;
782 	int error, status;
783 
784 	if (uap->rusage != NULL)
785 		rup = &ru;
786 	else
787 		rup = NULL;
788 	error = kern_wait(td, uap->pid, &status, uap->options, rup);
789 	if (uap->status != NULL && error == 0 && td->td_retval[0] != 0)
790 		error = copyout(&status, uap->status, sizeof(status));
791 	if (uap->rusage != NULL && error == 0 && td->td_retval[0] != 0)
792 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
793 	return (error);
794 }
795 
796 int
797 sys_wait6(struct thread *td, struct wait6_args *uap)
798 {
799 	struct __wrusage wru, *wrup;
800 	siginfo_t si, *sip;
801 	idtype_t idtype;
802 	id_t id;
803 	int error, status;
804 
805 	idtype = uap->idtype;
806 	id = uap->id;
807 
808 	if (uap->wrusage != NULL)
809 		wrup = &wru;
810 	else
811 		wrup = NULL;
812 
813 	if (uap->info != NULL) {
814 		sip = &si;
815 		bzero(sip, sizeof(*sip));
816 	} else
817 		sip = NULL;
818 
819 	/*
820 	 *  We expect all callers of wait6() to know about WEXITED and
821 	 *  WTRAPPED.
822 	 */
823 	error = kern_wait6(td, idtype, id, &status, uap->options, wrup, sip);
824 
825 	if (uap->status != NULL && error == 0 && td->td_retval[0] != 0)
826 		error = copyout(&status, uap->status, sizeof(status));
827 	if (uap->wrusage != NULL && error == 0 && td->td_retval[0] != 0)
828 		error = copyout(&wru, uap->wrusage, sizeof(wru));
829 	if (uap->info != NULL && error == 0)
830 		error = copyout(&si, uap->info, sizeof(si));
831 	return (error);
832 }
833 
834 /*
835  * Reap the remains of a zombie process and optionally return status and
836  * rusage.  Asserts and will release both the proctree_lock and the process
837  * lock as part of its work.
838  */
839 void
840 proc_reap(struct thread *td, struct proc *p, int *status, int options)
841 {
842 	struct proc *q, *t;
843 
844 	sx_assert(&proctree_lock, SA_XLOCKED);
845 	PROC_LOCK_ASSERT(p, MA_OWNED);
846 	KASSERT(p->p_state == PRS_ZOMBIE, ("proc_reap: !PRS_ZOMBIE"));
847 
848 	mtx_spin_wait_unlocked(&p->p_slock);
849 
850 	q = td->td_proc;
851 
852 	if (status)
853 		*status = KW_EXITCODE(p->p_xexit, p->p_xsig);
854 	if (options & WNOWAIT) {
855 		/*
856 		 *  Only poll, returning the status.  Caller does not wish to
857 		 * release the proc struct just yet.
858 		 */
859 		PROC_UNLOCK(p);
860 		sx_xunlock(&proctree_lock);
861 		return;
862 	}
863 
864 	PROC_LOCK(q);
865 	sigqueue_take(p->p_ksi);
866 	PROC_UNLOCK(q);
867 
868 	/*
869 	 * If we got the child via a ptrace 'attach', we need to give it back
870 	 * to the old parent.
871 	 */
872 	if (p->p_oppid != p->p_pptr->p_pid) {
873 		PROC_UNLOCK(p);
874 		t = proc_realparent(p);
875 		PROC_LOCK(t);
876 		PROC_LOCK(p);
877 		CTR2(KTR_PTRACE,
878 		    "wait: traced child %d moved back to parent %d", p->p_pid,
879 		    t->p_pid);
880 		proc_reparent(p, t, false);
881 		PROC_UNLOCK(p);
882 		pksignal(t, SIGCHLD, p->p_ksi);
883 		wakeup(t);
884 		cv_broadcast(&p->p_pwait);
885 		PROC_UNLOCK(t);
886 		sx_xunlock(&proctree_lock);
887 		return;
888 	}
889 	PROC_UNLOCK(p);
890 
891 	/*
892 	 * Remove other references to this process to ensure we have an
893 	 * exclusive reference.
894 	 */
895 	sx_xlock(PIDHASHLOCK(p->p_pid));
896 	LIST_REMOVE(p, p_hash);
897 	sx_xunlock(PIDHASHLOCK(p->p_pid));
898 	LIST_REMOVE(p, p_sibling);
899 	reaper_abandon_children(p, true);
900 	reaper_clear(p);
901 	PROC_LOCK(p);
902 	proc_clear_orphan(p);
903 	PROC_UNLOCK(p);
904 	leavepgrp(p);
905 	if (p->p_procdesc != NULL)
906 		procdesc_reap(p);
907 	sx_xunlock(&proctree_lock);
908 
909 	proc_id_clear(PROC_ID_PID, p->p_pid);
910 
911 	PROC_LOCK(p);
912 	knlist_detach(p->p_klist);
913 	p->p_klist = NULL;
914 	PROC_UNLOCK(p);
915 
916 	/*
917 	 * Removal from allproc list and process group list paired with
918 	 * PROC_LOCK which was executed during that time should guarantee
919 	 * nothing can reach this process anymore. As such further locking
920 	 * is unnecessary.
921 	 */
922 	p->p_xexit = p->p_xsig = 0;		/* XXX: why? */
923 
924 	PROC_LOCK(q);
925 	ruadd(&q->p_stats->p_cru, &q->p_crux, &p->p_ru, &p->p_rux);
926 	PROC_UNLOCK(q);
927 
928 	/*
929 	 * Decrement the count of procs running with this uid.
930 	 */
931 	(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
932 
933 	/*
934 	 * Destroy resource accounting information associated with the process.
935 	 */
936 #ifdef RACCT
937 	if (racct_enable) {
938 		PROC_LOCK(p);
939 		racct_sub(p, RACCT_NPROC, 1);
940 		PROC_UNLOCK(p);
941 	}
942 #endif
943 	racct_proc_exit(p);
944 
945 	/*
946 	 * Free credentials, arguments, and sigacts.
947 	 */
948 	proc_unset_cred(p);
949 	pargs_drop(p->p_args);
950 	p->p_args = NULL;
951 	sigacts_free(p->p_sigacts);
952 	p->p_sigacts = NULL;
953 
954 	/*
955 	 * Do any thread-system specific cleanups.
956 	 */
957 	thread_wait(p);
958 
959 	/*
960 	 * Give vm and machine-dependent layer a chance to free anything that
961 	 * cpu_exit couldn't release while still running in process context.
962 	 */
963 	vm_waitproc(p);
964 #ifdef MAC
965 	mac_proc_destroy(p);
966 #endif
967 
968 	KASSERT(FIRST_THREAD_IN_PROC(p),
969 	    ("proc_reap: no residual thread!"));
970 	uma_zfree(proc_zone, p);
971 	atomic_add_int(&nprocs, -1);
972 }
973 
974 static int
975 proc_to_reap(struct thread *td, struct proc *p, idtype_t idtype, id_t id,
976     int *status, int options, struct __wrusage *wrusage, siginfo_t *siginfo,
977     int check_only)
978 {
979 	struct rusage *rup;
980 
981 	sx_assert(&proctree_lock, SA_XLOCKED);
982 
983 	PROC_LOCK(p);
984 
985 	switch (idtype) {
986 	case P_ALL:
987 		if (p->p_procdesc == NULL ||
988 		   (p->p_pptr == td->td_proc &&
989 		   (p->p_flag & P_TRACED) != 0)) {
990 			break;
991 		}
992 
993 		PROC_UNLOCK(p);
994 		return (0);
995 	case P_PID:
996 		if (p->p_pid != (pid_t)id) {
997 			PROC_UNLOCK(p);
998 			return (0);
999 		}
1000 		break;
1001 	case P_PGID:
1002 		if (p->p_pgid != (pid_t)id) {
1003 			PROC_UNLOCK(p);
1004 			return (0);
1005 		}
1006 		break;
1007 	case P_SID:
1008 		if (p->p_session->s_sid != (pid_t)id) {
1009 			PROC_UNLOCK(p);
1010 			return (0);
1011 		}
1012 		break;
1013 	case P_UID:
1014 		if (p->p_ucred->cr_uid != (uid_t)id) {
1015 			PROC_UNLOCK(p);
1016 			return (0);
1017 		}
1018 		break;
1019 	case P_GID:
1020 		if (p->p_ucred->cr_gid != (gid_t)id) {
1021 			PROC_UNLOCK(p);
1022 			return (0);
1023 		}
1024 		break;
1025 	case P_JAILID:
1026 		if (p->p_ucred->cr_prison->pr_id != (int)id) {
1027 			PROC_UNLOCK(p);
1028 			return (0);
1029 		}
1030 		break;
1031 	/*
1032 	 * It seems that the thread structures get zeroed out
1033 	 * at process exit.  This makes it impossible to
1034 	 * support P_SETID, P_CID or P_CPUID.
1035 	 */
1036 	default:
1037 		PROC_UNLOCK(p);
1038 		return (0);
1039 	}
1040 
1041 	if (p_canwait(td, p)) {
1042 		PROC_UNLOCK(p);
1043 		return (0);
1044 	}
1045 
1046 	if (((options & WEXITED) == 0) && (p->p_state == PRS_ZOMBIE)) {
1047 		PROC_UNLOCK(p);
1048 		return (0);
1049 	}
1050 
1051 	/*
1052 	 * This special case handles a kthread spawned by linux_clone
1053 	 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
1054 	 * functions need to be able to distinguish between waiting
1055 	 * on a process and waiting on a thread.  It is a thread if
1056 	 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
1057 	 * signifies we want to wait for threads and not processes.
1058 	 */
1059 	if ((p->p_sigparent != SIGCHLD) ^
1060 	    ((options & WLINUXCLONE) != 0)) {
1061 		PROC_UNLOCK(p);
1062 		return (0);
1063 	}
1064 
1065 	if (siginfo != NULL) {
1066 		bzero(siginfo, sizeof(*siginfo));
1067 		siginfo->si_errno = 0;
1068 
1069 		/*
1070 		 * SUSv4 requires that the si_signo value is always
1071 		 * SIGCHLD. Obey it despite the rfork(2) interface
1072 		 * allows to request other signal for child exit
1073 		 * notification.
1074 		 */
1075 		siginfo->si_signo = SIGCHLD;
1076 
1077 		/*
1078 		 *  This is still a rough estimate.  We will fix the
1079 		 *  cases TRAPPED, STOPPED, and CONTINUED later.
1080 		 */
1081 		if (WCOREDUMP(p->p_xsig)) {
1082 			siginfo->si_code = CLD_DUMPED;
1083 			siginfo->si_status = WTERMSIG(p->p_xsig);
1084 		} else if (WIFSIGNALED(p->p_xsig)) {
1085 			siginfo->si_code = CLD_KILLED;
1086 			siginfo->si_status = WTERMSIG(p->p_xsig);
1087 		} else {
1088 			siginfo->si_code = CLD_EXITED;
1089 			siginfo->si_status = p->p_xexit;
1090 		}
1091 
1092 		siginfo->si_pid = p->p_pid;
1093 		siginfo->si_uid = p->p_ucred->cr_uid;
1094 
1095 		/*
1096 		 * The si_addr field would be useful additional
1097 		 * detail, but apparently the PC value may be lost
1098 		 * when we reach this point.  bzero() above sets
1099 		 * siginfo->si_addr to NULL.
1100 		 */
1101 	}
1102 
1103 	/*
1104 	 * There should be no reason to limit resources usage info to
1105 	 * exited processes only.  A snapshot about any resources used
1106 	 * by a stopped process may be exactly what is needed.
1107 	 */
1108 	if (wrusage != NULL) {
1109 		rup = &wrusage->wru_self;
1110 		*rup = p->p_ru;
1111 		PROC_STATLOCK(p);
1112 		calcru(p, &rup->ru_utime, &rup->ru_stime);
1113 		PROC_STATUNLOCK(p);
1114 
1115 		rup = &wrusage->wru_children;
1116 		*rup = p->p_stats->p_cru;
1117 		calccru(p, &rup->ru_utime, &rup->ru_stime);
1118 	}
1119 
1120 	if (p->p_state == PRS_ZOMBIE && !check_only) {
1121 		proc_reap(td, p, status, options);
1122 		return (-1);
1123 	}
1124 	return (1);
1125 }
1126 
1127 int
1128 kern_wait(struct thread *td, pid_t pid, int *status, int options,
1129     struct rusage *rusage)
1130 {
1131 	struct __wrusage wru, *wrup;
1132 	idtype_t idtype;
1133 	id_t id;
1134 	int ret;
1135 
1136 	/*
1137 	 * Translate the special pid values into the (idtype, pid)
1138 	 * pair for kern_wait6.  The WAIT_MYPGRP case is handled by
1139 	 * kern_wait6() on its own.
1140 	 */
1141 	if (pid == WAIT_ANY) {
1142 		idtype = P_ALL;
1143 		id = 0;
1144 	} else if (pid < 0) {
1145 		idtype = P_PGID;
1146 		id = (id_t)-pid;
1147 	} else {
1148 		idtype = P_PID;
1149 		id = (id_t)pid;
1150 	}
1151 
1152 	if (rusage != NULL)
1153 		wrup = &wru;
1154 	else
1155 		wrup = NULL;
1156 
1157 	/*
1158 	 * For backward compatibility we implicitly add flags WEXITED
1159 	 * and WTRAPPED here.
1160 	 */
1161 	options |= WEXITED | WTRAPPED;
1162 	ret = kern_wait6(td, idtype, id, status, options, wrup, NULL);
1163 	if (rusage != NULL)
1164 		*rusage = wru.wru_self;
1165 	return (ret);
1166 }
1167 
1168 static void
1169 report_alive_proc(struct thread *td, struct proc *p, siginfo_t *siginfo,
1170     int *status, int options, int si_code)
1171 {
1172 	bool cont;
1173 
1174 	PROC_LOCK_ASSERT(p, MA_OWNED);
1175 	sx_assert(&proctree_lock, SA_XLOCKED);
1176 	MPASS(si_code == CLD_TRAPPED || si_code == CLD_STOPPED ||
1177 	    si_code == CLD_CONTINUED);
1178 
1179 	cont = si_code == CLD_CONTINUED;
1180 	if ((options & WNOWAIT) == 0) {
1181 		if (cont)
1182 			p->p_flag &= ~P_CONTINUED;
1183 		else
1184 			p->p_flag |= P_WAITED;
1185 		PROC_LOCK(td->td_proc);
1186 		sigqueue_take(p->p_ksi);
1187 		PROC_UNLOCK(td->td_proc);
1188 	}
1189 	sx_xunlock(&proctree_lock);
1190 	if (siginfo != NULL) {
1191 		siginfo->si_code = si_code;
1192 		siginfo->si_status = cont ? SIGCONT : p->p_xsig;
1193 	}
1194 	if (status != NULL)
1195 		*status = cont ? SIGCONT : W_STOPCODE(p->p_xsig);
1196 	PROC_UNLOCK(p);
1197 	td->td_retval[0] = p->p_pid;
1198 }
1199 
1200 int
1201 kern_wait6(struct thread *td, idtype_t idtype, id_t id, int *status,
1202     int options, struct __wrusage *wrusage, siginfo_t *siginfo)
1203 {
1204 	struct proc *p, *q;
1205 	pid_t pid;
1206 	int error, nfound, ret;
1207 	bool report;
1208 
1209 	AUDIT_ARG_VALUE((int)idtype);	/* XXX - This is likely wrong! */
1210 	AUDIT_ARG_PID((pid_t)id);	/* XXX - This may be wrong! */
1211 	AUDIT_ARG_VALUE(options);
1212 
1213 	q = td->td_proc;
1214 
1215 	if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
1216 		PROC_LOCK(q);
1217 		id = (id_t)q->p_pgid;
1218 		PROC_UNLOCK(q);
1219 		idtype = P_PGID;
1220 	}
1221 
1222 	/* If we don't know the option, just return. */
1223 	if ((options & ~(WUNTRACED | WNOHANG | WCONTINUED | WNOWAIT |
1224 	    WEXITED | WTRAPPED | WLINUXCLONE)) != 0)
1225 		return (EINVAL);
1226 	if ((options & (WEXITED | WUNTRACED | WCONTINUED | WTRAPPED)) == 0) {
1227 		/*
1228 		 * We will be unable to find any matching processes,
1229 		 * because there are no known events to look for.
1230 		 * Prefer to return error instead of blocking
1231 		 * indefinitely.
1232 		 */
1233 		return (EINVAL);
1234 	}
1235 
1236 loop:
1237 	if (q->p_flag & P_STATCHILD) {
1238 		PROC_LOCK(q);
1239 		q->p_flag &= ~P_STATCHILD;
1240 		PROC_UNLOCK(q);
1241 	}
1242 	sx_xlock(&proctree_lock);
1243 loop_locked:
1244 	nfound = 0;
1245 	LIST_FOREACH(p, &q->p_children, p_sibling) {
1246 		pid = p->p_pid;
1247 		ret = proc_to_reap(td, p, idtype, id, status, options,
1248 		    wrusage, siginfo, 0);
1249 		if (ret == 0)
1250 			continue;
1251 		else if (ret != 1) {
1252 			td->td_retval[0] = pid;
1253 			return (0);
1254 		}
1255 
1256 		nfound++;
1257 		PROC_LOCK_ASSERT(p, MA_OWNED);
1258 
1259 		if ((options & WTRAPPED) != 0 &&
1260 		    (p->p_flag & P_TRACED) != 0) {
1261 			PROC_SLOCK(p);
1262 			report =
1263 			    ((p->p_flag & (P_STOPPED_TRACE | P_STOPPED_SIG)) &&
1264 			    p->p_suspcount == p->p_numthreads &&
1265 			    (p->p_flag & P_WAITED) == 0);
1266 			PROC_SUNLOCK(p);
1267 			if (report) {
1268 			CTR4(KTR_PTRACE,
1269 			    "wait: returning trapped pid %d status %#x "
1270 			    "(xstat %d) xthread %d",
1271 			    p->p_pid, W_STOPCODE(p->p_xsig), p->p_xsig,
1272 			    p->p_xthread != NULL ?
1273 			    p->p_xthread->td_tid : -1);
1274 				report_alive_proc(td, p, siginfo, status,
1275 				    options, CLD_TRAPPED);
1276 				return (0);
1277 			}
1278 		}
1279 		if ((options & WUNTRACED) != 0 &&
1280 		    (p->p_flag & P_STOPPED_SIG) != 0) {
1281 			PROC_SLOCK(p);
1282 			report = (p->p_suspcount == p->p_numthreads &&
1283 			    ((p->p_flag & P_WAITED) == 0));
1284 			PROC_SUNLOCK(p);
1285 			if (report) {
1286 				report_alive_proc(td, p, siginfo, status,
1287 				    options, CLD_STOPPED);
1288 				return (0);
1289 			}
1290 		}
1291 		if ((options & WCONTINUED) != 0 &&
1292 		    (p->p_flag & P_CONTINUED) != 0) {
1293 			report_alive_proc(td, p, siginfo, status, options,
1294 			    CLD_CONTINUED);
1295 			return (0);
1296 		}
1297 		PROC_UNLOCK(p);
1298 	}
1299 
1300 	/*
1301 	 * Look in the orphans list too, to allow the parent to
1302 	 * collect it's child exit status even if child is being
1303 	 * debugged.
1304 	 *
1305 	 * Debugger detaches from the parent upon successful
1306 	 * switch-over from parent to child.  At this point due to
1307 	 * re-parenting the parent loses the child to debugger and a
1308 	 * wait4(2) call would report that it has no children to wait
1309 	 * for.  By maintaining a list of orphans we allow the parent
1310 	 * to successfully wait until the child becomes a zombie.
1311 	 */
1312 	if (nfound == 0) {
1313 		LIST_FOREACH(p, &q->p_orphans, p_orphan) {
1314 			ret = proc_to_reap(td, p, idtype, id, NULL, options,
1315 			    NULL, NULL, 1);
1316 			if (ret != 0) {
1317 				KASSERT(ret != -1, ("reaped an orphan (pid %d)",
1318 				    (int)td->td_retval[0]));
1319 				PROC_UNLOCK(p);
1320 				nfound++;
1321 				break;
1322 			}
1323 		}
1324 	}
1325 	if (nfound == 0) {
1326 		sx_xunlock(&proctree_lock);
1327 		return (ECHILD);
1328 	}
1329 	if (options & WNOHANG) {
1330 		sx_xunlock(&proctree_lock);
1331 		td->td_retval[0] = 0;
1332 		return (0);
1333 	}
1334 	PROC_LOCK(q);
1335 	if (q->p_flag & P_STATCHILD) {
1336 		q->p_flag &= ~P_STATCHILD;
1337 		PROC_UNLOCK(q);
1338 		goto loop_locked;
1339 	}
1340 	sx_xunlock(&proctree_lock);
1341 	error = msleep(q, &q->p_mtx, PWAIT | PCATCH | PDROP, "wait", 0);
1342 	if (error)
1343 		return (error);
1344 	goto loop;
1345 }
1346 
1347 void
1348 proc_add_orphan(struct proc *child, struct proc *parent)
1349 {
1350 
1351 	sx_assert(&proctree_lock, SX_XLOCKED);
1352 	KASSERT((child->p_flag & P_TRACED) != 0,
1353 	    ("proc_add_orphan: not traced"));
1354 
1355 	if (LIST_EMPTY(&parent->p_orphans)) {
1356 		child->p_treeflag |= P_TREE_FIRST_ORPHAN;
1357 		LIST_INSERT_HEAD(&parent->p_orphans, child, p_orphan);
1358 	} else {
1359 		LIST_INSERT_AFTER(LIST_FIRST(&parent->p_orphans),
1360 		    child, p_orphan);
1361 	}
1362 	child->p_treeflag |= P_TREE_ORPHANED;
1363 }
1364 
1365 /*
1366  * Make process 'parent' the new parent of process 'child'.
1367  * Must be called with an exclusive hold of proctree lock.
1368  */
1369 void
1370 proc_reparent(struct proc *child, struct proc *parent, bool set_oppid)
1371 {
1372 
1373 	sx_assert(&proctree_lock, SX_XLOCKED);
1374 	PROC_LOCK_ASSERT(child, MA_OWNED);
1375 	if (child->p_pptr == parent)
1376 		return;
1377 
1378 	PROC_LOCK(child->p_pptr);
1379 	sigqueue_take(child->p_ksi);
1380 	PROC_UNLOCK(child->p_pptr);
1381 	LIST_REMOVE(child, p_sibling);
1382 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1383 
1384 	proc_clear_orphan(child);
1385 	if ((child->p_flag & P_TRACED) != 0) {
1386 		proc_add_orphan(child, child->p_pptr);
1387 	}
1388 
1389 	child->p_pptr = parent;
1390 	if (set_oppid)
1391 		child->p_oppid = parent->p_pid;
1392 }
1393