xref: /freebsd/sys/kern/kern_exit.c (revision bfe691b2f75de2224c7ceb304ebcdef2b42d4179)
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/sbuf.h>
60 #include <sys/signalvar.h>
61 #include <sys/sched.h>
62 #include <sys/sx.h>
63 #include <sys/syscallsubr.h>
64 #include <sys/syslog.h>
65 #include <sys/ptrace.h>
66 #include <sys/acct.h>		/* for acct_process() function prototype */
67 #include <sys/filedesc.h>
68 #include <sys/shm.h>
69 #include <sys/sem.h>
70 #ifdef KTRACE
71 #include <sys/ktrace.h>
72 #endif
73 
74 #include <security/audit/audit.h>
75 #include <security/mac/mac_framework.h>
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 
85 /* Required to be non-static for SysVR4 emulator */
86 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
87 
88 /* Hook for NFS teardown procedure. */
89 void (*nlminfo_release_p)(struct proc *p);
90 
91 /*
92  * exit -- death of process.
93  */
94 void
95 sys_exit(struct thread *td, struct sys_exit_args *uap)
96 {
97 
98 	exit1(td, W_EXITCODE(uap->rval, 0));
99 	/* NOTREACHED */
100 }
101 
102 /*
103  * Exit: deallocate address space and other resources, change proc state to
104  * zombie, and unlink proc from allproc and parent's lists.  Save exit status
105  * and rusage for wait().  Check for child processes and orphan them.
106  */
107 void
108 exit1(struct thread *td, int rv)
109 {
110 	struct proc *p, *nq, *q;
111 	struct tty *tp;
112 	struct vnode *ttyvp;
113 	struct vnode *vtmp;
114 #ifdef KTRACE
115 	struct vnode *tracevp;
116 	struct ucred *tracecred;
117 #endif
118 	struct plimit *plim;
119 	int locked;
120 
121 	/*
122 	 * Drop Giant if caller has it.  Eventually we should warn about
123 	 * being called with Giant held.
124 	 */
125 	while (mtx_owned(&Giant))
126 		mtx_unlock(&Giant);
127 
128 	p = td->td_proc;
129 	if (p == initproc) {
130 		printf("init died (signal %d, exit %d)\n",
131 		    WTERMSIG(rv), WEXITSTATUS(rv));
132 		panic("Going nowhere without my init!");
133 	}
134 
135 	/*
136 	 * MUST abort all other threads before proceeding past here.
137 	 */
138 	PROC_LOCK(p);
139 	if (p->p_flag & P_HADTHREADS) {
140 retry:
141 		/*
142 		 * First check if some other thread got here before us..
143 		 * if so, act apropriatly, (exit or suspend);
144 		 */
145 		thread_suspend_check(0);
146 
147 		/*
148 		 * Kill off the other threads. This requires
149 		 * some co-operation from other parts of the kernel
150 		 * so it may not be instantaneous.  With this state set
151 		 * any thread entering the kernel from userspace will
152 		 * thread_exit() in trap().  Any thread attempting to
153 		 * sleep will return immediately with EINTR or EWOULDBLOCK
154 		 * which will hopefully force them to back out to userland
155 		 * freeing resources as they go.  Any thread attempting
156 		 * to return to userland will thread_exit() from userret().
157 		 * thread_exit() will unsuspend us when the last of the
158 		 * other threads exits.
159 		 * If there is already a thread singler after resumption,
160 		 * calling thread_single will fail; in that case, we just
161 		 * re-check all suspension request, the thread should
162 		 * either be suspended there or exit.
163 		 */
164 		if (thread_single(SINGLE_EXIT))
165 			goto retry;
166 
167 		/*
168 		 * All other activity in this process is now stopped.
169 		 * Threading support has been turned off.
170 		 */
171 	}
172 
173 	/*
174 	 * Wakeup anyone in procfs' PIOCWAIT.  They should have a hold
175 	 * on our vmspace, so we should block below until they have
176 	 * released their reference to us.  Note that if they have
177 	 * requested S_EXIT stops we will block here until they ack
178 	 * via PIOCCONT.
179 	 */
180 	_STOPEVENT(p, S_EXIT, rv);
181 
182 	/*
183 	 * Note that we are exiting and do another wakeup of anyone in
184 	 * PIOCWAIT in case they aren't listening for S_EXIT stops or
185 	 * decided to wait again after we told them we are exiting.
186 	 */
187 	p->p_flag |= P_WEXIT;
188 	wakeup(&p->p_stype);
189 
190 	/*
191 	 * Wait for any processes that have a hold on our vmspace to
192 	 * release their reference.
193 	 */
194 	while (p->p_lock > 0)
195 		msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
196 
197 	PROC_UNLOCK(p);
198 
199 #ifdef AUDIT
200 	/*
201 	 * The Sun BSM exit token contains two components: an exit status as
202 	 * passed to exit(), and a return value to indicate what sort of exit
203 	 * it was.  The exit status is WEXITSTATUS(rv), but it's not clear
204 	 * what the return value is.
205 	 */
206 	AUDIT_ARG(exit, WEXITSTATUS(rv), 0);
207 	AUDIT_SYSCALL_EXIT(0, td);
208 #endif
209 
210 	/* Are we a task leader? */
211 	if (p == p->p_leader) {
212 		mtx_lock(&ppeers_lock);
213 		q = p->p_peers;
214 		while (q != NULL) {
215 			PROC_LOCK(q);
216 			psignal(q, SIGKILL);
217 			PROC_UNLOCK(q);
218 			q = q->p_peers;
219 		}
220 		while (p->p_peers != NULL)
221 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
222 		mtx_unlock(&ppeers_lock);
223 	}
224 
225 	/*
226 	 * Check if any loadable modules need anything done at process exit.
227 	 * E.g. SYSV IPC stuff
228 	 * XXX what if one of these generates an error?
229 	 */
230 	EVENTHANDLER_INVOKE(process_exit, p);
231 
232 	MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
233 		M_ZOMBIE, M_WAITOK);
234 	/*
235 	 * If parent is waiting for us to exit or exec,
236 	 * P_PPWAIT is set; we will wakeup the parent below.
237 	 */
238 	PROC_LOCK(p);
239 	stopprofclock(p);
240 	p->p_flag &= ~(P_TRACED | P_PPWAIT);
241 
242 	/*
243 	 * Stop the real interval timer.  If the handler is currently
244 	 * executing, prevent it from rearming itself and let it finish.
245 	 */
246 	if (timevalisset(&p->p_realtimer.it_value) &&
247 	    callout_stop(&p->p_itcallout) == 0) {
248 		timevalclear(&p->p_realtimer.it_interval);
249 		msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
250 		KASSERT(!timevalisset(&p->p_realtimer.it_value),
251 		    ("realtime timer is still armed"));
252 	}
253 	PROC_UNLOCK(p);
254 
255 	/*
256 	 * Reset any sigio structures pointing to us as a result of
257 	 * F_SETOWN with our pid.
258 	 */
259 	funsetownlst(&p->p_sigiolst);
260 
261 	/*
262 	 * If this process has an nlminfo data area (for lockd), release it
263 	 */
264 	if (nlminfo_release_p != NULL && p->p_nlminfo != NULL)
265 		(*nlminfo_release_p)(p);
266 
267 	/*
268 	 * Close open files and release open-file table.
269 	 * This may block!
270 	 */
271 	fdfree(td);
272 
273 	/*
274 	 * If this thread tickled GEOM, we need to wait for the giggling to
275 	 * stop before we return to userland
276 	 */
277 	if (td->td_pflags & TDP_GEOM)
278 		g_waitidle();
279 
280 	/*
281 	 * Remove ourself from our leader's peer list and wake our leader.
282 	 */
283 	mtx_lock(&ppeers_lock);
284 	if (p->p_leader->p_peers) {
285 		q = p->p_leader;
286 		while (q->p_peers != p)
287 			q = q->p_peers;
288 		q->p_peers = p->p_peers;
289 		wakeup(p->p_leader);
290 	}
291 	mtx_unlock(&ppeers_lock);
292 
293 	vmspace_exit(td);
294 
295 	mtx_lock(&Giant);	/* XXX TTY */
296 	sx_xlock(&proctree_lock);
297 	if (SESS_LEADER(p)) {
298 		struct session *sp;
299 
300 		sp = p->p_session;
301 		if (sp->s_ttyvp) {
302 			/*
303 			 * Controlling process.
304 			 * Signal foreground pgrp,
305 			 * drain controlling terminal
306 			 * and revoke access to controlling terminal.
307 			 */
308 			if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
309 				tp = sp->s_ttyp;
310 				if (sp->s_ttyp->t_pgrp) {
311 					PGRP_LOCK(sp->s_ttyp->t_pgrp);
312 					pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
313 					PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
314 				}
315 				/* XXX tp should be locked. */
316 				sx_xunlock(&proctree_lock);
317 				(void) ttywait(tp);
318 				sx_xlock(&proctree_lock);
319 				/*
320 				 * The tty could have been revoked
321 				 * if we blocked.
322 				 */
323 				if (sp->s_ttyvp) {
324 					ttyvp = sp->s_ttyvp;
325 					SESS_LOCK(p->p_session);
326 					sp->s_ttyvp = NULL;
327 					SESS_UNLOCK(p->p_session);
328 					sx_xunlock(&proctree_lock);
329 					VOP_LOCK(ttyvp, LK_EXCLUSIVE, td);
330 					VOP_REVOKE(ttyvp, REVOKEALL);
331 					vput(ttyvp);
332 					sx_xlock(&proctree_lock);
333 				}
334 			}
335 			if (sp->s_ttyvp) {
336 				ttyvp = sp->s_ttyvp;
337 				SESS_LOCK(p->p_session);
338 				sp->s_ttyvp = NULL;
339 				SESS_UNLOCK(p->p_session);
340 				vrele(ttyvp);
341 			}
342 			/*
343 			 * s_ttyp is not zero'd; we use this to indicate
344 			 * that the session once had a controlling terminal.
345 			 * (for logging and informational purposes)
346 			 */
347 		}
348 		SESS_LOCK(p->p_session);
349 		sp->s_leader = NULL;
350 		SESS_UNLOCK(p->p_session);
351 	}
352 	fixjobc(p, p->p_pgrp, 0);
353 	sx_xunlock(&proctree_lock);
354 	(void)acct_process(td);
355 	mtx_unlock(&Giant);
356 #ifdef KTRACE
357 	/*
358 	 * Drain any pending records on the thread and release the trace
359 	 * file.  It might be better if drain-and-clear were atomic.
360 	 */
361 	ktrprocexit(td);
362 	PROC_LOCK(p);
363 	mtx_lock(&ktrace_mtx);
364 	p->p_traceflag = 0;	/* don't trace the vrele() */
365 	tracevp = p->p_tracevp;
366 	p->p_tracevp = NULL;
367 	tracecred = p->p_tracecred;
368 	p->p_tracecred = NULL;
369 	mtx_unlock(&ktrace_mtx);
370 	PROC_UNLOCK(p);
371 	if (tracevp != NULL) {
372 		locked = VFS_LOCK_GIANT(tracevp->v_mount);
373 		vrele(tracevp);
374 		VFS_UNLOCK_GIANT(locked);
375 	}
376 	if (tracecred != NULL)
377 		crfree(tracecred);
378 #endif
379 	/*
380 	 * Release reference to text vnode
381 	 */
382 	if ((vtmp = p->p_textvp) != NULL) {
383 		p->p_textvp = NULL;
384 		locked = VFS_LOCK_GIANT(vtmp->v_mount);
385 		vrele(vtmp);
386 		VFS_UNLOCK_GIANT(locked);
387 	}
388 
389 	/*
390 	 * Release our limits structure.
391 	 */
392 	PROC_LOCK(p);
393 	plim = p->p_limit;
394 	p->p_limit = NULL;
395 	PROC_UNLOCK(p);
396 	lim_free(plim);
397 
398 	/*
399 	 * Remove proc from allproc queue and pidhash chain.
400 	 * Place onto zombproc.  Unlink from parent's child list.
401 	 */
402 	sx_xlock(&allproc_lock);
403 	LIST_REMOVE(p, p_list);
404 	LIST_INSERT_HEAD(&zombproc, p, p_list);
405 	LIST_REMOVE(p, p_hash);
406 	sx_xunlock(&allproc_lock);
407 
408 	/*
409 	 * Reparent all of our children to init.
410 	 */
411 	sx_xlock(&proctree_lock);
412 	q = LIST_FIRST(&p->p_children);
413 	if (q != NULL)		/* only need this if any child is S_ZOMB */
414 		wakeup(initproc);
415 	for (; q != NULL; q = nq) {
416 		nq = LIST_NEXT(q, p_sibling);
417 		PROC_LOCK(q);
418 		proc_reparent(q, initproc);
419 		q->p_sigparent = SIGCHLD;
420 		/*
421 		 * Traced processes are killed
422 		 * since their existence means someone is screwing up.
423 		 */
424 		if (q->p_flag & P_TRACED) {
425 			q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
426 			psignal(q, SIGKILL);
427 		}
428 		PROC_UNLOCK(q);
429 	}
430 
431 	/*
432 	 * Save exit status and finalize rusage info except for times,
433 	 * adding in child rusage info later when our time is locked.
434 	 */
435 	PROC_LOCK(p);
436 	p->p_xstat = rv;
437 	p->p_xthread = td;
438 	p->p_stats->p_ru.ru_nvcsw++;
439 	*p->p_ru = p->p_stats->p_ru;
440 
441 	/*
442 	 * Notify interested parties of our demise.
443 	 */
444 	KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
445 
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 		if (p->p_sigparent == SIGCHLD)
483 			childproc_exited(p);
484 		else	/* LINUX thread */
485 			psignal(p->p_pptr, p->p_sigparent);
486 	}
487 	PROC_UNLOCK(p->p_pptr);
488 	PROC_UNLOCK(p);
489 
490 	/*
491 	 * Finally, call machine-dependent code to release the remaining
492 	 * resources including address space.
493 	 * The address space is released by "vmspace_exitfree(p)" in
494 	 * vm_waitproc().
495 	 */
496 	cpu_exit(td);
497 
498 	WITNESS_WARN(WARN_PANIC, &proctree_lock.lock_object,
499 	    "process (pid %d) exiting", p->p_pid);
500 
501 	PROC_LOCK(p);
502 	PROC_LOCK(p->p_pptr);
503 	sx_xunlock(&proctree_lock);
504 
505 	/*
506 	 * The state PRS_ZOMBIE prevents other proesses from sending
507 	 * signal to the process, to avoid memory leak, we free memory
508 	 * for signal queue at the time when the state is set.
509 	 */
510 	sigqueue_flush(&p->p_sigqueue);
511 	sigqueue_flush(&td->td_sigqueue);
512 
513 	/*
514 	 * We have to wait until after acquiring all locks before
515 	 * changing p_state.  We need to avoid all possible context
516 	 * switches (including ones from blocking on a mutex) while
517 	 * marked as a zombie.  We also have to set the zombie state
518 	 * before we release the parent process' proc lock to avoid
519 	 * a lost wakeup.  So, we first call wakeup, then we grab the
520 	 * sched lock, update the state, and release the parent process'
521 	 * proc lock.
522 	 */
523 	wakeup(p->p_pptr);
524 	mtx_lock_spin(&sched_lock);
525 	p->p_state = PRS_ZOMBIE;
526 	PROC_UNLOCK(p->p_pptr);
527 
528 	sched_exit(p->p_pptr, td);
529 
530 	/*
531 	 * Hopefully no one will try to deliver a signal to the process this
532 	 * late in the game.
533 	 */
534 	knlist_destroy(&p->p_klist);
535 
536 	/*
537 	 * Make sure the scheduler takes this thread out of its tables etc.
538 	 * This will also release this thread's reference to the ucred.
539 	 * Other thread parts to release include pcb bits and such.
540 	 */
541 	thread_exit();
542 }
543 
544 
545 #ifndef _SYS_SYSPROTO_H_
546 struct abort2_args {
547 	char *why;
548 	int nargs;
549 	void **args;
550 };
551 #endif
552 
553 int
554 abort2(struct thread *td, struct abort2_args *uap)
555 {
556 	struct proc *p = td->td_proc;
557 	struct sbuf *sb;
558 	void *uargs[16];
559 	int error, i, sig;
560 
561 	error = 0;	/* satisfy compiler */
562 
563 	/*
564 	 * Do it right now so we can log either proper call of abort2(), or
565 	 * note, that invalid argument was passed. 512 is big enough to
566 	 * handle 16 arguments' descriptions with additional comments.
567 	 */
568 	sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
569 	sbuf_clear(sb);
570 	sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
571 	    p->p_comm, p->p_pid, td->td_ucred->cr_uid);
572 	/*
573 	 * Since we can't return from abort2(), send SIGKILL in cases, where
574 	 * abort2() was called improperly
575 	 */
576 	sig = SIGKILL;
577 	/* Prevent from DoSes from user-space. */
578 	if (uap->nargs < 0 || uap->nargs > 16)
579 		goto out;
580 	if (uap->args == NULL)
581 		goto out;
582 	error = copyin(uap->args, uargs, uap->nargs * sizeof(void *));
583 	if (error != 0)
584 		goto out;
585 	/*
586 	 * Limit size of 'reason' string to 128. Will fit even when
587 	 * maximal number of arguments was chosen to be logged.
588 	 */
589 	if (uap->why != NULL) {
590 		error = sbuf_copyin(sb, uap->why, 128);
591 		if (error < 0)
592 			goto out;
593 	} else {
594 		sbuf_printf(sb, "(null)");
595 	}
596 	if (uap->nargs) {
597 		sbuf_printf(sb, "(");
598 		for (i = 0;i < uap->nargs; i++)
599 			sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
600 		sbuf_printf(sb, ")");
601 	}
602 	/*
603 	 * Final stage: arguments were proper, string has been
604 	 * successfully copied from userspace, and copying pointers
605 	 * from user-space succeed.
606 	 */
607 	sig = SIGABRT;
608 out:
609 	if (sig == SIGKILL) {
610 		sbuf_trim(sb);
611 		sbuf_printf(sb, " (Reason text inaccessible)");
612 	}
613 	sbuf_cat(sb, "\n");
614 	sbuf_finish(sb);
615 	log(LOG_INFO, "%s", sbuf_data(sb));
616 	sbuf_delete(sb);
617 	exit1(td, W_EXITCODE(0, sig));
618 	return (0);
619 }
620 
621 
622 #ifdef COMPAT_43
623 /*
624  * The dirty work is handled by kern_wait().
625  */
626 int
627 owait(struct thread *td, struct owait_args *uap __unused)
628 {
629 	int error, status;
630 
631 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
632 	if (error == 0)
633 		td->td_retval[1] = status;
634 	return (error);
635 }
636 #endif /* COMPAT_43 */
637 
638 /*
639  * The dirty work is handled by kern_wait().
640  */
641 int
642 wait4(struct thread *td, struct wait_args *uap)
643 {
644 	struct rusage ru, *rup;
645 	int error, status;
646 
647 	if (uap->rusage != NULL)
648 		rup = &ru;
649 	else
650 		rup = NULL;
651 	error = kern_wait(td, uap->pid, &status, uap->options, rup);
652 	if (uap->status != NULL && error == 0)
653 		error = copyout(&status, uap->status, sizeof(status));
654 	if (uap->rusage != NULL && error == 0)
655 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
656 	return (error);
657 }
658 
659 int
660 kern_wait(struct thread *td, pid_t pid, int *status, int options,
661     struct rusage *rusage)
662 {
663 	struct proc *p, *q, *t;
664 	int error, nfound;
665 
666 	AUDIT_ARG(pid, pid);
667 
668 	q = td->td_proc;
669 	if (pid == 0) {
670 		PROC_LOCK(q);
671 		pid = -q->p_pgid;
672 		PROC_UNLOCK(q);
673 	}
674 	if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WLINUXCLONE))
675 		return (EINVAL);
676 loop:
677 	if (q->p_flag & P_STATCHILD) {
678 		PROC_LOCK(q);
679 		q->p_flag &= ~P_STATCHILD;
680 		PROC_UNLOCK(q);
681 	}
682 	nfound = 0;
683 	sx_xlock(&proctree_lock);
684 	LIST_FOREACH(p, &q->p_children, p_sibling) {
685 		PROC_LOCK(p);
686 		if (pid != WAIT_ANY &&
687 		    p->p_pid != pid && p->p_pgid != -pid) {
688 			PROC_UNLOCK(p);
689 			continue;
690 		}
691 		if (p_canwait(td, p)) {
692 			PROC_UNLOCK(p);
693 			continue;
694 		}
695 
696 		/*
697 		 * This special case handles a kthread spawned by linux_clone
698 		 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
699 		 * functions need to be able to distinguish between waiting
700 		 * on a process and waiting on a thread.  It is a thread if
701 		 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
702 		 * signifies we want to wait for threads and not processes.
703 		 */
704 		if ((p->p_sigparent != SIGCHLD) ^
705 		    ((options & WLINUXCLONE) != 0)) {
706 			PROC_UNLOCK(p);
707 			continue;
708 		}
709 
710 		nfound++;
711 		if (p->p_state == PRS_ZOMBIE) {
712 
713 			/*
714 			 * It is possible that the last thread of this
715 			 * process is still running on another CPU
716 			 * in thread_exit() after having dropped the process
717 			 * lock via PROC_UNLOCK() but before it has completed
718 			 * cpu_throw().  In that case, the other thread must
719 			 * still hold sched_lock, so simply by acquiring
720 			 * sched_lock once we will wait long enough for the
721 			 * thread to exit in that case.
722 			 */
723 			mtx_lock_spin(&sched_lock);
724 			mtx_unlock_spin(&sched_lock);
725 
726 			td->td_retval[0] = p->p_pid;
727 			if (status)
728 				*status = p->p_xstat;	/* convert to int */
729 			if (rusage) {
730 				*rusage = *p->p_ru;
731 				calcru(p, &rusage->ru_utime, &rusage->ru_stime);
732 			}
733 
734 			PROC_LOCK(q);
735 			sigqueue_take(p->p_ksi);
736 			PROC_UNLOCK(q);
737 
738 			/*
739 			 * If we got the child via a ptrace 'attach',
740 			 * we need to give it back to the old parent.
741 			 */
742 			PROC_UNLOCK(p);
743 			if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
744 				PROC_LOCK(p);
745 				p->p_oppid = 0;
746 				proc_reparent(p, t);
747 				PROC_UNLOCK(p);
748 				tdsignal(t, NULL, SIGCHLD, p->p_ksi);
749 				wakeup(t);
750 				PROC_UNLOCK(t);
751 				sx_xunlock(&proctree_lock);
752 				return (0);
753 			}
754 
755 			/*
756 			 * Remove other references to this process to ensure
757 			 * we have an exclusive reference.
758 			 */
759 			sx_xlock(&allproc_lock);
760 			LIST_REMOVE(p, p_list);	/* off zombproc */
761 			sx_xunlock(&allproc_lock);
762 			LIST_REMOVE(p, p_sibling);
763 			leavepgrp(p);
764 			sx_xunlock(&proctree_lock);
765 
766 			/*
767 			 * As a side effect of this lock, we know that
768 			 * all other writes to this proc are visible now, so
769 			 * no more locking is needed for p.
770 			 */
771 			PROC_LOCK(p);
772 			p->p_xstat = 0;		/* XXX: why? */
773 			PROC_UNLOCK(p);
774 			PROC_LOCK(q);
775 			ruadd(&q->p_stats->p_cru, &q->p_crux, p->p_ru,
776 			    &p->p_rux);
777 			PROC_UNLOCK(q);
778 			FREE(p->p_ru, M_ZOMBIE);
779 			p->p_ru = NULL;
780 
781 			/*
782 			 * Decrement the count of procs running with this uid.
783 			 */
784 			(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
785 
786 			/*
787 			 * Free credentials, arguments, and sigacts.
788 			 */
789 			crfree(p->p_ucred);
790 			p->p_ucred = NULL;
791 			pargs_drop(p->p_args);
792 			p->p_args = NULL;
793 			sigacts_free(p->p_sigacts);
794 			p->p_sigacts = NULL;
795 
796 			/*
797 			 * Do any thread-system specific cleanups.
798 			 */
799 			thread_wait(p);
800 
801 			/*
802 			 * Give vm and machine-dependent layer a chance
803 			 * to free anything that cpu_exit couldn't
804 			 * release while still running in process context.
805 			 */
806 			vm_waitproc(p);
807 #ifdef MAC
808 			mac_destroy_proc(p);
809 #endif
810 #ifdef AUDIT
811 			audit_proc_free(p);
812 #endif
813 			KASSERT(FIRST_THREAD_IN_PROC(p),
814 			    ("kern_wait: no residual thread!"));
815 			uma_zfree(proc_zone, p);
816 			sx_xlock(&allproc_lock);
817 			nprocs--;
818 			sx_xunlock(&allproc_lock);
819 			return (0);
820 		}
821 		mtx_lock_spin(&sched_lock);
822 		if ((p->p_flag & P_STOPPED_SIG) &&
823 		    (p->p_suspcount == p->p_numthreads) &&
824 		    (p->p_flag & P_WAITED) == 0 &&
825 		    (p->p_flag & P_TRACED || options & WUNTRACED)) {
826 			mtx_unlock_spin(&sched_lock);
827 			p->p_flag |= P_WAITED;
828 			sx_xunlock(&proctree_lock);
829 			td->td_retval[0] = p->p_pid;
830 			if (status)
831 				*status = W_STOPCODE(p->p_xstat);
832 
833 			PROC_LOCK(q);
834 			sigqueue_take(p->p_ksi);
835 			PROC_UNLOCK(q);
836 			PROC_UNLOCK(p);
837 
838 			return (0);
839 		}
840 		mtx_unlock_spin(&sched_lock);
841 		if (options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
842 			sx_xunlock(&proctree_lock);
843 			td->td_retval[0] = p->p_pid;
844 			p->p_flag &= ~P_CONTINUED;
845 
846 			PROC_LOCK(q);
847 			sigqueue_take(p->p_ksi);
848 			PROC_UNLOCK(q);
849 			PROC_UNLOCK(p);
850 
851 			if (status)
852 				*status = SIGCONT;
853 			return (0);
854 		}
855 		PROC_UNLOCK(p);
856 	}
857 	if (nfound == 0) {
858 		sx_xunlock(&proctree_lock);
859 		return (ECHILD);
860 	}
861 	if (options & WNOHANG) {
862 		sx_xunlock(&proctree_lock);
863 		td->td_retval[0] = 0;
864 		return (0);
865 	}
866 	PROC_LOCK(q);
867 	sx_xunlock(&proctree_lock);
868 	if (q->p_flag & P_STATCHILD) {
869 		q->p_flag &= ~P_STATCHILD;
870 		error = 0;
871 	} else
872 		error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
873 	PROC_UNLOCK(q);
874 	if (error)
875 		return (error);
876 	goto loop;
877 }
878 
879 /*
880  * Make process 'parent' the new parent of process 'child'.
881  * Must be called with an exclusive hold of proctree lock.
882  */
883 void
884 proc_reparent(struct proc *child, struct proc *parent)
885 {
886 
887 	sx_assert(&proctree_lock, SX_XLOCKED);
888 	PROC_LOCK_ASSERT(child, MA_OWNED);
889 	if (child->p_pptr == parent)
890 		return;
891 
892 	PROC_LOCK(child->p_pptr);
893 	sigqueue_take(child->p_ksi);
894 	PROC_UNLOCK(child->p_pptr);
895 	LIST_REMOVE(child, p_sibling);
896 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
897 	child->p_pptr = parent;
898 }
899