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