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