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