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