xref: /freebsd/sys/kern/kern_exit.c (revision cec50dea12481dc578c0805c887ab2097e1c06c5)
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 	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 instant.
149 		 * With this state set:
150 		 * Any thread entering the kernel from userspace will
151 		 * thread_exit() in trap().  Any thread attempting to
152 		 * sleep will return immediatly with EINTR or EWOULDBLOCK,
153 		 * which will hopefully force them to back out to userland,
154 		 * freeing resources as they go, and anything attempting
155 		 * to return to userland will thread_exit() from userret().
156 		 * thread_exit() will unsuspend us when the last other
157 		 * thread exits.
158 		 * If there is already a thread singler after resumption,
159 		 * calling thread_single will fail, in the case, we just
160 		 * re-check all suspension request, the thread should
161 		 * either be suspended there or exit.
162 		 */
163 		if (thread_single(SINGLE_EXIT))
164 			goto retry;
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;
407 			psignal(q, SIGKILL);
408 		}
409 		PROC_UNLOCK(q);
410 	}
411 
412 	/*
413 	 * Save exit status and final rusage info, adding in child rusage
414 	 * info and self times.
415 	 */
416 	mtx_lock(&Giant);
417 	PROC_LOCK(p);
418 	p->p_xstat = rv;
419 	p->p_xthread = td;
420 	*p->p_ru = p->p_stats->p_ru;
421 	mtx_lock_spin(&sched_lock);
422 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
423 	mtx_unlock_spin(&sched_lock);
424 	ruadd(p->p_ru, &p->p_stats->p_cru);
425 
426 	mtx_unlock(&Giant);
427 	/*
428 	 * Notify interested parties of our demise.
429 	 */
430 	KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
431 	/*
432 	 * Just delete all entries in the p_klist. At this point we won't
433 	 * report any more events, and there are nasty race conditions that
434 	 * can beat us if we don't.
435 	 */
436 	knlist_clear(&p->p_klist, 1);
437 
438 	/*
439 	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
440 	 * flag set, or if the handler is set to SIG_IGN, notify process
441 	 * 1 instead (and hope it will handle this situation).
442 	 */
443 	PROC_LOCK(p->p_pptr);
444 	mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
445 	if (p->p_pptr->p_sigacts->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
446 		struct proc *pp;
447 
448 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
449 		pp = p->p_pptr;
450 		PROC_UNLOCK(pp);
451 		proc_reparent(p, initproc);
452 		p->p_sigparent = SIGCHLD;
453 		PROC_LOCK(p->p_pptr);
454 		/*
455 		 * If this was the last child of our parent, notify
456 		 * parent, so in case he was wait(2)ing, he will
457 		 * continue.
458 		 */
459 		if (LIST_EMPTY(&pp->p_children))
460 			wakeup(pp);
461 	} else
462 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
463 
464 	if (p->p_pptr == initproc)
465 		psignal(p->p_pptr, SIGCHLD);
466 	else if (p->p_sigparent != 0)
467 		psignal(p->p_pptr, p->p_sigparent);
468 	PROC_UNLOCK(p->p_pptr);
469 
470 	/*
471 	 * If this is a kthread, then wakeup anyone waiting for it to exit.
472 	 */
473 	if (p->p_flag & P_KTHREAD)
474 		wakeup(p);
475 	PROC_UNLOCK(p);
476 
477 	/*
478 	 * Finally, call machine-dependent code to release the remaining
479 	 * resources including address space.
480 	 * The address space is released by "vmspace_exitfree(p)" in
481 	 * vm_waitproc().
482 	 */
483 	cpu_exit(td);
484 
485 	PROC_LOCK(p);
486 	PROC_LOCK(p->p_pptr);
487 	sx_xunlock(&proctree_lock);
488 
489 	while (mtx_owned(&Giant))
490 		mtx_unlock(&Giant);
491 
492 	/*
493 	 * We have to wait until after acquiring all locks before
494 	 * changing p_state.  We need to avoid any possibly context
495 	 * switches while marked as a zombie including blocking on
496 	 * a mutex.
497 	 */
498 	mtx_lock_spin(&sched_lock);
499 	p->p_state = PRS_ZOMBIE;
500 	critical_enter();
501 	mtx_unlock_spin(&sched_lock);
502 
503 	wakeup(p->p_pptr);
504 	PROC_UNLOCK(p->p_pptr);
505 
506 	mtx_lock_spin(&sched_lock);
507 	critical_exit();
508 
509 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
510 	binuptime(&new_switchtime);
511 	bintime_add(&p->p_runtime, &new_switchtime);
512 	bintime_sub(&p->p_runtime, PCPU_PTR(switchtime));
513 	PCPU_SET(switchtime, new_switchtime);
514 	PCPU_SET(switchticks, ticks);
515 
516 	cnt.v_swtch++;
517 	sched_exit(p->p_pptr, td);
518 
519 	/*
520 	 * hopefully no one will try to deliver a signal to the process this
521 	 * late in the game.
522 	 */
523 	knlist_destroy(&p->p_klist);
524 
525 	/*
526 	 * Make sure the scheduler takes this thread out of its tables etc.
527 	 * This will also release this thread's reference to the ucred.
528 	 * Other thread parts to release include pcb bits and such.
529 	 */
530 	thread_exit();
531 }
532 
533 #ifdef COMPAT_43
534 /*
535  * MPSAFE.  The dirty work is handled by kern_wait().
536  */
537 int
538 owait(struct thread *td, struct owait_args *uap __unused)
539 {
540 	int error, status;
541 
542 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
543 	if (error == 0)
544 		td->td_retval[1] = status;
545 	return (error);
546 }
547 #endif /* COMPAT_43 */
548 
549 /*
550  * MPSAFE.  The dirty work is handled by kern_wait().
551  */
552 int
553 wait4(struct thread *td, struct wait_args *uap)
554 {
555 	struct rusage ru;
556 	int error, status;
557 
558 	error = kern_wait(td, uap->pid, &status, uap->options, &ru);
559 	if (uap->status != NULL && error == 0)
560 		error = copyout(&status, uap->status, sizeof(status));
561 	if (uap->rusage != NULL && error == 0)
562 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
563 	return (error);
564 }
565 
566 int
567 kern_wait(struct thread *td, pid_t pid, int *status, int options, struct rusage *rusage)
568 {
569 	int nfound;
570 	struct proc *p, *q, *t;
571 	int error;
572 
573 	q = td->td_proc;
574 	if (pid == 0) {
575 		PROC_LOCK(q);
576 		pid = -q->p_pgid;
577 		PROC_UNLOCK(q);
578 	}
579 	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
580 		return (EINVAL);
581 loop:
582 	nfound = 0;
583 	sx_xlock(&proctree_lock);
584 	LIST_FOREACH(p, &q->p_children, p_sibling) {
585 		PROC_LOCK(p);
586 		if (pid != WAIT_ANY &&
587 		    p->p_pid != pid && p->p_pgid != -pid) {
588 			PROC_UNLOCK(p);
589 			continue;
590 		}
591 
592 		/*
593 		 * This special case handles a kthread spawned by linux_clone
594 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
595 		 * functions need to be able to distinguish between waiting
596 		 * on a process and waiting on a thread.  It is a thread if
597 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
598 		 * signifies we want to wait for threads and not processes.
599 		 */
600 		if ((p->p_sigparent != SIGCHLD) ^
601 		    ((options & WLINUXCLONE) != 0)) {
602 			PROC_UNLOCK(p);
603 			continue;
604 		}
605 
606 		nfound++;
607 		if (p->p_state == PRS_ZOMBIE) {
608 			td->td_retval[0] = p->p_pid;
609 			if (status)
610 				*status = p->p_xstat;	/* convert to int */
611 			if (rusage)
612 				bcopy(p->p_ru, rusage, sizeof(struct rusage));
613 
614 			/*
615 			 * If we got the child via a ptrace 'attach',
616 			 * we need to give it back to the old parent.
617 			 */
618 			PROC_UNLOCK(p);
619 			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
620 				PROC_LOCK(p);
621 				p->p_oppid = 0;
622 				proc_reparent(p, t);
623 				PROC_UNLOCK(p);
624 				psignal(t, SIGCHLD);
625 				wakeup(t);
626 				PROC_UNLOCK(t);
627 				sx_xunlock(&proctree_lock);
628 				return (0);
629 			}
630 
631 			/*
632 			 * Remove other references to this process to ensure
633 			 * we have an exclusive reference.
634 			 */
635 			sx_xlock(&allproc_lock);
636 			LIST_REMOVE(p, p_list);	/* off zombproc */
637 			sx_xunlock(&allproc_lock);
638 			LIST_REMOVE(p, p_sibling);
639 			leavepgrp(p);
640 			sx_xunlock(&proctree_lock);
641 
642 			/*
643 			 * As a side effect of this lock, we know that
644 			 * all other writes to this proc are visible now, so
645 			 * no more locking is needed for p.
646 			 */
647 			mtx_lock(&Giant);
648 			PROC_LOCK(p);
649 			p->p_xstat = 0;		/* XXX: why? */
650 			PROC_UNLOCK(p);
651 			PROC_LOCK(q);
652 			ruadd(&q->p_stats->p_cru, p->p_ru);
653 			PROC_UNLOCK(q);
654 			FREE(p->p_ru, M_ZOMBIE);
655 			p->p_ru = NULL;
656 			mtx_unlock(&Giant);
657 
658 			/*
659 			 * Decrement the count of procs running with this uid.
660 			 */
661 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
662 
663 			/*
664 			 * Free credentials, arguments, and sigacts
665 			 */
666 			crfree(p->p_ucred);
667 			p->p_ucred = NULL;
668 			pargs_drop(p->p_args);
669 			p->p_args = NULL;
670 			sigacts_free(p->p_sigacts);
671 			p->p_sigacts = NULL;
672 
673 			/*
674 			 * do any thread-system specific cleanups
675 			 */
676 			thread_wait(p);
677 
678 			/*
679 			 * Give vm and machine-dependent layer a chance
680 			 * to free anything that cpu_exit couldn't
681 			 * release while still running in process context.
682 			 */
683 			vm_waitproc(p);
684 #ifdef MAC
685 			mac_destroy_proc(p);
686 #endif
687 			KASSERT(FIRST_THREAD_IN_PROC(p),
688 			    ("kern_wait: no residual thread!"));
689 			uma_zfree(proc_zone, p);
690 			sx_xlock(&allproc_lock);
691 			nprocs--;
692 			sx_xunlock(&allproc_lock);
693 			return (0);
694 		}
695 		mtx_lock_spin(&sched_lock);
696 		if (P_SHOULDSTOP(p) && (p->p_suspcount == p->p_numthreads) &&
697 		    ((p->p_flag & P_WAITED) == 0) &&
698 		    (p->p_flag & P_TRACED || options & WUNTRACED)) {
699 			mtx_unlock_spin(&sched_lock);
700 			p->p_flag |= P_WAITED;
701 			sx_xunlock(&proctree_lock);
702 			td->td_retval[0] = p->p_pid;
703 			if (status)
704 				*status = W_STOPCODE(p->p_xstat);
705 			PROC_UNLOCK(p);
706 			return (0);
707 		}
708 		mtx_unlock_spin(&sched_lock);
709 		if (options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
710 			sx_xunlock(&proctree_lock);
711 			td->td_retval[0] = p->p_pid;
712 			p->p_flag &= ~P_CONTINUED;
713 			PROC_UNLOCK(p);
714 
715 			if (status)
716 				*status = SIGCONT;
717 			return (0);
718 		}
719 		PROC_UNLOCK(p);
720 	}
721 	if (nfound == 0) {
722 		sx_xunlock(&proctree_lock);
723 		return (ECHILD);
724 	}
725 	if (options & WNOHANG) {
726 		sx_xunlock(&proctree_lock);
727 		td->td_retval[0] = 0;
728 		return (0);
729 	}
730 	PROC_LOCK(q);
731 	sx_xunlock(&proctree_lock);
732 	error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
733 	PROC_UNLOCK(q);
734 	if (error)
735 		return (error);
736 	goto loop;
737 }
738 
739 /*
740  * Make process 'parent' the new parent of process 'child'.
741  * Must be called with an exclusive hold of proctree lock.
742  */
743 void
744 proc_reparent(struct proc *child, struct proc *parent)
745 {
746 
747 	sx_assert(&proctree_lock, SX_XLOCKED);
748 	PROC_LOCK_ASSERT(child, MA_OWNED);
749 	if (child->p_pptr == parent)
750 		return;
751 
752 	LIST_REMOVE(child, p_sibling);
753 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
754 	child->p_pptr = parent;
755 }
756