xref: /freebsd/sys/kern/kern_exit.c (revision 262e143bd46171a6415a5b28af260a5efa2a3db8)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_compat.h"
41 #include "opt_ktrace.h"
42 #include "opt_mac.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/sysproto.h>
47 #include <sys/eventhandler.h>
48 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/pioctl.h>
54 #include <sys/tty.h>
55 #include <sys/wait.h>
56 #include <sys/vmmeter.h>
57 #include <sys/vnode.h>
58 #include <sys/resourcevar.h>
59 #include <sys/signalvar.h>
60 #include <sys/sched.h>
61 #include <sys/sx.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/ptrace.h>
64 #include <sys/acct.h>		/* for acct_process() function prototype */
65 #include <sys/filedesc.h>
66 #include <sys/mac.h>
67 #include <sys/shm.h>
68 #include <sys/sem.h>
69 #ifdef KTRACE
70 #include <sys/ktrace.h>
71 #endif
72 
73 #include <vm/vm.h>
74 #include <vm/vm_extern.h>
75 #include <vm/vm_param.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_page.h>
79 #include <vm/uma.h>
80 
81 /* Required to be non-static for SysVR4 emulator */
82 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
83 
84 /* Hook for NFS teardown procedure. */
85 void (*nlminfo_release_p)(struct proc *p);
86 
87 /*
88  * exit --
89  *	Death of process.
90  *
91  * MPSAFE
92  */
93 void
94 sys_exit(struct thread *td, struct sys_exit_args *uap)
95 {
96 
97 	exit1(td, W_EXITCODE(uap->rval, 0));
98 	/* NOTREACHED */
99 }
100 
101 /*
102  * Exit: deallocate address space and other resources, change proc state
103  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
104  * status and rusage for wait().  Check for child processes and orphan them.
105  */
106 void
107 exit1(struct thread *td, int rv)
108 {
109 	struct bintime new_switchtime;
110 	struct proc *p, *nq, *q;
111 	struct tty *tp;
112 	struct vnode *ttyvp;
113 	struct vmspace *vm;
114 	struct vnode *vtmp;
115 #ifdef KTRACE
116 	struct vnode *tracevp;
117 	struct ucred *tracecred;
118 #endif
119 	struct plimit *plim;
120 	int locked, refcnt;
121 
122 	/*
123 	 * Drop Giant if caller has it.  Eventually we should warn about
124 	 * being called with Giant held.
125 	 */
126 	while (mtx_owned(&Giant))
127 		mtx_unlock(&Giant);
128 
129 	p = td->td_proc;
130 	if (p == initproc) {
131 		printf("init died (signal %d, exit %d)\n",
132 		    WTERMSIG(rv), WEXITSTATUS(rv));
133 		panic("Going nowhere without my init!");
134 	}
135 
136 	/*
137 	 * MUST abort all other threads before proceeding past here.
138 	 */
139 	PROC_LOCK(p);
140 	if (p->p_flag & P_HADTHREADS) {
141 retry:
142 		/*
143 		 * First check if some other thread got here before us..
144 		 * if so, act apropriatly, (exit or suspend);
145 		 */
146 		thread_suspend_check(0);
147 
148 		/*
149 		 * Kill off the other threads. This requires
150 		 * some co-operation from other parts of the kernel
151 		 * so it may not be instantaneous.  With this state set
152 		 * any thread entering the kernel from userspace will
153 		 * thread_exit() in trap().  Any thread attempting to
154 		 * sleep will return immediately with EINTR or EWOULDBLOCK
155 		 * which will hopefully force them to back out to userland
156 		 * freeing resources as they go.  Any thread attempting
157 		 * to return to userland will thread_exit() from userret().
158 		 * thread_exit() will unsuspend us when the last of the
159 		 * other threads exits.
160 		 * If there is already a thread singler after resumption,
161 		 * calling thread_single will fail; in that case, we just
162 		 * re-check all suspension request, the thread should
163 		 * either be suspended there or exit.
164 		 */
165 		if (thread_single(SINGLE_EXIT))
166 			goto retry;
167 
168 		/*
169 		 * All other activity in this process is now stopped.
170 		 * Threading support has been turned off.
171 		 */
172 	}
173 
174 	p->p_flag |= P_WEXIT;
175 
176 	PROC_LOCK(p->p_pptr);
177 	sigqueue_take(p->p_ksi);
178 	PROC_UNLOCK(p->p_pptr);
179 
180 	PROC_UNLOCK(p);
181 
182 	/* Are we a task leader? */
183 	if (p == p->p_leader) {
184 		mtx_lock(&ppeers_lock);
185 		q = p->p_peers;
186 		while (q != NULL) {
187 			PROC_LOCK(q);
188 			psignal(q, SIGKILL);
189 			PROC_UNLOCK(q);
190 			q = q->p_peers;
191 		}
192 		while (p->p_peers != NULL)
193 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
194 		mtx_unlock(&ppeers_lock);
195 	}
196 
197 	PROC_LOCK(p);
198 	_STOPEVENT(p, S_EXIT, rv);
199 	wakeup(&p->p_stype);	/* Wakeup anyone in procfs' PIOCWAIT */
200 	PROC_UNLOCK(p);
201 
202 	/*
203 	 * Check if any loadable modules need anything done at process exit.
204 	 * E.g. SYSV IPC stuff
205 	 * XXX what if one of these generates an error?
206 	 */
207 	EVENTHANDLER_INVOKE(process_exit, p);
208 
209 	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
210 		M_ZOMBIE, M_WAITOK);
211 	/*
212 	 * If parent is waiting for us to exit or exec,
213 	 * P_PPWAIT is set; we will wakeup the parent below.
214 	 */
215 	PROC_LOCK(p);
216 	stopprofclock(p);
217 	p->p_flag &= ~(P_TRACED | P_PPWAIT);
218 
219 	/*
220 	 * Stop the real interval timer.  If the handler is currently
221 	 * executing, prevent it from rearming itself and let it finish.
222 	 */
223 	if (timevalisset(&p->p_realtimer.it_value) &&
224 	    callout_stop(&p->p_itcallout) == 0) {
225 		timevalclear(&p->p_realtimer.it_interval);
226 		msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
227 		KASSERT(!timevalisset(&p->p_realtimer.it_value),
228 		    ("realtime timer is still armed"));
229 	}
230 	sigqueue_flush(&p->p_sigqueue);
231 	sigqueue_flush(&td->td_sigqueue);
232 	PROC_UNLOCK(p);
233 
234 	/*
235 	 * Reset any sigio structures pointing to us as a result of
236 	 * F_SETOWN with our pid.
237 	 */
238 	mtx_lock(&Giant);	/* XXX: not sure if needed */
239 	funsetownlst(&p->p_sigiolst);
240 	mtx_unlock(&Giant);
241 
242 	/*
243 	 * If this process has an nlminfo data area (for lockd), release it
244 	 */
245 	if (nlminfo_release_p != NULL && p->p_nlminfo != NULL)
246 		(*nlminfo_release_p)(p);
247 
248 	/*
249 	 * Close open files and release open-file table.
250 	 * This may block!
251 	 */
252 	fdfree(td);
253 
254 	/*
255 	 * If this thread tickled GEOM, we need to wait for the giggling to
256 	 * stop before we return to userland
257 	 */
258 	if (td->td_pflags & TDP_GEOM)
259 		g_waitidle();
260 
261 	/*
262 	 * Remove ourself from our leader's peer list and wake our leader.
263 	 */
264 	mtx_lock(&ppeers_lock);
265 	if (p->p_leader->p_peers) {
266 		q = p->p_leader;
267 		while (q->p_peers != p)
268 			q = q->p_peers;
269 		q->p_peers = p->p_peers;
270 		wakeup(p->p_leader);
271 	}
272 	mtx_unlock(&ppeers_lock);
273 
274 	/* The next two chunks should probably be moved to vmspace_exit. */
275 	vm = p->p_vmspace;
276 	/*
277 	 * Release user portion of address space.
278 	 * This releases references to vnodes,
279 	 * which could cause I/O if the file has been unlinked.
280 	 * Need to do this early enough that we can still sleep.
281 	 * Can't free the entire vmspace as the kernel stack
282 	 * may be mapped within that space also.
283 	 *
284 	 * Processes sharing the same vmspace may exit in one order, and
285 	 * get cleaned up by vmspace_exit() in a different order.  The
286 	 * last exiting process to reach this point releases as much of
287 	 * the environment as it can, and the last process cleaned up
288 	 * by vmspace_exit() (which decrements exitingcnt) cleans up the
289 	 * remainder.
290 	 */
291 	atomic_add_int(&vm->vm_exitingcnt, 1);
292 	do
293 		refcnt = vm->vm_refcnt;
294 	while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
295 	if (refcnt == 1) {
296 		shmexit(vm);
297 		pmap_remove_pages(vmspace_pmap(vm), vm_map_min(&vm->vm_map),
298 		    vm_map_max(&vm->vm_map));
299 		(void) vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
300 		    vm_map_max(&vm->vm_map));
301 	}
302 
303 	sx_xlock(&proctree_lock);
304 	if (SESS_LEADER(p)) {
305 		struct session *sp;
306 
307 		sp = p->p_session;
308 		if (sp->s_ttyvp) {
309 			locked = VFS_LOCK_GIANT(sp->s_ttyvp->v_mount);
310 			/*
311 			 * Controlling process.
312 			 * Signal foreground pgrp,
313 			 * drain controlling terminal
314 			 * and revoke access to controlling terminal.
315 			 */
316 			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
317 				tp = sp->s_ttyp;
318 				if (sp->s_ttyp->t_pgrp) {
319 					PGRP_LOCK(sp->s_ttyp->t_pgrp);
320 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
321 					PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
322 				}
323 				/* XXX tp should be locked. */
324 				sx_xunlock(&proctree_lock);
325 				(void) ttywait(tp);
326 				sx_xlock(&proctree_lock);
327 				/*
328 				 * The tty could have been revoked
329 				 * if we blocked.
330 				 */
331 				if (sp->s_ttyvp) {
332 					ttyvp = sp->s_ttyvp;
333 					SESS_LOCK(p->p_session);
334 					sp->s_ttyvp = NULL;
335 					SESS_UNLOCK(p->p_session);
336 					sx_xunlock(&proctree_lock);
337 					VOP_LOCK(ttyvp, LK_EXCLUSIVE, td);
338 					VOP_REVOKE(ttyvp, REVOKEALL);
339 					vput(ttyvp);
340 					sx_xlock(&proctree_lock);
341 				}
342 			}
343 			if (sp->s_ttyvp) {
344 				ttyvp = sp->s_ttyvp;
345 				SESS_LOCK(p->p_session);
346 				sp->s_ttyvp = NULL;
347 				SESS_UNLOCK(p->p_session);
348 				vrele(ttyvp);
349 			}
350 			/*
351 			 * s_ttyp is not zero'd; we use this to indicate
352 			 * that the session once had a controlling terminal.
353 			 * (for logging and informational purposes)
354 			 */
355 			VFS_UNLOCK_GIANT(locked);
356 		}
357 		SESS_LOCK(p->p_session);
358 		sp->s_leader = NULL;
359 		SESS_UNLOCK(p->p_session);
360 	}
361 	fixjobc(p, p->p_pgrp, 0);
362 	sx_xunlock(&proctree_lock);
363 	(void)acct_process(td);
364 #ifdef KTRACE
365 	/*
366 	 * Drain any pending records on the thread and release the trace
367 	 * file.  It might be better if drain-and-clear were atomic.
368 	 */
369 	ktrprocexit(td);
370 	PROC_LOCK(p);
371 	mtx_lock(&ktrace_mtx);
372 	p->p_traceflag = 0;	/* don't trace the vrele() */
373 	tracevp = p->p_tracevp;
374 	p->p_tracevp = NULL;
375 	tracecred = p->p_tracecred;
376 	p->p_tracecred = NULL;
377 	mtx_unlock(&ktrace_mtx);
378 	PROC_UNLOCK(p);
379 	if (tracevp != NULL) {
380 		locked = VFS_LOCK_GIANT(tracevp->v_mount);
381 		vrele(tracevp);
382 		VFS_UNLOCK_GIANT(locked);
383 	}
384 	if (tracecred != NULL)
385 		crfree(tracecred);
386 #endif
387 	/*
388 	 * Release reference to text vnode
389 	 */
390 	if ((vtmp = p->p_textvp) != NULL) {
391 		p->p_textvp = NULL;
392 		locked = VFS_LOCK_GIANT(vtmp->v_mount);
393 		vrele(vtmp);
394 		VFS_UNLOCK_GIANT(locked);
395 	}
396 
397 	/*
398 	 * Release our limits structure.
399 	 */
400 	PROC_LOCK(p);
401 	plim = p->p_limit;
402 	p->p_limit = NULL;
403 	PROC_UNLOCK(p);
404 	lim_free(plim);
405 
406 	/*
407 	 * Remove proc from allproc queue and pidhash chain.
408 	 * Place onto zombproc.  Unlink from parent's child list.
409 	 */
410 	sx_xlock(&allproc_lock);
411 	LIST_REMOVE(p, p_list);
412 	LIST_INSERT_HEAD(&zombproc, p, p_list);
413 	LIST_REMOVE(p, p_hash);
414 	sx_xunlock(&allproc_lock);
415 
416 	sx_xlock(&proctree_lock);
417 	q = LIST_FIRST(&p->p_children);
418 	if (q != NULL)		/* only need this if any child is S_ZOMB */
419 		wakeup(initproc);
420 	for (; q != NULL; q = nq) {
421 		nq = LIST_NEXT(q, p_sibling);
422 		PROC_LOCK(q);
423 		proc_reparent(q, initproc);
424 		q->p_sigparent = SIGCHLD;
425 		/*
426 		 * Traced processes are killed
427 		 * since their existence means someone is screwing up.
428 		 */
429 		if (q->p_flag & P_TRACED) {
430 			q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
431 			psignal(q, SIGKILL);
432 		}
433 		PROC_UNLOCK(q);
434 	}
435 
436 	/*
437 	 * Save exit status and finalize rusage info except for times,
438 	 * adding in child rusage info.
439 	 */
440 	PROC_LOCK(p);
441 	p->p_xstat = rv;
442 	p->p_xthread = td;
443 	p->p_stats->p_ru.ru_nvcsw++;
444 	*p->p_ru = p->p_stats->p_ru;
445 	ruadd(p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
446 
447 	/*
448 	 * Notify interested parties of our demise.
449 	 */
450 	KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
451 
452 	/*
453 	 * Just delete all entries in the p_klist. At this point we won't
454 	 * report any more events, and there are nasty race conditions that
455 	 * can beat us if we don't.
456 	 */
457 	knlist_clear(&p->p_klist, 1);
458 
459 	/*
460 	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
461 	 * flag set, or if the handler is set to SIG_IGN, notify process
462 	 * 1 instead (and hope it will handle this situation).
463 	 */
464 	PROC_LOCK(p->p_pptr);
465 	mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
466 	if (p->p_pptr->p_sigacts->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
467 		struct proc *pp;
468 
469 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
470 		pp = p->p_pptr;
471 		PROC_UNLOCK(pp);
472 		proc_reparent(p, initproc);
473 		p->p_sigparent = SIGCHLD;
474 		PROC_LOCK(p->p_pptr);
475 		/*
476 		 * If this was the last child of our parent, notify
477 		 * parent, so in case he was wait(2)ing, he will
478 		 * continue.
479 		 */
480 		if (LIST_EMPTY(&pp->p_children))
481 			wakeup(pp);
482 	} else
483 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
484 
485 	if (p->p_pptr == initproc)
486 		psignal(p->p_pptr, SIGCHLD);
487 	else if (p->p_sigparent != 0) {
488 		if (p->p_sigparent == SIGCHLD)
489 			childproc_exited(p);
490 		else	/* LINUX thread */
491 			psignal(p->p_pptr, p->p_sigparent);
492 	}
493 	PROC_UNLOCK(p->p_pptr);
494 
495 	/*
496 	 * If this is a kthread, then wakeup anyone waiting for it to exit.
497 	 */
498 	if (p->p_flag & P_KTHREAD)
499 		wakeup(p);
500 	PROC_UNLOCK(p);
501 
502 	/*
503 	 * Finally, call machine-dependent code to release the remaining
504 	 * resources including address space.
505 	 * The address space is released by "vmspace_exitfree(p)" in
506 	 * vm_waitproc().
507 	 */
508 	cpu_exit(td);
509 
510 	WITNESS_WARN(WARN_PANIC, &proctree_lock.sx_object,
511 	    "process (pid %d) exiting", p->p_pid);
512 
513 	PROC_LOCK(p);
514 	PROC_LOCK(p->p_pptr);
515 	sx_xunlock(&proctree_lock);
516 
517 	/*
518 	 * We have to wait until after acquiring all locks before
519 	 * changing p_state.  We need to avoid all possible context
520 	 * switches (including ones from blocking on a mutex) while
521 	 * marked as a zombie.  We also have to set the zombie state
522 	 * before we release the parent process' proc lock to avoid
523 	 * a lost wakeup.  So, we first call wakeup, then we grab the
524 	 * sched lock, update the state, and release the parent process'
525 	 * proc lock.
526 	 */
527 	wakeup(p->p_pptr);
528 	mtx_lock_spin(&sched_lock);
529 	p->p_state = PRS_ZOMBIE;
530 	PROC_UNLOCK(p->p_pptr);
531 
532 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
533 	binuptime(&new_switchtime);
534 	bintime_add(&p->p_rux.rux_runtime, &new_switchtime);
535 	bintime_sub(&p->p_rux.rux_runtime, PCPU_PTR(switchtime));
536 	PCPU_SET(switchtime, new_switchtime);
537 	PCPU_SET(switchticks, ticks);
538 	cnt.v_swtch++;
539 
540 	sched_exit(p->p_pptr, td);
541 
542 	/*
543 	 * Hopefully no one will try to deliver a signal to the process this
544 	 * late in the game.
545 	 */
546 	knlist_destroy(&p->p_klist);
547 
548 	/*
549 	 * Make sure the scheduler takes this thread out of its tables etc.
550 	 * This will also release this thread's reference to the ucred.
551 	 * Other thread parts to release include pcb bits and such.
552 	 */
553 	thread_exit();
554 }
555 
556 #ifdef COMPAT_43
557 /*
558  * The dirty work is handled by kern_wait().
559  *
560  * MPSAFE.
561  */
562 int
563 owait(struct thread *td, struct owait_args *uap __unused)
564 {
565 	int error, status;
566 
567 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
568 	if (error == 0)
569 		td->td_retval[1] = status;
570 	return (error);
571 }
572 #endif /* COMPAT_43 */
573 
574 /*
575  * The dirty work is handled by kern_wait().
576  *
577  * MPSAFE.
578  */
579 int
580 wait4(struct thread *td, struct wait_args *uap)
581 {
582 	struct rusage ru, *rup;
583 	int error, status;
584 
585 	if (uap->rusage != NULL)
586 		rup = &ru;
587 	else
588 		rup = NULL;
589 	error = kern_wait(td, uap->pid, &status, uap->options, rup);
590 	if (uap->status != NULL && error == 0)
591 		error = copyout(&status, uap->status, sizeof(status));
592 	if (uap->rusage != NULL && error == 0)
593 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
594 	return (error);
595 }
596 
597 int
598 kern_wait(struct thread *td, pid_t pid, int *status, int options,
599     struct rusage *rusage)
600 {
601 	struct proc *p, *q, *t;
602 	int error, nfound;
603 
604 	q = td->td_proc;
605 	if (pid == 0) {
606 		PROC_LOCK(q);
607 		pid = -q->p_pgid;
608 		PROC_UNLOCK(q);
609 	}
610 	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
611 		return (EINVAL);
612 loop:
613 	if (q->p_flag & P_STATCHILD) {
614 		PROC_LOCK(q);
615 		q->p_flag &= ~P_STATCHILD;
616 		PROC_UNLOCK(q);
617 	}
618 	nfound = 0;
619 	sx_xlock(&proctree_lock);
620 	LIST_FOREACH(p, &q->p_children, p_sibling) {
621 		PROC_LOCK(p);
622 		if (pid != WAIT_ANY &&
623 		    p->p_pid != pid && p->p_pgid != -pid) {
624 			PROC_UNLOCK(p);
625 			continue;
626 		}
627 		if (p_canwait(td, p)) {
628 			PROC_UNLOCK(p);
629 			continue;
630 		}
631 
632 		/*
633 		 * This special case handles a kthread spawned by linux_clone
634 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
635 		 * functions need to be able to distinguish between waiting
636 		 * on a process and waiting on a thread.  It is a thread if
637 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
638 		 * signifies we want to wait for threads and not processes.
639 		 */
640 		if ((p->p_sigparent != SIGCHLD) ^
641 		    ((options & WLINUXCLONE) != 0)) {
642 			PROC_UNLOCK(p);
643 			continue;
644 		}
645 
646 		nfound++;
647 		if (p->p_state == PRS_ZOMBIE) {
648 
649 			/*
650 			 * It is possible that the last thread of this
651 			 * process is still running on another CPU
652 			 * in thread_exit() after having dropped the process
653 			 * lock via PROC_UNLOCK() but before it has completed
654 			 * cpu_throw().  In that case, the other thread must
655 			 * still hold sched_lock, so simply by acquiring
656 			 * sched_lock once we will wait long enough for the
657 			 * thread to exit in that case.
658 			 */
659 			mtx_lock_spin(&sched_lock);
660 			mtx_unlock_spin(&sched_lock);
661 
662 			td->td_retval[0] = p->p_pid;
663 			if (status)
664 				*status = p->p_xstat;	/* convert to int */
665 			if (rusage) {
666 				*rusage = *p->p_ru;
667 				calcru(p, &rusage->ru_utime, &rusage->ru_stime);
668 			}
669 
670 			PROC_LOCK(q);
671 			sigqueue_take(p->p_ksi);
672 			PROC_UNLOCK(q);
673 
674 			/*
675 			 * If we got the child via a ptrace 'attach',
676 			 * we need to give it back to the old parent.
677 			 */
678 			PROC_UNLOCK(p);
679 			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
680 				PROC_LOCK(p);
681 				p->p_oppid = 0;
682 				proc_reparent(p, t);
683 				PROC_UNLOCK(p);
684 				tdsignal(t, NULL, SIGCHLD, p->p_ksi);
685 				wakeup(t);
686 				PROC_UNLOCK(t);
687 				sx_xunlock(&proctree_lock);
688 				return (0);
689 			}
690 
691 			/*
692 			 * Remove other references to this process to ensure
693 			 * we have an exclusive reference.
694 			 */
695 			sx_xlock(&allproc_lock);
696 			LIST_REMOVE(p, p_list);	/* off zombproc */
697 			sx_xunlock(&allproc_lock);
698 			LIST_REMOVE(p, p_sibling);
699 			leavepgrp(p);
700 			sx_xunlock(&proctree_lock);
701 
702 			/*
703 			 * As a side effect of this lock, we know that
704 			 * all other writes to this proc are visible now, so
705 			 * no more locking is needed for p.
706 			 */
707 			PROC_LOCK(p);
708 			p->p_xstat = 0;		/* XXX: why? */
709 			PROC_UNLOCK(p);
710 			PROC_LOCK(q);
711 			ruadd(&q->p_stats->p_cru, &q->p_crux, p->p_ru,
712 			    &p->p_rux);
713 			PROC_UNLOCK(q);
714 			FREE(p->p_ru, M_ZOMBIE);
715 			p->p_ru = NULL;
716 
717 			/*
718 			 * Decrement the count of procs running with this uid.
719 			 */
720 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
721 
722 			/*
723 			 * Free credentials, arguments, and sigacts.
724 			 */
725 			crfree(p->p_ucred);
726 			p->p_ucred = NULL;
727 			pargs_drop(p->p_args);
728 			p->p_args = NULL;
729 			sigacts_free(p->p_sigacts);
730 			p->p_sigacts = NULL;
731 
732 			/*
733 			 * Do any thread-system specific cleanups.
734 			 */
735 			thread_wait(p);
736 
737 			/*
738 			 * Give vm and machine-dependent layer a chance
739 			 * to free anything that cpu_exit couldn't
740 			 * release while still running in process context.
741 			 */
742 			vm_waitproc(p);
743 #ifdef MAC
744 			mac_destroy_proc(p);
745 #endif
746 			KASSERT(FIRST_THREAD_IN_PROC(p),
747 			    ("kern_wait: no residual thread!"));
748 			uma_zfree(proc_zone, p);
749 			sx_xlock(&allproc_lock);
750 			nprocs--;
751 			sx_xunlock(&allproc_lock);
752 			return (0);
753 		}
754 		mtx_lock_spin(&sched_lock);
755 		if ((p->p_flag & P_STOPPED_SIG) &&
756 		    (p->p_suspcount == p->p_numthreads) &&
757 		    (p->p_flag & P_WAITED) == 0 &&
758 		    (p->p_flag & P_TRACED || options & WUNTRACED)) {
759 			mtx_unlock_spin(&sched_lock);
760 			p->p_flag |= P_WAITED;
761 			sx_xunlock(&proctree_lock);
762 			td->td_retval[0] = p->p_pid;
763 			if (status)
764 				*status = W_STOPCODE(p->p_xstat);
765 			PROC_UNLOCK(p);
766 
767 			PROC_LOCK(q);
768 			sigqueue_take(p->p_ksi);
769 			PROC_UNLOCK(q);
770 
771 			return (0);
772 		}
773 		mtx_unlock_spin(&sched_lock);
774 		if (options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
775 			sx_xunlock(&proctree_lock);
776 			td->td_retval[0] = p->p_pid;
777 			p->p_flag &= ~P_CONTINUED;
778 			PROC_UNLOCK(p);
779 
780 			PROC_LOCK(q);
781 			sigqueue_take(p->p_ksi);
782 			PROC_UNLOCK(q);
783 
784 			if (status)
785 				*status = SIGCONT;
786 			return (0);
787 		}
788 		PROC_UNLOCK(p);
789 	}
790 	if (nfound == 0) {
791 		sx_xunlock(&proctree_lock);
792 		return (ECHILD);
793 	}
794 	if (options & WNOHANG) {
795 		sx_xunlock(&proctree_lock);
796 		td->td_retval[0] = 0;
797 		return (0);
798 	}
799 	PROC_LOCK(q);
800 	sx_xunlock(&proctree_lock);
801 	if (q->p_flag & P_STATCHILD) {
802 		q->p_flag &= ~P_STATCHILD;
803 		error = 0;
804 	} else
805 		error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
806 	PROC_UNLOCK(q);
807 	if (error)
808 		return (error);
809 	goto loop;
810 }
811 
812 /*
813  * Make process 'parent' the new parent of process 'child'.
814  * Must be called with an exclusive hold of proctree lock.
815  */
816 void
817 proc_reparent(struct proc *child, struct proc *parent)
818 {
819 
820 	sx_assert(&proctree_lock, SX_XLOCKED);
821 	PROC_LOCK_ASSERT(child, MA_OWNED);
822 	if (child->p_pptr == parent)
823 		return;
824 
825 	LIST_REMOVE(child, p_sibling);
826 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
827 	child->p_pptr = parent;
828 }
829