xref: /freebsd/sys/kern/kern_exit.c (revision e858faa9bb929e040dfa2ee6f9e4806cec4d685d)
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 #ifdef KTRACE
73 #include <sys/ktrace.h>
74 #endif
75 
76 #include <vm/vm.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_param.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/uma.h>
83 #include <sys/user.h>
84 
85 /* Required to be non-static for SysVR4 emulator */
86 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
87 
88 static int wait1(struct thread *, struct wait_args *, int);
89 
90 /*
91  * exit --
92  *	Death of process.
93  *
94  * MPSAFE
95  */
96 void
97 sys_exit(struct thread *td, struct sys_exit_args *uap)
98 {
99 
100 	mtx_lock(&Giant);
101 	exit1(td, W_EXITCODE(uap->rval, 0));
102 	/* NOTREACHED */
103 }
104 
105 /*
106  * Exit: deallocate address space and other resources, change proc state
107  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
108  * status and rusage for wait().  Check for child processes and orphan them.
109  */
110 void
111 exit1(struct thread *td, int rv)
112 {
113 	struct proc *p, *nq, *q;
114 	struct tty *tp;
115 	struct vnode *ttyvp;
116 	struct vmspace *vm;
117 	struct vnode *vtmp;
118 #ifdef KTRACE
119 	struct vnode *tracevp;
120 	struct ucred *tracecred;
121 #endif
122 	struct plimit *plim;
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 	PROC_LOCK(p);
378 	plim = p->p_limit;
379 	p->p_limit = NULL;
380 	PROC_UNLOCK(p);
381 	lim_free(plim);
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 		p->p_sigparent = SIGCHLD;
462 		PROC_LOCK(p->p_pptr);
463 		/*
464 		 * If this was the last child of our parent, notify
465 		 * parent, so in case he was wait(2)ing, he will
466 		 * continue.
467 		 */
468 		if (LIST_EMPTY(&pp->p_children))
469 			wakeup(pp);
470 	} else
471 		mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
472 
473 	if (p->p_pptr == initproc)
474 		psignal(p->p_pptr, SIGCHLD);
475 	else if (p->p_sigparent != 0)
476 		psignal(p->p_pptr, p->p_sigparent);
477 	PROC_UNLOCK(p->p_pptr);
478 
479 	/*
480 	 * If this is a kthread, then wakeup anyone waiting for it to exit.
481 	 */
482 	if (p->p_flag & P_KTHREAD)
483 		wakeup(p);
484 	PROC_UNLOCK(p);
485 
486 	/*
487 	 * Finally, call machine-dependent code to release the remaining
488 	 * resources including address space.
489 	 * The address space is released by "vmspace_exitfree(p)" in
490 	 * vm_waitproc().
491 	 */
492 	cpu_exit(td);
493 
494 	PROC_LOCK(p);
495 	PROC_LOCK(p->p_pptr);
496 	sx_xunlock(&proctree_lock);
497 	mtx_lock_spin(&sched_lock);
498 
499 	while (mtx_owned(&Giant))
500 		mtx_unlock(&Giant);
501 
502 	/*
503 	 * We have to wait until after acquiring all locks before
504 	 * changing p_state.  If we block on a mutex then we will be
505 	 * back at SRUN when we resume and our parent will never
506 	 * harvest us.
507 	 */
508 	p->p_state = PRS_ZOMBIE;
509 
510 	wakeup(p->p_pptr);
511 	PROC_UNLOCK(p->p_pptr);
512 	cnt.v_swtch++;
513 	binuptime(PCPU_PTR(switchtime));
514 	PCPU_SET(switchticks, ticks);
515 
516 	cpu_sched_exit(td); /* XXXKSE check if this should be in thread_exit */
517 	/*
518 	 * Allow the scheduler to adjust the priority of the
519 	 * parent when a kseg is exiting.
520 	 */
521 	if (p->p_pid != 1)
522 		sched_exit(p->p_pptr, p);
523 
524 	/*
525 	 * Make sure the scheduler takes this thread out of its tables etc.
526 	 * This will also release this thread's reference to the ucred.
527 	 * Other thread parts to release include pcb bits and such.
528 	 */
529 	thread_exit();
530 }
531 
532 #ifdef COMPAT_43
533 /*
534  * MPSAFE.  The dirty work is handled by wait1().
535  */
536 int
537 owait(struct thread *td, struct owait_args *uap __unused)
538 {
539 	struct wait_args w;
540 
541 	w.options = 0;
542 	w.rusage = NULL;
543 	w.pid = WAIT_ANY;
544 	w.status = NULL;
545 	return (wait1(td, &w, 1));
546 }
547 #endif /* COMPAT_43 */
548 
549 /*
550  * MPSAFE.  The dirty work is handled by wait1().
551  */
552 int
553 wait4(struct thread *td, struct wait_args *uap)
554 {
555 
556 	return (wait1(td, uap, 0));
557 }
558 
559 /*
560  * MPSAFE
561  */
562 static int
563 wait1(struct thread *td, struct wait_args *uap, int compat)
564 {
565 	struct rusage ru;
566 	int nfound;
567 	struct proc *p, *q, *t;
568 	int status, error;
569 
570 	q = td->td_proc;
571 	if (uap->pid == 0) {
572 		PROC_LOCK(q);
573 		uap->pid = -q->p_pgid;
574 		PROC_UNLOCK(q);
575 	}
576 	if (uap->options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
577 		return (EINVAL);
578 	mtx_lock(&Giant);
579 loop:
580 	nfound = 0;
581 	sx_xlock(&proctree_lock);
582 	LIST_FOREACH(p, &q->p_children, p_sibling) {
583 		PROC_LOCK(p);
584 		if (uap->pid != WAIT_ANY &&
585 		    p->p_pid != uap->pid && p->p_pgid != -uap->pid) {
586 			PROC_UNLOCK(p);
587 			continue;
588 		}
589 
590 		/*
591 		 * This special case handles a kthread spawned by linux_clone
592 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
593 		 * functions need to be able to distinguish between waiting
594 		 * on a process and waiting on a thread.  It is a thread if
595 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
596 		 * signifies we want to wait for threads and not processes.
597 		 */
598 		if ((p->p_sigparent != SIGCHLD) ^
599 		    ((uap->options & WLINUXCLONE) != 0)) {
600 			PROC_UNLOCK(p);
601 			continue;
602 		}
603 
604 		nfound++;
605 		if (p->p_state == PRS_ZOMBIE) {
606 			td->td_retval[0] = p->p_pid;
607 #ifdef COMPAT_43
608 			if (compat)
609 				td->td_retval[1] = p->p_xstat;
610 			else
611 #endif
612 			if (uap->status) {
613 				status = p->p_xstat;	/* convert to int */
614 				PROC_UNLOCK(p);
615 				if ((error = copyout(&status,
616 				    uap->status, sizeof(status)))) {
617 					sx_xunlock(&proctree_lock);
618 					mtx_unlock(&Giant);
619 					return (error);
620 				}
621 				PROC_LOCK(p);
622 			}
623 			if (uap->rusage) {
624 				bcopy(p->p_ru, &ru, sizeof(ru));
625 				PROC_UNLOCK(p);
626 				if ((error = copyout(&ru,
627 				    uap->rusage, sizeof (struct rusage)))) {
628 					sx_xunlock(&proctree_lock);
629 					mtx_unlock(&Giant);
630 					return (error);
631 				}
632 			} else
633 				PROC_UNLOCK(p);
634 			/*
635 			 * If we got the child via a ptrace 'attach',
636 			 * we need to give it back to the old parent.
637 			 */
638 			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
639 				PROC_LOCK(p);
640 				p->p_oppid = 0;
641 				proc_reparent(p, t);
642 				PROC_UNLOCK(p);
643 				psignal(t, SIGCHLD);
644 				wakeup(t);
645 				PROC_UNLOCK(t);
646 				sx_xunlock(&proctree_lock);
647 				mtx_unlock(&Giant);
648 				return (0);
649 			}
650 
651 			/*
652 			 * Remove other references to this process to ensure
653 			 * we have an exclusive reference.
654 			 */
655 			sx_xlock(&allproc_lock);
656 			LIST_REMOVE(p, p_list);	/* off zombproc */
657 			sx_xunlock(&allproc_lock);
658 			LIST_REMOVE(p, p_sibling);
659 			leavepgrp(p);
660 			sx_xunlock(&proctree_lock);
661 
662 			/*
663 			 * As a side effect of this lock, we know that
664 			 * all other writes to this proc are visible now, so
665 			 * no more locking is needed for p.
666 			 */
667 			PROC_LOCK(p);
668 			p->p_xstat = 0;		/* XXX: why? */
669 			PROC_UNLOCK(p);
670 			PROC_LOCK(q);
671 			ruadd(&q->p_stats->p_cru, p->p_ru);
672 			PROC_UNLOCK(q);
673 			FREE(p->p_ru, M_ZOMBIE);
674 			p->p_ru = NULL;
675 
676 			/*
677 			 * Decrement the count of procs running with this uid.
678 			 */
679 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
680 
681 			/*
682 			 * Free credentials, arguments, and sigacts
683 			 */
684 			crfree(p->p_ucred);
685 			p->p_ucred = NULL;
686 			pargs_drop(p->p_args);
687 			p->p_args = NULL;
688 			sigacts_free(p->p_sigacts);
689 			p->p_sigacts = NULL;
690 
691 			/*
692 			 * do any thread-system specific cleanups
693 			 */
694 			thread_wait(p);
695 
696 			/*
697 			 * Give vm and machine-dependent layer a chance
698 			 * to free anything that cpu_exit couldn't
699 			 * release while still running in process context.
700 			 */
701 			vm_waitproc(p);
702 #ifdef MAC
703 			mac_destroy_proc(p);
704 #endif
705 			KASSERT(FIRST_THREAD_IN_PROC(p),
706 			    ("wait1: no residual thread!"));
707 			uma_zfree(proc_zone, p);
708 			sx_xlock(&allproc_lock);
709 			nprocs--;
710 			sx_xunlock(&allproc_lock);
711 			mtx_unlock(&Giant);
712 			return (0);
713 		}
714 		mtx_lock_spin(&sched_lock);
715 		if (P_SHOULDSTOP(p) && (p->p_suspcount == p->p_numthreads) &&
716 		    ((p->p_flag & P_WAITED) == 0) &&
717 		    (p->p_flag & P_TRACED || uap->options & WUNTRACED)) {
718 			mtx_unlock_spin(&sched_lock);
719 			p->p_flag |= P_WAITED;
720 			sx_xunlock(&proctree_lock);
721 			td->td_retval[0] = p->p_pid;
722 #ifdef COMPAT_43
723 			if (compat) {
724 				td->td_retval[1] = W_STOPCODE(p->p_xstat);
725 				PROC_UNLOCK(p);
726 				error = 0;
727 			} else
728 #endif
729 			if (uap->status) {
730 				status = W_STOPCODE(p->p_xstat);
731 				PROC_UNLOCK(p);
732 				error = copyout(&status,
733 					uap->status, sizeof(status));
734 			} else {
735 				PROC_UNLOCK(p);
736 				error = 0;
737 			}
738 			mtx_unlock(&Giant);
739 			return (error);
740 		}
741 		mtx_unlock_spin(&sched_lock);
742 		if (uap->options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
743 			sx_xunlock(&proctree_lock);
744 			td->td_retval[0] = p->p_pid;
745 			p->p_flag &= ~P_CONTINUED;
746 			PROC_UNLOCK(p);
747 
748 			if (uap->status) {
749 				status = SIGCONT;
750 				error = copyout(&status,
751 				    uap->status, sizeof(status));
752 			} else
753 				error = 0;
754 
755 			mtx_unlock(&Giant);
756 			return (error);
757 		}
758 		PROC_UNLOCK(p);
759 	}
760 	if (nfound == 0) {
761 		sx_xunlock(&proctree_lock);
762 		mtx_unlock(&Giant);
763 		return (ECHILD);
764 	}
765 	if (uap->options & WNOHANG) {
766 		sx_xunlock(&proctree_lock);
767 		td->td_retval[0] = 0;
768 		mtx_unlock(&Giant);
769 		return (0);
770 	}
771 	PROC_LOCK(q);
772 	sx_xunlock(&proctree_lock);
773 	error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
774 	PROC_UNLOCK(q);
775 	if (error) {
776 		mtx_unlock(&Giant);
777 		return (error);
778 	}
779 	goto loop;
780 }
781 
782 /*
783  * Make process 'parent' the new parent of process 'child'.
784  * Must be called with an exclusive hold of proctree lock.
785  */
786 void
787 proc_reparent(struct proc *child, struct proc *parent)
788 {
789 
790 	sx_assert(&proctree_lock, SX_XLOCKED);
791 	PROC_LOCK_ASSERT(child, MA_OWNED);
792 	if (child->p_pptr == parent)
793 		return;
794 
795 	LIST_REMOVE(child, p_sibling);
796 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
797 	child->p_pptr = parent;
798 }
799