xref: /freebsd/sys/kern/kern_exit.c (revision 95d45410b5100e07f6f98450bcd841a8945d4726)
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 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysproto.h>
46 #include <sys/capsicum.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/procdesc.h>
54 #include <sys/pioctl.h>
55 #include <sys/jail.h>
56 #include <sys/tty.h>
57 #include <sys/wait.h>
58 #include <sys/vmmeter.h>
59 #include <sys/vnode.h>
60 #include <sys/racct.h>
61 #include <sys/resourcevar.h>
62 #include <sys/sbuf.h>
63 #include <sys/signalvar.h>
64 #include <sys/sched.h>
65 #include <sys/sx.h>
66 #include <sys/syscallsubr.h>
67 #include <sys/syslog.h>
68 #include <sys/ptrace.h>
69 #include <sys/acct.h>		/* for acct_process() function prototype */
70 #include <sys/filedesc.h>
71 #include <sys/sdt.h>
72 #include <sys/shm.h>
73 #include <sys/sem.h>
74 #ifdef KTRACE
75 #include <sys/ktrace.h>
76 #endif
77 
78 #include <security/audit/audit.h>
79 #include <security/mac/mac_framework.h>
80 
81 #include <vm/vm.h>
82 #include <vm/vm_extern.h>
83 #include <vm/vm_param.h>
84 #include <vm/pmap.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_page.h>
87 #include <vm/uma.h>
88 
89 #ifdef KDTRACE_HOOKS
90 #include <sys/dtrace_bsd.h>
91 dtrace_execexit_func_t	dtrace_fasttrap_exit;
92 #endif
93 
94 SDT_PROVIDER_DECLARE(proc);
95 SDT_PROBE_DEFINE1(proc, kernel, , exit, "int");
96 
97 /* Hook for NFS teardown procedure. */
98 void (*nlminfo_release_p)(struct proc *p);
99 
100 static void
101 clear_orphan(struct proc *p)
102 {
103 
104 	PROC_LOCK_ASSERT(p, MA_OWNED);
105 
106 	if (p->p_flag & P_ORPHAN) {
107 		LIST_REMOVE(p, p_orphan);
108 		p->p_flag &= ~P_ORPHAN;
109 	}
110 }
111 
112 /*
113  * exit -- death of process.
114  */
115 void
116 sys_sys_exit(struct thread *td, struct sys_exit_args *uap)
117 {
118 
119 	exit1(td, W_EXITCODE(uap->rval, 0));
120 	/* NOTREACHED */
121 }
122 
123 /*
124  * Exit: deallocate address space and other resources, change proc state to
125  * zombie, and unlink proc from allproc and parent's lists.  Save exit status
126  * and rusage for wait().  Check for child processes and orphan them.
127  */
128 void
129 exit1(struct thread *td, int rv)
130 {
131 	struct proc *p, *nq, *q;
132 	struct vnode *ttyvp = NULL;
133 
134 	mtx_assert(&Giant, MA_NOTOWNED);
135 
136 	p = td->td_proc;
137 	/*
138 	 * XXX in case we're rebooting we just let init die in order to
139 	 * work around an unsolved stack overflow seen very late during
140 	 * shutdown on sparc64 when the gmirror worker process exists.
141 	 */
142 	if (p == initproc && rebooting == 0) {
143 		printf("init died (signal %d, exit %d)\n",
144 		    WTERMSIG(rv), WEXITSTATUS(rv));
145 		panic("Going nowhere without my init!");
146 	}
147 
148 	/*
149 	 * MUST abort all other threads before proceeding past here.
150 	 */
151 	PROC_LOCK(p);
152 	while (p->p_flag & P_HADTHREADS) {
153 		/*
154 		 * First check if some other thread got here before us.
155 		 * If so, act appropriately: exit or suspend.
156 		 */
157 		thread_suspend_check(0);
158 
159 		/*
160 		 * Kill off the other threads. This requires
161 		 * some co-operation from other parts of the kernel
162 		 * so it may not be instantaneous.  With this state set
163 		 * any thread entering the kernel from userspace will
164 		 * thread_exit() in trap().  Any thread attempting to
165 		 * sleep will return immediately with EINTR or EWOULDBLOCK
166 		 * which will hopefully force them to back out to userland
167 		 * freeing resources as they go.  Any thread attempting
168 		 * to return to userland will thread_exit() from userret().
169 		 * thread_exit() will unsuspend us when the last of the
170 		 * other threads exits.
171 		 * If there is already a thread singler after resumption,
172 		 * calling thread_single will fail; in that case, we just
173 		 * re-check all suspension request, the thread should
174 		 * either be suspended there or exit.
175 		 */
176 		if (!thread_single(SINGLE_EXIT))
177 			break;
178 
179 		/*
180 		 * All other activity in this process is now stopped.
181 		 * Threading support has been turned off.
182 		 */
183 	}
184 	KASSERT(p->p_numthreads == 1,
185 	    ("exit1: proc %p exiting with %d threads", p, p->p_numthreads));
186 	racct_sub(p, RACCT_NTHR, 1);
187 	/*
188 	 * Wakeup anyone in procfs' PIOCWAIT.  They should have a hold
189 	 * on our vmspace, so we should block below until they have
190 	 * released their reference to us.  Note that if they have
191 	 * requested S_EXIT stops we will block here until they ack
192 	 * via PIOCCONT.
193 	 */
194 	_STOPEVENT(p, S_EXIT, rv);
195 
196 	/*
197 	 * Ignore any pending request to stop due to a stop signal.
198 	 * Once P_WEXIT is set, future requests will be ignored as
199 	 * well.
200 	 */
201 	p->p_flag &= ~P_STOPPED_SIG;
202 	KASSERT(!P_SHOULDSTOP(p), ("exiting process is stopped"));
203 
204 	/*
205 	 * Note that we are exiting and do another wakeup of anyone in
206 	 * PIOCWAIT in case they aren't listening for S_EXIT stops or
207 	 * decided to wait again after we told them we are exiting.
208 	 */
209 	p->p_flag |= P_WEXIT;
210 	wakeup(&p->p_stype);
211 
212 	/*
213 	 * Wait for any processes that have a hold on our vmspace to
214 	 * release their reference.
215 	 */
216 	while (p->p_lock > 0)
217 		msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
218 
219 	p->p_xstat = rv;	/* Let event handler change exit status */
220 	PROC_UNLOCK(p);
221 	/* Drain the limit callout while we don't have the proc locked */
222 	callout_drain(&p->p_limco);
223 
224 #ifdef AUDIT
225 	/*
226 	 * The Sun BSM exit token contains two components: an exit status as
227 	 * passed to exit(), and a return value to indicate what sort of exit
228 	 * it was.  The exit status is WEXITSTATUS(rv), but it's not clear
229 	 * what the return value is.
230 	 */
231 	AUDIT_ARG_EXIT(WEXITSTATUS(rv), 0);
232 	AUDIT_SYSCALL_EXIT(0, td);
233 #endif
234 
235 	/* Are we a task leader? */
236 	if (p == p->p_leader) {
237 		mtx_lock(&ppeers_lock);
238 		q = p->p_peers;
239 		while (q != NULL) {
240 			PROC_LOCK(q);
241 			kern_psignal(q, SIGKILL);
242 			PROC_UNLOCK(q);
243 			q = q->p_peers;
244 		}
245 		while (p->p_peers != NULL)
246 			msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
247 		mtx_unlock(&ppeers_lock);
248 	}
249 
250 	/*
251 	 * Check if any loadable modules need anything done at process exit.
252 	 * E.g. SYSV IPC stuff
253 	 * XXX what if one of these generates an error?
254 	 */
255 	EVENTHANDLER_INVOKE(process_exit, p);
256 
257 	/*
258 	 * If parent is waiting for us to exit or exec,
259 	 * P_PPWAIT is set; we will wakeup the parent below.
260 	 */
261 	PROC_LOCK(p);
262 	rv = p->p_xstat;	/* Event handler could change exit status */
263 	stopprofclock(p);
264 	p->p_flag &= ~(P_TRACED | P_PPWAIT | P_PPTRACE);
265 
266 	/*
267 	 * Stop the real interval timer.  If the handler is currently
268 	 * executing, prevent it from rearming itself and let it finish.
269 	 */
270 	if (timevalisset(&p->p_realtimer.it_value) &&
271 	    callout_stop(&p->p_itcallout) == 0) {
272 		timevalclear(&p->p_realtimer.it_interval);
273 		msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
274 		KASSERT(!timevalisset(&p->p_realtimer.it_value),
275 		    ("realtime timer is still armed"));
276 	}
277 	PROC_UNLOCK(p);
278 
279 	/*
280 	 * Reset any sigio structures pointing to us as a result of
281 	 * F_SETOWN with our pid.
282 	 */
283 	funsetownlst(&p->p_sigiolst);
284 
285 	/*
286 	 * If this process has an nlminfo data area (for lockd), release it
287 	 */
288 	if (nlminfo_release_p != NULL && p->p_nlminfo != NULL)
289 		(*nlminfo_release_p)(p);
290 
291 	/*
292 	 * Close open files and release open-file table.
293 	 * This may block!
294 	 */
295 	fdescfree(td);
296 
297 	/*
298 	 * If this thread tickled GEOM, we need to wait for the giggling to
299 	 * stop before we return to userland
300 	 */
301 	if (td->td_pflags & TDP_GEOM)
302 		g_waitidle();
303 
304 	/*
305 	 * Remove ourself from our leader's peer list and wake our leader.
306 	 */
307 	mtx_lock(&ppeers_lock);
308 	if (p->p_leader->p_peers) {
309 		q = p->p_leader;
310 		while (q->p_peers != p)
311 			q = q->p_peers;
312 		q->p_peers = p->p_peers;
313 		wakeup(p->p_leader);
314 	}
315 	mtx_unlock(&ppeers_lock);
316 
317 	vmspace_exit(td);
318 
319 	sx_xlock(&proctree_lock);
320 	if (SESS_LEADER(p)) {
321 		struct session *sp = p->p_session;
322 		struct tty *tp;
323 
324 		/*
325 		 * s_ttyp is not zero'd; we use this to indicate that
326 		 * the session once had a controlling terminal. (for
327 		 * logging and informational purposes)
328 		 */
329 		SESS_LOCK(sp);
330 		ttyvp = sp->s_ttyvp;
331 		tp = sp->s_ttyp;
332 		sp->s_ttyvp = NULL;
333 		sp->s_ttydp = NULL;
334 		sp->s_leader = NULL;
335 		SESS_UNLOCK(sp);
336 
337 		/*
338 		 * Signal foreground pgrp and revoke access to
339 		 * controlling terminal if it has not been revoked
340 		 * already.
341 		 *
342 		 * Because the TTY may have been revoked in the mean
343 		 * time and could already have a new session associated
344 		 * with it, make sure we don't send a SIGHUP to a
345 		 * foreground process group that does not belong to this
346 		 * session.
347 		 */
348 
349 		if (tp != NULL) {
350 			tty_lock(tp);
351 			if (tp->t_session == sp)
352 				tty_signal_pgrp(tp, SIGHUP);
353 			tty_unlock(tp);
354 		}
355 
356 		if (ttyvp != NULL) {
357 			sx_xunlock(&proctree_lock);
358 			if (vn_lock(ttyvp, LK_EXCLUSIVE) == 0) {
359 				VOP_REVOKE(ttyvp, REVOKEALL);
360 				VOP_UNLOCK(ttyvp, 0);
361 			}
362 			sx_xlock(&proctree_lock);
363 		}
364 	}
365 	fixjobc(p, p->p_pgrp, 0);
366 	sx_xunlock(&proctree_lock);
367 	(void)acct_process(td);
368 
369 	/* Release the TTY now we've unlocked everything. */
370 	if (ttyvp != NULL)
371 		vrele(ttyvp);
372 #ifdef KTRACE
373 	ktrprocexit(td);
374 #endif
375 	/*
376 	 * Release reference to text vnode
377 	 */
378 	if (p->p_textvp != NULL) {
379 		vrele(p->p_textvp);
380 		p->p_textvp = NULL;
381 	}
382 
383 	/*
384 	 * Release our limits structure.
385 	 */
386 	lim_free(p->p_limit);
387 	p->p_limit = NULL;
388 
389 	tidhash_remove(td);
390 
391 	/*
392 	 * Remove proc from allproc queue and pidhash chain.
393 	 * Place onto zombproc.  Unlink from parent's child list.
394 	 */
395 	sx_xlock(&allproc_lock);
396 	LIST_REMOVE(p, p_list);
397 	LIST_INSERT_HEAD(&zombproc, p, p_list);
398 	LIST_REMOVE(p, p_hash);
399 	sx_xunlock(&allproc_lock);
400 
401 	/*
402 	 * Call machine-dependent code to release any
403 	 * machine-dependent resources other than the address space.
404 	 * The address space is released by "vmspace_exitfree(p)" in
405 	 * vm_waitproc().
406 	 */
407 	cpu_exit(td);
408 
409 	WITNESS_WARN(WARN_PANIC, NULL, "process (pid %d) exiting", p->p_pid);
410 
411 	/*
412 	 * Reparent all of our children to init.
413 	 */
414 	sx_xlock(&proctree_lock);
415 	q = LIST_FIRST(&p->p_children);
416 	if (q != NULL)		/* only need this if any child is S_ZOMB */
417 		wakeup(initproc);
418 	for (; q != NULL; q = nq) {
419 		nq = LIST_NEXT(q, p_sibling);
420 		PROC_LOCK(q);
421 		proc_reparent(q, initproc);
422 		q->p_sigparent = SIGCHLD;
423 		/*
424 		 * Traced processes are killed
425 		 * since their existence means someone is screwing up.
426 		 */
427 		if (q->p_flag & P_TRACED) {
428 			struct thread *temp;
429 
430 			/*
431 			 * Since q was found on our children list, the
432 			 * proc_reparent() call moved q to the orphan
433 			 * list due to present P_TRACED flag. Clear
434 			 * orphan link for q now while q is locked.
435 			 */
436 			clear_orphan(q);
437 			q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
438 			FOREACH_THREAD_IN_PROC(q, temp)
439 				temp->td_dbgflags &= ~TDB_SUSPEND;
440 			kern_psignal(q, SIGKILL);
441 		}
442 		PROC_UNLOCK(q);
443 	}
444 
445 	/*
446 	 * Also get rid of our orphans.
447 	 */
448 	while ((q = LIST_FIRST(&p->p_orphans)) != NULL) {
449 		PROC_LOCK(q);
450 		clear_orphan(q);
451 		PROC_UNLOCK(q);
452 	}
453 
454 	/* Save exit status. */
455 	PROC_LOCK(p);
456 	p->p_xthread = td;
457 
458 	/* Tell the prison that we are gone. */
459 	prison_proc_free(p->p_ucred->cr_prison);
460 
461 #ifdef KDTRACE_HOOKS
462 	/*
463 	 * Tell the DTrace fasttrap provider about the exit if it
464 	 * has declared an interest.
465 	 */
466 	if (dtrace_fasttrap_exit)
467 		dtrace_fasttrap_exit(p);
468 #endif
469 
470 	/*
471 	 * Notify interested parties of our demise.
472 	 */
473 	KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
474 
475 #ifdef KDTRACE_HOOKS
476 	int reason = CLD_EXITED;
477 	if (WCOREDUMP(rv))
478 		reason = CLD_DUMPED;
479 	else if (WIFSIGNALED(rv))
480 		reason = CLD_KILLED;
481 	SDT_PROBE(proc, kernel, , exit, reason, 0, 0, 0, 0);
482 #endif
483 
484 	/*
485 	 * Just delete all entries in the p_klist. At this point we won't
486 	 * report any more events, and there are nasty race conditions that
487 	 * can beat us if we don't.
488 	 */
489 	knlist_clear(&p->p_klist, 1);
490 
491 	/*
492 	 * If this is a process with a descriptor, we may not need to deliver
493 	 * a signal to the parent.  proctree_lock is held over
494 	 * procdesc_exit() to serialize concurrent calls to close() and
495 	 * exit().
496 	 */
497 	if (p->p_procdesc == NULL || procdesc_exit(p)) {
498 		/*
499 		 * Notify parent that we're gone.  If parent has the
500 		 * PS_NOCLDWAIT flag set, or if the handler is set to SIG_IGN,
501 		 * notify process 1 instead (and hope it will handle this
502 		 * situation).
503 		 */
504 		PROC_LOCK(p->p_pptr);
505 		mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
506 		if (p->p_pptr->p_sigacts->ps_flag &
507 		    (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
508 			struct proc *pp;
509 
510 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
511 			pp = p->p_pptr;
512 			PROC_UNLOCK(pp);
513 			proc_reparent(p, initproc);
514 			p->p_sigparent = SIGCHLD;
515 			PROC_LOCK(p->p_pptr);
516 
517 			/*
518 			 * Notify parent, so in case he was wait(2)ing or
519 			 * executing waitpid(2) with our pid, he will
520 			 * continue.
521 			 */
522 			wakeup(pp);
523 		} else
524 			mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
525 
526 		if (p->p_pptr == initproc)
527 			kern_psignal(p->p_pptr, SIGCHLD);
528 		else if (p->p_sigparent != 0) {
529 			if (p->p_sigparent == SIGCHLD)
530 				childproc_exited(p);
531 			else	/* LINUX thread */
532 				kern_psignal(p->p_pptr, p->p_sigparent);
533 		}
534 	} else
535 		PROC_LOCK(p->p_pptr);
536 	sx_xunlock(&proctree_lock);
537 
538 	/*
539 	 * The state PRS_ZOMBIE prevents other proesses from sending
540 	 * signal to the process, to avoid memory leak, we free memory
541 	 * for signal queue at the time when the state is set.
542 	 */
543 	sigqueue_flush(&p->p_sigqueue);
544 	sigqueue_flush(&td->td_sigqueue);
545 
546 	/*
547 	 * We have to wait until after acquiring all locks before
548 	 * changing p_state.  We need to avoid all possible context
549 	 * switches (including ones from blocking on a mutex) while
550 	 * marked as a zombie.  We also have to set the zombie state
551 	 * before we release the parent process' proc lock to avoid
552 	 * a lost wakeup.  So, we first call wakeup, then we grab the
553 	 * sched lock, update the state, and release the parent process'
554 	 * proc lock.
555 	 */
556 	wakeup(p->p_pptr);
557 	cv_broadcast(&p->p_pwait);
558 	sched_exit(p->p_pptr, td);
559 	PROC_SLOCK(p);
560 	p->p_state = PRS_ZOMBIE;
561 	PROC_UNLOCK(p->p_pptr);
562 
563 	/*
564 	 * Hopefully no one will try to deliver a signal to the process this
565 	 * late in the game.
566 	 */
567 	knlist_destroy(&p->p_klist);
568 
569 	/*
570 	 * Save our children's rusage information in our exit rusage.
571 	 */
572 	ruadd(&p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
573 
574 	/*
575 	 * Make sure the scheduler takes this thread out of its tables etc.
576 	 * This will also release this thread's reference to the ucred.
577 	 * Other thread parts to release include pcb bits and such.
578 	 */
579 	thread_exit();
580 }
581 
582 
583 #ifndef _SYS_SYSPROTO_H_
584 struct abort2_args {
585 	char *why;
586 	int nargs;
587 	void **args;
588 };
589 #endif
590 
591 int
592 sys_abort2(struct thread *td, struct abort2_args *uap)
593 {
594 	struct proc *p = td->td_proc;
595 	struct sbuf *sb;
596 	void *uargs[16];
597 	int error, i, sig;
598 
599 	/*
600 	 * Do it right now so we can log either proper call of abort2(), or
601 	 * note, that invalid argument was passed. 512 is big enough to
602 	 * handle 16 arguments' descriptions with additional comments.
603 	 */
604 	sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
605 	sbuf_clear(sb);
606 	sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
607 	    p->p_comm, p->p_pid, td->td_ucred->cr_uid);
608 	/*
609 	 * Since we can't return from abort2(), send SIGKILL in cases, where
610 	 * abort2() was called improperly
611 	 */
612 	sig = SIGKILL;
613 	/* Prevent from DoSes from user-space. */
614 	if (uap->nargs < 0 || uap->nargs > 16)
615 		goto out;
616 	if (uap->nargs > 0) {
617 		if (uap->args == NULL)
618 			goto out;
619 		error = copyin(uap->args, uargs, uap->nargs * sizeof(void *));
620 		if (error != 0)
621 			goto out;
622 	}
623 	/*
624 	 * Limit size of 'reason' string to 128. Will fit even when
625 	 * maximal number of arguments was chosen to be logged.
626 	 */
627 	if (uap->why != NULL) {
628 		error = sbuf_copyin(sb, uap->why, 128);
629 		if (error < 0)
630 			goto out;
631 	} else {
632 		sbuf_printf(sb, "(null)");
633 	}
634 	if (uap->nargs > 0) {
635 		sbuf_printf(sb, "(");
636 		for (i = 0;i < uap->nargs; i++)
637 			sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
638 		sbuf_printf(sb, ")");
639 	}
640 	/*
641 	 * Final stage: arguments were proper, string has been
642 	 * successfully copied from userspace, and copying pointers
643 	 * from user-space succeed.
644 	 */
645 	sig = SIGABRT;
646 out:
647 	if (sig == SIGKILL) {
648 		sbuf_trim(sb);
649 		sbuf_printf(sb, " (Reason text inaccessible)");
650 	}
651 	sbuf_cat(sb, "\n");
652 	sbuf_finish(sb);
653 	log(LOG_INFO, "%s", sbuf_data(sb));
654 	sbuf_delete(sb);
655 	exit1(td, W_EXITCODE(0, sig));
656 	return (0);
657 }
658 
659 
660 #ifdef COMPAT_43
661 /*
662  * The dirty work is handled by kern_wait().
663  */
664 int
665 owait(struct thread *td, struct owait_args *uap __unused)
666 {
667 	int error, status;
668 
669 	error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
670 	if (error == 0)
671 		td->td_retval[1] = status;
672 	return (error);
673 }
674 #endif /* COMPAT_43 */
675 
676 /*
677  * The dirty work is handled by kern_wait().
678  */
679 int
680 sys_wait4(struct thread *td, struct wait4_args *uap)
681 {
682 	struct rusage ru, *rup;
683 	int error, status;
684 
685 	if (uap->rusage != NULL)
686 		rup = &ru;
687 	else
688 		rup = NULL;
689 	error = kern_wait(td, uap->pid, &status, uap->options, rup);
690 	if (uap->status != NULL && error == 0)
691 		error = copyout(&status, uap->status, sizeof(status));
692 	if (uap->rusage != NULL && error == 0)
693 		error = copyout(&ru, uap->rusage, sizeof(struct rusage));
694 	return (error);
695 }
696 
697 int
698 sys_wait6(struct thread *td, struct wait6_args *uap)
699 {
700 	struct __wrusage wru, *wrup;
701 	siginfo_t si, *sip;
702 	idtype_t idtype;
703 	id_t id;
704 	int error, status;
705 
706 	idtype = uap->idtype;
707 	id = uap->id;
708 
709 	if (uap->wrusage != NULL)
710 		wrup = &wru;
711 	else
712 		wrup = NULL;
713 
714 	if (uap->info != NULL) {
715 		sip = &si;
716 		bzero(sip, sizeof(*sip));
717 	} else
718 		sip = NULL;
719 
720 	/*
721 	 *  We expect all callers of wait6() to know about WEXITED and
722 	 *  WTRAPPED.
723 	 */
724 	error = kern_wait6(td, idtype, id, &status, uap->options, wrup, sip);
725 
726 	if (uap->status != NULL && error == 0)
727 		error = copyout(&status, uap->status, sizeof(status));
728 	if (uap->wrusage != NULL && error == 0)
729 		error = copyout(&wru, uap->wrusage, sizeof(wru));
730 	if (uap->info != NULL && error == 0)
731 		error = copyout(&si, uap->info, sizeof(si));
732 	return (error);
733 }
734 
735 /*
736  * Reap the remains of a zombie process and optionally return status and
737  * rusage.  Asserts and will release both the proctree_lock and the process
738  * lock as part of its work.
739  */
740 void
741 proc_reap(struct thread *td, struct proc *p, int *status, int options)
742 {
743 	struct proc *q, *t;
744 
745 	sx_assert(&proctree_lock, SA_XLOCKED);
746 	PROC_LOCK_ASSERT(p, MA_OWNED);
747 	PROC_SLOCK_ASSERT(p, MA_OWNED);
748 	KASSERT(p->p_state == PRS_ZOMBIE, ("proc_reap: !PRS_ZOMBIE"));
749 
750 	q = td->td_proc;
751 
752 	PROC_SUNLOCK(p);
753 	td->td_retval[0] = p->p_pid;
754 	if (status)
755 		*status = p->p_xstat;	/* convert to int */
756 	if (options & WNOWAIT) {
757 		/*
758 		 *  Only poll, returning the status.  Caller does not wish to
759 		 * release the proc struct just yet.
760 		 */
761 		PROC_UNLOCK(p);
762 		sx_xunlock(&proctree_lock);
763 		return;
764 	}
765 
766 	PROC_LOCK(q);
767 	sigqueue_take(p->p_ksi);
768 	PROC_UNLOCK(q);
769 	PROC_UNLOCK(p);
770 
771 	/*
772 	 * If we got the child via a ptrace 'attach', we need to give it back
773 	 * to the old parent.
774 	 */
775 	if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
776 		PROC_LOCK(p);
777 		proc_reparent(p, t);
778 		p->p_oppid = 0;
779 		PROC_UNLOCK(p);
780 		pksignal(t, SIGCHLD, p->p_ksi);
781 		wakeup(t);
782 		cv_broadcast(&p->p_pwait);
783 		PROC_UNLOCK(t);
784 		sx_xunlock(&proctree_lock);
785 		return;
786 	}
787 
788 	/*
789 	 * Remove other references to this process to ensure we have an
790 	 * exclusive reference.
791 	 */
792 	sx_xlock(&allproc_lock);
793 	LIST_REMOVE(p, p_list);	/* off zombproc */
794 	sx_xunlock(&allproc_lock);
795 	LIST_REMOVE(p, p_sibling);
796 	PROC_LOCK(p);
797 	clear_orphan(p);
798 	PROC_UNLOCK(p);
799 	leavepgrp(p);
800 	if (p->p_procdesc != NULL)
801 		procdesc_reap(p);
802 	sx_xunlock(&proctree_lock);
803 
804 	/*
805 	 * As a side effect of this lock, we know that all other writes to
806 	 * this proc are visible now, so no more locking is needed for p.
807 	 */
808 	PROC_LOCK(p);
809 	p->p_xstat = 0;		/* XXX: why? */
810 	PROC_UNLOCK(p);
811 	PROC_LOCK(q);
812 	ruadd(&q->p_stats->p_cru, &q->p_crux, &p->p_ru, &p->p_rux);
813 	PROC_UNLOCK(q);
814 
815 	/*
816 	 * Decrement the count of procs running with this uid.
817 	 */
818 	(void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
819 
820 	/*
821 	 * Destroy resource accounting information associated with the process.
822 	 */
823 #ifdef RACCT
824 	PROC_LOCK(p);
825 	racct_sub(p, RACCT_NPROC, 1);
826 	PROC_UNLOCK(p);
827 #endif
828 	racct_proc_exit(p);
829 
830 	/*
831 	 * Free credentials, arguments, and sigacts.
832 	 */
833 	crfree(p->p_ucred);
834 	p->p_ucred = NULL;
835 	pargs_drop(p->p_args);
836 	p->p_args = NULL;
837 	sigacts_free(p->p_sigacts);
838 	p->p_sigacts = NULL;
839 
840 	/*
841 	 * Do any thread-system specific cleanups.
842 	 */
843 	thread_wait(p);
844 
845 	/*
846 	 * Give vm and machine-dependent layer a chance to free anything that
847 	 * cpu_exit couldn't release while still running in process context.
848 	 */
849 	vm_waitproc(p);
850 #ifdef MAC
851 	mac_proc_destroy(p);
852 #endif
853 	KASSERT(FIRST_THREAD_IN_PROC(p),
854 	    ("proc_reap: no residual thread!"));
855 	uma_zfree(proc_zone, p);
856 	sx_xlock(&allproc_lock);
857 	nprocs--;
858 	sx_xunlock(&allproc_lock);
859 }
860 
861 static int
862 proc_to_reap(struct thread *td, struct proc *p, idtype_t idtype, id_t id,
863     int *status, int options, struct __wrusage *wrusage, siginfo_t *siginfo)
864 {
865 	struct proc *q;
866 	struct rusage *rup;
867 
868 	sx_assert(&proctree_lock, SA_XLOCKED);
869 
870 	q = td->td_proc;
871 	PROC_LOCK(p);
872 
873 	switch (idtype) {
874 	case P_ALL:
875 		break;
876 	case P_PID:
877 		if (p->p_pid != (pid_t)id) {
878 			PROC_UNLOCK(p);
879 			return (0);
880 		}
881 		break;
882 	case P_PGID:
883 		if (p->p_pgid != (pid_t)id) {
884 			PROC_UNLOCK(p);
885 			return (0);
886 		}
887 		break;
888 	case P_SID:
889 		if (p->p_session->s_sid != (pid_t)id) {
890 			PROC_UNLOCK(p);
891 			return (0);
892 		}
893 		break;
894 	case P_UID:
895 		if (p->p_ucred->cr_uid != (uid_t)id) {
896 			PROC_UNLOCK(p);
897 			return (0);
898 		}
899 		break;
900 	case P_GID:
901 		if (p->p_ucred->cr_gid != (gid_t)id) {
902 			PROC_UNLOCK(p);
903 			return (0);
904 		}
905 		break;
906 	case P_JAILID:
907 		if (p->p_ucred->cr_prison->pr_id != (int)id) {
908 			PROC_UNLOCK(p);
909 			return (0);
910 		}
911 		break;
912 	/*
913 	 * It seems that the thread structures get zeroed out
914 	 * at process exit.  This makes it impossible to
915 	 * support P_SETID, P_CID or P_CPUID.
916 	 */
917 	default:
918 		PROC_UNLOCK(p);
919 		return (0);
920 	}
921 
922 	if (p_canwait(td, p)) {
923 		PROC_UNLOCK(p);
924 		return (0);
925 	}
926 
927 	if (((options & WEXITED) == 0) && (p->p_state == PRS_ZOMBIE)) {
928 		PROC_UNLOCK(p);
929 		return (0);
930 	}
931 
932 	/*
933 	 * This special case handles a kthread spawned by linux_clone
934 	 * (see linux_misc.c).  The linux_wait4 and linux_waitpid
935 	 * functions need to be able to distinguish between waiting
936 	 * on a process and waiting on a thread.  It is a thread if
937 	 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
938 	 * signifies we want to wait for threads and not processes.
939 	 */
940 	if ((p->p_sigparent != SIGCHLD) ^
941 	    ((options & WLINUXCLONE) != 0)) {
942 		PROC_UNLOCK(p);
943 		return (0);
944 	}
945 
946 	PROC_SLOCK(p);
947 
948 	if (siginfo != NULL) {
949 		bzero(siginfo, sizeof(*siginfo));
950 		siginfo->si_errno = 0;
951 
952 		/*
953 		 * SUSv4 requires that the si_signo value is always
954 		 * SIGCHLD. Obey it despite the rfork(2) interface
955 		 * allows to request other signal for child exit
956 		 * notification.
957 		 */
958 		siginfo->si_signo = SIGCHLD;
959 
960 		/*
961 		 *  This is still a rough estimate.  We will fix the
962 		 *  cases TRAPPED, STOPPED, and CONTINUED later.
963 		 */
964 		if (WCOREDUMP(p->p_xstat)) {
965 			siginfo->si_code = CLD_DUMPED;
966 			siginfo->si_status = WTERMSIG(p->p_xstat);
967 		} else if (WIFSIGNALED(p->p_xstat)) {
968 			siginfo->si_code = CLD_KILLED;
969 			siginfo->si_status = WTERMSIG(p->p_xstat);
970 		} else {
971 			siginfo->si_code = CLD_EXITED;
972 			siginfo->si_status = WEXITSTATUS(p->p_xstat);
973 		}
974 
975 		siginfo->si_pid = p->p_pid;
976 		siginfo->si_uid = p->p_ucred->cr_uid;
977 
978 		/*
979 		 * The si_addr field would be useful additional
980 		 * detail, but apparently the PC value may be lost
981 		 * when we reach this point.  bzero() above sets
982 		 * siginfo->si_addr to NULL.
983 		 */
984 	}
985 
986 	/*
987 	 * There should be no reason to limit resources usage info to
988 	 * exited processes only.  A snapshot about any resources used
989 	 * by a stopped process may be exactly what is needed.
990 	 */
991 	if (wrusage != NULL) {
992 		rup = &wrusage->wru_self;
993 		*rup = p->p_ru;
994 		calcru(p, &rup->ru_utime, &rup->ru_stime);
995 
996 		rup = &wrusage->wru_children;
997 		*rup = p->p_stats->p_cru;
998 		calccru(p, &rup->ru_utime, &rup->ru_stime);
999 	}
1000 
1001 	if (p->p_state == PRS_ZOMBIE) {
1002 		proc_reap(td, p, status, options);
1003 		return (-1);
1004 	}
1005 	PROC_SUNLOCK(p);
1006 	PROC_UNLOCK(p);
1007 	return (1);
1008 }
1009 
1010 int
1011 kern_wait(struct thread *td, pid_t pid, int *status, int options,
1012     struct rusage *rusage)
1013 {
1014 	struct __wrusage wru, *wrup;
1015 	idtype_t idtype;
1016 	id_t id;
1017 	int ret;
1018 
1019 	/*
1020 	 * Translate the special pid values into the (idtype, pid)
1021 	 * pair for kern_wait6.  The WAIT_MYPGRP case is handled by
1022 	 * kern_wait6() on its own.
1023 	 */
1024 	if (pid == WAIT_ANY) {
1025 		idtype = P_ALL;
1026 		id = 0;
1027 	} else if (pid < 0) {
1028 		idtype = P_PGID;
1029 		id = (id_t)-pid;
1030 	} else {
1031 		idtype = P_PID;
1032 		id = (id_t)pid;
1033 	}
1034 
1035 	if (rusage != NULL)
1036 		wrup = &wru;
1037 	else
1038 		wrup = NULL;
1039 
1040 	/*
1041 	 * For backward compatibility we implicitly add flags WEXITED
1042 	 * and WTRAPPED here.
1043 	 */
1044 	options |= WEXITED | WTRAPPED;
1045 	ret = kern_wait6(td, idtype, id, status, options, wrup, NULL);
1046 	if (rusage != NULL)
1047 		*rusage = wru.wru_self;
1048 	return (ret);
1049 }
1050 
1051 int
1052 kern_wait6(struct thread *td, idtype_t idtype, id_t id, int *status,
1053     int options, struct __wrusage *wrusage, siginfo_t *siginfo)
1054 {
1055 	struct proc *p, *q;
1056 	int error, nfound, ret;
1057 
1058 	AUDIT_ARG_VALUE((int)idtype);	/* XXX - This is likely wrong! */
1059 	AUDIT_ARG_PID((pid_t)id);	/* XXX - This may be wrong! */
1060 	AUDIT_ARG_VALUE(options);
1061 
1062 	q = td->td_proc;
1063 
1064 	if ((pid_t)id == WAIT_MYPGRP && (idtype == P_PID || idtype == P_PGID)) {
1065 		PROC_LOCK(q);
1066 		id = (id_t)q->p_pgid;
1067 		PROC_UNLOCK(q);
1068 		idtype = P_PGID;
1069 	}
1070 
1071 	/* If we don't know the option, just return. */
1072 	if ((options & ~(WUNTRACED | WNOHANG | WCONTINUED | WNOWAIT |
1073 	    WEXITED | WTRAPPED | WLINUXCLONE)) != 0)
1074 		return (EINVAL);
1075 	if ((options & (WEXITED | WUNTRACED | WCONTINUED | WTRAPPED)) == 0) {
1076 		/*
1077 		 * We will be unable to find any matching processes,
1078 		 * because there are no known events to look for.
1079 		 * Prefer to return error instead of blocking
1080 		 * indefinitely.
1081 		 */
1082 		return (EINVAL);
1083 	}
1084 
1085 loop:
1086 	if (q->p_flag & P_STATCHILD) {
1087 		PROC_LOCK(q);
1088 		q->p_flag &= ~P_STATCHILD;
1089 		PROC_UNLOCK(q);
1090 	}
1091 	nfound = 0;
1092 	sx_xlock(&proctree_lock);
1093 	LIST_FOREACH(p, &q->p_children, p_sibling) {
1094 		ret = proc_to_reap(td, p, idtype, id, status, options,
1095 		    wrusage, siginfo);
1096 		if (ret == 0)
1097 			continue;
1098 		else if (ret == 1)
1099 			nfound++;
1100 		else
1101 			return (0);
1102 
1103 		PROC_LOCK(p);
1104 		PROC_SLOCK(p);
1105 
1106 		if ((options & WTRAPPED) != 0 &&
1107 		    (p->p_flag & P_TRACED) != 0 &&
1108 		    (p->p_flag & (P_STOPPED_TRACE | P_STOPPED_SIG)) != 0 &&
1109 		    (p->p_suspcount == p->p_numthreads) &&
1110 		    ((p->p_flag & P_WAITED) == 0)) {
1111 			PROC_SUNLOCK(p);
1112 			if ((options & WNOWAIT) == 0)
1113 				p->p_flag |= P_WAITED;
1114 			sx_xunlock(&proctree_lock);
1115 			td->td_retval[0] = p->p_pid;
1116 
1117 			if (status != NULL)
1118 				*status = W_STOPCODE(p->p_xstat);
1119 			if (siginfo != NULL) {
1120 				siginfo->si_status = p->p_xstat;
1121 				siginfo->si_code = CLD_TRAPPED;
1122 			}
1123 			if ((options & WNOWAIT) == 0) {
1124 				PROC_LOCK(q);
1125 				sigqueue_take(p->p_ksi);
1126 				PROC_UNLOCK(q);
1127 			}
1128 
1129 			PROC_UNLOCK(p);
1130 			return (0);
1131 		}
1132 		if ((options & WUNTRACED) != 0 &&
1133 		    (p->p_flag & P_STOPPED_SIG) != 0 &&
1134 		    (p->p_suspcount == p->p_numthreads) &&
1135 		    ((p->p_flag & P_WAITED) == 0)) {
1136 			PROC_SUNLOCK(p);
1137 			if ((options & WNOWAIT) == 0)
1138 				p->p_flag |= P_WAITED;
1139 			sx_xunlock(&proctree_lock);
1140 			td->td_retval[0] = p->p_pid;
1141 
1142 			if (status != NULL)
1143 				*status = W_STOPCODE(p->p_xstat);
1144 			if (siginfo != NULL) {
1145 				siginfo->si_status = p->p_xstat;
1146 				siginfo->si_code = CLD_STOPPED;
1147 			}
1148 			if ((options & WNOWAIT) == 0) {
1149 				PROC_LOCK(q);
1150 				sigqueue_take(p->p_ksi);
1151 				PROC_UNLOCK(q);
1152 			}
1153 
1154 			PROC_UNLOCK(p);
1155 			return (0);
1156 		}
1157 		PROC_SUNLOCK(p);
1158 		if ((options & WCONTINUED) != 0 &&
1159 		    (p->p_flag & P_CONTINUED) != 0) {
1160 			sx_xunlock(&proctree_lock);
1161 			td->td_retval[0] = p->p_pid;
1162 			if ((options & WNOWAIT) == 0) {
1163 				p->p_flag &= ~P_CONTINUED;
1164 				PROC_LOCK(q);
1165 				sigqueue_take(p->p_ksi);
1166 				PROC_UNLOCK(q);
1167 			}
1168 			PROC_UNLOCK(p);
1169 
1170 			if (status != NULL)
1171 				*status = SIGCONT;
1172 			if (siginfo != NULL) {
1173 				siginfo->si_status = SIGCONT;
1174 				siginfo->si_code = CLD_CONTINUED;
1175 			}
1176 			return (0);
1177 		}
1178 		PROC_UNLOCK(p);
1179 	}
1180 
1181 	/*
1182 	 * Look in the orphans list too, to allow the parent to
1183 	 * collect it's child exit status even if child is being
1184 	 * debugged.
1185 	 *
1186 	 * Debugger detaches from the parent upon successful
1187 	 * switch-over from parent to child.  At this point due to
1188 	 * re-parenting the parent loses the child to debugger and a
1189 	 * wait4(2) call would report that it has no children to wait
1190 	 * for.  By maintaining a list of orphans we allow the parent
1191 	 * to successfully wait until the child becomes a zombie.
1192 	 */
1193 	LIST_FOREACH(p, &q->p_orphans, p_orphan) {
1194 		ret = proc_to_reap(td, p, idtype, id, status, options,
1195 		    wrusage, siginfo);
1196 		if (ret == 0)
1197 			continue;
1198 		else if (ret == 1)
1199 			nfound++;
1200 		else
1201 			return (0);
1202 	}
1203 	if (nfound == 0) {
1204 		sx_xunlock(&proctree_lock);
1205 		return (ECHILD);
1206 	}
1207 	if (options & WNOHANG) {
1208 		sx_xunlock(&proctree_lock);
1209 		td->td_retval[0] = 0;
1210 		return (0);
1211 	}
1212 	PROC_LOCK(q);
1213 	sx_xunlock(&proctree_lock);
1214 	if (q->p_flag & P_STATCHILD) {
1215 		q->p_flag &= ~P_STATCHILD;
1216 		error = 0;
1217 	} else
1218 		error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
1219 	PROC_UNLOCK(q);
1220 	if (error)
1221 		return (error);
1222 	goto loop;
1223 }
1224 
1225 /*
1226  * Make process 'parent' the new parent of process 'child'.
1227  * Must be called with an exclusive hold of proctree lock.
1228  */
1229 void
1230 proc_reparent(struct proc *child, struct proc *parent)
1231 {
1232 
1233 	sx_assert(&proctree_lock, SX_XLOCKED);
1234 	PROC_LOCK_ASSERT(child, MA_OWNED);
1235 	if (child->p_pptr == parent)
1236 		return;
1237 
1238 	PROC_LOCK(child->p_pptr);
1239 	sigqueue_take(child->p_ksi);
1240 	PROC_UNLOCK(child->p_pptr);
1241 	LIST_REMOVE(child, p_sibling);
1242 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
1243 
1244 	clear_orphan(child);
1245 	if (child->p_flag & P_TRACED) {
1246 		LIST_INSERT_HEAD(&child->p_pptr->p_orphans, child, p_orphan);
1247 		child->p_flag |= P_ORPHAN;
1248 	}
1249 
1250 	child->p_pptr = parent;
1251 }
1252