xref: /freebsd/sys/kern/kern_exit.c (revision 6780ab54325a71e7e70112b11657973edde8655e)
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, 0);
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 	 * Processes sharing the same vmspace may exit in one order, and
292 	 * get cleaned up by vmspace_exit() in a different order.  The
293 	 * last exiting process to reach this point releases as much of
294 	 * the environment as it can, and the last process cleaned up
295 	 * by vmspace_exit() (which decrements exitingcnt) cleans up the
296 	 * remainder.
297 	 */
298 	++vm->vm_exitingcnt;
299 	if (--vm->vm_refcnt == 0) {
300 		shmexit(vm);
301 		vm_page_lock_queues();
302 		pmap_remove_pages(vmspace_pmap(vm), vm_map_min(&vm->vm_map),
303 		    vm_map_max(&vm->vm_map));
304 		vm_page_unlock_queues();
305 		(void) vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
306 		    vm_map_max(&vm->vm_map));
307 	}
308 
309 	sx_xlock(&proctree_lock);
310 	if (SESS_LEADER(p)) {
311 		register struct session *sp;
312 
313 		sp = p->p_session;
314 		if (sp->s_ttyvp) {
315 			/*
316 			 * Controlling process.
317 			 * Signal foreground pgrp,
318 			 * drain controlling terminal
319 			 * and revoke access to controlling terminal.
320 			 */
321 			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
322 				tp = sp->s_ttyp;
323 				if (sp->s_ttyp->t_pgrp) {
324 					PGRP_LOCK(sp->s_ttyp->t_pgrp);
325 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
326 					PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
327 				}
328 				/* XXX tp should be locked. */
329 				sx_xunlock(&proctree_lock);
330 				(void) ttywait(tp);
331 				sx_xlock(&proctree_lock);
332 				/*
333 				 * The tty could have been revoked
334 				 * if we blocked.
335 				 */
336 				if (sp->s_ttyvp) {
337 					ttyvp = sp->s_ttyvp;
338 					SESS_LOCK(p->p_session);
339 					sp->s_ttyvp = NULL;
340 					SESS_UNLOCK(p->p_session);
341 					sx_xunlock(&proctree_lock);
342 					VOP_REVOKE(ttyvp, REVOKEALL);
343 					vrele(ttyvp);
344 					sx_xlock(&proctree_lock);
345 				}
346 			}
347 			if (sp->s_ttyvp) {
348 				ttyvp = sp->s_ttyvp;
349 				SESS_LOCK(p->p_session);
350 				sp->s_ttyvp = NULL;
351 				SESS_UNLOCK(p->p_session);
352 				vrele(ttyvp);
353 			}
354 			/*
355 			 * s_ttyp is not zero'd; we use this to indicate
356 			 * that the session once had a controlling terminal.
357 			 * (for logging and informational purposes)
358 			 */
359 		}
360 		SESS_LOCK(p->p_session);
361 		sp->s_leader = NULL;
362 		SESS_UNLOCK(p->p_session);
363 	}
364 	fixjobc(p, p->p_pgrp, 0);
365 	sx_xunlock(&proctree_lock);
366 	(void)acct_process(td);
367 #ifdef KTRACE
368 	/*
369 	 * release trace file
370 	 */
371 	PROC_LOCK(p);
372 	mtx_lock(&ktrace_mtx);
373 	p->p_traceflag = 0;	/* don't trace the vrele() */
374 	tracevp = p->p_tracep;
375 	p->p_tracep = NULL;
376 	mtx_unlock(&ktrace_mtx);
377 	PROC_UNLOCK(p);
378 	if (tracevp != NULL)
379 		vrele(tracevp);
380 #endif
381 	/*
382 	 * Release reference to text vnode
383 	 */
384 	if ((vtmp = p->p_textvp) != NULL) {
385 		p->p_textvp = NULL;
386 		vrele(vtmp);
387 	}
388 
389 	/*
390 	 * Release our limits structure.
391 	 */
392 	mtx_assert(&Giant, MA_OWNED);
393 	if (--p->p_limit->p_refcnt == 0) {
394 		FREE(p->p_limit, M_SUBPROC);
395 		p->p_limit = NULL;
396 	}
397 
398 	/*
399 	 * Release this thread's reference to the ucred.  The actual proc
400 	 * reference will stay around until the proc is harvested by
401 	 * wait().  At this point the ucred is immutable (no other threads
402 	 * from this proc are around that can change it) so we leave the
403 	 * per-thread ucred pointer intact in case it is needed although
404 	 * in theory nothing should be using it at this point.
405 	 */
406 	crfree(td->td_ucred);
407 
408 	/*
409 	 * Remove proc from allproc queue and pidhash chain.
410 	 * Place onto zombproc.  Unlink from parent's child list.
411 	 */
412 	sx_xlock(&allproc_lock);
413 	LIST_REMOVE(p, p_list);
414 	LIST_INSERT_HEAD(&zombproc, p, p_list);
415 	LIST_REMOVE(p, p_hash);
416 	sx_xunlock(&allproc_lock);
417 
418 	sx_xlock(&proctree_lock);
419 	q = LIST_FIRST(&p->p_children);
420 	if (q != NULL)		/* only need this if any child is S_ZOMB */
421 		wakeup(initproc);
422 	for (; q != NULL; q = nq) {
423 		nq = LIST_NEXT(q, p_sibling);
424 		PROC_LOCK(q);
425 		proc_reparent(q, initproc);
426 		q->p_sigparent = SIGCHLD;
427 		/*
428 		 * Traced processes are killed
429 		 * since their existence means someone is screwing up.
430 		 */
431 		if (q->p_flag & P_TRACED) {
432 			q->p_flag &= ~P_TRACED;
433 			psignal(q, SIGKILL);
434 		}
435 		PROC_UNLOCK(q);
436 	}
437 
438 	/*
439 	 * Save exit status and final rusage info, adding in child rusage
440 	 * info and self times.
441 	 */
442 	PROC_LOCK(p);
443 	p->p_xstat = rv;
444 	*p->p_ru = p->p_stats->p_ru;
445 	mtx_lock_spin(&sched_lock);
446 	calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
447 	mtx_unlock_spin(&sched_lock);
448 	ruadd(p->p_ru, &p->p_stats->p_cru);
449 
450 	/*
451 	 * Notify interested parties of our demise.
452 	 */
453 	KNOTE(&p->p_klist, NOTE_EXIT);
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 	if (p->p_pptr->p_procsig->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
462 		struct proc *pp;
463 
464 		pp = p->p_pptr;
465 		PROC_UNLOCK(pp);
466 		proc_reparent(p, initproc);
467 		PROC_LOCK(p->p_pptr);
468 		/*
469 		 * If this was the last child of our parent, notify
470 		 * parent, so in case he was wait(2)ing, he will
471 		 * continue.
472 		 */
473 		if (LIST_EMPTY(&pp->p_children))
474 			wakeup(pp);
475 	}
476 
477 	if (p->p_sigparent && p->p_pptr != initproc)
478 		psignal(p->p_pptr, p->p_sigparent);
479 	else
480 		psignal(p->p_pptr, SIGCHLD);
481 	PROC_UNLOCK(p->p_pptr);
482 
483 	/*
484 	 * If this is a kthread, then wakeup anyone waiting for it to exit.
485 	 */
486 	if (p->p_flag & P_KTHREAD)
487 		wakeup(p);
488 	PROC_UNLOCK(p);
489 
490 	/*
491 	 * Finally, call machine-dependent code to release the remaining
492 	 * resources including address space.
493 	 * The address space is released by "vmspace_exitfree(p)" in
494 	 * vm_waitproc().
495 	 */
496 	cpu_exit(td);
497 
498 	PROC_LOCK(p);
499 	PROC_LOCK(p->p_pptr);
500 	sx_xunlock(&proctree_lock);
501 	mtx_lock_spin(&sched_lock);
502 
503 	while (mtx_owned(&Giant))
504 		mtx_unlock(&Giant);
505 
506 	/*
507 	 * We have to wait until after releasing all locks before
508 	 * changing p_state.  If we block on a mutex then we will be
509 	 * back at SRUN when we resume and our parent will never
510 	 * harvest us.
511 	 */
512 	p->p_state = PRS_ZOMBIE;
513 
514 	wakeup(p->p_pptr);
515 	PROC_UNLOCK(p->p_pptr);
516 	cnt.v_swtch++;
517 	binuptime(PCPU_PTR(switchtime));
518 	PCPU_SET(switchticks, ticks);
519 
520 	cpu_sched_exit(td); /* XXXKSE check if this should be in thread_exit */
521 	/*
522 	 * Make sure the scheduler takes this thread out of its tables etc.
523 	 * This will also release this thread's reference to the ucred.
524  	 * Other thread parts to release include pcb bits and such.
525 	 */
526 	thread_exit();
527 }
528 
529 #ifdef COMPAT_43
530 /*
531  * MPSAFE.  The dirty work is handled by wait1().
532  */
533 int
534 owait(td, uap)
535 	struct thread *td;
536 	register struct owait_args /* {
537 		int     dummy;
538 	} */ *uap;
539 {
540 	struct wait_args w;
541 
542 	w.options = 0;
543 	w.rusage = NULL;
544 	w.pid = WAIT_ANY;
545 	w.status = NULL;
546 	return (wait1(td, &w, 1));
547 }
548 #endif /* COMPAT_43 */
549 
550 /*
551  * MPSAFE.  The dirty work is handled by wait1().
552  */
553 int
554 wait4(td, uap)
555 	struct thread *td;
556 	struct wait_args *uap;
557 {
558 
559 	return (wait1(td, uap, 0));
560 }
561 
562 /*
563  * MPSAFE
564  */
565 static int
566 wait1(td, uap, compat)
567 	register struct thread *td;
568 	register struct wait_args /* {
569 		int pid;
570 		int *status;
571 		int options;
572 		struct rusage *rusage;
573 	} */ *uap;
574 	int compat;
575 {
576 	struct rusage ru;
577 	int nfound;
578 	struct proc *p, *q, *t;
579 	int status, error;
580 
581 	q = td->td_proc;
582 	if (uap->pid == 0) {
583 		PROC_LOCK(q);
584 		uap->pid = -q->p_pgid;
585 		PROC_UNLOCK(q);
586 	}
587 	if (uap->options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
588 		return (EINVAL);
589 	mtx_lock(&Giant);
590 loop:
591 	nfound = 0;
592 	sx_xlock(&proctree_lock);
593 	LIST_FOREACH(p, &q->p_children, p_sibling) {
594 		PROC_LOCK(p);
595 		if (uap->pid != WAIT_ANY &&
596 		    p->p_pid != uap->pid && p->p_pgid != -uap->pid) {
597 			PROC_UNLOCK(p);
598 			continue;
599 		}
600 
601 		/*
602 		 * This special case handles a kthread spawned by linux_clone
603 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
604 		 * functions need to be able to distinguish between waiting
605 		 * on a process and waiting on a thread.  It is a thread if
606 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
607 		 * signifies we want to wait for threads and not processes.
608 		 */
609 		if ((p->p_sigparent != SIGCHLD) ^
610 		    ((uap->options & WLINUXCLONE) != 0)) {
611 			PROC_UNLOCK(p);
612 			continue;
613 		}
614 
615 		nfound++;
616 		if (p->p_state == PRS_ZOMBIE) {
617 			/*
618 			 * Allow the scheduler to adjust the priority of the
619 			 * parent when a kseg is exiting.
620 			 */
621 			if (curthread->td_proc->p_pid != 1) {
622 				mtx_lock_spin(&sched_lock);
623 				sched_exit(curthread->td_ksegrp,
624 				    FIRST_KSEGRP_IN_PROC(p));
625 				mtx_unlock_spin(&sched_lock);
626 			}
627 
628 			td->td_retval[0] = p->p_pid;
629 #ifdef COMPAT_43
630 			if (compat)
631 				td->td_retval[1] = p->p_xstat;
632 			else
633 #endif
634 			if (uap->status) {
635 				status = p->p_xstat;	/* convert to int */
636 				PROC_UNLOCK(p);
637 				if ((error = copyout(&status,
638 				    uap->status, sizeof(status)))) {
639 					sx_xunlock(&proctree_lock);
640 					mtx_unlock(&Giant);
641 					return (error);
642 				}
643 				PROC_LOCK(p);
644 			}
645 			if (uap->rusage) {
646 				bcopy(p->p_ru, &ru, sizeof(ru));
647 				PROC_UNLOCK(p);
648 				if ((error = copyout(&ru,
649 				    uap->rusage, sizeof (struct rusage)))) {
650 					sx_xunlock(&proctree_lock);
651 					mtx_unlock(&Giant);
652 					return (error);
653 				}
654 			} else
655 				PROC_UNLOCK(p);
656 			/*
657 			 * If we got the child via a ptrace 'attach',
658 			 * we need to give it back to the old parent.
659 			 */
660 			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
661 				PROC_LOCK(p);
662 				p->p_oppid = 0;
663 				proc_reparent(p, t);
664 				PROC_UNLOCK(p);
665 				psignal(t, SIGCHLD);
666 				wakeup(t);
667 				PROC_UNLOCK(t);
668 				sx_xunlock(&proctree_lock);
669 				mtx_unlock(&Giant);
670 				return (0);
671 			}
672 			/*
673 			 * Remove other references to this process to ensure
674 			 * we have an exclusive reference.
675 			 */
676 			leavepgrp(p);
677 
678 			sx_xlock(&allproc_lock);
679 			LIST_REMOVE(p, p_list);	/* off zombproc */
680 			sx_xunlock(&allproc_lock);
681 
682 			LIST_REMOVE(p, p_sibling);
683 			sx_xunlock(&proctree_lock);
684 
685 			/*
686 			 * As a side effect of this lock, we know that
687 			 * all other writes to this proc are visible now, so
688 			 * no more locking is needed for p.
689 			 */
690 			PROC_LOCK(p);
691 			p->p_xstat = 0;		/* XXX: why? */
692 			PROC_UNLOCK(p);
693 			PROC_LOCK(q);
694 			ruadd(&q->p_stats->p_cru, p->p_ru);
695 			PROC_UNLOCK(q);
696 			FREE(p->p_ru, M_ZOMBIE);
697 			p->p_ru = NULL;
698 
699 			/*
700 			 * Decrement the count of procs running with this uid.
701 			 */
702 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
703 
704 			/*
705 			 * Free up credentials.
706 			 */
707 			crfree(p->p_ucred);
708 			p->p_ucred = NULL;	/* XXX: why? */
709 
710 			/*
711 			 * Remove unused arguments
712 			 */
713 			pargs_drop(p->p_args);
714 			p->p_args = NULL;
715 
716 			if (--p->p_procsig->ps_refcnt == 0) {
717 				if (p->p_sigacts != &p->p_uarea->u_sigacts)
718 					FREE(p->p_sigacts, M_SUBPROC);
719 				FREE(p->p_procsig, M_SUBPROC);
720 				p->p_procsig = NULL;
721 			}
722 
723 			/*
724 			 * do any thread-system specific cleanups
725 			 */
726 			thread_wait(p);
727 
728 			/*
729 			 * Give vm and machine-dependent layer a chance
730 			 * to free anything that cpu_exit couldn't
731 			 * release while still running in process context.
732 			 */
733 			vm_waitproc(p);
734 			mtx_destroy(&p->p_mtx);
735 #ifdef MAC
736 			mac_destroy_proc(p);
737 #endif
738 			KASSERT(FIRST_THREAD_IN_PROC(p),
739 			    ("wait1: no residual thread!"));
740 			uma_zfree(proc_zone, p);
741 			sx_xlock(&allproc_lock);
742 			nprocs--;
743 			sx_xunlock(&allproc_lock);
744 			mtx_unlock(&Giant);
745 			return (0);
746 		}
747 		if (P_SHOULDSTOP(p) && ((p->p_flag & P_WAITED) == 0) &&
748 		    (p->p_flag & P_TRACED || uap->options & WUNTRACED)) {
749 			p->p_flag |= P_WAITED;
750 			sx_xunlock(&proctree_lock);
751 			td->td_retval[0] = p->p_pid;
752 #ifdef COMPAT_43
753 			if (compat) {
754 				td->td_retval[1] = W_STOPCODE(p->p_xstat);
755 				PROC_UNLOCK(p);
756 				error = 0;
757 			} else
758 #endif
759 			if (uap->status) {
760 				status = W_STOPCODE(p->p_xstat);
761 				PROC_UNLOCK(p);
762 				error = copyout(&status,
763 					uap->status, sizeof(status));
764 			} else {
765 				PROC_UNLOCK(p);
766 				error = 0;
767 			}
768 			mtx_unlock(&Giant);
769 			return (error);
770 		}
771 		if (uap->options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
772 			sx_xunlock(&proctree_lock);
773 			td->td_retval[0] = p->p_pid;
774 			p->p_flag &= ~P_CONTINUED;
775 			PROC_UNLOCK(p);
776 
777 			if (uap->status) {
778 				status = SIGCONT;
779 				error = copyout(&status,
780 				    uap->status, sizeof(status));
781 			} else
782 				error = 0;
783 
784 			mtx_unlock(&Giant);
785 			return (error);
786 		}
787 		PROC_UNLOCK(p);
788 	}
789 	if (nfound == 0) {
790 		sx_xunlock(&proctree_lock);
791 		mtx_unlock(&Giant);
792 		return (ECHILD);
793 	}
794 	if (uap->options & WNOHANG) {
795 		sx_xunlock(&proctree_lock);
796 		td->td_retval[0] = 0;
797 		mtx_unlock(&Giant);
798 		return (0);
799 	}
800 	PROC_LOCK(q);
801 	sx_xunlock(&proctree_lock);
802 	error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
803 	PROC_UNLOCK(q);
804 	if (error) {
805 		mtx_unlock(&Giant);
806 		return (error);
807 	}
808 	goto loop;
809 }
810 
811 /*
812  * Make process 'parent' the new parent of process 'child'.
813  * Must be called with an exclusive hold of proctree lock.
814  */
815 void
816 proc_reparent(child, parent)
817 	register struct proc *child;
818 	register struct proc *parent;
819 {
820 
821 	sx_assert(&proctree_lock, SX_XLOCKED);
822 	PROC_LOCK_ASSERT(child, MA_OWNED);
823 	if (child->p_pptr == parent)
824 		return;
825 
826 	LIST_REMOVE(child, p_sibling);
827 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
828 	child->p_pptr = parent;
829 }
830 
831 /*
832  * The next two functions are to handle adding/deleting items on the
833  * exit callout list
834  *
835  * at_exit():
836  * Take the arguments given and put them onto the exit callout list,
837  * However first make sure that it's not already there.
838  * returns 0 on success.
839  */
840 
841 int
842 at_exit(function)
843 	exitlist_fn function;
844 {
845 	struct exitlist *ep;
846 
847 #ifdef INVARIANTS
848 	/* Be noisy if the programmer has lost track of things */
849 	if (rm_at_exit(function))
850 		printf("WARNING: exit callout entry (%p) already present\n",
851 		    function);
852 #endif
853 	ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
854 	if (ep == NULL)
855 		return (ENOMEM);
856 	ep->function = function;
857 	TAILQ_INSERT_TAIL(&exit_list, ep, next);
858 	return (0);
859 }
860 
861 /*
862  * Scan the exit callout list for the given item and remove it.
863  * Returns the number of items removed (0 or 1)
864  */
865 int
866 rm_at_exit(function)
867 	exitlist_fn function;
868 {
869 	struct exitlist *ep;
870 
871 	TAILQ_FOREACH(ep, &exit_list, next) {
872 		if (ep->function == function) {
873 			TAILQ_REMOVE(&exit_list, ep, next);
874 			free(ep, M_ATEXIT);
875 			return (1);
876 		}
877 	}
878 	return (0);
879 }
880