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