xref: /freebsd/sys/kern/kern_exit.c (revision 6fd05b64b5b65dd4ba9b86482a0634a5f0b96c29)
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/ptrace.h>
63 #include <sys/acct.h>		/* for acct_process() function prototype */
64 #include <sys/filedesc.h>
65 #include <sys/mac.h>
66 #include <sys/shm.h>
67 #include <sys/sem.h>
68 #ifdef KTRACE
69 #include <sys/ktrace.h>
70 #endif
71 
72 #include <vm/vm.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_param.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_page.h>
78 #include <vm/uma.h>
79 #include <sys/user.h>
80 
81 /* Required to be non-static for SysVR4 emulator */
82 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
83 
84 /*
85  * exit --
86  *	Death of process.
87  *
88  * MPSAFE
89  */
90 void
91 sys_exit(struct thread *td, struct sys_exit_args *uap)
92 {
93 
94 	exit1(td, W_EXITCODE(uap->rval, 0));
95 	/* NOTREACHED */
96 }
97 
98 /*
99  * Exit: deallocate address space and other resources, change proc state
100  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
101  * status and rusage for wait().  Check for child processes and orphan them.
102  */
103 void
104 exit1(struct thread *td, int rv)
105 {
106  	struct bintime new_switchtime;
107 	struct proc *p, *nq, *q;
108 	struct tty *tp;
109 	struct vnode *ttyvp;
110 	struct vmspace *vm;
111 	struct vnode *vtmp;
112 #ifdef KTRACE
113 	struct vnode *tracevp;
114 	struct ucred *tracecred;
115 #endif
116 	struct plimit *plim;
117 
118 	/*
119 	 * Drop Giant if caller has it.  Eventually we should warn about
120 	 * being called with Giant held.
121 	 */
122 	while (mtx_owned(&Giant))
123 		mtx_unlock(&Giant);
124 
125 	p = td->td_proc;
126 	if (p == initproc) {
127 		printf("init died (signal %d, exit %d)\n",
128 		    WTERMSIG(rv), WEXITSTATUS(rv));
129 		panic("Going nowhere without my init!");
130 	}
131 
132 	/*
133 	 * MUST abort all other threads before proceeding past here.
134 	 */
135 	PROC_LOCK(p);
136 	if (p->p_flag & P_SA || p->p_numthreads > 1) {
137 retry:
138 		/*
139 		 * First check if some other thread got here before us..
140 		 * if so, act apropriatly, (exit or suspend);
141 		 */
142 		thread_suspend_check(0);
143 
144 		/*
145 		 * Kill off the other threads. This requires
146 		 * Some co-operation from other parts of the kernel
147 		 * so it may not be instant.
148 		 * With this state set:
149 		 * Any thread entering the kernel from userspace will
150 		 * thread_exit() in trap().  Any thread attempting to
151 		 * sleep will return immediatly with EINTR or EWOULDBLOCK,
152 		 * which will hopefully force them to back out to userland,
153 		 * freeing resources as they go, and anything attempting
154 		 * to return to userland will thread_exit() from userret().
155 		 * thread_exit() will unsuspend us when the last other
156 		 * thread exits.
157 		 * If there is already a thread singler after resumption,
158 		 * calling thread_single will fail, in the case, we just
159 		 * re-check all suspension request, the thread should
160 		 * either be suspended there or exit.
161 		 */
162 		if (thread_single(SINGLE_EXIT))
163 			goto retry;
164 		/*
165 		 * All other activity in this process is now stopped.
166 		 * Remove excess KSEs and KSEGRPS. XXXKSE (when we have them)
167 		 * ...
168 		 * Turn off threading support.
169 		 */
170 		p->p_flag &= ~P_SA;
171 		td->td_pflags &= ~TDP_SA;
172 		thread_single_end();	/* Don't need this any more. */
173 	}
174 
175 	p->p_flag |= P_WEXIT;
176 	PROC_UNLOCK(p);
177 
178 	/* Are we a task leader? */
179 	if (p == p->p_leader) {
180 		mtx_lock(&ppeers_lock);
181 		q = p->p_peers;
182 		while (q != NULL) {
183 			PROC_LOCK(q);
184 			psignal(q, SIGKILL);
185 			PROC_UNLOCK(q);
186 			q = q->p_peers;
187 		}
188 		while (p->p_peers != NULL)
189 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
190 		mtx_unlock(&ppeers_lock);
191 	}
192 
193 	PROC_LOCK(p);
194 	_STOPEVENT(p, S_EXIT, rv);
195 	wakeup(&p->p_stype);	/* Wakeup anyone in procfs' PIOCWAIT */
196 	PROC_UNLOCK(p);
197 
198 	/*
199 	 * Check if any loadable modules need anything done at process exit.
200 	 * e.g. SYSV IPC stuff
201 	 * XXX what if one of these generates an error?
202 	 */
203 	EVENTHANDLER_INVOKE(process_exit, p);
204 
205 	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
206 		M_ZOMBIE, M_WAITOK);
207 	/*
208 	 * If parent is waiting for us to exit or exec,
209 	 * P_PPWAIT is set; we will wakeup the parent below.
210 	 */
211 	PROC_LOCK(p);
212 	stopprofclock(p);
213 	p->p_flag &= ~(P_TRACED | P_PPWAIT);
214 	SIGEMPTYSET(p->p_siglist);
215 	SIGEMPTYSET(td->td_siglist);
216 
217 	/*
218 	 * Stop the real interval timer.  If the handler is currently
219 	 * executing, prevent it from rearming itself and let it finish.
220 	 */
221 	if (timevalisset(&p->p_realtimer.it_value) &&
222 	    callout_stop(&p->p_itcallout) == 0) {
223 		timevalclear(&p->p_realtimer.it_interval);
224 		msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
225 		KASSERT(!timevalisset(&p->p_realtimer.it_value),
226 		    ("realtime timer is still armed"));
227 	}
228 	PROC_UNLOCK(p);
229 
230 	/*
231 	 * Reset any sigio structures pointing to us as a result of
232 	 * F_SETOWN with our pid.
233 	 */
234 	mtx_lock(&Giant);	/* XXX: not sure if needed */
235 	funsetownlst(&p->p_sigiolst);
236 
237 	/*
238 	 * Close open files and release open-file table.
239 	 * This may block!
240 	 */
241 	fdfree(td);
242 	mtx_unlock(&Giant);
243 
244 	/*
245 	 * Remove ourself from our leader's peer list and wake our leader.
246 	 */
247 	mtx_lock(&ppeers_lock);
248 	if (p->p_leader->p_peers) {
249 		q = p->p_leader;
250 		while (q->p_peers != p)
251 			q = q->p_peers;
252 		q->p_peers = p->p_peers;
253 		wakeup(p->p_leader);
254 	}
255 	mtx_unlock(&ppeers_lock);
256 
257 	mtx_lock(&Giant);
258 	/* The next two chunks should probably be moved to vmspace_exit. */
259 	vm = p->p_vmspace;
260 	/*
261 	 * Release user portion of address space.
262 	 * This releases references to vnodes,
263 	 * which could cause I/O if the file has been unlinked.
264 	 * Need to do this early enough that we can still sleep.
265 	 * Can't free the entire vmspace as the kernel stack
266 	 * may be mapped within that space also.
267 	 *
268 	 * Processes sharing the same vmspace may exit in one order, and
269 	 * get cleaned up by vmspace_exit() in a different order.  The
270 	 * last exiting process to reach this point releases as much of
271 	 * the environment as it can, and the last process cleaned up
272 	 * by vmspace_exit() (which decrements exitingcnt) cleans up the
273 	 * remainder.
274 	 */
275 	++vm->vm_exitingcnt;
276 	if (--vm->vm_refcnt == 0) {
277 		shmexit(vm);
278 		pmap_remove_pages(vmspace_pmap(vm), vm_map_min(&vm->vm_map),
279 		    vm_map_max(&vm->vm_map));
280 		(void) vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
281 		    vm_map_max(&vm->vm_map));
282 	}
283 
284 	sx_xlock(&proctree_lock);
285 	if (SESS_LEADER(p)) {
286 		struct session *sp;
287 
288 		sp = p->p_session;
289 		if (sp->s_ttyvp) {
290 			/*
291 			 * Controlling process.
292 			 * Signal foreground pgrp,
293 			 * drain controlling terminal
294 			 * and revoke access to controlling terminal.
295 			 */
296 			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
297 				tp = sp->s_ttyp;
298 				if (sp->s_ttyp->t_pgrp) {
299 					PGRP_LOCK(sp->s_ttyp->t_pgrp);
300 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
301 					PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
302 				}
303 				/* XXX tp should be locked. */
304 				sx_xunlock(&proctree_lock);
305 				(void) ttywait(tp);
306 				sx_xlock(&proctree_lock);
307 				/*
308 				 * The tty could have been revoked
309 				 * if we blocked.
310 				 */
311 				if (sp->s_ttyvp) {
312 					ttyvp = sp->s_ttyvp;
313 					SESS_LOCK(p->p_session);
314 					sp->s_ttyvp = NULL;
315 					SESS_UNLOCK(p->p_session);
316 					sx_xunlock(&proctree_lock);
317 					VOP_REVOKE(ttyvp, REVOKEALL);
318 					vrele(ttyvp);
319 					sx_xlock(&proctree_lock);
320 				}
321 			}
322 			if (sp->s_ttyvp) {
323 				ttyvp = sp->s_ttyvp;
324 				SESS_LOCK(p->p_session);
325 				sp->s_ttyvp = NULL;
326 				SESS_UNLOCK(p->p_session);
327 				vrele(ttyvp);
328 			}
329 			/*
330 			 * s_ttyp is not zero'd; we use this to indicate
331 			 * that the session once had a controlling terminal.
332 			 * (for logging and informational purposes)
333 			 */
334 		}
335 		SESS_LOCK(p->p_session);
336 		sp->s_leader = NULL;
337 		SESS_UNLOCK(p->p_session);
338 	}
339 	fixjobc(p, p->p_pgrp, 0);
340 	sx_xunlock(&proctree_lock);
341 	(void)acct_process(td);
342 	mtx_unlock(&Giant);
343 #ifdef KTRACE
344 	/*
345 	 * release trace file
346 	 */
347 	PROC_LOCK(p);
348 	mtx_lock(&ktrace_mtx);
349 	p->p_traceflag = 0;	/* don't trace the vrele() */
350 	tracevp = p->p_tracevp;
351 	p->p_tracevp = NULL;
352 	tracecred = p->p_tracecred;
353 	p->p_tracecred = NULL;
354 	mtx_unlock(&ktrace_mtx);
355 	PROC_UNLOCK(p);
356 	if (tracevp != NULL) {
357 		mtx_lock(&Giant);
358 		vrele(tracevp);
359 		mtx_unlock(&Giant);
360 	}
361 	if (tracecred != NULL)
362 		crfree(tracecred);
363 #endif
364 	/*
365 	 * Release reference to text vnode
366 	 */
367 	if ((vtmp = p->p_textvp) != NULL) {
368 		p->p_textvp = NULL;
369 		mtx_lock(&Giant);
370 		vrele(vtmp);
371 		mtx_unlock(&Giant);
372 	}
373 
374 	/*
375 	 * Release our limits structure.
376 	 */
377 	PROC_LOCK(p);
378 	plim = p->p_limit;
379 	p->p_limit = NULL;
380 	PROC_UNLOCK(p);
381 	lim_free(plim);
382 
383 	/*
384 	 * Release this thread's reference to the ucred.  The actual proc
385 	 * reference will stay around until the proc is harvested by
386 	 * wait().  At this point the ucred is immutable (no other threads
387 	 * from this proc are around that can change it) so we leave the
388 	 * per-thread ucred pointer intact in case it is needed although
389 	 * in theory nothing should be using it at this point.
390 	 */
391 	crfree(td->td_ucred);
392 
393 	/*
394 	 * Remove proc from allproc queue and pidhash chain.
395 	 * Place onto zombproc.  Unlink from parent's child list.
396 	 */
397 	sx_xlock(&allproc_lock);
398 	LIST_REMOVE(p, p_list);
399 	LIST_INSERT_HEAD(&zombproc, p, p_list);
400 	LIST_REMOVE(p, p_hash);
401 	sx_xunlock(&allproc_lock);
402 
403 	sx_xlock(&proctree_lock);
404 	q = LIST_FIRST(&p->p_children);
405 	if (q != NULL)		/* only need this if any child is S_ZOMB */
406 		wakeup(initproc);
407 	for (; q != NULL; q = nq) {
408 		nq = LIST_NEXT(q, p_sibling);
409 		PROC_LOCK(q);
410 		proc_reparent(q, initproc);
411 		q->p_sigparent = SIGCHLD;
412 		/*
413 		 * Traced processes are killed
414 		 * since their existence means someone is screwing up.
415 		 */
416 		if (q->p_flag & P_TRACED) {
417 			q->p_flag &= ~P_TRACED;
418 			psignal(q, SIGKILL);
419 		}
420 		PROC_UNLOCK(q);
421 	}
422 
423 	/*
424 	 * Save exit status and final rusage info, adding in child rusage
425 	 * info and self times.
426 	 */
427 	mtx_lock(&Giant);
428 	PROC_LOCK(p);
429 	p->p_xstat = rv;
430 	p->p_xthread = td;
431 	*p->p_ru = p->p_stats->p_ru;
432 	mtx_lock_spin(&sched_lock);
433 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
434 	mtx_unlock_spin(&sched_lock);
435 	ruadd(p->p_ru, &p->p_stats->p_cru);
436 
437 	/*
438 	 * Notify interested parties of our demise.
439 	 */
440 	KNOTE(&p->p_klist, NOTE_EXIT);
441 	mtx_unlock(&Giant);
442 	/*
443 	 * Just delete all entries in the p_klist. At this point we won't
444 	 * report any more events, and there are nasty race conditions that
445 	 * can beat us if we don't.
446 	 */
447 	while (SLIST_FIRST(&p->p_klist))
448 		SLIST_REMOVE_HEAD(&p->p_klist, kn_selnext);
449 
450 	/*
451 	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
452 	 * flag set, or if the handler is set to SIG_IGN, notify process
453 	 * 1 instead (and hope it will handle this situation).
454 	 */
455 	PROC_LOCK(p->p_pptr);
456 	mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
457 	if (p->p_pptr->p_sigacts->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
458 		struct proc *pp;
459 
460 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
461 		pp = p->p_pptr;
462 		PROC_UNLOCK(pp);
463 		proc_reparent(p, initproc);
464 		p->p_sigparent = SIGCHLD;
465 		PROC_LOCK(p->p_pptr);
466 		/*
467 		 * If this was the last child of our parent, notify
468 		 * parent, so in case he was wait(2)ing, he will
469 		 * continue.
470 		 */
471 		if (LIST_EMPTY(&pp->p_children))
472 			wakeup(pp);
473 	} else
474 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
475 
476 	if (p->p_pptr == initproc)
477 		psignal(p->p_pptr, SIGCHLD);
478 	else if (p->p_sigparent != 0)
479 		psignal(p->p_pptr, p->p_sigparent);
480 	PROC_UNLOCK(p->p_pptr);
481 
482 	/*
483 	 * If this is a kthread, then wakeup anyone waiting for it to exit.
484 	 */
485 	if (p->p_flag & P_KTHREAD)
486 		wakeup(p);
487 	PROC_UNLOCK(p);
488 
489 	/*
490 	 * Finally, call machine-dependent code to release the remaining
491 	 * resources including address space.
492 	 * The address space is released by "vmspace_exitfree(p)" in
493 	 * vm_waitproc().
494 	 */
495 	cpu_exit(td);
496 
497 	PROC_LOCK(p);
498 	PROC_LOCK(p->p_pptr);
499 	sx_xunlock(&proctree_lock);
500 
501 	while (mtx_owned(&Giant))
502 		mtx_unlock(&Giant);
503 
504 	/*
505 	 * We have to wait until after acquiring all locks before
506 	 * changing p_state.  We need to avoid any possibly context
507 	 * switches while marked as a zombie including blocking on
508 	 * a mutex.
509 	 */
510 	mtx_lock_spin(&sched_lock);
511 	p->p_state = PRS_ZOMBIE;
512 	critical_enter();
513 	mtx_unlock_spin(&sched_lock);
514 
515 	wakeup(p->p_pptr);
516 	PROC_UNLOCK(p->p_pptr);
517 
518 	mtx_lock_spin(&sched_lock);
519 	critical_exit();
520 
521 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
522 	binuptime(&new_switchtime);
523 	bintime_add(&p->p_runtime, &new_switchtime);
524 	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
525 	PCPU_SET(switchtime, new_switchtime);
526 	PCPU_SET(switchticks, ticks);
527 
528 	cnt.v_swtch++;
529 	sched_exit(p->p_pptr, p);
530 
531 	/*
532 	 * Make sure the scheduler takes this thread out of its tables etc.
533 	 * This will also release this thread's reference to the ucred.
534 	 * Other thread parts to release include pcb bits and such.
535 	 */
536 	thread_exit();
537 }
538 
539 #ifdef COMPAT_43
540 /*
541  * MPSAFE.  The dirty work is handled by kern_wait().
542  */
543 int
544 owait(struct thread *td, struct owait_args *uap __unused)
545 {
546 	int error, status;
547 
548 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
549 	if (error == 0)
550 		td->td_retval[1] = status;
551 	return (error);
552 }
553 #endif /* COMPAT_43 */
554 
555 /*
556  * MPSAFE.  The dirty work is handled by kern_wait().
557  */
558 int
559 wait4(struct thread *td, struct wait_args *uap)
560 {
561 	struct rusage ru;
562 	int error, status;
563 
564 	error = kern_wait(td, uap->pid, &status, uap->options, &ru);
565 	if (uap->status != NULL && error == 0)
566 		error = copyout(&status, uap->status, sizeof(status));
567 	if (uap->rusage != NULL && error == 0)
568 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
569 	return (error);
570 }
571 
572 int
573 kern_wait(struct thread *td, pid_t pid, int *status, int options, struct rusage *rusage)
574 {
575 	int nfound;
576 	struct proc *p, *q, *t;
577 	int error;
578 
579 	q = td->td_proc;
580 	if (pid == 0) {
581 		PROC_LOCK(q);
582 		pid = -q->p_pgid;
583 		PROC_UNLOCK(q);
584 	}
585 	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
586 		return (EINVAL);
587 loop:
588 	nfound = 0;
589 	sx_xlock(&proctree_lock);
590 	LIST_FOREACH(p, &q->p_children, p_sibling) {
591 		PROC_LOCK(p);
592 		if (pid != WAIT_ANY &&
593 		    p->p_pid != pid && p->p_pgid != -pid) {
594 			PROC_UNLOCK(p);
595 			continue;
596 		}
597 
598 		/*
599 		 * This special case handles a kthread spawned by linux_clone
600 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
601 		 * functions need to be able to distinguish between waiting
602 		 * on a process and waiting on a thread.  It is a thread if
603 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
604 		 * signifies we want to wait for threads and not processes.
605 		 */
606 		if ((p->p_sigparent != SIGCHLD) ^
607 		    ((options & WLINUXCLONE) != 0)) {
608 			PROC_UNLOCK(p);
609 			continue;
610 		}
611 
612 		nfound++;
613 		if (p->p_state == PRS_ZOMBIE) {
614 			td->td_retval[0] = p->p_pid;
615 			if (status)
616 				*status = p->p_xstat;	/* convert to int */
617 			if (rusage)
618 				bcopy(p->p_ru, rusage, sizeof(struct rusage));
619 
620 			/*
621 			 * If we got the child via a ptrace 'attach',
622 			 * we need to give it back to the old parent.
623 			 */
624 			PROC_UNLOCK(p);
625 			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
626 				PROC_LOCK(p);
627 				p->p_oppid = 0;
628 				proc_reparent(p, t);
629 				PROC_UNLOCK(p);
630 				psignal(t, SIGCHLD);
631 				wakeup(t);
632 				PROC_UNLOCK(t);
633 				sx_xunlock(&proctree_lock);
634 				return (0);
635 			}
636 
637 			/*
638 			 * Remove other references to this process to ensure
639 			 * we have an exclusive reference.
640 			 */
641 			sx_xlock(&allproc_lock);
642 			LIST_REMOVE(p, p_list);	/* off zombproc */
643 			sx_xunlock(&allproc_lock);
644 			LIST_REMOVE(p, p_sibling);
645 			leavepgrp(p);
646 			sx_xunlock(&proctree_lock);
647 
648 			/*
649 			 * As a side effect of this lock, we know that
650 			 * all other writes to this proc are visible now, so
651 			 * no more locking is needed for p.
652 			 */
653 			mtx_lock(&Giant);
654 			PROC_LOCK(p);
655 			p->p_xstat = 0;		/* XXX: why? */
656 			PROC_UNLOCK(p);
657 			PROC_LOCK(q);
658 			ruadd(&q->p_stats->p_cru, p->p_ru);
659 			PROC_UNLOCK(q);
660 			FREE(p->p_ru, M_ZOMBIE);
661 			p->p_ru = NULL;
662 			mtx_unlock(&Giant);
663 
664 			/*
665 			 * Decrement the count of procs running with this uid.
666 			 */
667 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
668 
669 			/*
670 			 * Free credentials, arguments, and sigacts
671 			 */
672 			crfree(p->p_ucred);
673 			p->p_ucred = NULL;
674 			pargs_drop(p->p_args);
675 			p->p_args = NULL;
676 			sigacts_free(p->p_sigacts);
677 			p->p_sigacts = NULL;
678 
679 			/*
680 			 * do any thread-system specific cleanups
681 			 */
682 			thread_wait(p);
683 
684 			/*
685 			 * Give vm and machine-dependent layer a chance
686 			 * to free anything that cpu_exit couldn't
687 			 * release while still running in process context.
688 			 */
689 			mtx_lock(&Giant);
690 			vm_waitproc(p);
691 			mtx_unlock(&Giant);
692 #ifdef MAC
693 			mac_destroy_proc(p);
694 #endif
695 			KASSERT(FIRST_THREAD_IN_PROC(p),
696 			    ("kern_wait: no residual thread!"));
697 			uma_zfree(proc_zone, p);
698 			sx_xlock(&allproc_lock);
699 			nprocs--;
700 			sx_xunlock(&allproc_lock);
701 			return (0);
702 		}
703 		mtx_lock_spin(&sched_lock);
704 		if (P_SHOULDSTOP(p) && (p->p_suspcount == p->p_numthreads) &&
705 		    ((p->p_flag & P_WAITED) == 0) &&
706 		    (p->p_flag & P_TRACED || options & WUNTRACED)) {
707 			mtx_unlock_spin(&sched_lock);
708 			p->p_flag |= P_WAITED;
709 			sx_xunlock(&proctree_lock);
710 			td->td_retval[0] = p->p_pid;
711 			if (status)
712 				*status = W_STOPCODE(p->p_xstat);
713 			PROC_UNLOCK(p);
714 			return (0);
715 		}
716 		mtx_unlock_spin(&sched_lock);
717 		if (options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
718 			sx_xunlock(&proctree_lock);
719 			td->td_retval[0] = p->p_pid;
720 			p->p_flag &= ~P_CONTINUED;
721 			PROC_UNLOCK(p);
722 
723 			if (status)
724 				*status = SIGCONT;
725 			return (0);
726 		}
727 		PROC_UNLOCK(p);
728 	}
729 	if (nfound == 0) {
730 		sx_xunlock(&proctree_lock);
731 		return (ECHILD);
732 	}
733 	if (options & WNOHANG) {
734 		sx_xunlock(&proctree_lock);
735 		td->td_retval[0] = 0;
736 		return (0);
737 	}
738 	PROC_LOCK(q);
739 	sx_xunlock(&proctree_lock);
740 	error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
741 	PROC_UNLOCK(q);
742 	if (error)
743 		return (error);
744 	goto loop;
745 }
746 
747 /*
748  * Make process 'parent' the new parent of process 'child'.
749  * Must be called with an exclusive hold of proctree lock.
750  */
751 void
752 proc_reparent(struct proc *child, struct proc *parent)
753 {
754 
755 	sx_assert(&proctree_lock, SX_XLOCKED);
756 	PROC_LOCK_ASSERT(child, MA_OWNED);
757 	if (child->p_pptr == parent)
758 		return;
759 
760 	LIST_REMOVE(child, p_sibling);
761 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
762 	child->p_pptr = parent;
763 }
764