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