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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
34 * @(#)kern_exit.c 8.7 (Berkeley) 2/12/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_compat.h"
41 #include "opt_kdtrace.h"
42 #include "opt_ktrace.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/sysproto.h>
48 #include <sys/eventhandler.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
52 #include <sys/mutex.h>
54 #include <sys/pioctl.h>
58 #include <sys/vmmeter.h>
59 #include <sys/vnode.h>
60 #include <sys/resourcevar.h>
62 #include <sys/signalvar.h>
63 #include <sys/sched.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/syslog.h>
67 #include <sys/ptrace.h>
68 #include <sys/acct.h> /* for acct_process() function prototype */
69 #include <sys/filedesc.h>
74 #include <sys/ktrace.h>
77 #include <security/audit/audit.h>
78 #include <security/mac/mac_framework.h>
81 #include <vm/vm_extern.h>
82 #include <vm/vm_param.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_page.h>
89 #include <sys/dtrace_bsd.h>
90 dtrace_execexit_func_t dtrace_fasttrap_exit;
93 SDT_PROVIDER_DECLARE(proc);
94 SDT_PROBE_DEFINE(proc, kernel, , exit);
95 SDT_PROBE_ARGTYPE(proc, kernel, , exit, 0, "int");
97 /* Required to be non-static for SysVR4 emulator */
98 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
100 /* Hook for NFS teardown procedure. */
101 void (*nlminfo_release_p)(struct proc *p);
104 * exit -- death of process.
107 sys_exit(struct thread *td, struct sys_exit_args *uap)
110 exit1(td, W_EXITCODE(uap->rval, 0));
115 * Exit: deallocate address space and other resources, change proc state to
116 * zombie, and unlink proc from allproc and parent's lists. Save exit status
117 * and rusage for wait(). Check for child processes and orphan them.
120 exit1(struct thread *td, int rv)
122 struct proc *p, *nq, *q;
127 struct vnode *tracevp;
128 struct ucred *tracecred;
134 * Drop Giant if caller has it. Eventually we should warn about
135 * being called with Giant held.
137 while (mtx_owned(&Giant))
142 printf("init died (signal %d, exit %d)\n",
143 WTERMSIG(rv), WEXITSTATUS(rv));
144 panic("Going nowhere without my init!");
148 * MUST abort all other threads before proceeding past here.
151 if (p->p_flag & P_HADTHREADS) {
154 * First check if some other thread got here before us..
155 * if so, act apropriatly, (exit or suspend);
157 thread_suspend_check(0);
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.
176 if (thread_single(SINGLE_EXIT))
180 * All other activity in this process is now stopped.
181 * Threading support has been turned off.
184 KASSERT(p->p_numthreads == 1,
185 ("exit1: proc %p exiting with %d threads", p, p->p_numthreads));
187 * Wakeup anyone in procfs' PIOCWAIT. They should have a hold
188 * on our vmspace, so we should block below until they have
189 * released their reference to us. Note that if they have
190 * requested S_EXIT stops we will block here until they ack
193 _STOPEVENT(p, S_EXIT, rv);
196 * Note that we are exiting and do another wakeup of anyone in
197 * PIOCWAIT in case they aren't listening for S_EXIT stops or
198 * decided to wait again after we told them we are exiting.
200 p->p_flag |= P_WEXIT;
204 * Wait for any processes that have a hold on our vmspace to
205 * release their reference.
207 while (p->p_lock > 0)
208 msleep(&p->p_lock, &p->p_mtx, PWAIT, "exithold", 0);
211 /* Drain the limit callout while we don't have the proc locked */
212 callout_drain(&p->p_limco);
216 * The Sun BSM exit token contains two components: an exit status as
217 * passed to exit(), and a return value to indicate what sort of exit
218 * it was. The exit status is WEXITSTATUS(rv), but it's not clear
219 * what the return value is.
221 AUDIT_ARG(exit, WEXITSTATUS(rv), 0);
222 AUDIT_SYSCALL_EXIT(0, td);
225 /* Are we a task leader? */
226 if (p == p->p_leader) {
227 mtx_lock(&ppeers_lock);
235 while (p->p_peers != NULL)
236 msleep(p, &ppeers_lock, PWAIT, "exit1", 0);
237 mtx_unlock(&ppeers_lock);
241 * Check if any loadable modules need anything done at process exit.
242 * E.g. SYSV IPC stuff
243 * XXX what if one of these generates an error?
245 EVENTHANDLER_INVOKE(process_exit, p);
248 * If parent is waiting for us to exit or exec,
249 * P_PPWAIT is set; we will wakeup the parent below.
253 p->p_flag &= ~(P_TRACED | P_PPWAIT);
256 * Stop the real interval timer. If the handler is currently
257 * executing, prevent it from rearming itself and let it finish.
259 if (timevalisset(&p->p_realtimer.it_value) &&
260 callout_stop(&p->p_itcallout) == 0) {
261 timevalclear(&p->p_realtimer.it_interval);
262 msleep(&p->p_itcallout, &p->p_mtx, PWAIT, "ritwait", 0);
263 KASSERT(!timevalisset(&p->p_realtimer.it_value),
264 ("realtime timer is still armed"));
269 * Reset any sigio structures pointing to us as a result of
270 * F_SETOWN with our pid.
272 funsetownlst(&p->p_sigiolst);
275 * If this process has an nlminfo data area (for lockd), release it
277 if (nlminfo_release_p != NULL && p->p_nlminfo != NULL)
278 (*nlminfo_release_p)(p);
281 * Close open files and release open-file table.
287 * If this thread tickled GEOM, we need to wait for the giggling to
288 * stop before we return to userland
290 if (td->td_pflags & TDP_GEOM)
294 * Remove ourself from our leader's peer list and wake our leader.
296 mtx_lock(&ppeers_lock);
297 if (p->p_leader->p_peers) {
299 while (q->p_peers != p)
301 q->p_peers = p->p_peers;
304 mtx_unlock(&ppeers_lock);
308 mtx_lock(&Giant); /* XXX TTY */
309 sx_xlock(&proctree_lock);
310 if (SESS_LEADER(p)) {
316 * Controlling process.
317 * Signal foreground pgrp,
318 * drain controlling terminal
319 * and revoke access to controlling terminal.
321 if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
323 if (sp->s_ttyp->t_pgrp) {
324 PGRP_LOCK(sp->s_ttyp->t_pgrp);
325 pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
326 PGRP_UNLOCK(sp->s_ttyp->t_pgrp);
328 /* XXX tp should be locked. */
329 sx_xunlock(&proctree_lock);
331 sx_xlock(&proctree_lock);
333 * The tty could have been revoked
338 SESS_LOCK(p->p_session);
340 SESS_UNLOCK(p->p_session);
341 sx_xunlock(&proctree_lock);
342 VOP_LOCK(ttyvp, LK_EXCLUSIVE, td);
343 VOP_REVOKE(ttyvp, REVOKEALL);
345 sx_xlock(&proctree_lock);
350 SESS_LOCK(p->p_session);
352 SESS_UNLOCK(p->p_session);
356 * s_ttyp is not zero'd; we use this to indicate
357 * that the session once had a controlling terminal.
358 * (for logging and informational purposes)
361 SESS_LOCK(p->p_session);
363 SESS_UNLOCK(p->p_session);
365 fixjobc(p, p->p_pgrp, 0);
366 sx_xunlock(&proctree_lock);
367 (void)acct_process(td);
371 * Disable tracing, then drain any pending records and release
374 if (p->p_traceflag != 0) {
376 mtx_lock(&ktrace_mtx);
378 mtx_unlock(&ktrace_mtx);
382 mtx_lock(&ktrace_mtx);
383 tracevp = p->p_tracevp;
385 tracecred = p->p_tracecred;
386 p->p_tracecred = NULL;
387 mtx_unlock(&ktrace_mtx);
389 if (tracevp != NULL) {
390 locked = VFS_LOCK_GIANT(tracevp->v_mount);
392 VFS_UNLOCK_GIANT(locked);
394 if (tracecred != NULL)
399 * Release reference to text vnode
401 if ((vtmp = p->p_textvp) != NULL) {
403 locked = VFS_LOCK_GIANT(vtmp->v_mount);
405 VFS_UNLOCK_GIANT(locked);
409 * Release our limits structure.
418 * Remove proc from allproc queue and pidhash chain.
419 * Place onto zombproc. Unlink from parent's child list.
421 sx_xlock(&allproc_lock);
422 LIST_REMOVE(p, p_list);
423 LIST_INSERT_HEAD(&zombproc, p, p_list);
424 LIST_REMOVE(p, p_hash);
425 sx_xunlock(&allproc_lock);
428 * Call machine-dependent code to release any
429 * machine-dependent resources other than the address space.
430 * The address space is released by "vmspace_exitfree(p)" in
435 WITNESS_WARN(WARN_PANIC, NULL, "process (pid %d) exiting", p->p_pid);
438 * Reparent all of our children to init.
440 sx_xlock(&proctree_lock);
441 q = LIST_FIRST(&p->p_children);
442 if (q != NULL) /* only need this if any child is S_ZOMB */
444 for (; q != NULL; q = nq) {
445 nq = LIST_NEXT(q, p_sibling);
447 proc_reparent(q, initproc);
448 q->p_sigparent = SIGCHLD;
450 * Traced processes are killed
451 * since their existence means someone is screwing up.
453 if (q->p_flag & P_TRACED) {
454 q->p_flag &= ~(P_TRACED | P_STOPPED_TRACE);
460 /* Save exit status. */
465 /* In case we are jailed tell the prison that we are gone. */
466 if (jailed(p->p_ucred))
467 prison_proc_free(p->p_ucred->cr_prison);
471 * Tell the DTrace fasttrap provider about the exit if it
472 * has declared an interest.
474 if (dtrace_fasttrap_exit)
475 dtrace_fasttrap_exit(p);
479 * Notify interested parties of our demise.
481 KNOTE_LOCKED(&p->p_klist, NOTE_EXIT);
484 int reason = CLD_EXITED;
487 else if (WIFSIGNALED(rv))
489 SDT_PROBE(proc, kernel, , exit, reason, 0, 0, 0, 0);
492 * Just delete all entries in the p_klist. At this point we won't
493 * report any more events, and there are nasty race conditions that
494 * can beat us if we don't.
496 knlist_clear(&p->p_klist, 1);
499 * Notify parent that we're gone. If parent has the PS_NOCLDWAIT
500 * flag set, or if the handler is set to SIG_IGN, notify process
501 * 1 instead (and hope it will handle this situation).
503 PROC_LOCK(p->p_pptr);
504 mtx_lock(&p->p_pptr->p_sigacts->ps_mtx);
505 if (p->p_pptr->p_sigacts->ps_flag & (PS_NOCLDWAIT | PS_CLDSIGIGN)) {
508 mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
511 proc_reparent(p, initproc);
512 p->p_sigparent = SIGCHLD;
513 PROC_LOCK(p->p_pptr);
515 * If this was the last child of our parent, notify
516 * parent, so in case he was wait(2)ing, he will
519 if (LIST_EMPTY(&pp->p_children))
522 mtx_unlock(&p->p_pptr->p_sigacts->ps_mtx);
524 if (p->p_pptr == initproc)
525 psignal(p->p_pptr, SIGCHLD);
526 else if (p->p_sigparent != 0) {
527 if (p->p_sigparent == SIGCHLD)
529 else /* LINUX thread */
530 psignal(p->p_pptr, p->p_sigparent);
532 sx_xunlock(&proctree_lock);
535 * The state PRS_ZOMBIE prevents other proesses from sending
536 * signal to the process, to avoid memory leak, we free memory
537 * for signal queue at the time when the state is set.
539 sigqueue_flush(&p->p_sigqueue);
540 sigqueue_flush(&td->td_sigqueue);
543 * We have to wait until after acquiring all locks before
544 * changing p_state. We need to avoid all possible context
545 * switches (including ones from blocking on a mutex) while
546 * marked as a zombie. We also have to set the zombie state
547 * before we release the parent process' proc lock to avoid
548 * a lost wakeup. So, we first call wakeup, then we grab the
549 * sched lock, update the state, and release the parent process'
553 PROC_SLOCK(p->p_pptr);
554 sched_exit(p->p_pptr, td);
555 PROC_SUNLOCK(p->p_pptr);
557 p->p_state = PRS_ZOMBIE;
558 PROC_UNLOCK(p->p_pptr);
561 * Hopefully no one will try to deliver a signal to the process this
564 knlist_destroy(&p->p_klist);
567 * Save our children's rusage information in our exit rusage.
569 ruadd(&p->p_ru, &p->p_rux, &p->p_stats->p_cru, &p->p_crux);
572 * Make sure the scheduler takes this thread out of its tables etc.
573 * This will also release this thread's reference to the ucred.
574 * Other thread parts to release include pcb bits and such.
580 #ifndef _SYS_SYSPROTO_H_
589 abort2(struct thread *td, struct abort2_args *uap)
591 struct proc *p = td->td_proc;
596 error = 0; /* satisfy compiler */
599 * Do it right now so we can log either proper call of abort2(), or
600 * note, that invalid argument was passed. 512 is big enough to
601 * handle 16 arguments' descriptions with additional comments.
603 sb = sbuf_new(NULL, NULL, 512, SBUF_FIXEDLEN);
605 sbuf_printf(sb, "%s(pid %d uid %d) aborted: ",
606 p->p_comm, p->p_pid, td->td_ucred->cr_uid);
608 * Since we can't return from abort2(), send SIGKILL in cases, where
609 * abort2() was called improperly
612 /* Prevent from DoSes from user-space. */
613 if (uap->nargs < 0 || uap->nargs > 16)
615 if (uap->nargs > 0) {
616 if (uap->args == NULL)
618 error = copyin(uap->args, uargs, uap->nargs * sizeof(void *));
623 * Limit size of 'reason' string to 128. Will fit even when
624 * maximal number of arguments was chosen to be logged.
626 if (uap->why != NULL) {
627 error = sbuf_copyin(sb, uap->why, 128);
631 sbuf_printf(sb, "(null)");
633 if (uap->nargs > 0) {
634 sbuf_printf(sb, "(");
635 for (i = 0;i < uap->nargs; i++)
636 sbuf_printf(sb, "%s%p", i == 0 ? "" : ", ", uargs[i]);
637 sbuf_printf(sb, ")");
640 * Final stage: arguments were proper, string has been
641 * successfully copied from userspace, and copying pointers
642 * from user-space succeed.
646 if (sig == SIGKILL) {
648 sbuf_printf(sb, " (Reason text inaccessible)");
652 log(LOG_INFO, "%s", sbuf_data(sb));
654 exit1(td, W_EXITCODE(0, sig));
661 * The dirty work is handled by kern_wait().
664 owait(struct thread *td, struct owait_args *uap __unused)
668 error = kern_wait(td, WAIT_ANY, &status, 0, NULL);
670 td->td_retval[1] = status;
673 #endif /* COMPAT_43 */
676 * The dirty work is handled by kern_wait().
679 wait4(struct thread *td, struct wait_args *uap)
681 struct rusage ru, *rup;
684 if (uap->rusage != NULL)
688 error = kern_wait(td, uap->pid, &status, uap->options, rup);
689 if (uap->status != NULL && error == 0)
690 error = copyout(&status, uap->status, sizeof(status));
691 if (uap->rusage != NULL && error == 0)
692 error = copyout(&ru, uap->rusage, sizeof(struct rusage));
697 kern_wait(struct thread *td, pid_t pid, int *status, int options,
698 struct rusage *rusage)
700 struct proc *p, *q, *t;
711 if (options &~ (WUNTRACED|WNOHANG|WCONTINUED|WNOWAIT|WLINUXCLONE))
714 if (q->p_flag & P_STATCHILD) {
716 q->p_flag &= ~P_STATCHILD;
720 sx_xlock(&proctree_lock);
721 LIST_FOREACH(p, &q->p_children, p_sibling) {
723 if (pid != WAIT_ANY &&
724 p->p_pid != pid && p->p_pgid != -pid) {
728 if (p_canwait(td, p)) {
734 * This special case handles a kthread spawned by linux_clone
735 * (see linux_misc.c). The linux_wait4 and linux_waitpid
736 * functions need to be able to distinguish between waiting
737 * on a process and waiting on a thread. It is a thread if
738 * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
739 * signifies we want to wait for threads and not processes.
741 if ((p->p_sigparent != SIGCHLD) ^
742 ((options & WLINUXCLONE) != 0)) {
749 if (p->p_state == PRS_ZOMBIE) {
752 calcru(p, &rusage->ru_utime, &rusage->ru_stime);
755 td->td_retval[0] = p->p_pid;
757 *status = p->p_xstat; /* convert to int */
758 if (options & WNOWAIT) {
761 * Only poll, returning the status.
762 * Caller does not wish to release the proc
766 sx_xunlock(&proctree_lock);
771 sigqueue_take(p->p_ksi);
776 * If we got the child via a ptrace 'attach',
777 * we need to give it back to the old parent.
779 if (p->p_oppid && (t = pfind(p->p_oppid)) != NULL) {
784 tdsignal(t, NULL, SIGCHLD, p->p_ksi);
787 sx_xunlock(&proctree_lock);
792 * Remove other references to this process to ensure
793 * we have an exclusive reference.
795 sx_xlock(&allproc_lock);
796 LIST_REMOVE(p, p_list); /* off zombproc */
797 sx_xunlock(&allproc_lock);
798 LIST_REMOVE(p, p_sibling);
800 sx_xunlock(&proctree_lock);
803 * As a side effect of this lock, we know that
804 * all other writes to this proc are visible now, so
805 * no more locking is needed for p.
808 p->p_xstat = 0; /* XXX: why? */
811 ruadd(&q->p_stats->p_cru, &q->p_crux, &p->p_ru,
816 * Decrement the count of procs running with this uid.
818 (void)chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
821 * Free credentials, arguments, and sigacts.
825 pargs_drop(p->p_args);
827 sigacts_free(p->p_sigacts);
831 * Do any thread-system specific cleanups.
836 * Give vm and machine-dependent layer a chance
837 * to free anything that cpu_exit couldn't
838 * release while still running in process context.
844 KASSERT(FIRST_THREAD_IN_PROC(p),
845 ("kern_wait: no residual thread!"));
846 uma_zfree(proc_zone, p);
847 sx_xlock(&allproc_lock);
849 sx_xunlock(&allproc_lock);
852 if ((p->p_flag & P_STOPPED_SIG) &&
853 (p->p_suspcount == p->p_numthreads) &&
854 (p->p_flag & P_WAITED) == 0 &&
855 (p->p_flag & P_TRACED || options & WUNTRACED)) {
857 p->p_flag |= P_WAITED;
858 sx_xunlock(&proctree_lock);
859 td->td_retval[0] = p->p_pid;
861 *status = W_STOPCODE(p->p_xstat);
864 sigqueue_take(p->p_ksi);
871 if (options & WCONTINUED && (p->p_flag & P_CONTINUED)) {
872 sx_xunlock(&proctree_lock);
873 td->td_retval[0] = p->p_pid;
874 p->p_flag &= ~P_CONTINUED;
877 sigqueue_take(p->p_ksi);
888 sx_xunlock(&proctree_lock);
891 if (options & WNOHANG) {
892 sx_xunlock(&proctree_lock);
893 td->td_retval[0] = 0;
897 sx_xunlock(&proctree_lock);
898 if (q->p_flag & P_STATCHILD) {
899 q->p_flag &= ~P_STATCHILD;
902 error = msleep(q, &q->p_mtx, PWAIT | PCATCH, "wait", 0);
910 * Make process 'parent' the new parent of process 'child'.
911 * Must be called with an exclusive hold of proctree lock.
914 proc_reparent(struct proc *child, struct proc *parent)
917 sx_assert(&proctree_lock, SX_XLOCKED);
918 PROC_LOCK_ASSERT(child, MA_OWNED);
919 if (child->p_pptr == parent)
922 PROC_LOCK(child->p_pptr);
923 sigqueue_take(child->p_ksi);
924 PROC_UNLOCK(child->p_pptr);
925 LIST_REMOVE(child, p_sibling);
926 LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
927 child->p_pptr = parent;