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