Add kern/lwkt_rwlock.c -- reader/writer locks. Clean up the process exit &
[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.7 2003/06/21 17:31:19 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
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <sys/lock.h>
69 #include <vm/pmap.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_zone.h>
72 #include <vm/vm_extern.h>
73 #include <sys/user.h>
74
75 /* Required to be non-static for SysVR4 emulator */
76 MALLOC_DEFINE(M_ZOMBIE, "zombie", "zombie proc status");
77
78 static MALLOC_DEFINE(M_ATEXIT, "atexit", "atexit callback");
79
80 static int wait1 __P((struct proc *, struct wait_args *, int));
81
82 /*
83  * callout list for things to do at exit time
84  */
85 struct exitlist {
86         exitlist_fn function;
87         TAILQ_ENTRY(exitlist) next;
88 };
89
90 TAILQ_HEAD(exit_list_head, exitlist);
91 static struct exit_list_head exit_list = TAILQ_HEAD_INITIALIZER(exit_list);
92
93 /*
94  * exit --
95  *      Death of process.
96  */
97 void
98 sys_exit(p, uap)
99         struct proc *p;
100         struct sys_exit_args /* {
101                 int     rval;
102         } */ *uap;
103 {
104
105         exit1(p, W_EXITCODE(uap->rval, 0));
106         /* NOTREACHED */
107 }
108
109 /*
110  * Exit: deallocate address space and other resources, change proc state
111  * to zombie, and unlink proc from allproc and parent's lists.  Save exit
112  * status and rusage for wait().  Check for child processes and orphan them.
113  */
114 void
115 exit1(p, rv)
116         register struct proc *p;
117         int rv;
118 {
119         register struct proc *q, *nq;
120         register struct vmspace *vm;
121         struct vnode *vtmp;
122         struct exitlist *ep;
123
124         if (p->p_pid == 1) {
125                 printf("init died (signal %d, exit %d)\n",
126                     WTERMSIG(rv), WEXITSTATUS(rv));
127                 panic("Going nowhere without my init!");
128         }
129
130         aio_proc_rundown(p);
131
132         /* are we a task leader? */
133         if(p == p->p_leader) {
134                 struct kill_args killArgs;
135                 killArgs.signum = SIGKILL;
136                 q = p->p_peers;
137                 while(q) {
138                         killArgs.pid = q->p_pid;
139                         /*
140                          * The interface for kill is better
141                          * than the internal signal
142                          */
143                         kill(p, &killArgs);
144                         nq = q;
145                         q = q->p_peers;
146                 }
147                 while (p->p_peers) 
148                   tsleep((caddr_t)p, PWAIT, "exit1", 0);
149         } 
150
151 #ifdef PGINPROF
152         vmsizmon();
153 #endif
154         STOPEVENT(p, S_EXIT, rv);
155         wakeup(&p->p_stype);    /* Wakeup anyone in procfs' PIOCWAIT */
156
157         /* 
158          * Check if any loadable modules need anything done at process exit.
159          * e.g. SYSV IPC stuff
160          * XXX what if one of these generates an error?
161          */
162         TAILQ_FOREACH(ep, &exit_list, next) 
163                 (*ep->function)(p);
164
165         if (p->p_flag & P_PROFIL)
166                 stopprofclock(p);
167         MALLOC(p->p_ru, struct rusage *, sizeof(struct rusage),
168                 M_ZOMBIE, M_WAITOK);
169         /*
170          * If parent is waiting for us to exit or exec,
171          * P_PPWAIT is set; we will wakeup the parent below.
172          */
173         p->p_flag &= ~(P_TRACED | P_PPWAIT);
174         p->p_flag |= P_WEXIT;
175         SIGEMPTYSET(p->p_siglist);
176         if (timevalisset(&p->p_realtimer.it_value))
177                 untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
178
179         /*
180          * Reset any sigio structures pointing to us as a result of
181          * F_SETOWN with our pid.
182          */
183         funsetownlst(&p->p_sigiolst);
184
185         /*
186          * Close open files and release open-file table.
187          * This may block!
188          */
189         fdfree(p);
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         /* The next two chunks should probably be moved to vmspace_exit. */
205         vm = p->p_vmspace;
206         /*
207          * Release user portion of address space.
208          * This releases references to vnodes,
209          * which could cause I/O if the file has been unlinked.
210          * Need to do this early enough that we can still sleep.
211          * Can't free the entire vmspace as the kernel stack
212          * may be mapped within that space also.
213          *
214          * Processes sharing the same vmspace may exit in one order, and
215          * get cleaned up by vmspace_exit() in a different order.  The
216          * last exiting process to reach this point releases as much of
217          * the environment as it can, and the last process cleaned up
218          * by vmspace_exit() (which decrements exitingcnt) cleans up the
219          * remainder.
220          */
221         ++vm->vm_exitingcnt;
222         if (--vm->vm_refcnt == 0) {
223                 if (vm->vm_shm)
224                         shmexit(p);
225                 pmap_remove_pages(vmspace_pmap(vm), VM_MIN_ADDRESS,
226                     VM_MAXUSER_ADDRESS);
227                 (void) vm_map_remove(&vm->vm_map, VM_MIN_ADDRESS,
228                     VM_MAXUSER_ADDRESS);
229         }
230
231         if (SESS_LEADER(p)) {
232                 register struct session *sp = p->p_session;
233
234                 if (sp->s_ttyvp) {
235                         /*
236                          * Controlling process.
237                          * Signal foreground pgrp,
238                          * drain controlling terminal
239                          * and revoke access to controlling terminal.
240                          */
241                         if (sp->s_ttyp && (sp->s_ttyp->t_session == sp)) {
242                                 if (sp->s_ttyp->t_pgrp)
243                                         pgsignal(sp->s_ttyp->t_pgrp, SIGHUP, 1);
244                                 (void) ttywait(sp->s_ttyp);
245                                 /*
246                                  * The tty could have been revoked
247                                  * if we blocked.
248                                  */
249                                 if (sp->s_ttyvp)
250                                         VOP_REVOKE(sp->s_ttyvp, REVOKEALL);
251                         }
252                         if (sp->s_ttyvp)
253                                 vrele(sp->s_ttyvp);
254                         sp->s_ttyvp = NULL;
255                         /*
256                          * s_ttyp is not zero'd; we use this to indicate
257                          * that the session once had a controlling terminal.
258                          * (for logging and informational purposes)
259                          */
260                 }
261                 sp->s_leader = NULL;
262         }
263         fixjobc(p, p->p_pgrp, 0);
264         (void)acct_process(p);
265 #ifdef KTRACE
266         /*
267          * release trace file
268          */
269         p->p_traceflag = 0;     /* don't trace the vrele() */
270         if ((vtmp = p->p_tracep) != NULL) {
271                 p->p_tracep = NULL;
272                 vrele(vtmp);
273         }
274 #endif
275         /*
276          * Release reference to text vnode
277          */
278         if ((vtmp = p->p_textvp) != NULL) {
279                 p->p_textvp = NULL;
280                 vrele(vtmp);
281         }
282
283         /*
284          * Once we set SZOMB the process can get reaped.  To prevent this
285          * from occuring we obtain an exclusive access lock on the underlying
286          * thread which will not be released until the thread has been
287          * completed switched out.
288          */
289         lwkt_exlock(&curthread->td_rwlock, "exit");
290
291         /*
292          * Remove proc from allproc queue and pidhash chain.
293          * Place onto zombproc.  Unlink from parent's child list.
294          */
295         LIST_REMOVE(p, p_list);
296         LIST_INSERT_HEAD(&zombproc, p, p_list);
297         p->p_stat = SZOMB;
298
299         LIST_REMOVE(p, p_hash);
300
301         q = LIST_FIRST(&p->p_children);
302         if (q)          /* only need this if any child is S_ZOMB */
303                 wakeup((caddr_t) initproc);
304         for (; q != 0; q = nq) {
305                 nq = LIST_NEXT(q, p_sibling);
306                 LIST_REMOVE(q, p_sibling);
307                 LIST_INSERT_HEAD(&initproc->p_children, q, p_sibling);
308                 q->p_pptr = initproc;
309                 q->p_sigparent = SIGCHLD;
310                 /*
311                  * Traced processes are killed
312                  * since their existence means someone is screwing up.
313                  */
314                 if (q->p_flag & P_TRACED) {
315                         q->p_flag &= ~P_TRACED;
316                         psignal(q, SIGKILL);
317                 }
318         }
319
320         /*
321          * Save exit status and final rusage info, adding in child rusage
322          * info and self times.
323          */
324         p->p_xstat = rv;
325         *p->p_ru = p->p_stats->p_ru;
326         calcru(p, &p->p_ru->ru_utime, &p->p_ru->ru_stime, NULL);
327         ruadd(p->p_ru, &p->p_stats->p_cru);
328
329         /*
330          * Pretend that an mi_switch() to the next process occurs now.  We
331          * must set `switchtime' directly since we will call cpu_switch()
332          * directly.  Set it now so that the rest of the exit time gets
333          * counted somewhere if possible.
334          */
335         microuptime(&mycpu->gd_switchtime);
336         mycpu->gd_switchticks = ticks;
337
338         /*
339          * notify interested parties of our demise.
340          */
341         KNOTE(&p->p_klist, NOTE_EXIT);
342
343         /*
344          * Notify parent that we're gone.  If parent has the PS_NOCLDWAIT
345          * flag set, notify process 1 instead (and hope it will handle
346          * this situation).
347          */
348         if (p->p_pptr->p_procsig->ps_flag & PS_NOCLDWAIT) {
349                 struct proc *pp = p->p_pptr;
350                 proc_reparent(p, initproc);
351                 /*
352                  * If this was the last child of our parent, notify
353                  * parent, so in case he was wait(2)ing, he will
354                  * continue.
355                  */
356                 if (LIST_EMPTY(&pp->p_children))
357                         wakeup((caddr_t)pp);
358         }
359
360         if (p->p_sigparent && p->p_pptr != initproc) {
361                 psignal(p->p_pptr, p->p_sigparent);
362         } else {
363                 psignal(p->p_pptr, SIGCHLD);
364         }
365
366         wakeup((caddr_t)p->p_pptr);
367 #if defined(tahoe)
368         /* move this to cpu_exit */
369         p->p_thread->td_pcb->pcb_saveacc.faddr = (float *)NULL;
370 #endif
371         /*
372          * cpu_exit is responsible for clearing curproc, since
373          * it is heavily integrated with the thread/switching sequence.
374          *
375          * Other substructures are freed from wait().
376          */
377         if (--p->p_limit->p_refcnt == 0) {
378                 FREE(p->p_limit, M_SUBPROC);
379                 p->p_limit = NULL;
380         }
381
382         /*
383          * Finally, call machine-dependent code to release the remaining
384          * resources including address space, the kernel stack and pcb.
385          * The address space is released by "vmspace_free(p->p_vmspace)";
386          * This is machine-dependent, as we may have to change stacks
387          * or ensure that the current one isn't reallocated before we
388          * finish.  cpu_exit will end with a call to cpu_switch(), finishing
389          * our execution (pun intended).
390          */
391         cpu_exit(p);
392 }
393
394 #ifdef COMPAT_43
395 int
396 owait(p, uap)
397         struct proc *p;
398         register struct owait_args /* {
399                 int     dummy;
400         } */ *uap;
401 {
402         struct wait_args w;
403
404         w.options = 0;
405         w.rusage = NULL;
406         w.pid = WAIT_ANY;
407         w.status = NULL;
408         return (wait1(p, &w, 1));
409 }
410 #endif /* COMPAT_43 */
411
412 int
413 wait4(p, uap)
414         struct proc *p;
415         struct wait_args *uap;
416 {
417
418         return (wait1(p, uap, 0));
419 }
420
421 static int
422 wait1(q, uap, compat)
423         register struct proc *q;
424         register struct wait_args /* {
425                 int pid;
426                 int *status;
427                 int options;
428                 struct rusage *rusage;
429         } */ *uap;
430         int compat;
431 {
432         register int nfound;
433         register struct proc *p, *t;
434         int status, error;
435
436         if (uap->pid == 0)
437                 uap->pid = -q->p_pgid;
438         if (uap->options &~ (WUNTRACED|WNOHANG|WLINUXCLONE))
439                 return (EINVAL);
440 loop:
441         nfound = 0;
442         LIST_FOREACH(p, &q->p_children, p_sibling) {
443                 if (uap->pid != WAIT_ANY &&
444                     p->p_pid != uap->pid && p->p_pgid != -uap->pid)
445                         continue;
446
447                 /* This special case handles a kthread spawned by linux_clone 
448                  * (see linux_misc.c).  The linux_wait4 and linux_waitpid functions
449                  * need to be able to distinguish between waiting on a process and
450                  * waiting on a thread.  It is a thread if p_sigparent is not SIGCHLD,
451                  * and the WLINUXCLONE option signifies we want to wait for threads
452                  * and not processes.
453                  */
454                 if ((p->p_sigparent != SIGCHLD) ^ ((uap->options & WLINUXCLONE) != 0))
455                         continue;
456
457                 nfound++;
458                 if (p->p_stat == SZOMB) {
459                         /*
460                          * This is a tad nasty because lwkt_*() functions can
461                          * block, causing our information to become out of
462                          * date.
463                          *
464                          * YYY there may be some inefficiency here.
465                          */
466                         if ((p->p_flag & P_EXITINTERLOCK) == 0) {
467                             lwkt_exlock(&p->p_thread->td_rwlock, "reap");
468                             p->p_flag |= P_EXITINTERLOCK;
469                             lwkt_exunlock(&p->p_thread->td_rwlock);
470                             goto loop;
471                         }
472                         KASSERT(p->p_lock == 0, ("p_lock not 0! %p", p));
473
474                         /* charge childs scheduling cpu usage to parent */
475                         if (curproc->p_pid != 1) {
476                                 curproc->p_estcpu =
477                                     ESTCPULIM(curproc->p_estcpu + p->p_estcpu);
478                         }
479
480                         q->p_retval[0] = p->p_pid;
481 #ifdef COMPAT_43
482                         if (compat)
483                                 q->p_retval[1] = p->p_xstat;
484                         else
485 #endif
486                         if (uap->status) {
487                                 status = p->p_xstat;    /* convert to int */
488                                 if ((error = copyout((caddr_t)&status,
489                                     (caddr_t)uap->status, sizeof(status))))
490                                         return (error);
491                         }
492                         if (uap->rusage && (error = copyout((caddr_t)p->p_ru,
493                             (caddr_t)uap->rusage, sizeof (struct rusage))))
494                                 return (error);
495                         /*
496                          * If we got the child via a ptrace 'attach',
497                          * we need to give it back to the old parent.
498                          */
499                         if (p->p_oppid && (t = pfind(p->p_oppid))) {
500                                 p->p_oppid = 0;
501                                 proc_reparent(p, t);
502                                 psignal(t, SIGCHLD);
503                                 wakeup((caddr_t)t);
504                                 return (0);
505                         }
506                         p->p_xstat = 0;
507                         ruadd(&q->p_stats->p_cru, p->p_ru);
508                         FREE(p->p_ru, M_ZOMBIE);
509                         p->p_ru = NULL;
510
511                         /*
512                          * Decrement the count of procs running with this uid.
513                          */
514                         (void)chgproccnt(p->p_cred->p_uidinfo, -1, 0);
515
516                         /*
517                          * Free up credentials.
518                          */
519                         if (--p->p_cred->p_refcnt == 0) {
520                                 crfree(p->p_ucred);
521                                 uifree(p->p_cred->p_uidinfo);
522                                 FREE(p->p_cred, M_SUBPROC);
523                                 p->p_cred = NULL;
524                         }
525
526                         /*
527                          * Destroy empty prisons
528                          */
529                         if (p->p_prison && !--p->p_prison->pr_ref) {
530                                 if (p->p_prison->pr_linux != NULL)
531                                         FREE(p->p_prison->pr_linux, M_PRISON);
532                                 FREE(p->p_prison, M_PRISON);
533                         }
534
535                         /*
536                          * Remove unused arguments
537                          */
538                         if (p->p_args && --p->p_args->ar_ref == 0)
539                                 FREE(p->p_args, M_PARGS);
540
541                         /*
542                          * Finally finished with old proc entry.
543                          * Unlink it from its process group and free it.
544                          */
545                         leavepgrp(p);
546                         LIST_REMOVE(p, p_list); /* off zombproc */
547                         LIST_REMOVE(p, p_sibling);
548
549                         if (--p->p_procsig->ps_refcnt == 0) {
550                                 if (p->p_sigacts != &p->p_addr->u_sigacts)
551                                         FREE(p->p_sigacts, M_SUBPROC);
552                                 FREE(p->p_procsig, M_SUBPROC);
553                                 p->p_procsig = NULL;
554                         }
555
556                         vm_waitproc(p);
557                         zfree(proc_zone, p);
558                         nprocs--;
559                         return (0);
560                 }
561                 if (p->p_stat == SSTOP && (p->p_flag & P_WAITED) == 0 &&
562                     (p->p_flag & P_TRACED || uap->options & WUNTRACED)) {
563                         p->p_flag |= P_WAITED;
564                         q->p_retval[0] = p->p_pid;
565 #ifdef COMPAT_43
566                         if (compat) {
567                                 q->p_retval[1] = W_STOPCODE(p->p_xstat);
568                                 error = 0;
569                         } else
570 #endif
571                         if (uap->status) {
572                                 status = W_STOPCODE(p->p_xstat);
573                                 error = copyout((caddr_t)&status,
574                                         (caddr_t)uap->status, sizeof(status));
575                         } else
576                                 error = 0;
577                         return (error);
578                 }
579         }
580         if (nfound == 0)
581                 return (ECHILD);
582         if (uap->options & WNOHANG) {
583                 q->p_retval[0] = 0;
584                 return (0);
585         }
586         if ((error = tsleep((caddr_t)q, PWAIT | PCATCH, "wait", 0)))
587                 return (error);
588         goto loop;
589 }
590
591 /*
592  * make process 'parent' the new parent of process 'child'.
593  */
594 void
595 proc_reparent(child, parent)
596         register struct proc *child;
597         register struct proc *parent;
598 {
599
600         if (child->p_pptr == parent)
601                 return;
602
603         LIST_REMOVE(child, p_sibling);
604         LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
605         child->p_pptr = parent;
606 }
607
608 /*
609  * The next two functions are to handle adding/deleting items on the
610  * exit callout list
611  * 
612  * at_exit():
613  * Take the arguments given and put them onto the exit callout list,
614  * However first make sure that it's not already there.
615  * returns 0 on success.
616  */
617
618 int
619 at_exit(function)
620         exitlist_fn function;
621 {
622         struct exitlist *ep;
623
624 #ifdef INVARIANTS
625         /* Be noisy if the programmer has lost track of things */
626         if (rm_at_exit(function)) 
627                 printf("WARNING: exit callout entry (%p) already present\n",
628                     function);
629 #endif
630         ep = malloc(sizeof(*ep), M_ATEXIT, M_NOWAIT);
631         if (ep == NULL)
632                 return (ENOMEM);
633         ep->function = function;
634         TAILQ_INSERT_TAIL(&exit_list, ep, next);
635         return (0);
636 }
637
638 /*
639  * Scan the exit callout list for the given item and remove it.
640  * Returns the number of items removed (0 or 1)
641  */
642 int
643 rm_at_exit(function)
644         exitlist_fn function;
645 {
646         struct exitlist *ep;
647
648         TAILQ_FOREACH(ep, &exit_list, next) {
649                 if (ep->function == function) {
650                         TAILQ_REMOVE(&exit_list, ep, next);
651                         free(ep, M_ATEXIT);
652                         return(1);
653                 }
654         }       
655         return (0);
656 }
657
658 void check_sigacts (void)
659 {
660         struct proc *p = curproc;
661         struct sigacts *pss;
662         int s;
663
664         if (p->p_procsig->ps_refcnt == 1 &&
665             p->p_sigacts != &p->p_addr->u_sigacts) {
666                 pss = p->p_sigacts;
667                 s = splhigh();
668                 p->p_addr->u_sigacts = *pss;
669                 p->p_sigacts = &p->p_addr->u_sigacts;
670                 splx(s);
671                 FREE(pss, M_SUBPROC);
672         }
673 }
674