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