kern_exit.c revision 99072
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 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 *	@(#)kern_exit.c	8.7 (Berkeley) 2/12/94
39 * $FreeBSD: head/sys/kern/kern_exit.c 99072 2002-06-29 17:26:22Z julian $
40 */
41
42#include "opt_compat.h"
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/sysproto.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/sx.h>
61#include <sys/ptrace.h>
62#include <sys/acct.h>		/* for acct_process() function prototype */
63#include <sys/filedesc.h>
64#include <sys/shm.h>
65#include <sys/sem.h>
66#include <sys/jail.h>
67#ifdef KTRACE
68#include <sys/ktrace.h>
69#endif
70
71#include <vm/vm.h>
72#include <vm/vm_extern.h>
73#include <vm/vm_param.h>
74#include <vm/pmap.h>
75#include <vm/vm_map.h>
76#include <vm/uma.h>
77#include <sys/user.h>
78
79/* Required to be non-static for SysVR4 emulator */
80MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
81
82static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
83
84static int wait1(struct thread *, struct wait_args *, int);
85
86/*
87 * callout list for things to do at exit time
88 */
89struct exitlist {
90	exitlist_fn function;
91	TAILQ_ENTRY(exitlist) next;
92};
93
94TAILQ_HEAD(exit_list_head, exitlist);
95static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
96
97/*
98 * exit --
99 *	Death of process.
100 *
101 * MPSAFE
102 */
103void
104sys_exit(td, uap)
105	struct thread *td;
106	struct sys_exit_args /* {
107		int	rval;
108	} */ *uap;
109{
110
111	mtx_lock(&Giant);
112	exit1(td, W_EXITCODE(uap->rval, 0));
113	/* NOTREACHED */
114}
115
116/*
117 * Exit: deallocate address space and other resources, change proc state
118 * to zombie, and unlink proc from allproc and parent's lists.  Save exit
119 * status and rusage for wait().  Check for child processes and orphan them.
120 */
121void
122exit1(td, rv)
123	register struct thread *td;
124	int rv;
125{
126	struct exitlist *ep;
127	struct proc *p, *nq, *q;
128	struct tty *tp;
129	struct vnode *ttyvp;
130	register struct vmspace *vm;
131	struct vnode *vtmp;
132#ifdef KTRACE
133	struct vnode *tracevp;
134#endif
135
136	GIANT_REQUIRED;
137
138	p = td->td_proc;
139	if (p == initproc) {
140		printf("init died (signal %d, exit %d)\n",
141		    WTERMSIG(rv), WEXITSTATUS(rv));
142		panic("Going nowhere without my init!");
143	}
144
145	/*
146	 * XXXXKSE: MUST abort all other threads before proceeding past here.
147	 */
148	PROC_LOCK(p);
149	if (p->p_flag & P_KSES) {
150		/*
151		 * First check if some other thread got here before us..
152		 * if so, act apropriatly, (exit or suspend);
153		 */
154		thread_suspend_check(0);
155		/*
156		 * Here is a trick..
157		 * We need to free up our KSE to process other threads
158		 * so that we can safely set the UNBOUND flag
159		 * (whether or not we have a mailbox) as we are NEVER
160		 * going to return to the user.
161		 * The flag will not be set yet if we are exiting
162		 * because of a signal, pagefault, or similar
163		 * (or even an exit(2) from the UTS).
164		 */
165		td->td_flags |= TDF_UNBOUND;
166
167		/*
168		 * Kill off the other threads. This requires
169		 * Some co-operation from other parts of the kernel
170		 * so it may not be instant.
171		 * With this state set:
172		 * Any thread entering the kernel from userspace will
173		 * thread_exit() in trap().  Any thread attempting to
174		 * sleep will return immediatly
175		 * with EINTR or EWOULDBLOCK, which will hopefully force them
176		 * to back out to userland, freeing resources as they go, and
177		 * anything attempting to return to userland will thread_exit()
178		 * from userret().  thread_exit() will unsuspend us
179		 * when the last other thread exits.
180		 */
181		if (thread_single(SNGLE_EXIT)) {
182			panic ("Exit: Single threading fouled up");
183		}
184		/*
185		 * All other activity in this process is now stopped.
186		 * Remove excess KSEs and KSEGRPS. XXXKSE (when we have them)
187		 * ...
188		 * Turn off threading support.
189		 */
190		p->p_flag &= ~P_KSES;
191		td->td_flags &= ~TDF_UNBOUND;
192		thread_single_end(); 	/* Don't need this any more. */
193	}
194	/*
195	 * With this state set:
196	 * Any thread entering the kernel from userspace will thread_exit()
197	 * in trap().  Any thread attempting to sleep will return immediatly
198	 * with EINTR or EWOULDBLOCK, which will hopefully force them
199	 * to back out to userland, freeing resources as they go, and
200	 * anything attempting to return to userland will thread_exit()
201	 * from userret().  thread_exit() will do a wakeup on p->p_numthreads
202	 * if it transitions to 1.
203	 */
204
205	p->p_flag |= P_WEXIT;
206	PROC_UNLOCK(p);
207	if (td->td_kse->ke_mdstorage)
208		cpu_free_kse_mdstorage(td->td_kse);
209
210	/* Are we a task leader? */
211	PROC_LOCK(p);
212	if (p == p->p_leader) {
213		q = p->p_peers;
214		while (q != NULL) {
215			PROC_LOCK(q);
216			psignal(q, SIGKILL);
217			PROC_UNLOCK(q);
218			q = q->p_peers;
219		}
220		while (p->p_peers)
221			msleep(p, &p->p_mtx, PWAIT, "exit1", 0);
222	}
223	PROC_UNLOCK(p);
224
225#ifdef PGINPROF
226	vmsizmon();
227#endif
228	STOPEVENT(p, S_EXIT, rv);
229	wakeup(&p->p_stype);	/* Wakeup anyone in procfs' PIOCWAIT */
230
231	/*
232	 * Check if any loadable modules need anything done at process exit.
233	 * e.g. SYSV IPC stuff
234	 * XXX what if one of these generates an error?
235	 */
236	TAILQ_FOREACH(ep, &exit_list, next)
237		(*ep->function)(p);
238
239	stopprofclock(p);
240
241	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
242		M_ZOMBIE, M_WAITOK);
243	/*
244	 * If parent is waiting for us to exit or exec,
245	 * P_PPWAIT is set; we will wakeup the parent below.
246	 */
247	PROC_LOCK(p);
248	p->p_flag &= ~(P_TRACED | P_PPWAIT);
249	SIGEMPTYSET(p->p_siglist);
250	PROC_UNLOCK(p);
251	if (timevalisset(&p->p_realtimer.it_value))
252		callout_stop(&p->p_itcallout);
253
254	/*
255	 * Reset any sigio structures pointing to us as a result of
256	 * F_SETOWN with our pid.
257	 */
258	funsetownlst(&p->p_sigiolst);
259
260	/*
261	 * Close open files and release open-file table.
262	 * This may block!
263	 */
264	fdfree(td); /* XXXKSE *//* may not be the one in proc */
265
266	/*
267	 * Remove ourself from our leader's peer list and wake our leader.
268	 */
269	PROC_LOCK(p->p_leader);
270	if (p->p_leader->p_peers) {
271		q = p->p_leader;
272		while (q->p_peers != p)
273			q = q->p_peers;
274		q->p_peers = p->p_peers;
275		wakeup(p->p_leader);
276	}
277	PROC_UNLOCK(p->p_leader);
278
279	/* The next two chunks should probably be moved to vmspace_exit. */
280	vm = p->p_vmspace;
281	/*
282	 * Release user portion of address space.
283	 * This releases references to vnodes,
284	 * which could cause I/O if the file has been unlinked.
285	 * Need to do this early enough that we can still sleep.
286	 * Can't free the entire vmspace as the kernel stack
287	 * may be mapped within that space also.
288	 */
289	if (--vm->vm_refcnt == 0) {
290		if (vm->vm_shm)
291			shmexit(p);
292		pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
293		    VM_MAXUSER_ADDRESS);
294		(void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
295		    VM_MAXUSER_ADDRESS);
296		vm->vm_freer = p;
297	}
298
299	sx_xlock(&proctree_lock);
300	if (SESS_LEADER(p)) {
301		register struct session *sp;
302
303		sp = p->p_session;
304		if (sp->s_ttyvp) {
305			/*
306			 * Controlling process.
307			 * Signal foreground pgrp,
308			 * drain controlling terminal
309			 * and revoke access to controlling terminal.
310			 */
311			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
312				tp = sp->s_ttyp;
313				if (sp->s_ttyp->t_pgrp) {
314					PGRP_LOCK(sp->s_ttyp->t_pgrp);
315					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
316					PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
317				}
318				/* XXX tp should be locked. */
319				sx_xunlock(&proctree_lock);
320				(void) ttywait(tp);
321				sx_xlock(&proctree_lock);
322				/*
323				 * The tty could have been revoked
324				 * if we blocked.
325				 */
326				if (sp->s_ttyvp) {
327					ttyvp = sp->s_ttyvp;
328					SESS_LOCK(p->p_session);
329					sp->s_ttyvp = NULL;
330					SESS_UNLOCK(p->p_session);
331					sx_xunlock(&proctree_lock);
332					VOP_REVOKE(ttyvp, REVOKEALL);
333					vrele(ttyvp);
334					sx_xlock(&proctree_lock);
335				}
336			}
337			if (sp->s_ttyvp) {
338				ttyvp = sp->s_ttyvp;
339				SESS_LOCK(p->p_session);
340				sp->s_ttyvp = NULL;
341				SESS_UNLOCK(p->p_session);
342				vrele(ttyvp);
343			}
344			/*
345			 * s_ttyp is not zero'd; we use this to indicate
346			 * that the session once had a controlling terminal.
347			 * (for logging and informational purposes)
348			 */
349		}
350		SESS_LOCK(p->p_session);
351		sp->s_leader = NULL;
352		SESS_UNLOCK(p->p_session);
353	}
354	fixjobc(p, p->p_pgrp, 0);
355	sx_xunlock(&proctree_lock);
356	(void)acct_process(td);
357#ifdef KTRACE
358	/*
359	 * release trace file
360	 */
361	PROC_LOCK(p);
362	mtx_lock(&ktrace_mtx);
363	p->p_traceflag = 0;	/* don't trace the vrele() */
364	tracevp = p->p_tracep;
365	p->p_tracep = NULL;
366	mtx_unlock(&ktrace_mtx);
367	PROC_UNLOCK(p);
368	if (tracevp != NULL)
369		vrele(tracevp);
370#endif
371	/*
372	 * Release reference to text vnode
373	 */
374	if ((vtmp = p->p_textvp) != NULL) {
375		p->p_textvp = NULL;
376		vrele(vtmp);
377	}
378
379	/*
380	 * Release our limits structure.
381	 */
382	mtx_assert(&Giant, MA_OWNED);
383	if (--p->p_limit->p_refcnt == 0) {
384		FREE(p->p_limit, M_SUBPROC);
385		p->p_limit = NULL;
386	}
387
388	/*
389	 * Release this thread's reference to the ucred.  The actual proc
390	 * reference will stay around until the proc is harvested by
391	 * wait().  At this point the ucred is immutable (no other threads
392	 * from this proc are around that can change it) so we leave the
393	 * per-thread ucred pointer intact in case it is needed although
394	 * in theory nothing should be using it at this point.
395	 */
396	crfree(td->td_ucred);
397
398	/*
399	 * Remove proc from allproc queue and pidhash chain.
400	 * Place onto zombproc.  Unlink from parent's child list.
401	 */
402	sx_xlock(&allproc_lock);
403	LIST_REMOVE(p, p_list);
404	LIST_INSERT_HEAD(&zombproc, p, p_list);
405	LIST_REMOVE(p, p_hash);
406	sx_xunlock(&allproc_lock);
407
408	sx_xlock(&proctree_lock);
409	q = LIST_FIRST(&p->p_children);
410	if (q != NULL)		/* only need this if any child is S_ZOMB */
411		wakeup(initproc);
412	for (; q != NULL; q = nq) {
413		nq = LIST_NEXT(q, p_sibling);
414		PROC_LOCK(q);
415		proc_reparent(q, initproc);
416		q->p_sigparent = SIGCHLD;
417		/*
418		 * Traced processes are killed
419		 * since their existence means someone is screwing up.
420		 */
421		if (q->p_flag & P_TRACED) {
422			q->p_flag &= ~P_TRACED;
423			psignal(q, SIGKILL);
424		}
425		PROC_UNLOCK(q);
426	}
427
428	/*
429	 * Save exit status and final rusage info, adding in child rusage
430	 * info and self times.
431	 */
432	PROC_LOCK(p);
433	p->p_xstat = rv;
434	*p->p_ru = p->p_stats->p_ru;
435	mtx_lock_spin(&sched_lock);
436	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
437	mtx_unlock_spin(&sched_lock);
438	ruadd(p->p_ru, &p->p_stats->p_cru);
439
440	/*
441	 * Notify interested parties of our demise.
442	 */
443	KNOTE(&p->p_klist, NOTE_EXIT);
444
445	/*
446	 * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
447	 * flag set, or if the handler is set to SIG_IGN, notify process
448	 * 1 instead (and hope it will handle this situation).
449	 */
450	PROC_LOCK(p->p_pptr);
451	if (p->p_pptr->p_procsig->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
452		struct proc *pp;
453
454		pp = p->p_pptr;
455		PROC_UNLOCK(pp);
456		proc_reparent(p, initproc);
457		PROC_LOCK(p->p_pptr);
458		/*
459		 * If this was the last child of our parent, notify
460		 * parent, so in case he was wait(2)ing, he will
461		 * continue.
462		 */
463		if (LIST_EMPTY(&pp->p_children))
464			wakeup(pp);
465	}
466
467	if (p->p_sigparent && p->p_pptr != initproc)
468	        psignal(p->p_pptr, p->p_sigparent);
469	else
470	        psignal(p->p_pptr, SIGCHLD);
471	PROC_UNLOCK(p->p_pptr);
472
473	/*
474	 * If this is a kthread, then wakeup anyone waiting for it to exit.
475	 */
476	if (p->p_flag & P_KTHREAD)
477		wakeup(p);
478	PROC_UNLOCK(p);
479
480	/*
481	 * Finally, call machine-dependent code to release the remaining
482	 * resources including address space, the kernel stack and pcb.
483	 * The address space is released by "vmspace_exitfree(p)" in
484	 * vm_waitproc().
485	 */
486	cpu_exit(td);
487
488	PROC_LOCK(p);
489	PROC_LOCK(p->p_pptr);
490	sx_xunlock(&proctree_lock);
491	mtx_lock_spin(&sched_lock);
492	while (mtx_owned(&Giant))
493		mtx_unlock(&Giant);
494
495	/*
496	 * We have to wait until after releasing all locks before
497	 * changing p_state.  If we block on a mutex then we will be
498	 * back at SRUN when we resume and our parent will never
499	 * harvest us.
500	 */
501	p->p_state = PRS_ZOMBIE;
502
503	wakeup(p->p_pptr);
504	PROC_UNLOCK(p->p_pptr);
505	cnt.v_swtch++;
506	binuptime(PCPU_PTR(switchtime));
507	PCPU_SET(switchticks, ticks);
508
509	cpu_sched_exit(td); /* XXXKSE check if this should be in thread_exit */
510	/*
511	 * Make sure this thread is discarded from the zombie.
512	 * This will also release this thread's reference to the ucred.
513	 */
514	thread_exit();
515	panic("exit1");
516}
517
518#ifdef COMPAT_43
519/*
520 * MPSAFE.  The dirty work is handled by wait1().
521 */
522int
523owait(td, uap)
524	struct thread *td;
525	register struct owait_args /* {
526		int     dummy;
527	} */ *uap;
528{
529	struct wait_args w;
530
531	w.options = 0;
532	w.rusage = NULL;
533	w.pid = WAIT_ANY;
534	w.status = NULL;
535	return (wait1(td, &w, 1));
536}
537#endif /* COMPAT_43 */
538
539/*
540 * MPSAFE.  The dirty work is handled by wait1().
541 */
542int
543wait4(td, uap)
544	struct thread *td;
545	struct wait_args *uap;
546{
547
548	return (wait1(td, uap, 0));
549}
550
551/*
552 * MPSAFE
553 */
554static int
555wait1(td, uap, compat)
556	register struct thread *td;
557	register struct wait_args /* {
558		int pid;
559		int *status;
560		int options;
561		struct rusage *rusage;
562	} */ *uap;
563	int compat;
564{
565	struct rusage ru;
566	register int nfound;
567	register struct proc *p, *q, *t;
568	int status, error;
569	struct kse *ke;
570	struct ksegrp *kg;
571
572	q = td->td_proc;
573	if (uap->pid == 0) {
574		PROC_LOCK(q);
575		uap->pid = -q->p_pgid;
576		PROC_UNLOCK(q);
577	}
578	if (uap->options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
579		return (EINVAL);
580	mtx_lock(&Giant);
581loop:
582	nfound = 0;
583	sx_xlock(&proctree_lock);
584	LIST_FOREACH(p, &q->p_children, p_sibling) {
585		PROC_LOCK(p);
586		if (uap->pid != WAIT_ANY &&
587		    p->p_pid != uap->pid && p->p_pgid != -uap->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		    ((uap->options & WLINUXCLONE) != 0)) {
602			PROC_UNLOCK(p);
603			continue;
604		}
605
606		nfound++;
607		if (p->p_state == PRS_ZOMBIE) {
608			/*
609			 * charge childs scheduling cpu usage to parent
610			 * XXXKSE assume only one thread & kse & ksegrp
611			 * keep estcpu in each ksegrp
612			 * so charge it to the ksegrp that did the wait
613			 * since process estcpu is sum of all ksegrps,
614			 * this is strictly as expected.
615			 * Assume that the child process aggregated all
616			 * tke estcpu into the 'build-in' ksegrp.
617			 * XXXKSE
618			 */
619			if (curthread->td_proc->p_pid != 1) {
620				mtx_lock_spin(&sched_lock);
621				curthread->td_ksegrp->kg_estcpu =
622				    ESTCPULIM(curthread->td_ksegrp->kg_estcpu +
623				    p->p_ksegrp.kg_estcpu);
624				mtx_unlock_spin(&sched_lock);
625			}
626
627			td->td_retval[0] = p->p_pid;
628#ifdef COMPAT_43
629			if (compat)
630				td->td_retval[1] = p->p_xstat;
631			else
632#endif
633			if (uap->status) {
634				status = p->p_xstat;	/* convert to int */
635				PROC_UNLOCK(p);
636				if ((error = copyout(&status,
637				    uap->status, sizeof(status)))) {
638					sx_xunlock(&proctree_lock);
639					mtx_unlock(&Giant);
640					return (error);
641				}
642				PROC_LOCK(p);
643			}
644			if (uap->rusage) {
645				bcopy(p->p_ru, &ru, sizeof(ru));
646				PROC_UNLOCK(p);
647				if ((error = copyout(&ru,
648				    uap->rusage, sizeof (struct rusage)))) {
649					sx_xunlock(&proctree_lock);
650					mtx_unlock(&Giant);
651					return (error);
652				}
653			} else
654				PROC_UNLOCK(p);
655			/*
656			 * If we got the child via a ptrace 'attach',
657			 * we need to give it back to the old parent.
658			 */
659			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
660				PROC_LOCK(p);
661				p->p_oppid = 0;
662				proc_reparent(p, t);
663				PROC_UNLOCK(p);
664				psignal(t, SIGCHLD);
665				wakeup(t);
666				PROC_UNLOCK(t);
667				sx_xunlock(&proctree_lock);
668				mtx_unlock(&Giant);
669				return (0);
670			}
671			/*
672			 * Remove other references to this process to ensure
673			 * we have an exclusive reference.
674			 */
675			leavepgrp(p);
676
677			sx_xlock(&allproc_lock);
678			LIST_REMOVE(p, p_list);	/* off zombproc */
679			sx_xunlock(&allproc_lock);
680
681			LIST_REMOVE(p, p_sibling);
682			sx_xunlock(&proctree_lock);
683
684			/*
685			 * As a side effect of this lock, we know that
686			 * all other writes to this proc are visible now, so
687			 * no more locking is needed for p.
688			 */
689			PROC_LOCK(p);
690			p->p_xstat = 0;		/* XXX: why? */
691			PROC_UNLOCK(p);
692			PROC_LOCK(q);
693			ruadd(&q->p_stats->p_cru, p->p_ru);
694			PROC_UNLOCK(q);
695			FREE(p->p_ru, M_ZOMBIE);
696			p->p_ru = NULL;
697
698			/*
699			 * Decrement the count of procs running with this uid.
700			 */
701			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
702
703			/*
704			 * Free up credentials.
705			 */
706			crfree(p->p_ucred);
707			p->p_ucred = NULL;	/* XXX: why? */
708
709			/*
710			 * Remove unused arguments
711			 */
712			pargs_drop(p->p_args);
713			p->p_args = NULL;
714
715			if (--p->p_procsig->ps_refcnt == 0) {
716				if (p->p_sigacts != &p->p_uarea->u_sigacts)
717					FREE(p->p_sigacts, M_SUBPROC);
718			        FREE(p->p_procsig, M_SUBPROC);
719				p->p_procsig = NULL;
720			}
721
722			/*
723			 * There should only be one KSE/KSEGRP but
724			 * do it right anyhow.
725			 */
726			FOREACH_KSEGRP_IN_PROC(p, kg) {
727				FOREACH_KSE_IN_GROUP(kg, ke) {
728					/* Free the KSE spare thread. */
729					if (ke->ke_tdspare != NULL) {
730						thread_free(ke->ke_tdspare);
731						p->p_kse.ke_tdspare = NULL;
732					}
733				}
734			}
735			thread_reap();	/* check for zombie threads */
736
737			/*
738			 * Give vm and machine-dependent layer a chance
739			 * to free anything that cpu_exit couldn't
740			 * release while still running in process context.
741			 */
742			vm_waitproc(p);
743			mtx_destroy(&p->p_mtx);
744			uma_zfree(proc_zone, p);
745			sx_xlock(&allproc_lock);
746			nprocs--;
747			sx_xunlock(&allproc_lock);
748			mtx_unlock(&Giant);
749			return (0);
750		}
751		if (P_SHOULDSTOP(p) && ((p->p_flag & P_WAITED) == 0) &&
752		    (p->p_flag & P_TRACED || uap->options & WUNTRACED)) {
753			p->p_flag |= P_WAITED;
754			sx_xunlock(&proctree_lock);
755			td->td_retval[0] = p->p_pid;
756#ifdef COMPAT_43
757			if (compat) {
758				td->td_retval[1] = W_STOPCODE(p->p_xstat);
759				PROC_UNLOCK(p);
760				error = 0;
761			} else
762#endif
763			if (uap->status) {
764				status = W_STOPCODE(p->p_xstat);
765				PROC_UNLOCK(p);
766				error = copyout(&status,
767					uap->status, sizeof(status));
768			} else {
769				PROC_UNLOCK(p);
770				error = 0;
771			}
772			mtx_unlock(&Giant);
773			return (error);
774		}
775		if (uap->options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
776			sx_xunlock(&proctree_lock);
777			td->td_retval[0] = p->p_pid;
778			p->p_flag &= ~P_CONTINUED;
779			PROC_UNLOCK(p);
780
781			if (uap->status) {
782				status = SIGCONT;
783				error = copyout(&status,
784				    uap->status, sizeof(status));
785			} else
786				error = 0;
787
788			mtx_unlock(&Giant);
789			return (error);
790		}
791		PROC_UNLOCK(p);
792	}
793	if (nfound == 0) {
794		sx_xunlock(&proctree_lock);
795		mtx_unlock(&Giant);
796		return (ECHILD);
797	}
798	if (uap->options & WNOHANG) {
799		sx_xunlock(&proctree_lock);
800		td->td_retval[0] = 0;
801		mtx_unlock(&Giant);
802		return (0);
803	}
804	PROC_LOCK(q);
805	sx_xunlock(&proctree_lock);
806	error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
807	PROC_UNLOCK(q);
808	if (error) {
809		mtx_unlock(&Giant);
810		return (error);
811	}
812	goto loop;
813}
814
815/*
816 * Make process 'parent' the new parent of process 'child'.
817 * Must be called with an exclusive hold of proctree lock.
818 */
819void
820proc_reparent(child, parent)
821	register struct proc *child;
822	register struct proc *parent;
823{
824
825	sx_assert(&proctree_lock, SX_XLOCKED);
826	PROC_LOCK_ASSERT(child, MA_OWNED);
827	if (child->p_pptr == parent)
828		return;
829
830	LIST_REMOVE(child, p_sibling);
831	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
832	child->p_pptr = parent;
833}
834
835/*
836 * The next two functions are to handle adding/deleting items on the
837 * exit callout list
838 *
839 * at_exit():
840 * Take the arguments given and put them onto the exit callout list,
841 * However first make sure that it's not already there.
842 * returns 0 on success.
843 */
844
845int
846at_exit(function)
847	exitlist_fn function;
848{
849	struct exitlist *ep;
850
851#ifdef INVARIANTS
852	/* Be noisy if the programmer has lost track of things */
853	if (rm_at_exit(function))
854		printf("WARNING: exit callout entry (%p) already present\n",
855		    function);
856#endif
857	ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
858	if (ep == NULL)
859		return (ENOMEM);
860	ep->function = function;
861	TAILQ_INSERT_TAIL(&exit_list, ep, next);
862	return (0);
863}
864
865/*
866 * Scan the exit callout list for the given item and remove it.
867 * Returns the number of items removed (0 or 1)
868 */
869int
870rm_at_exit(function)
871	exitlist_fn function;
872{
873	struct exitlist *ep;
874
875	TAILQ_FOREACH(ep, &exit_list, next) {
876		if (ep->function == function) {
877			TAILQ_REMOVE(&exit_list, ep, next);
878			free(ep, M_ATEXIT);
879			return (1);
880		}
881	}
882	return (0);
883}
884