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 * 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.
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
38 * @(#)kern_exit.c 8.7 (Berkeley) 2/12/94
39 * $FreeBSD: src/sys/kern/kern_exit.c,v 1.92.2.11 2003/01/13 22:51:16 dillon Exp $
40 * $DragonFly: src/sys/kern/kern_exit.c,v 1.36 2004/06/15 00:30:53 dillon Exp $
43 #include "opt_compat.h"
44 #include "opt_ktrace.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/sysproto.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
52 #include <sys/pioctl.h>
55 #include <sys/vnode.h>
56 #include <sys/resourcevar.h>
57 #include <sys/signalvar.h>
58 #include <sys/ptrace.h>
59 #include <sys/acct.h> /* for acct_process() function prototype */
60 #include <sys/filedesc.h>
65 #include <sys/kern_syscall.h>
66 #include <sys/upcall.h>
70 #include <vm/vm_param.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_zone.h>
75 #include <vm/vm_extern.h>
78 /* Required to be non-static for SysVR4 emulator */
79 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
81 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
84 * callout list for things to do at exit time
88 TAILQ_ENTRY(exitlist) next;
91 TAILQ_HEAD(exit_list_head, exitlist);
92 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
98 * SYS_EXIT_ARGS(int rval)
101 sys_exit(struct sys_exit_args *uap)
103 exit1(W_EXITCODE(uap->rval, 0));
108 * Exit: deallocate address space and other resources, change proc state
109 * to zombie, and unlink proc from allproc and parent's lists. Save exit
110 * status and rusage for wait(). Check for child processes and orphan them.
115 struct proc *p = curproc;
122 printf("init died (signal %d, exit %d)\n",
123 WTERMSIG(rv), WEXITSTATUS(rv));
124 panic("Going nowhere without my init!");
127 sysmsg_rundown(p, 1);
128 caps_exit(p->p_thread);
131 /* are we a task leader? */
132 if(p == p->p_leader) {
133 struct kill_args killArgs;
134 killArgs.signum = SIGKILL;
137 killArgs.pid = q->p_pid;
139 * The interface for kill is better
140 * than the internal signal
147 tsleep((caddr_t)p, 0, "exit1", 0);
153 STOPEVENT(p, S_EXIT, rv);
154 wakeup(&p->p_stype); /* Wakeup anyone in procfs' PIOCWAIT */
157 * Check if any loadable modules need anything done at process exit.
158 * e.g. SYSV IPC stuff
159 * XXX what if one of these generates an error?
161 TAILQ_FOREACH(ep, &exit_list, next)
162 (*ep->function)(p->p_thread);
164 if (p->p_flag & P_PROFIL)
166 MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
169 * If parent is waiting for us to exit or exec,
170 * P_PPWAIT is set; we will wakeup the parent below.
172 p->p_flag &= ~(P_TRACED | P_PPWAIT);
173 p->p_flag |= P_WEXIT;
174 SIGEMPTYSET(p->p_siglist);
175 if (timevalisset(&p->p_realtimer.it_value))
176 untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
179 * Reset any sigio structures pointing to us as a result of
180 * F_SETOWN with our pid.
182 funsetownlst(&p->p_sigiolst);
185 * Close open files and release open-file table.
191 if(p->p_leader->p_peers) {
193 while(q->p_peers != p)
195 q->p_peers = p->p_peers;
196 wakeup((caddr_t)p->p_leader);
200 * XXX Shutdown SYSV semaphores
204 KKASSERT(p->p_numposixlocks == 0);
206 /* The next two chunks should probably be moved to vmspace_exit. */
210 * Release upcalls associated with this process
216 * Release user portion of address space.
217 * This releases references to vnodes,
218 * which could cause I/O if the file has been unlinked.
219 * Need to do this early enough that we can still sleep.
220 * Can't free the entire vmspace as the kernel stack
221 * may be mapped within that space also.
223 * Processes sharing the same vmspace may exit in one order, and
224 * get cleaned up by vmspace_exit() in a different order. The
225 * last exiting process to reach this point releases as much of
226 * the environment as it can, and the last process cleaned up
227 * by vmspace_exit() (which decrements exitingcnt) cleans up the
231 if (--vm->vm_refcnt == 0) {
233 pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
235 (void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
239 if (SESS_LEADER(p)) {
240 struct session *sp = p->p_session;
245 * We are the controlling process. Signal the
246 * foreground process group, drain the controlling
247 * terminal, and revoke access to the controlling
250 * NOTE: while waiting for the process group to exit
251 * it is possible that one of the processes in the
252 * group will revoke the tty, so we have to recheck.
254 if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
255 if (sp->s_ttyp->t_pgrp)
256 pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
257 (void) ttywait(sp->s_ttyp);
259 * The tty could have been revoked
262 if ((vp = sp->s_ttyvp) != NULL) {
264 VOP_REVOKE(vp, REVOKEALL);
268 if ((vp = sp->s_ttyvp) != NULL) {
273 * s_ttyp is not zero'd; we use this to indicate
274 * that the session once had a controlling terminal.
275 * (for logging and informational purposes)
280 fixjobc(p, p->p_pgrp, 0);
281 (void)acct_process(p);
286 p->p_traceflag = 0; /* don't trace the vrele() */
287 if ((vtmp = p->p_tracep) != NULL) {
293 * Release reference to text vnode
295 if ((vtmp = p->p_textvp) != NULL) {
301 * Once we set SZOMB the process can get reaped. The wait1 code
302 * will also wait for TDF_RUNNING to be cleared in the thread's flags,
303 * indicating that it has been completely switched out.
307 * Remove proc from allproc queue and pidhash chain.
308 * Place onto zombproc. Unlink from parent's child list.
310 LIST_REMOVE(p, p_list);
311 LIST_INSERT_HEAD(&zombproc, p, p_list);
314 LIST_REMOVE(p, p_hash);
316 q = LIST_FIRST(&p->p_children);
317 if (q) /* only need this if any child is S_ZOMB */
318 wakeup((caddr_t) initproc);
319 for (; q != 0; q = nq) {
320 nq = LIST_NEXT(q, p_sibling);
321 LIST_REMOVE(q, p_sibling);
322 LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
323 q->p_pptr = initproc;
324 q->p_sigparent = SIGCHLD;
326 * Traced processes are killed
327 * since their existence means someone is screwing up.
329 if (q->p_flag & P_TRACED) {
330 q->p_flag &= ~P_TRACED;
336 * Save exit status and final rusage info, adding in child rusage
337 * info and self times.
340 *p->p_ru = p->p_stats->p_ru;
341 calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
342 ruadd(p->p_ru, &p->p_stats->p_cru);
345 * notify interested parties of our demise.
347 KNOTE(&p->p_klist, NOTE_EXIT);
350 * Notify parent that we're gone. If parent has the PS_NOCLDWAIT
351 * flag set, notify process 1 instead (and hope it will handle
354 if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
355 struct proc *pp = p->p_pptr;
356 proc_reparent(p, initproc);
358 * If this was the last child of our parent, notify
359 * parent, so in case he was wait(2)ing, he will
362 if (LIST_EMPTY(&pp->p_children))
366 if (p->p_sigparent && p->p_pptr != initproc) {
367 psignal(p->p_pptr, p->p_sigparent);
369 psignal(p->p_pptr, SIGCHLD);
372 wakeup((caddr_t)p->p_pptr);
374 /* move this to cpu_exit */
375 p->p_thread->td_pcb->pcb_saveacc.faddr = (float *)NULL;
378 * cpu_exit is responsible for clearing curproc, since
379 * it is heavily integrated with the thread/switching sequence.
381 * Other substructures are freed from wait().
383 if (--p->p_limit->p_refcnt == 0) {
384 FREE(p->p_limit, M_SUBPROC);
389 * Release the current user process designation on the process so
390 * the userland scheduler can work in someone else.
395 * Finally, call machine-dependent code to release the remaining
396 * resources including address space, the kernel stack and pcb.
397 * The address space is released by "vmspace_free(p->p_vmspace)";
398 * This is machine-dependent, as we may have to change stacks
399 * or ensure that the current one isn't reallocated before we
400 * finish. cpu_exit will end with a call to cpu_switch(), finishing
401 * our execution (pun intended).
407 wait4(struct wait_args *uap)
409 struct rusage rusage;
412 error = kern_wait(uap->pid, uap->status ? &status : NULL,
413 uap->options, uap->rusage ? &rusage : NULL, &uap->sysmsg_fds[0]);
415 if (error == 0 && uap->status)
416 error = copyout(&status, uap->status, sizeof(*uap->status));
417 if (error == 0 && uap->rusage)
418 error = copyout(&rusage, uap->rusage, sizeof(*uap->rusage));
425 * wait_args(int pid, int *status, int options, struct rusage *rusage)
428 kern_wait(pid_t pid, int *status, int options, struct rusage *rusage, int *res)
430 struct thread *td = curthread;
431 struct proc *q = td->td_proc;
437 if (options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
441 LIST_FOREACH(p, &q->p_children, p_sibling) {
442 if (pid != WAIT_ANY &&
443 p->p_pid != pid && p->p_pgid != -pid)
446 /* This special case handles a kthread spawned by linux_clone
447 * (see linux_misc.c). The linux_wait4 and linux_waitpid functions
448 * need to be able to distinguish between waiting on a process and
449 * waiting on a thread. It is a thread if p_sigparent is not SIGCHLD,
450 * and the WLINUXCLONE option signifies we want to wait for threads
453 if ((p->p_sigparent != SIGCHLD) ^ ((options & WLINUXCLONE) != 0))
457 if (p->p_stat == SZOMB) {
459 * The process's thread may still be in the middle
460 * of switching away, we can't rip its stack out from
461 * under it until TDF_RUNNING clears!
463 * YYY no wakeup occurs so we depend on the timeout.
465 if ((p->p_thread->td_flags & TDF_RUNNING) != 0) {
466 tsleep(p->p_thread, 0, "reap", 1);
471 * Other kernel threads may be in the middle of
472 * accessing the proc. For example, kern/kern_proc.c
473 * could be blocked writing proc data to a sysctl.
474 * At the moment, if this occurs, we are not woken
475 * up and rely on a one-second retry.
479 tsleep(p, 0, "reap2", hz);
481 lwkt_wait_free(p->p_thread);
484 * Charge the parent for the child's change in
485 * estimated cpu as of when the child exits to
486 * account for batch scripts, large make's, etc.
489 if (p->p_estcpu > p->p_estcpu_fork) {
490 q->p_estcpu = ESTCPULIM(q->p_estcpu +
491 p->p_estcpu - p->p_estcpu_fork);
495 /* Take care of our return values. */
498 *status = p->p_xstat;
502 * If we got the child via a ptrace 'attach',
503 * we need to give it back to the old parent.
505 if (p->p_oppid && (t = pfind(p->p_oppid))) {
513 ruadd(&q->p_stats->p_cru, p->p_ru);
514 FREE(p->p_ru, M_ZOMBIE);
518 * Decrement the count of procs running with this uid.
520 chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
523 * Free up credentials.
529 * Remove unused arguments
531 if (p->p_args && --p->p_args->ar_ref == 0)
532 FREE(p->p_args, M_PARGS);
535 * Finally finished with old proc entry.
536 * Unlink it from its process group and free it.
539 LIST_REMOVE(p, p_list); /* off zombproc */
540 LIST_REMOVE(p, p_sibling);
542 if (--p->p_procsig->ps_refcnt == 0) {
543 if (p->p_sigacts != &p->p_addr->u_sigacts)
544 FREE(p->p_sigacts, M_SUBPROC);
545 FREE(p->p_procsig, M_SUBPROC);
554 if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
555 (p->p_flag & P_TRACED || options & WUNTRACED)) {
556 p->p_flag |= P_WAITED;
560 *status = W_STOPCODE(p->p_xstat);
561 /* Zero rusage so we get something consistent. */
563 bzero(rusage, sizeof(rusage));
569 if (options & WNOHANG) {
573 error = tsleep((caddr_t)q, PCATCH, "wait", 0);
580 * make process 'parent' the new parent of process 'child'.
583 proc_reparent(child, parent)
588 if (child->p_pptr == parent)
591 LIST_REMOVE(child, p_sibling);
592 LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
593 child->p_pptr = parent;
597 * The next two functions are to handle adding/deleting items on the
601 * Take the arguments given and put them onto the exit callout list,
602 * However first make sure that it's not already there.
603 * returns 0 on success.
608 exitlist_fn function;
613 /* Be noisy if the programmer has lost track of things */
614 if (rm_at_exit(function))
615 printf("WARNING: exit callout entry (%p) already present\n",
618 ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
621 ep->function = function;
622 TAILQ_INSERT_TAIL(&exit_list, ep, next);
627 * Scan the exit callout list for the given item and remove it.
628 * Returns the number of items removed (0 or 1)
632 exitlist_fn function;
636 TAILQ_FOREACH(ep, &exit_list, next) {
637 if (ep->function == function) {
638 TAILQ_REMOVE(&exit_list, ep, next);
646 void check_sigacts (void)
648 struct proc *p = curproc;
652 if (p->p_procsig->ps_refcnt == 1 &&
653 p->p_sigacts != &p->p_addr->u_sigacts) {
656 p->p_addr->u_sigacts = *pss;
657 p->p_sigacts = &p->p_addr->u_sigacts;
659 FREE(pss, M_SUBPROC);