kern_exit.c revision 151316
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: head/sys/kern/kern_exit.c 151316 2005-10-14 12:43:47Z davidxu $");
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 */
82MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
83
84/*
85 * exit --
86 *	Death of process.
87 *
88 * MPSAFE
89 */
90void
91sys_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 */
103void
104exit1(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) {
138retry:
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	sigqueue_flush(&p->p_sigqueue);
211	sigqueue_flush(&td->td_sigqueue);
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	 * If this thread tickled GEOM, we need to wait for the giggling to
242	 * stop before we return to userland
243	 */
244	if (td->td_pflags & TDP_GEOM)
245		g_waitidle();
246
247	/*
248	 * Remove ourself from our leader's peer list and wake our leader.
249	 */
250	mtx_lock(&ppeers_lock);
251	if (p->p_leader->p_peers) {
252		q = p->p_leader;
253		while (q->p_peers != p)
254			q = q->p_peers;
255		q->p_peers = p->p_peers;
256		wakeup(p->p_leader);
257	}
258	mtx_unlock(&ppeers_lock);
259
260	/* The next two chunks should probably be moved to vmspace_exit. */
261	vm = p->p_vmspace;
262	/*
263	 * Release user portion of address space.
264	 * This releases references to vnodes,
265	 * which could cause I/O if the file has been unlinked.
266	 * Need to do this early enough that we can still sleep.
267	 * Can't free the entire vmspace as the kernel stack
268	 * may be mapped within that space also.
269	 *
270	 * Processes sharing the same vmspace may exit in one order, and
271	 * get cleaned up by vmspace_exit() in a different order.  The
272	 * last exiting process to reach this point releases as much of
273	 * the environment as it can, and the last process cleaned up
274	 * by vmspace_exit() (which decrements exitingcnt) cleans up the
275	 * remainder.
276	 */
277	atomic_add_int(&vm->vm_exitingcnt, 1);
278	do
279		refcnt = vm->vm_refcnt;
280	while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
281	if (refcnt == 1) {
282		shmexit(vm);
283		pmap_remove_pages(vmspace_pmap(vm), vm_map_min(&vm->vm_map),
284		    vm_map_max(&vm->vm_map));
285		(void) vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
286		    vm_map_max(&vm->vm_map));
287	}
288
289	mtx_lock(&Giant);
290	sx_xlock(&proctree_lock);
291	if (SESS_LEADER(p)) {
292		struct session *sp;
293
294		sp = p->p_session;
295		if (sp->s_ttyvp) {
296			/*
297			 * Controlling process.
298			 * Signal foreground pgrp,
299			 * drain controlling terminal
300			 * and revoke access to controlling terminal.
301			 */
302			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
303				tp = sp->s_ttyp;
304				if (sp->s_ttyp->t_pgrp) {
305					PGRP_LOCK(sp->s_ttyp->t_pgrp);
306					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
307					PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
308				}
309				/* XXX tp should be locked. */
310				sx_xunlock(&proctree_lock);
311				(void) ttywait(tp);
312				sx_xlock(&proctree_lock);
313				/*
314				 * The tty could have been revoked
315				 * if we blocked.
316				 */
317				if (sp->s_ttyvp) {
318					ttyvp = sp->s_ttyvp;
319					SESS_LOCK(p->p_session);
320					sp->s_ttyvp = NULL;
321					SESS_UNLOCK(p->p_session);
322					sx_xunlock(&proctree_lock);
323					VOP_LOCK(ttyvp, LK_EXCLUSIVE, td);
324					VOP_REVOKE(ttyvp, REVOKEALL);
325					vput(ttyvp);
326					sx_xlock(&proctree_lock);
327				}
328			}
329			if (sp->s_ttyvp) {
330				ttyvp = sp->s_ttyvp;
331				SESS_LOCK(p->p_session);
332				sp->s_ttyvp = NULL;
333				SESS_UNLOCK(p->p_session);
334				vrele(ttyvp);
335			}
336			/*
337			 * s_ttyp is not zero'd; we use this to indicate
338			 * that the session once had a controlling terminal.
339			 * (for logging and informational purposes)
340			 */
341		}
342		SESS_LOCK(p->p_session);
343		sp->s_leader = NULL;
344		SESS_UNLOCK(p->p_session);
345	}
346	fixjobc(p, p->p_pgrp, 0);
347	sx_xunlock(&proctree_lock);
348	(void)acct_process(td);
349	mtx_unlock(&Giant);
350#ifdef KTRACE
351	/*
352	 * release trace file
353	 */
354	PROC_LOCK(p);
355	mtx_lock(&ktrace_mtx);
356	p->p_traceflag = 0;	/* don't trace the vrele() */
357	tracevp = p->p_tracevp;
358	p->p_tracevp = NULL;
359	tracecred = p->p_tracecred;
360	p->p_tracecred = NULL;
361	mtx_unlock(&ktrace_mtx);
362	PROC_UNLOCK(p);
363	if (tracevp != NULL) {
364		mtx_lock(&Giant);
365		vrele(tracevp);
366		mtx_unlock(&Giant);
367	}
368	if (tracecred != NULL)
369		crfree(tracecred);
370#endif
371	/*
372	 * Release reference to text vnode
373	 */
374	if ((vtmp = p->p_textvp) != NULL) {
375		p->p_textvp = NULL;
376		mtx_lock(&Giant);
377		vrele(vtmp);
378		mtx_unlock(&Giant);
379	}
380
381	/*
382	 * Release our limits structure.
383	 */
384	PROC_LOCK(p);
385	plim = p->p_limit;
386	p->p_limit = NULL;
387	PROC_UNLOCK(p);
388	lim_free(plim);
389
390	/*
391	 * Remove proc from allproc queue and pidhash chain.
392	 * Place onto zombproc.  Unlink from parent's child list.
393	 */
394	sx_xlock(&allproc_lock);
395	LIST_REMOVE(p, p_list);
396	LIST_INSERT_HEAD(&zombproc, p, p_list);
397	LIST_REMOVE(p, p_hash);
398	sx_xunlock(&allproc_lock);
399
400	sx_xlock(&proctree_lock);
401	q = LIST_FIRST(&p->p_children);
402	if (q != NULL)		/* only need this if any child is S_ZOMB */
403		wakeup(initproc);
404	for (; q != NULL; q = nq) {
405		nq = LIST_NEXT(q, p_sibling);
406		PROC_LOCK(q);
407		proc_reparent(q, initproc);
408		q->p_sigparent = SIGCHLD;
409		/*
410		 * Traced processes are killed
411		 * since their existence means someone is screwing up.
412		 */
413		if (q->p_flag & P_TRACED) {
414			q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
415			psignal(q, SIGKILL);
416		}
417		PROC_UNLOCK(q);
418	}
419
420	/*
421	 * Save exit status and finalize rusage info except for times,
422	 * adding in child rusage info.
423	 */
424	PROC_LOCK(p);
425	p->p_xstat = rv;
426	p->p_xthread = td;
427	p->p_stats->p_ru.ru_nvcsw++;
428	*p->p_ru = p->p_stats->p_ru;
429	ruadd(p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
430
431	/*
432	 * Notify interested parties of our demise.
433	 */
434	KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
435
436	/*
437	 * Just delete all entries in the p_klist. At this point we won't
438	 * report any more events, and there are nasty race conditions that
439	 * can beat us if we don't.
440	 */
441	knlist_clear(&p->p_klist, 1);
442
443	/*
444	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
445	 * flag set, or if the handler is set to SIG_IGN, notify process
446	 * 1 instead (and hope it will handle this situation).
447	 */
448	PROC_LOCK(p->p_pptr);
449	mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
450	if (p->p_pptr->p_sigacts->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
451		struct proc *pp;
452
453		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
454		pp = p->p_pptr;
455		PROC_UNLOCK(pp);
456		proc_reparent(p, initproc);
457		p->p_sigparent = SIGCHLD;
458		PROC_LOCK(p->p_pptr);
459		/*
460		 * If this was the last child of our parent, notify
461		 * parent, so in case he was wait(2)ing, he will
462		 * continue.
463		 */
464		if (LIST_EMPTY(&pp->p_children))
465			wakeup(pp);
466	} else
467		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
468
469	if (p->p_pptr == initproc)
470		psignal(p->p_pptr, SIGCHLD);
471	else if (p->p_sigparent != 0)
472		psignal(p->p_pptr, p->p_sigparent);
473	PROC_UNLOCK(p->p_pptr);
474
475	/*
476	 * If this is a kthread, then wakeup anyone waiting for it to exit.
477	 */
478	if (p->p_flag & P_KTHREAD)
479		wakeup(p);
480	PROC_UNLOCK(p);
481
482	/*
483	 * Finally, call machine-dependent code to release the remaining
484	 * resources including address space.
485	 * The address space is released by "vmspace_exitfree(p)" in
486	 * vm_waitproc().
487	 */
488	cpu_exit(td);
489
490	WITNESS_WARN(WARN_PANIC, &proctree_lock.sx_object,
491	    "process (pid %d) exiting", p->p_pid);
492
493	PROC_LOCK(p);
494	PROC_LOCK(p->p_pptr);
495	sx_xunlock(&proctree_lock);
496
497	/*
498	 * We have to wait until after acquiring all locks before
499	 * changing p_state.  We need to avoid all possible context
500	 * switches (including ones from blocking on a mutex) while
501	 * marked as a zombie.  We also have to set the zombie state
502	 * before we release the parent process' proc lock to avoid
503	 * a lost wakeup.  So, we first call wakeup, then we grab the
504	 * sched lock, update the state, and release the parent process'
505	 * proc lock.
506	 */
507	wakeup(p->p_pptr);
508	mtx_lock_spin(&sched_lock);
509	p->p_state = PRS_ZOMBIE;
510	PROC_UNLOCK(p->p_pptr);
511
512	/* Do the same timestamp bookkeeping that mi_switch() would do. */
513	binuptime(&new_switchtime);
514	bintime_add(&p->p_rux.rux_runtime, &new_switchtime);
515	bintime_sub(&p->p_rux.rux_runtime, PCPU_PTR(switchtime));
516	PCPU_SET(switchtime, new_switchtime);
517	PCPU_SET(switchticks, ticks);
518	cnt.v_swtch++;
519
520	sched_exit(p->p_pptr, td);
521
522	/*
523	 * Hopefully no one will try to deliver a signal to the process this
524	 * late in the game.
525	 */
526	knlist_destroy(&p->p_klist);
527
528	/*
529	 * Make sure the scheduler takes this thread out of its tables etc.
530	 * This will also release this thread's reference to the ucred.
531	 * Other thread parts to release include pcb bits and such.
532	 */
533	thread_exit();
534}
535
536#ifdef COMPAT_43
537/*
538 * The dirty work is handled by kern_wait().
539 *
540 * MPSAFE.
541 */
542int
543owait(struct thread *td, struct owait_args *uap __unused)
544{
545	int error, status;
546
547	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
548	if (error == 0)
549		td->td_retval[1] = status;
550	return (error);
551}
552#endif /* COMPAT_43 */
553
554/*
555 * The dirty work is handled by kern_wait().
556 *
557 * MPSAFE.
558 */
559int
560wait4(struct thread *td, struct wait_args *uap)
561{
562	struct rusage ru, *rup;
563	int error, status;
564
565	if (uap->rusage != NULL)
566		rup = &ru;
567	else
568		rup = NULL;
569	error = kern_wait(td, uap->pid, &status, uap->options, rup);
570	if (uap->status != NULL && error == 0)
571		error = copyout(&status, uap->status, sizeof(status));
572	if (uap->rusage != NULL && error == 0)
573		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
574	return (error);
575}
576
577int
578kern_wait(struct thread *td, pid_t pid, int *status, int options,
579    struct rusage *rusage)
580{
581	struct proc *p, *q, *t;
582	int error, nfound;
583
584	q = td->td_proc;
585	if (pid == 0) {
586		PROC_LOCK(q);
587		pid = -q->p_pgid;
588		PROC_UNLOCK(q);
589	}
590	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
591		return (EINVAL);
592loop:
593	if (q->p_flag & P_STATCHILD) {
594		PROC_LOCK(q);
595		q->p_flag &= ~P_STATCHILD;
596		PROC_UNLOCK(q);
597	}
598	nfound = 0;
599	sx_xlock(&proctree_lock);
600	LIST_FOREACH(p, &q->p_children, p_sibling) {
601		PROC_LOCK(p);
602		if (pid != WAIT_ANY &&
603		    p->p_pid != pid && p->p_pgid != -pid) {
604			PROC_UNLOCK(p);
605			continue;
606		}
607		if (p_canwait(td, p)) {
608			PROC_UNLOCK(p);
609			continue;
610		}
611
612		/*
613		 * This special case handles a kthread spawned by linux_clone
614		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
615		 * functions need to be able to distinguish between waiting
616		 * on a process and waiting on a thread.  It is a thread if
617		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
618		 * signifies we want to wait for threads and not processes.
619		 */
620		if ((p->p_sigparent != SIGCHLD) ^
621		    ((options & WLINUXCLONE) != 0)) {
622			PROC_UNLOCK(p);
623			continue;
624		}
625
626		nfound++;
627		if (p->p_state == PRS_ZOMBIE) {
628
629			/*
630			 * It is possible that the last thread of this
631			 * process is still running on another CPU
632			 * in thread_exit() after having dropped the process
633			 * lock via PROC_UNLOCK() but before it has completed
634			 * cpu_throw().  In that case, the other thread must
635			 * still hold sched_lock, so simply by acquiring
636			 * sched_lock once we will wait long enough for the
637			 * thread to exit in that case.
638			 */
639			mtx_lock_spin(&sched_lock);
640			mtx_unlock_spin(&sched_lock);
641
642			td->td_retval[0] = p->p_pid;
643			if (status)
644				*status = p->p_xstat;	/* convert to int */
645			if (rusage) {
646				*rusage = *p->p_ru;
647				calcru(p, &rusage->ru_utime, &rusage->ru_stime);
648			}
649
650			/*
651			 * If we got the child via a ptrace 'attach',
652			 * we need to give it back to the old parent.
653			 */
654			PROC_UNLOCK(p);
655			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
656				PROC_LOCK(p);
657				p->p_oppid = 0;
658				proc_reparent(p, t);
659				PROC_UNLOCK(p);
660				psignal(t, SIGCHLD);
661				wakeup(t);
662				PROC_UNLOCK(t);
663				sx_xunlock(&proctree_lock);
664				return (0);
665			}
666
667			/*
668			 * Remove other references to this process to ensure
669			 * we have an exclusive reference.
670			 */
671			sx_xlock(&allproc_lock);
672			LIST_REMOVE(p, p_list);	/* off zombproc */
673			sx_xunlock(&allproc_lock);
674			LIST_REMOVE(p, p_sibling);
675			leavepgrp(p);
676			sx_xunlock(&proctree_lock);
677
678			/*
679			 * As a side effect of this lock, we know that
680			 * all other writes to this proc are visible now, so
681			 * no more locking is needed for p.
682			 */
683			PROC_LOCK(p);
684			p->p_xstat = 0;		/* XXX: why? */
685			PROC_UNLOCK(p);
686			PROC_LOCK(q);
687			ruadd(&q->p_stats->p_cru, &q->p_crux, p->p_ru,
688			    &p->p_rux);
689			PROC_UNLOCK(q);
690			FREE(p->p_ru, M_ZOMBIE);
691			p->p_ru = NULL;
692
693			/*
694			 * Decrement the count of procs running with this uid.
695			 */
696			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
697
698			/*
699			 * Free credentials, arguments, and sigacts.
700			 */
701			crfree(p->p_ucred);
702			p->p_ucred = NULL;
703			pargs_drop(p->p_args);
704			p->p_args = NULL;
705			sigacts_free(p->p_sigacts);
706			p->p_sigacts = NULL;
707
708			/*
709			 * Do any thread-system specific cleanups.
710			 */
711			thread_wait(p);
712
713			/*
714			 * Give vm and machine-dependent layer a chance
715			 * to free anything that cpu_exit couldn't
716			 * release while still running in process context.
717			 */
718			vm_waitproc(p);
719#ifdef MAC
720			mac_destroy_proc(p);
721#endif
722			KASSERT(FIRST_THREAD_IN_PROC(p),
723			    ("kern_wait: no residual thread!"));
724			uma_zfree(proc_zone, p);
725			sx_xlock(&allproc_lock);
726			nprocs--;
727			sx_xunlock(&allproc_lock);
728			return (0);
729		}
730		mtx_lock_spin(&sched_lock);
731		if ((p->p_flag & P_STOPPED_SIG) &&
732		    (p->p_suspcount == p->p_numthreads) &&
733		    (p->p_flag & P_WAITED) == 0 &&
734		    (p->p_flag & P_TRACED || options & WUNTRACED)) {
735			mtx_unlock_spin(&sched_lock);
736			p->p_flag |= P_WAITED;
737			sx_xunlock(&proctree_lock);
738			td->td_retval[0] = p->p_pid;
739			if (status)
740				*status = W_STOPCODE(p->p_xstat);
741			PROC_UNLOCK(p);
742			return (0);
743		}
744		mtx_unlock_spin(&sched_lock);
745		if (options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
746			sx_xunlock(&proctree_lock);
747			td->td_retval[0] = p->p_pid;
748			p->p_flag &= ~P_CONTINUED;
749			PROC_UNLOCK(p);
750
751			if (status)
752				*status = SIGCONT;
753			return (0);
754		}
755		PROC_UNLOCK(p);
756	}
757	if (nfound == 0) {
758		sx_xunlock(&proctree_lock);
759		return (ECHILD);
760	}
761	if (options & WNOHANG) {
762		sx_xunlock(&proctree_lock);
763		td->td_retval[0] = 0;
764		return (0);
765	}
766	PROC_LOCK(q);
767	sx_xunlock(&proctree_lock);
768	if (q->p_flag & P_STATCHILD) {
769		q->p_flag &= ~P_STATCHILD;
770		error = 0;
771	} else
772		error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
773	PROC_UNLOCK(q);
774	if (error)
775		return (error);
776	goto loop;
777}
778
779/*
780 * Make process 'parent' the new parent of process 'child'.
781 * Must be called with an exclusive hold of proctree lock.
782 */
783void
784proc_reparent(struct proc *child, struct proc *parent)
785{
786
787	sx_assert(&proctree_lock, SX_XLOCKED);
788	PROC_LOCK_ASSERT(child, MA_OWNED);
789	if (child->p_pptr == parent)
790		return;
791
792	LIST_REMOVE(child, p_sibling);
793	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
794	child->p_pptr = parent;
795}
796