1599a6ce35db2dce1ef3123f523bba79dbce0c79
[games.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.69 2007/02/03 17:05:57 corecode 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/ktrace.h>
53 #include <sys/pioctl.h>
54 #include <sys/tty.h>
55 #include <sys/wait.h>
56 #include <sys/vnode.h>
57 #include <sys/resourcevar.h>
58 #include <sys/signalvar.h>
59 #include <sys/ptrace.h>
60 #include <sys/acct.h>           /* for acct_process() function prototype */
61 #include <sys/filedesc.h>
62 #include <sys/shm.h>
63 #include <sys/sem.h>
64 #include <sys/aio.h>
65 #include <sys/jail.h>
66 #include <sys/kern_syscall.h>
67 #include <sys/upcall.h>
68 #include <sys/caps.h>
69
70 #include <vm/vm.h>
71 #include <vm/vm_param.h>
72 #include <sys/lock.h>
73 #include <vm/pmap.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_zone.h>
76 #include <vm/vm_extern.h>
77 #include <sys/user.h>
78
79 #include <sys/thread2.h>
80
81 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
82 static MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
83
84 /*
85  * callout list for things to do at exit time
86  */
87 struct exitlist {
88         exitlist_fn function;
89         TAILQ_ENTRY(exitlist) next;
90 };
91
92 TAILQ_HEAD(exit_list_head, exitlist);
93 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
94
95 /*
96  * exit --
97  *      Death of process.
98  *
99  * SYS_EXIT_ARGS(int rval)
100  */
101 int
102 sys_exit(struct exit_args *uap)
103 {
104         exit1(W_EXITCODE(uap->rval, 0));
105         /* NOTREACHED */
106 }
107
108 /*
109  * Exit: deallocate address space and other resources, change proc state
110  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
111  * status and rusage for wait().  Check for child processes and orphan them.
112  */
113 void
114 exit1(int rv)
115 {
116         struct thread *td = curthread;
117         struct proc *p = td->td_proc;
118         struct lwp *lp = td->td_lwp;
119         struct proc *q, *nq;
120         struct vmspace *vm;
121         struct vnode *vtmp;
122         struct exitlist *ep;
123
124         if (p->p_pid == 1) {
125                 kprintf("init died (signal %d, exit %d)\n",
126                     WTERMSIG(rv), WEXITSTATUS(rv));
127                 panic("Going nowhere without my init!");
128         }
129
130         /* XXX lwp kill other threads */
131
132         caps_exit(lp->lwp_thread);
133         aio_proc_rundown(p);
134
135         /* are we a task leader? */
136         if(p == p->p_leader) {
137                 struct kill_args killArgs;
138                 killArgs.signum = SIGKILL;
139                 q = p->p_peers;
140                 while(q) {
141                         killArgs.pid = q->p_pid;
142                         /*
143                          * The interface for kill is better
144                          * than the internal signal
145                          */
146                         sys_kill(&killArgs);
147                         nq = q;
148                         q = q->p_peers;
149                 }
150                 while (p->p_peers) 
151                   tsleep((caddr_t)p, 0, "exit1", 0);
152         } 
153
154 #ifdef PGINPROF
155         vmsizmon();
156 #endif
157         STOPEVENT(p, S_EXIT, rv);
158         wakeup(&p->p_stype);    /* Wakeup anyone in procfs' PIOCWAIT */
159
160         /* 
161          * Check if any loadable modules need anything done at process exit.
162          * e.g. SYSV IPC stuff
163          * XXX what if one of these generates an error?
164          */
165         TAILQ_FOREACH(ep, &exit_list, next) 
166                 (*ep->function)(td);
167
168         if (p->p_flag & P_PROFIL)
169                 stopprofclock(p);
170         /*
171          * If parent is waiting for us to exit or exec,
172          * P_PPWAIT is set; we will wakeup the parent below.
173          */
174         p->p_flag &= ~(P_TRACED | P_PPWAIT);
175         p->p_flag |= P_WEXIT;
176         SIGEMPTYSET(p->p_siglist);
177         if (timevalisset(&p->p_realtimer.it_value))
178                 callout_stop(&p->p_ithandle);
179
180         /*
181          * Reset any sigio structures pointing to us as a result of
182          * F_SETOWN with our pid.
183          */
184         funsetownlst(&p->p_sigiolst);
185
186         /*
187          * Close open files and release open-file table.
188          * This may block!
189          */
190         fdfree(p);
191         p->p_fd = NULL;
192
193         if(p->p_leader->p_peers) {
194                 q = p->p_leader;
195                 while(q->p_peers != p)
196                         q = q->p_peers;
197                 q->p_peers = p->p_peers;
198                 wakeup((caddr_t)p->p_leader);
199         }
200
201         /*
202          * XXX Shutdown SYSV semaphores
203          */
204         semexit(p);
205
206         KKASSERT(p->p_numposixlocks == 0);
207
208         /* The next two chunks should probably be moved to vmspace_exit. */
209         vm = p->p_vmspace;
210
211         /*
212          * Release upcalls associated with this process
213          */
214         if (vm->vm_upcalls)
215                 upc_release(vm, lp);
216
217         /* clean up data related to virtual kernel operation */
218         if (p->p_vkernel)
219                 vkernel_exit(p);
220
221         /*
222          * Release user portion of address space.
223          * This releases references to vnodes,
224          * which could cause I/O if the file has been unlinked.
225          * Need to do this early enough that we can still sleep.
226          * Can't free the entire vmspace as the kernel stack
227          * may be mapped within that space also.
228          *
229          * Processes sharing the same vmspace may exit in one order, and
230          * get cleaned up by vmspace_exit() in a different order.  The
231          * last exiting process to reach this point releases as much of
232          * the environment as it can, and the last process cleaned up
233          * by vmspace_exit() (which decrements exitingcnt) cleans up the
234          * remainder.
235          */
236         ++vm->vm_exitingcnt;
237         if (--vm->vm_refcnt == 0) {
238                 shmexit(vm);
239                 pmap_remove_pages(vmspace_pmap(vm), VM_MIN_USER_ADDRESS,
240                                   VM_MAX_USER_ADDRESS);
241                 vm_map_remove(&vm->vm_map, VM_MIN_USER_ADDRESS,
242                               VM_MAX_USER_ADDRESS);
243         }
244
245         if (SESS_LEADER(p)) {
246                 struct session *sp = p->p_session;
247                 struct vnode *vp;
248
249                 if (sp->s_ttyvp) {
250                         /*
251                          * We are the controlling process.  Signal the 
252                          * foreground process group, drain the controlling
253                          * terminal, and revoke access to the controlling
254                          * terminal.
255                          *
256                          * NOTE: while waiting for the process group to exit
257                          * it is possible that one of the processes in the
258                          * group will revoke the tty, so we have to recheck.
259                          */
260                         if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
261                                 if (sp->s_ttyp->t_pgrp)
262                                         pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
263                                 (void) ttywait(sp->s_ttyp);
264                                 /*
265                                  * The tty could have been revoked
266                                  * if we blocked.
267                                  */
268                                 if ((vp = sp->s_ttyvp) != NULL) {
269                                         ttyclosesession(sp, 0);
270                                         vx_lock(vp);
271                                         VOP_REVOKE(vp, REVOKEALL);
272                                         vx_unlock(vp);
273                                         vrele(vp);      /* s_ttyvp ref */
274                                 }
275                         }
276                         /*
277                          * Release the tty.  If someone has it open via
278                          * /dev/tty then close it (since they no longer can
279                          * once we've NULL'd it out).
280                          */
281                         if (sp->s_ttyvp)
282                                 ttyclosesession(sp, 1);
283                         /*
284                          * s_ttyp is not zero'd; we use this to indicate
285                          * that the session once had a controlling terminal.
286                          * (for logging and informational purposes)
287                          */
288                 }
289                 sp->s_leader = NULL;
290         }
291         fixjobc(p, p->p_pgrp, 0);
292         (void)acct_process(p);
293 #ifdef KTRACE
294         /*
295          * release trace file
296          */
297         if (p->p_tracenode)
298                 ktrdestroy(&p->p_tracenode);
299         p->p_traceflag = 0;
300 #endif
301         /*
302          * Release reference to text vnode
303          */
304         if ((vtmp = p->p_textvp) != NULL) {
305                 p->p_textvp = NULL;
306                 vrele(vtmp);
307         }
308
309         /*
310          * Move the process to the zombie list.  This will block
311          * until the process p_lock count reaches 0.  The process will
312          * not be reaped until TDF_EXITING is set by cpu_thread_exit(),
313          * which is called from cpu_proc_exit().
314          */
315         proc_move_allproc_zombie(p);
316
317         q = LIST_FIRST(&p->p_children);
318         if (q)          /* only need this if any child is S_ZOMB */
319                 wakeup((caddr_t) initproc);
320         for (; q != 0; q = nq) {
321                 nq = LIST_NEXT(q, p_sibling);
322                 LIST_REMOVE(q, p_sibling);
323                 LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
324                 q->p_pptr = initproc;
325                 q->p_sigparent = SIGCHLD;
326                 /*
327                  * Traced processes are killed
328                  * since their existence means someone is screwing up.
329                  */
330                 if (q->p_flag & P_TRACED) {
331                         q->p_flag &= ~P_TRACED;
332                         ksignal(q, SIGKILL);
333                 }
334         }
335
336         /*
337          * Save exit status and final rusage info, adding in child rusage
338          * info and self times.
339          */
340         p->p_xstat = rv;
341         calcru_proc(p, &p->p_ru);
342         ruadd(&p->p_ru, &p->p_cru);
343
344         /*
345          * notify interested parties of our demise.
346          */
347         KNOTE(&p->p_klist, NOTE_EXIT);
348
349         /*
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
352          * this situation).
353          */
354         if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
355                 struct proc *pp = p->p_pptr;
356                 proc_reparent(p, initproc);
357                 /*
358                  * If this was the last child of our parent, notify
359                  * parent, so in case he was wait(2)ing, he will
360                  * continue.
361                  */
362                 if (LIST_EMPTY(&pp->p_children))
363                         wakeup((caddr_t)pp);
364         }
365
366         if (p->p_sigparent && p->p_pptr != initproc) {
367                 ksignal(p->p_pptr, p->p_sigparent);
368         } else {
369                 ksignal(p->p_pptr, SIGCHLD);
370         }
371
372         wakeup((caddr_t)p->p_pptr);
373         /*
374          * cpu_exit is responsible for clearing curproc, since
375          * it is heavily integrated with the thread/switching sequence.
376          *
377          * Other substructures are freed from wait().
378          */
379         plimit_free(&p->p_limit);
380
381         /*
382          * Release the current user process designation on the process so
383          * the userland scheduler can work in someone else.
384          */
385         p->p_usched->release_curproc(lp);
386
387         /*
388          * Finally, call machine-dependent code to release the remaining
389          * resources including address space, the kernel stack and pcb.
390          * The address space is released by "vmspace_free(p->p_vmspace)";
391          * This is machine-dependent, as we may have to change stacks
392          * or ensure that the current one isn't reallocated before we
393          * finish.  cpu_exit will end with a call to cpu_switch(), finishing
394          * our execution (pun intended).
395          */
396         cpu_proc_exit();
397 }
398
399 int
400 sys_wait4(struct wait_args *uap)
401 {
402         struct rusage rusage;
403         int error, status;
404
405         error = kern_wait(uap->pid, uap->status ? &status : NULL,
406             uap->options, uap->rusage ? &rusage : NULL, &uap->sysmsg_fds[0]);
407
408         if (error == 0 && uap->status)
409                 error = copyout(&status, uap->status, sizeof(*uap->status));
410         if (error == 0 && uap->rusage)
411                 error = copyout(&rusage, uap->rusage, sizeof(*uap->rusage));
412         return (error);
413 }
414
415 /*
416  * wait1()
417  *
418  * wait_args(int pid, int *status, int options, struct rusage *rusage)
419  */
420 int
421 kern_wait(pid_t pid, int *status, int options, struct rusage *rusage, int *res)
422 {
423         struct thread *td = curthread;
424         struct lwp *deadlp;
425         struct proc *q = td->td_proc;
426         struct proc *p, *t;
427         int nfound, error;
428
429         if (pid == 0)
430                 pid = -q->p_pgid;
431         if (options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
432                 return (EINVAL);
433 loop:
434         /*
435          * Hack for backwards compatibility with badly written user code.  
436          * Or perhaps we have to do this anyway, it is unclear. XXX
437          *
438          * The problem is that if a process group is stopped and the parent
439          * is doing a wait*(..., WUNTRACED, ...), it will see the STOP
440          * of the child and then stop itself when it tries to return from the
441          * system call.  When the process group is resumed the parent will
442          * then get the STOP status even though the child has now resumed
443          * (a followup wait*() will get the CONT status).
444          *
445          * Previously the CONT would overwrite the STOP because the tstop
446          * was handled within tsleep(), and the parent would only see
447          * the CONT when both are stopped and continued together.  This litte
448          * two-line hack restores this effect.
449          */
450         while (q->p_flag & P_STOPPED)  
451             tstop(q);
452
453         nfound = 0;
454         LIST_FOREACH(p, &q->p_children, p_sibling) {
455                 if (pid != WAIT_ANY &&
456                     p->p_pid != pid && p->p_pgid != -pid)
457                         continue;
458
459                 /* This special case handles a kthread spawned by linux_clone 
460                  * (see linux_misc.c).  The linux_wait4 and linux_waitpid 
461                  * functions need to be able to distinguish between waiting
462                  * on a process and waiting on a thread.  It is a thread if
463                  * p_sigparent is not SIGCHLD, and the WLINUXCLONE option
464                  * signifies we want to wait for threads and not processes.
465                  */
466                 if ((p->p_sigparent != SIGCHLD) ^ 
467                     ((options & WLINUXCLONE) != 0)) {
468                         continue;
469                 }
470
471                 nfound++;
472                 if (p->p_flag & P_ZOMBIE) {
473                         deadlp = ONLY_LWP_IN_PROC(p);
474
475                         /*
476                          * Other kernel threads may be in the middle of 
477                          * accessing the proc.  For example, kern/kern_proc.c
478                          * could be blocked writing proc data to a sysctl.
479                          * At the moment, if this occurs, we are not woken
480                          * up and rely on a one-second retry.
481                          */
482                         if (p->p_lock) {
483                                 while (p->p_lock)
484                                         tsleep(p, 0, "reap3", hz);
485                         }
486                         lwkt_wait_free(deadlp->lwp_thread);
487
488                         /*
489                          * The process's thread may still be in the middle
490                          * of switching away, we can't rip its stack out from
491                          * under it until TDF_EXITING is set and both
492                          * TDF_RUNNING and TDF_PREEMPT_LOCK are clear.
493                          * TDF_PREEMPT_LOCK must be checked because TDF_RUNNING
494                          * will be cleared temporarily if a thread gets
495                          * preempted.
496                          *
497                          * YYY no wakeup occurs so we depend on the timeout.
498                          */
499                         if ((deadlp->lwp_thread->td_flags & (TDF_RUNNING|TDF_PREEMPT_LOCK|TDF_EXITING)) != TDF_EXITING) {
500                                 tsleep(deadlp->lwp_thread, 0, "reap2", 1);
501                                 goto loop;
502                         }
503
504                         /* scheduling hook for heuristic */
505                         p->p_usched->heuristic_exiting(td->td_lwp, deadlp);
506
507                         /* Take care of our return values. */
508                         *res = p->p_pid;
509                         if (status)
510                                 *status = p->p_xstat;
511                         if (rusage)
512                                 *rusage = p->p_ru;
513                         /*
514                          * If we got the child via a ptrace 'attach',
515                          * we need to give it back to the old parent.
516                          */
517                         if (p->p_oppid && (t = pfind(p->p_oppid))) {
518                                 p->p_oppid = 0;
519                                 proc_reparent(p, t);
520                                 ksignal(t, SIGCHLD);
521                                 wakeup((caddr_t)t);
522                                 return (0);
523                         }
524                         p->p_xstat = 0;
525                         ruadd(&q->p_cru, &p->p_ru);
526
527                         /*
528                          * Decrement the count of procs running with this uid.
529                          */
530                         chgproccnt(p->p_ucred->cr_ruidinfo, -1, 0);
531
532                         /*
533                          * Free up credentials.
534                          */
535                         crfree(p->p_ucred);
536                         p->p_ucred = NULL;
537
538                         /*
539                          * Remove unused arguments
540                          */
541                         if (p->p_args && --p->p_args->ar_ref == 0)
542                                 FREE(p->p_args, M_PARGS);
543
544                         /*
545                          * Finally finished with old proc entry.
546                          * Unlink it from its process group and free it.
547                          */
548                         proc_remove_zombie(p);
549                         leavepgrp(p);
550
551                         if (--p->p_procsig->ps_refcnt == 0) {
552                                 if (p->p_sigacts != &p->p_addr->u_sigacts)
553                                         FREE(p->p_sigacts, M_SUBPROC);
554                                 FREE(p->p_procsig, M_SUBPROC);
555                                 p->p_procsig = NULL;
556                         }
557
558                         vm_waitproc(p);
559                         zfree(lwp_zone, deadlp);
560                         zfree(proc_zone, p);
561                         nprocs--;
562                         return (0);
563                 }
564                 if ((p->p_flag & P_STOPPED) && (p->p_flag & P_WAITED) == 0 &&
565                     (p->p_flag & P_TRACED || options & WUNTRACED)) {
566                         p->p_flag |= P_WAITED;
567
568                         *res = p->p_pid;
569                         if (status)
570                                 *status = W_STOPCODE(p->p_xstat);
571                         /* Zero rusage so we get something consistent. */
572                         if (rusage)
573                                 bzero(rusage, sizeof(rusage));
574                         return (0);
575                 }
576         }
577         if (nfound == 0)
578                 return (ECHILD);
579         if (options & WNOHANG) {
580                 *res = 0;
581                 return (0);
582         }
583         error = tsleep((caddr_t)q, PCATCH, "wait", 0);
584         if (error)
585                 return (error);
586         goto loop;
587 }
588
589 /*
590  * make process 'parent' the new parent of process 'child'.
591  */
592 void
593 proc_reparent(struct proc *child, struct proc *parent)
594 {
595
596         if (child->p_pptr == parent)
597                 return;
598
599         LIST_REMOVE(child, p_sibling);
600         LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
601         child->p_pptr = parent;
602 }
603
604 /*
605  * The next two functions are to handle adding/deleting items on the
606  * exit callout list
607  * 
608  * at_exit():
609  * Take the arguments given and put them onto the exit callout list,
610  * However first make sure that it's not already there.
611  * returns 0 on success.
612  */
613
614 int
615 at_exit(exitlist_fn function)
616 {
617         struct exitlist *ep;
618
619 #ifdef INVARIANTS
620         /* Be noisy if the programmer has lost track of things */
621         if (rm_at_exit(function)) 
622                 kprintf("WARNING: exit callout entry (%p) already present\n",
623                     function);
624 #endif
625         ep = kmalloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
626         if (ep == NULL)
627                 return (ENOMEM);
628         ep->function = function;
629         TAILQ_INSERT_TAIL(&exit_list, ep, next);
630         return (0);
631 }
632
633 /*
634  * Scan the exit callout list for the given item and remove it.
635  * Returns the number of items removed (0 or 1)
636  */
637 int
638 rm_at_exit(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                         kfree(ep, M_ATEXIT);
646                         return(1);
647                 }
648         }       
649         return (0);
650 }
651
652 void
653 check_sigacts(void)
654 {
655         struct proc *p = curproc;
656         struct sigacts *pss;
657
658         if (p->p_procsig->ps_refcnt == 1 &&
659             p->p_sigacts != &p->p_addr->u_sigacts) {
660                 pss = p->p_sigacts;
661                 crit_enter();
662                 p->p_addr->u_sigacts = *pss;
663                 p->p_sigacts = &p->p_addr->u_sigacts;
664                 crit_exit();
665                 FREE(pss, M_SUBPROC);
666         }
667 }
668