Merge from vendor branch NTPD:
[dragonfly.git] / sys / kern / kern_exit.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)kern_exit.c 8.7 (Berkeley) 2/12/94
39  * $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.39 2004/10/12 19:20:46 dillon Exp $
41  */
42
43 #include "opt_compat.h"
44 #include "opt_ktrace.h"
45
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>
51 #include <sys/proc.h>
52 #include <sys/pioctl.h>
53 #include <sys/tty.h>
54 #include <sys/wait.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>
61 #include <sys/shm.h>
62 #include <sys/sem.h>
63 #include <sys/aio.h>
64 #include <sys/jail.h>
65 #include <sys/kern_syscall.h>
66 #include <sys/upcall.h>
67 #include <sys/caps.h>
68
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <sys/lock.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_zone.h>
75 #include <vm/vm_extern.h>
76 #include <sys/user.h>
77
78 /* Required to be non-static for SysVR4 emulator */
79 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
80
81 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
82
83 /*
84  * callout list for things to do at exit time
85  */
86 struct exitlist {
87         exitlist_fn function;
88         TAILQ_ENTRY(exitlist) next;
89 };
90
91 TAILQ_HEAD(exit_list_head, exitlist);
92 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
93
94 /*
95  * exit --
96  *      Death of process.
97  *
98  * SYS_EXIT_ARGS(int rval)
99  */
100 void
101 sys_exit(struct sys_exit_args *uap)
102 {
103         exit1(W_EXITCODE(uap->rval, 0));
104         /* NOTREACHED */
105 }
106
107 /*
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.
111  */
112 void
113 exit1(int rv)
114 {
115         struct proc *p = curproc;
116         struct proc *q, *nq;
117         struct vmspace *vm;
118         struct vnode *vtmp;
119         struct exitlist *ep;
120
121         if (p->p_pid == 1) {
122                 printf("init died (signal %d, exit %d)\n",
123                     WTERMSIG(rv), WEXITSTATUS(rv));
124                 panic("Going nowhere without my init!");
125         }
126
127         sysmsg_rundown(p, 1);
128         caps_exit(p->p_thread);
129         aio_proc_rundown(p);
130
131         /* are we a task leader? */
132         if(p == p->p_leader) {
133                 struct kill_args killArgs;
134                 killArgs.signum = SIGKILL;
135                 q = p->p_peers;
136                 while(q) {
137                         killArgs.pid = q->p_pid;
138                         /*
139                          * The interface for kill is better
140                          * than the internal signal
141                          */
142                         kill(&killArgs);
143                         nq = q;
144                         q = q->p_peers;
145                 }
146                 while (p->p_peers) 
147                   tsleep((caddr_t)p, 0, "exit1", 0);
148         } 
149
150 #ifdef PGINPROF
151         vmsizmon();
152 #endif
153         STOPEVENT(p, S_EXIT, rv);
154         wakeup(&p->p_stype);    /* Wakeup anyone in procfs' PIOCWAIT */
155
156         /* 
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?
160          */
161         TAILQ_FOREACH(ep, &exit_list, next) 
162                 (*ep->function)(p->p_thread);
163
164         if (p->p_flag & P_PROFIL)
165                 stopprofclock(p);
166         MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
167                 M_ZOMBIE, M_WAITOK);
168         /*
169          * If parent is waiting for us to exit or exec,
170          * P_PPWAIT is set; we will wakeup the parent below.
171          */
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                 callout_stop(&p->p_ithandle);
177
178         /*
179          * Reset any sigio structures pointing to us as a result of
180          * F_SETOWN with our pid.
181          */
182         funsetownlst(&p->p_sigiolst);
183
184         /*
185          * Close open files and release open-file table.
186          * This may block!
187          */
188         fdfree(p);
189         p->p_fd = NULL;
190
191         if(p->p_leader->p_peers) {
192                 q = p->p_leader;
193                 while(q->p_peers != p)
194                         q = q->p_peers;
195                 q->p_peers = p->p_peers;
196                 wakeup((caddr_t)p->p_leader);
197         }
198
199         /*
200          * XXX Shutdown SYSV semaphores
201          */
202         semexit(p);
203
204         KKASSERT(p->p_numposixlocks == 0);
205
206         /* The next two chunks should probably be moved to vmspace_exit. */
207         vm = p->p_vmspace;
208
209         /*
210          * Release upcalls associated with this process
211          */
212         if (vm->vm_upcalls)
213                 upc_release(vm, p);
214
215         /*
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.
222          *
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
228          * remainder.
229          */
230         ++vm->vm_exitingcnt;
231         if (--vm->vm_refcnt == 0) {
232                 shmexit(vm);
233                 pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
234                     VM_MAXUSER_ADDRESS);
235                 (void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
236                     VM_MAXUSER_ADDRESS);
237         }
238
239         if (SESS_LEADER(p)) {
240                 struct session *sp = p->p_session;
241                 struct vnode *vp;
242
243                 if (sp->s_ttyvp) {
244                         /*
245                          * We are the controlling process.  Signal the 
246                          * foreground process group, drain the controlling
247                          * terminal, and revoke access to the controlling
248                          * terminal.
249                          *
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.
253                          */
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);
258                                 /*
259                                  * The tty could have been revoked
260                                  * if we blocked.
261                                  */
262                                 if ((vp = sp->s_ttyvp) != NULL) {
263                                         ttyclosesession(sp, 0);
264                                         if (vx_lock(vp) == 0) {
265                                                 VOP_REVOKE(vp, REVOKEALL);
266                                                 vx_unlock(vp);
267                                         }
268                                         vrele(vp);      /* s_ttyvp ref */
269                                 }
270                         }
271                         /*
272                          * Release the tty.  If someone has it open via
273                          * /dev/tty then close it (since they no longer can
274                          * once we've NULL'd it out).
275                          */
276                         if (sp->s_ttyvp)
277                                 ttyclosesession(sp, 1);
278                         /*
279                          * s_ttyp is not zero'd; we use this to indicate
280                          * that the session once had a controlling terminal.
281                          * (for logging and informational purposes)
282                          */
283                 }
284                 sp->s_leader = NULL;
285         }
286         fixjobc(p, p->p_pgrp, 0);
287         (void)acct_process(p);
288 #ifdef KTRACE
289         /*
290          * release trace file
291          */
292         p->p_traceflag = 0;     /* don't trace the vrele() */
293         if ((vtmp = p->p_tracep) != NULL) {
294                 p->p_tracep = NULL;
295                 vrele(vtmp);
296         }
297 #endif
298         /*
299          * Release reference to text vnode
300          */
301         if ((vtmp = p->p_textvp) != NULL) {
302                 p->p_textvp = NULL;
303                 vrele(vtmp);
304         }
305
306         /*
307          * Once we set SZOMB the process can get reaped.  The wait1 code
308          * will also wait for TDF_RUNNING to be cleared in the thread's flags,
309          * indicating that it has been completely switched out.
310          */
311
312         /*
313          * Remove proc from allproc queue and pidhash chain.
314          * Place onto zombproc.  Unlink from parent's child list.
315          */
316         LIST_REMOVE(p, p_list);
317         LIST_INSERT_HEAD(&zombproc, p, p_list);
318         p->p_stat = SZOMB;
319
320         LIST_REMOVE(p, p_hash);
321
322         q = LIST_FIRST(&p->p_children);
323         if (q)          /* only need this if any child is S_ZOMB */
324                 wakeup((caddr_t) initproc);
325         for (; q != 0; q = nq) {
326                 nq = LIST_NEXT(q, p_sibling);
327                 LIST_REMOVE(q, p_sibling);
328                 LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
329                 q->p_pptr = initproc;
330                 q->p_sigparent = SIGCHLD;
331                 /*
332                  * Traced processes are killed
333                  * since their existence means someone is screwing up.
334                  */
335                 if (q->p_flag & P_TRACED) {
336                         q->p_flag &= ~P_TRACED;
337                         psignal(q, SIGKILL);
338                 }
339         }
340
341         /*
342          * Save exit status and final rusage info, adding in child rusage
343          * info and self times.
344          */
345         p->p_xstat = rv;
346         *p->p_ru = p->p_stats->p_ru;
347         calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
348         ruadd(p->p_ru, &p->p_stats->p_cru);
349
350         /*
351          * notify interested parties of our demise.
352          */
353         KNOTE(&p->p_klist, NOTE_EXIT);
354
355         /*
356          * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
357          * flag set, notify process 1 instead (and hope it will handle
358          * this situation).
359          */
360         if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
361                 struct proc *pp = p->p_pptr;
362                 proc_reparent(p, initproc);
363                 /*
364                  * If this was the last child of our parent, notify
365                  * parent, so in case he was wait(2)ing, he will
366                  * continue.
367                  */
368                 if (LIST_EMPTY(&pp->p_children))
369                         wakeup((caddr_t)pp);
370         }
371
372         if (p->p_sigparent && p->p_pptr != initproc) {
373                 psignal(p->p_pptr, p->p_sigparent);
374         } else {
375                 psignal(p->p_pptr, SIGCHLD);
376         }
377
378         wakeup((caddr_t)p->p_pptr);
379 #if defined(tahoe)
380         /* move this to cpu_exit */
381         p->p_thread->td_pcb->pcb_saveacc.faddr = (float *)NULL;
382 #endif
383         /*
384          * cpu_exit is responsible for clearing curproc, since
385          * it is heavily integrated with the thread/switching sequence.
386          *
387          * Other substructures are freed from wait().
388          */
389         if (--p->p_limit->p_refcnt == 0) {
390                 FREE(p->p_limit, M_SUBPROC);
391                 p->p_limit = NULL;
392         }
393
394         /*
395          * Release the current user process designation on the process so
396          * the userland scheduler can work in someone else.
397          */
398         release_curproc(p);
399
400         /*
401          * Finally, call machine-dependent code to release the remaining
402          * resources including address space, the kernel stack and pcb.
403          * The address space is released by "vmspace_free(p->p_vmspace)";
404          * This is machine-dependent, as we may have to change stacks
405          * or ensure that the current one isn't reallocated before we
406          * finish.  cpu_exit will end with a call to cpu_switch(), finishing
407          * our execution (pun intended).
408          */
409         cpu_proc_exit();
410 }
411
412 int
413 wait4(struct wait_args *uap)
414 {
415         struct rusage rusage;
416         int error, status;
417
418         error = kern_wait(uap->pid, uap->status ? &status : NULL,
419             uap->options, uap->rusage ? &rusage : NULL, &uap->sysmsg_fds[0]);
420
421         if (error == 0 && uap->status)
422                 error = copyout(&status, uap->status, sizeof(*uap->status));
423         if (error == 0 && uap->rusage)
424                 error = copyout(&rusage, uap->rusage, sizeof(*uap->rusage));
425         return (error);
426 }
427
428 /*
429  * wait1()
430  *
431  * wait_args(int pid, int *status, int options, struct rusage *rusage)
432  */
433 int
434 kern_wait(pid_t pid, int *status, int options, struct rusage *rusage, int *res)
435 {
436         struct thread *td = curthread;
437         struct proc *q = td->td_proc;
438         struct proc *p, *t;
439         int nfound, error;
440
441         if (pid == 0)
442                 pid = -q->p_pgid;
443         if (options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
444                 return (EINVAL);
445 loop:
446         nfound = 0;
447         LIST_FOREACH(p, &q->p_children, p_sibling) {
448                 if (pid != WAIT_ANY &&
449                     p->p_pid != pid && p->p_pgid != -pid)
450                         continue;
451
452                 /* This special case handles a kthread spawned by linux_clone 
453                  * (see linux_misc.c).  The linux_wait4 and linux_waitpid functions
454                  * need to be able to distinguish between waiting on a process and
455                  * waiting on a thread.  It is a thread if p_sigparent is not SIGCHLD,
456                  * and the WLINUXCLONE option signifies we want to wait for threads
457                  * and not processes.
458                  */
459                 if ((p->p_sigparent != SIGCHLD) ^ ((options & WLINUXCLONE) != 0))
460                         continue;
461
462                 nfound++;
463                 if (p->p_stat == SZOMB) {
464                         /*
465                          * The process's thread may still be in the middle
466                          * of switching away, we can't rip its stack out from
467                          * under it until TDF_RUNNING clears!
468                          *
469                          * YYY no wakeup occurs so we depend on the timeout.
470                          */
471                         if ((p->p_thread->td_flags & TDF_RUNNING) != 0) {
472                                 tsleep(p->p_thread, 0, "reap", 1);
473                                 goto loop;
474                         }
475
476                         /*
477                          * Other kernel threads may be in the middle of 
478                          * accessing the proc.  For example, kern/kern_proc.c
479                          * could be blocked writing proc data to a sysctl.
480                          * At the moment, if this occurs, we are not woken
481                          * up and rely on a one-second retry.
482                          */
483                         if (p->p_lock) {
484                                 while (p->p_lock)
485                                         tsleep(p, 0, "reap2", hz);
486                         }
487                         lwkt_wait_free(p->p_thread);
488
489                         /*
490                          * Charge the parent for the child's change in
491                          * estimated cpu as of when the child exits to
492                          * account for batch scripts, large make's, etc.
493                          */
494                         if (q->p_pid != 1) {
495                             if (p->p_estcpu > p->p_estcpu_fork) {
496                                 q->p_estcpu = ESTCPULIM(q->p_estcpu +
497                                                 p->p_estcpu - p->p_estcpu_fork);
498                             }
499                         }
500
501                         /* Take care of our return values. */
502                         *res = p->p_pid;
503                         if (status)
504                                 *status = p->p_xstat;
505                         if (rusage)
506                                 *rusage = *p->p_ru;
507                         /*
508                          * If we got the child via a ptrace 'attach',
509                          * we need to give it back to the old parent.
510                          */
511                         if (p->p_oppid && (t = pfind(p->p_oppid))) {
512                                 p->p_oppid = 0;
513                                 proc_reparent(p, t);
514                                 psignal(t, SIGCHLD);
515                                 wakeup((caddr_t)t);
516                                 return (0);
517                         }
518                         p->p_xstat = 0;
519                         ruadd(&q->p_stats->p_cru, p->p_ru);
520                         FREE(p->p_ru, M_ZOMBIE);
521                         p->p_ru = NULL;
522
523                         /*
524                          * Decrement the count of procs running with this uid.
525                          */
526                         chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
527
528                         /*
529                          * Free up credentials.
530                          */
531                         crfree(p->p_ucred);
532                         p->p_ucred = NULL;
533
534                         /*
535                          * Remove unused arguments
536                          */
537                         if (p->p_args && --p->p_args->ar_ref == 0)
538                                 FREE(p->p_args, M_PARGS);
539
540                         /*
541                          * Finally finished with old proc entry.
542                          * Unlink it from its process group and free it.
543                          */
544                         leavepgrp(p);
545                         LIST_REMOVE(p, p_list); /* off zombproc */
546                         LIST_REMOVE(p, p_sibling);
547
548                         if (--p->p_procsig->ps_refcnt == 0) {
549                                 if (p->p_sigacts != &p->p_addr->u_sigacts)
550                                         FREE(p->p_sigacts, M_SUBPROC);
551                                 FREE(p->p_procsig, M_SUBPROC);
552                                 p->p_procsig = NULL;
553                         }
554
555                         vm_waitproc(p);
556                         zfree(proc_zone, p);
557                         nprocs--;
558                         return (0);
559                 }
560                 if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
561                     (p->p_flag & P_TRACED || options & WUNTRACED)) {
562                         p->p_flag |= P_WAITED;
563
564                         *res = p->p_pid;
565                         if (status)
566                                 *status = W_STOPCODE(p->p_xstat);
567                         /* Zero rusage so we get something consistent. */
568                         if (rusage)
569                                 bzero(rusage, sizeof(rusage));
570                         return (0);
571                 }
572         }
573         if (nfound == 0)
574                 return (ECHILD);
575         if (options & WNOHANG) {
576                 *res = 0;
577                 return (0);
578         }
579         error = tsleep((caddr_t)q, PCATCH, "wait", 0);
580         if (error)
581                 return (error);
582         goto loop;
583 }
584
585 /*
586  * make process 'parent' the new parent of process 'child'.
587  */
588 void
589 proc_reparent(child, parent)
590         struct proc *child;
591         struct proc *parent;
592 {
593
594         if (child->p_pptr == parent)
595                 return;
596
597         LIST_REMOVE(child, p_sibling);
598         LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
599         child->p_pptr = parent;
600 }
601
602 /*
603  * The next two functions are to handle adding/deleting items on the
604  * exit callout list
605  * 
606  * at_exit():
607  * Take the arguments given and put them onto the exit callout list,
608  * However first make sure that it's not already there.
609  * returns 0 on success.
610  */
611
612 int
613 at_exit(function)
614         exitlist_fn function;
615 {
616         struct exitlist *ep;
617
618 #ifdef INVARIANTS
619         /* Be noisy if the programmer has lost track of things */
620         if (rm_at_exit(function)) 
621                 printf("WARNING: exit callout entry (%p) already present\n",
622                     function);
623 #endif
624         ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
625         if (ep == NULL)
626                 return (ENOMEM);
627         ep->function = function;
628         TAILQ_INSERT_TAIL(&exit_list, ep, next);
629         return (0);
630 }
631
632 /*
633  * Scan the exit callout list for the given item and remove it.
634  * Returns the number of items removed (0 or 1)
635  */
636 int
637 rm_at_exit(function)
638         exitlist_fn function;
639 {
640         struct exitlist *ep;
641
642         TAILQ_FOREACH(ep, &exit_list, next) {
643                 if (ep->function == function) {
644                         TAILQ_REMOVE(&exit_list, ep, next);
645                         free(ep, M_ATEXIT);
646                         return(1);
647                 }
648         }       
649         return (0);
650 }
651
652 void check_sigacts (void)
653 {
654         struct proc *p = curproc;
655         struct sigacts *pss;
656         int s;
657
658         if (p->p_procsig->ps_refcnt == 1 &&
659             p->p_sigacts != &p->p_addr->u_sigacts) {
660                 pss = p->p_sigacts;
661                 s = splhigh();
662                 p->p_addr->u_sigacts = *pss;
663                 p->p_sigacts = &p->p_addr->u_sigacts;
664                 splx(s);
665                 FREE(pss, M_SUBPROC);
666         }
667 }
668