patch-2.6.6-vs1.9.0
[linux-2.6.git] / kernel / exit.c
1 /*
2  *  linux/kernel/exit.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 #include <linux/config.h>
8 #include <linux/mm.h>
9 #include <linux/slab.h>
10 #include <linux/interrupt.h>
11 #include <linux/smp_lock.h>
12 #include <linux/module.h>
13 #include <linux/completion.h>
14 #include <linux/personality.h>
15 #include <linux/tty.h>
16 #include <linux/namespace.h>
17 #include <linux/security.h>
18 #include <linux/acct.h>
19 #include <linux/file.h>
20 #include <linux/binfmts.h>
21 #include <linux/ptrace.h>
22 #include <linux/profile.h>
23 #include <linux/mount.h>
24 #include <linux/proc_fs.h>
25
26 #include <asm/uaccess.h>
27 #include <asm/pgtable.h>
28 #include <asm/mmu_context.h>
29
30 extern void sem_exit (void);
31 extern struct task_struct *child_reaper;
32
33 int getrusage(struct task_struct *, int, struct rusage *);
34
35 static void __unhash_process(struct task_struct *p)
36 {
37         nr_threads--;
38         /* tasklist_lock is held, is this sufficient? */
39         if (p->vx_info) {
40                 atomic_dec(&p->vx_info->cacct.nr_threads);
41                 atomic_dec(&p->vx_info->limit.res[RLIMIT_NPROC]);
42         }
43         detach_pid(p, PIDTYPE_PID);
44         detach_pid(p, PIDTYPE_TGID);
45         if (thread_group_leader(p)) {
46                 detach_pid(p, PIDTYPE_PGID);
47                 detach_pid(p, PIDTYPE_SID);
48                 if (p->pid)
49                         __get_cpu_var(process_counts)--;
50         }
51
52         REMOVE_LINKS(p);
53 }
54
55 void release_task(struct task_struct * p)
56 {
57         int zap_leader;
58         task_t *leader;
59         struct dentry *proc_dentry;
60
61 repeat: 
62         BUG_ON(p->state < TASK_ZOMBIE);
63  
64         atomic_dec(&p->user->processes);
65         spin_lock(&p->proc_lock);
66         proc_dentry = proc_pid_unhash(p);
67         write_lock_irq(&tasklist_lock);
68         if (unlikely(p->ptrace))
69                 __ptrace_unlink(p);
70         BUG_ON(!list_empty(&p->ptrace_list) || !list_empty(&p->ptrace_children));
71         __exit_signal(p);
72         __exit_sighand(p);
73         __unhash_process(p);
74
75         /*
76          * If we are the last non-leader member of the thread
77          * group, and the leader is zombie, then notify the
78          * group leader's parent process. (if it wants notification.)
79          */
80         zap_leader = 0;
81         leader = p->group_leader;
82         if (leader != p && thread_group_empty(leader) && leader->state == TASK_ZOMBIE) {
83                 BUG_ON(leader->exit_signal == -1);
84                 do_notify_parent(leader, leader->exit_signal);
85                 /*
86                  * If we were the last child thread and the leader has
87                  * exited already, and the leader's parent ignores SIGCHLD,
88                  * then we are the one who should release the leader.
89                  *
90                  * do_notify_parent() will have marked it self-reaping in
91                  * that case.
92                  */
93                 zap_leader = (leader->exit_signal == -1);
94         }
95
96         p->parent->cutime += p->utime + p->cutime;
97         p->parent->cstime += p->stime + p->cstime;
98         p->parent->cmin_flt += p->min_flt + p->cmin_flt;
99         p->parent->cmaj_flt += p->maj_flt + p->cmaj_flt;
100         p->parent->cnvcsw += p->nvcsw + p->cnvcsw;
101         p->parent->cnivcsw += p->nivcsw + p->cnivcsw;
102         sched_exit(p);
103         write_unlock_irq(&tasklist_lock);
104         spin_unlock(&p->proc_lock);
105         proc_pid_flush(proc_dentry);
106         release_thread(p);
107         put_task_struct(p);
108
109         p = leader;
110         if (unlikely(zap_leader))
111                 goto repeat;
112 }
113
114 /* we are using it only for SMP init */
115
116 void unhash_process(struct task_struct *p)
117 {
118         struct dentry *proc_dentry;
119
120         spin_lock(&p->proc_lock);
121         proc_dentry = proc_pid_unhash(p);
122         write_lock_irq(&tasklist_lock);
123         __unhash_process(p);
124         write_unlock_irq(&tasklist_lock);
125         spin_unlock(&p->proc_lock);
126         proc_pid_flush(proc_dentry);
127 }
128
129 /*
130  * This checks not only the pgrp, but falls back on the pid if no
131  * satisfactory pgrp is found. I dunno - gdb doesn't work correctly
132  * without this...
133  */
134 int session_of_pgrp(int pgrp)
135 {
136         struct task_struct *p;
137         struct list_head *l;
138         struct pid *pid;
139         int sid = -1;
140
141         read_lock(&tasklist_lock);
142         for_each_task_pid(pgrp, PIDTYPE_PGID, p, l, pid)
143                 if (p->signal->session > 0) {
144                         sid = p->signal->session;
145                         goto out;
146                 }
147         p = find_task_by_pid(pgrp);
148         if (p)
149                 sid = p->signal->session;
150 out:
151         read_unlock(&tasklist_lock);
152         
153         return sid;
154 }
155
156 /*
157  * Determine if a process group is "orphaned", according to the POSIX
158  * definition in 2.2.2.52.  Orphaned process groups are not to be affected
159  * by terminal-generated stop signals.  Newly orphaned process groups are
160  * to receive a SIGHUP and a SIGCONT.
161  *
162  * "I ask you, have you ever known what it is to be an orphan?"
163  */
164 static int will_become_orphaned_pgrp(int pgrp, task_t *ignored_task)
165 {
166         struct task_struct *p;
167         struct list_head *l;
168         struct pid *pid;
169         int ret = 1;
170
171         for_each_task_pid(pgrp, PIDTYPE_PGID, p, l, pid) {
172                 if (p == ignored_task
173                                 || p->state >= TASK_ZOMBIE 
174                                 || p->real_parent->pid == 1)
175                         continue;
176                 if (process_group(p->real_parent) != pgrp
177                             && p->real_parent->signal->session == p->signal->session) {
178                         ret = 0;
179                         break;
180                 }
181         }
182         return ret;     /* (sighing) "Often!" */
183 }
184
185 int is_orphaned_pgrp(int pgrp)
186 {
187         int retval;
188
189         read_lock(&tasklist_lock);
190         retval = will_become_orphaned_pgrp(pgrp, NULL);
191         read_unlock(&tasklist_lock);
192
193         return retval;
194 }
195
196 static inline int has_stopped_jobs(int pgrp)
197 {
198         int retval = 0;
199         struct task_struct *p;
200         struct list_head *l;
201         struct pid *pid;
202
203         for_each_task_pid(pgrp, PIDTYPE_PGID, p, l, pid) {
204                 if (p->state != TASK_STOPPED)
205                         continue;
206
207                 /* If p is stopped by a debugger on a signal that won't
208                    stop it, then don't count p as stopped.  This isn't
209                    perfect but it's a good approximation.  */
210                 if (unlikely (p->ptrace)
211                     && p->exit_code != SIGSTOP
212                     && p->exit_code != SIGTSTP
213                     && p->exit_code != SIGTTOU
214                     && p->exit_code != SIGTTIN)
215                         continue;
216
217                 retval = 1;
218                 break;
219         }
220         return retval;
221 }
222
223 /**
224  * reparent_to_init() - Reparent the calling kernel thread to the init task.
225  *
226  * If a kernel thread is launched as a result of a system call, or if
227  * it ever exits, it should generally reparent itself to init so that
228  * it is correctly cleaned up on exit.
229  *
230  * The various task state such as scheduling policy and priority may have
231  * been inherited from a user process, so we reset them to sane values here.
232  *
233  * NOTE that reparent_to_init() gives the caller full capabilities.
234  */
235 void reparent_to_init(void)
236 {
237         write_lock_irq(&tasklist_lock);
238
239         ptrace_unlink(current);
240         /* Reparent to init */
241         REMOVE_LINKS(current);
242         /* FIXME handle vchild_reaper/initpid */
243         current->parent = child_reaper;
244         current->real_parent = child_reaper;
245         SET_LINKS(current);
246
247         /* Set the exit signal to SIGCHLD so we signal init on exit */
248         current->exit_signal = SIGCHLD;
249
250         if ((current->policy == SCHED_NORMAL) && (task_nice(current) < 0))
251                 set_user_nice(current, 0);
252         /* cpus_allowed? */
253         /* rt_priority? */
254         /* signals? */
255         security_task_reparent_to_init(current);
256         memcpy(current->rlim, init_task.rlim, sizeof(*(current->rlim)));
257         atomic_inc(&(INIT_USER->__count));
258         switch_uid(INIT_USER);
259
260         write_unlock_irq(&tasklist_lock);
261 }
262
263 void __set_special_pids(pid_t session, pid_t pgrp)
264 {
265         struct task_struct *curr = current;
266
267         if (curr->signal->session != session) {
268                 detach_pid(curr, PIDTYPE_SID);
269                 curr->signal->session = session;
270                 attach_pid(curr, PIDTYPE_SID, session);
271         }
272         if (process_group(curr) != pgrp) {
273                 detach_pid(curr, PIDTYPE_PGID);
274                 curr->signal->pgrp = pgrp;
275                 attach_pid(curr, PIDTYPE_PGID, pgrp);
276         }
277 }
278
279 void set_special_pids(pid_t session, pid_t pgrp)
280 {
281         write_lock_irq(&tasklist_lock);
282         __set_special_pids(session, pgrp);
283         write_unlock_irq(&tasklist_lock);
284 }
285
286 /*
287  * Let kernel threads use this to say that they
288  * allow a certain signal (since daemonize() will
289  * have disabled all of them by default).
290  */
291 int allow_signal(int sig)
292 {
293         if (sig < 1 || sig > _NSIG)
294                 return -EINVAL;
295
296         spin_lock_irq(&current->sighand->siglock);
297         sigdelset(&current->blocked, sig);
298         if (!current->mm) {
299                 /* Kernel threads handle their own signals.
300                    Let the signal code know it'll be handled, so
301                    that they don't get converted to SIGKILL or
302                    just silently dropped */
303                 current->sighand->action[(sig)-1].sa.sa_handler = (void *)2;
304         }
305         recalc_sigpending();
306         spin_unlock_irq(&current->sighand->siglock);
307         return 0;
308 }
309
310 EXPORT_SYMBOL(allow_signal);
311
312 int disallow_signal(int sig)
313 {
314         if (sig < 1 || sig > _NSIG)
315                 return -EINVAL;
316
317         spin_lock_irq(&current->sighand->siglock);
318         sigaddset(&current->blocked, sig);
319         recalc_sigpending();
320         spin_unlock_irq(&current->sighand->siglock);
321         return 0;
322 }
323
324 EXPORT_SYMBOL(disallow_signal);
325
326 /*
327  *      Put all the gunge required to become a kernel thread without
328  *      attached user resources in one place where it belongs.
329  */
330
331 void daemonize(const char *name, ...)
332 {
333         va_list args;
334         struct fs_struct *fs;
335         sigset_t blocked;
336
337         va_start(args, name);
338         vsnprintf(current->comm, sizeof(current->comm), name, args);
339         va_end(args);
340
341         /*
342          * If we were started as result of loading a module, close all of the
343          * user space pages.  We don't need them, and if we didn't close them
344          * they would be locked into memory.
345          */
346         exit_mm(current);
347
348         set_special_pids(1, 1);
349         current->signal->tty = NULL;
350
351         /* Block and flush all signals */
352         sigfillset(&blocked);
353         sigprocmask(SIG_BLOCK, &blocked, NULL);
354         flush_signals(current);
355
356         /* Become as one with the init task */
357
358         exit_fs(current);       /* current->fs->count--; */
359         fs = init_task.fs;
360         current->fs = fs;
361         atomic_inc(&fs->count);
362         exit_files(current);
363         current->files = init_task.files;
364         atomic_inc(&current->files->count);
365
366         reparent_to_init();
367 }
368
369 EXPORT_SYMBOL(daemonize);
370
371 static inline void close_files(struct files_struct * files)
372 {
373         int i, j;
374
375         j = 0;
376         for (;;) {
377                 unsigned long set;
378                 i = j * __NFDBITS;
379                 if (i >= files->max_fdset || i >= files->max_fds)
380                         break;
381                 set = files->open_fds->fds_bits[j++];
382                 while (set) {
383                         if (set & 1) {
384                                 struct file * file = xchg(&files->fd[i], NULL);
385                                 if (file)
386                                         filp_close(file, files);
387                                 vx_openfd_dec(fd);
388                         }
389                         i++;
390                         set >>= 1;
391                 }
392         }
393 }
394
395 struct files_struct *get_files_struct(struct task_struct *task)
396 {
397         struct files_struct *files;
398
399         task_lock(task);
400         files = task->files;
401         if (files)
402                 atomic_inc(&files->count);
403         task_unlock(task);
404
405         return files;
406 }
407
408 void fastcall put_files_struct(struct files_struct *files)
409 {
410         if (atomic_dec_and_test(&files->count)) {
411                 close_files(files);
412                 /*
413                  * Free the fd and fdset arrays if we expanded them.
414                  */
415                 if (files->fd != &files->fd_array[0])
416                         free_fd_array(files->fd, files->max_fds);
417                 if (files->max_fdset > __FD_SETSIZE) {
418                         free_fdset(files->open_fds, files->max_fdset);
419                         free_fdset(files->close_on_exec, files->max_fdset);
420                 }
421                 kmem_cache_free(files_cachep, files);
422         }
423 }
424
425 EXPORT_SYMBOL(put_files_struct);
426
427 static inline void __exit_files(struct task_struct *tsk)
428 {
429         struct files_struct * files = tsk->files;
430
431         if (files) {
432                 task_lock(tsk);
433                 tsk->files = NULL;
434                 task_unlock(tsk);
435                 put_files_struct(files);
436         }
437 }
438
439 void exit_files(struct task_struct *tsk)
440 {
441         __exit_files(tsk);
442 }
443
444 static inline void __put_fs_struct(struct fs_struct *fs)
445 {
446         /* No need to hold fs->lock if we are killing it */
447         if (atomic_dec_and_test(&fs->count)) {
448                 dput(fs->root);
449                 mntput(fs->rootmnt);
450                 dput(fs->pwd);
451                 mntput(fs->pwdmnt);
452                 if (fs->altroot) {
453                         dput(fs->altroot);
454                         mntput(fs->altrootmnt);
455                 }
456                 kmem_cache_free(fs_cachep, fs);
457         }
458 }
459
460 void put_fs_struct(struct fs_struct *fs)
461 {
462         __put_fs_struct(fs);
463 }
464
465 static inline void __exit_fs(struct task_struct *tsk)
466 {
467         struct fs_struct * fs = tsk->fs;
468
469         if (fs) {
470                 task_lock(tsk);
471                 tsk->fs = NULL;
472                 task_unlock(tsk);
473                 __put_fs_struct(fs);
474         }
475 }
476
477 void exit_fs(struct task_struct *tsk)
478 {
479         __exit_fs(tsk);
480 }
481
482 EXPORT_SYMBOL_GPL(exit_fs);
483
484 /*
485  * Turn us into a lazy TLB process if we
486  * aren't already..
487  */
488 static inline void __exit_mm(struct task_struct * tsk)
489 {
490         struct mm_struct *mm = tsk->mm;
491
492         mm_release(tsk, mm);
493         if (!mm)
494                 return;
495         /*
496          * Serialize with any possible pending coredump.
497          * We must hold mmap_sem around checking core_waiters
498          * and clearing tsk->mm.  The core-inducing thread
499          * will increment core_waiters for each thread in the
500          * group with ->mm != NULL.
501          */
502         down_read(&mm->mmap_sem);
503         if (mm->core_waiters) {
504                 up_read(&mm->mmap_sem);
505                 down_write(&mm->mmap_sem);
506                 if (!--mm->core_waiters)
507                         complete(mm->core_startup_done);
508                 up_write(&mm->mmap_sem);
509
510                 wait_for_completion(&mm->core_done);
511                 down_read(&mm->mmap_sem);
512         }
513         atomic_inc(&mm->mm_count);
514         if (mm != tsk->active_mm) BUG();
515         /* more a memory barrier than a real lock */
516         task_lock(tsk);
517         tsk->mm = NULL;
518         up_read(&mm->mmap_sem);
519         enter_lazy_tlb(mm, current);
520         task_unlock(tsk);
521         mmput(mm);
522 }
523
524 void exit_mm(struct task_struct *tsk)
525 {
526         __exit_mm(tsk);
527 }
528
529 EXPORT_SYMBOL(exit_mm);
530
531 static inline void choose_new_parent(task_t *p, task_t *reaper, task_t *child_reaper)
532 {
533         /*
534          * Make sure we're not reparenting to ourselves and that
535          * the parent is not a zombie.
536          */
537         if (p == reaper || reaper->state >= TASK_ZOMBIE)
538                 p->real_parent = child_reaper;
539         else
540                 p->real_parent = reaper;
541         if (p->parent == p->real_parent)
542                 BUG();
543 }
544
545 static inline void reparent_thread(task_t *p, task_t *father, int traced)
546 {
547         /* We don't want people slaying init.  */
548         if (p->exit_signal != -1)
549                 p->exit_signal = SIGCHLD;
550         p->self_exec_id++;
551
552         if (p->pdeath_signal)
553                 /* We already hold the tasklist_lock here.  */
554                 group_send_sig_info(p->pdeath_signal, (void *) 0, p);
555
556         /* Move the child from its dying parent to the new one.  */
557         if (unlikely(traced)) {
558                 /* Preserve ptrace links if someone else is tracing this child.  */
559                 list_del_init(&p->ptrace_list);
560                 if (p->parent != p->real_parent)
561                         list_add(&p->ptrace_list, &p->real_parent->ptrace_children);
562         } else {
563                 /* If this child is being traced, then we're the one tracing it
564                  * anyway, so let go of it.
565                  */
566                 p->ptrace = 0;
567                 list_del_init(&p->sibling);
568                 p->parent = p->real_parent;
569                 list_add_tail(&p->sibling, &p->parent->children);
570
571                 /* If we'd notified the old parent about this child's death,
572                  * also notify the new parent.
573                  */
574                 if (p->state == TASK_ZOMBIE && p->exit_signal != -1 &&
575                     thread_group_empty(p))
576                         do_notify_parent(p, p->exit_signal);
577         }
578
579         /*
580          * process group orphan check
581          * Case ii: Our child is in a different pgrp
582          * than we are, and it was the only connection
583          * outside, so the child pgrp is now orphaned.
584          */
585         if ((process_group(p) != process_group(father)) &&
586             (p->signal->session == father->signal->session)) {
587                 int pgrp = process_group(p);
588
589                 if (will_become_orphaned_pgrp(pgrp, NULL) && has_stopped_jobs(pgrp)) {
590                         __kill_pg_info(SIGHUP, (void *)1, pgrp);
591                         __kill_pg_info(SIGCONT, (void *)1, pgrp);
592                 }
593         }
594 }
595
596 /*
597  * When we die, we re-parent all our children.
598  * Try to give them to another thread in our thread
599  * group, and if no such member exists, give it to
600  * the global child reaper process (ie "init")
601  */
602 static inline void forget_original_parent(struct task_struct * father)
603 {
604         struct task_struct *p, *reaper = father;
605         struct list_head *_p, *_n;
606
607         /* FIXME handle vchild_reaper/initpid */
608         reaper = father->group_leader;
609         if (reaper == father)
610                 reaper = child_reaper;
611
612         /*
613          * There are only two places where our children can be:
614          *
615          * - in our child list
616          * - in our ptraced child list
617          *
618          * Search them and reparent children.
619          */
620         list_for_each_safe(_p, _n, &father->children) {
621                 p = list_entry(_p,struct task_struct,sibling);
622                 if (father == p->real_parent) {
623                         choose_new_parent(p, reaper, child_reaper);
624                         reparent_thread(p, father, 0);
625                 } else {
626                         ptrace_unlink (p);
627                         if (p->state == TASK_ZOMBIE && p->exit_signal != -1 &&
628                             thread_group_empty(p))
629                                 do_notify_parent(p, p->exit_signal);
630                 }
631         }
632         list_for_each_safe(_p, _n, &father->ptrace_children) {
633                 p = list_entry(_p,struct task_struct,ptrace_list);
634                 choose_new_parent(p, reaper, child_reaper);
635                 reparent_thread(p, father, 1);
636         }
637 }
638
639 /*
640  * Send signals to all our closest relatives so that they know
641  * to properly mourn us..
642  */
643 static void exit_notify(struct task_struct *tsk)
644 {
645         int state;
646         struct task_struct *t;
647
648         if (signal_pending(tsk) && !tsk->signal->group_exit
649             && !thread_group_empty(tsk)) {
650                 /*
651                  * This occurs when there was a race between our exit
652                  * syscall and a group signal choosing us as the one to
653                  * wake up.  It could be that we are the only thread
654                  * alerted to check for pending signals, but another thread
655                  * should be woken now to take the signal since we will not.
656                  * Now we'll wake all the threads in the group just to make
657                  * sure someone gets all the pending signals.
658                  */
659                 read_lock(&tasklist_lock);
660                 spin_lock_irq(&tsk->sighand->siglock);
661                 for (t = next_thread(tsk); t != tsk; t = next_thread(t))
662                         if (!signal_pending(t) && !(t->flags & PF_EXITING)) {
663                                 recalc_sigpending_tsk(t);
664                                 if (signal_pending(t))
665                                         signal_wake_up(t, 0);
666                         }
667                 spin_unlock_irq(&tsk->sighand->siglock);
668                 read_unlock(&tasklist_lock);
669         }
670
671         write_lock_irq(&tasklist_lock);
672
673         /*
674          * This does two things:
675          *
676          * A.  Make init inherit all the child processes
677          * B.  Check to see if any process groups have become orphaned
678          *      as a result of our exiting, and if they have any stopped
679          *      jobs, send them a SIGHUP and then a SIGCONT.  (POSIX 3.2.2.2)
680          */
681
682         forget_original_parent(tsk);
683         BUG_ON(!list_empty(&tsk->children));
684
685         /*
686          * Check to see if any process groups have become orphaned
687          * as a result of our exiting, and if they have any stopped
688          * jobs, send them a SIGHUP and then a SIGCONT.  (POSIX 3.2.2.2)
689          *
690          * Case i: Our father is in a different pgrp than we are
691          * and we were the only connection outside, so our pgrp
692          * is about to become orphaned.
693          */
694          
695         t = tsk->real_parent;
696         
697         if ((process_group(t) != process_group(tsk)) &&
698             (t->signal->session == tsk->signal->session) &&
699             will_become_orphaned_pgrp(process_group(tsk), tsk) &&
700             has_stopped_jobs(process_group(tsk))) {
701                 __kill_pg_info(SIGHUP, (void *)1, process_group(tsk));
702                 __kill_pg_info(SIGCONT, (void *)1, process_group(tsk));
703         }
704
705         /* Let father know we died 
706          *
707          * Thread signals are configurable, but you aren't going to use
708          * that to send signals to arbitary processes. 
709          * That stops right now.
710          *
711          * If the parent exec id doesn't match the exec id we saved
712          * when we started then we know the parent has changed security
713          * domain.
714          *
715          * If our self_exec id doesn't match our parent_exec_id then
716          * we have changed execution domain as these two values started
717          * the same after a fork.
718          *      
719          */
720         
721         if (tsk->exit_signal != SIGCHLD && tsk->exit_signal != -1 &&
722             ( tsk->parent_exec_id != t->self_exec_id  ||
723               tsk->self_exec_id != tsk->parent_exec_id)
724             && !capable(CAP_KILL))
725                 tsk->exit_signal = SIGCHLD;
726
727
728         /* If something other than our normal parent is ptracing us, then
729          * send it a SIGCHLD instead of honoring exit_signal.  exit_signal
730          * only has special meaning to our real parent.
731          */
732         if (tsk->exit_signal != -1 && thread_group_empty(tsk)) {
733                 int signal = tsk->parent == tsk->real_parent ? tsk->exit_signal : SIGCHLD;
734                 do_notify_parent(tsk, signal);
735         } else if (tsk->ptrace) {
736                 do_notify_parent(tsk, SIGCHLD);
737         }
738
739         state = TASK_ZOMBIE;
740         if (tsk->exit_signal == -1 && tsk->ptrace == 0)
741                 state = TASK_DEAD;
742         tsk->state = state;
743         tsk->flags |= PF_DEAD;
744
745         /*
746          * In the preemption case it must be impossible for the task
747          * to get runnable again, so use "_raw_" unlock to keep
748          * preempt_count elevated until we schedule().
749          *
750          * To avoid deadlock on SMP, interrupts must be unmasked.  If we
751          * don't, subsequently called functions (e.g, wait_task_inactive()
752          * via release_task()) will spin, with interrupt flags
753          * unwittingly blocked, until the other task sleeps.  That task
754          * may itself be waiting for smp_call_function() to answer and
755          * complete, and with interrupts blocked that will never happen.
756          */
757         _raw_write_unlock(&tasklist_lock);
758         local_irq_enable();
759
760         /* If the process is dead, release it - nobody will wait for it */
761         if (state == TASK_DEAD)
762                 release_task(tsk);
763
764 }
765
766 asmlinkage NORET_TYPE void do_exit(long code)
767 {
768         struct task_struct *tsk = current;
769
770         if (unlikely(in_interrupt()))
771                 panic("Aiee, killing interrupt handler!");
772         if (unlikely(!tsk->pid))
773                 panic("Attempted to kill the idle task!");
774         if (unlikely(tsk->pid == 1))
775                 panic("Attempted to kill init!");
776         if (tsk->io_context)
777                 exit_io_context();
778         tsk->flags |= PF_EXITING;
779         del_timer_sync(&tsk->real_timer);
780
781         if (unlikely(in_atomic()))
782                 printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n",
783                                 current->comm, current->pid,
784                                 preempt_count());
785
786         profile_exit_task(tsk);
787  
788         if (unlikely(current->ptrace & PT_TRACE_EXIT)) {
789                 current->ptrace_message = code;
790                 ptrace_notify((PTRACE_EVENT_EXIT << 8) | SIGTRAP);
791         }
792
793         acct_process(code);
794         __exit_mm(tsk);
795
796         exit_sem(tsk);
797         __exit_files(tsk);
798         __exit_fs(tsk);
799         exit_namespace(tsk);
800         exit_thread();
801
802         if (tsk->signal->leader)
803                 disassociate_ctty(1);
804
805         module_put(tsk->thread_info->exec_domain->module);
806         if (tsk->binfmt)
807                 module_put(tsk->binfmt->module);
808
809         tsk->exit_code = code;
810         exit_notify(tsk);
811         schedule();
812         BUG();
813         /* Avoid "noreturn function does return".  */
814         for (;;) ;
815 }
816
817 NORET_TYPE void complete_and_exit(struct completion *comp, long code)
818 {
819         if (comp)
820                 complete(comp);
821         
822         do_exit(code);
823 }
824
825 EXPORT_SYMBOL(complete_and_exit);
826
827 asmlinkage long sys_exit(int error_code)
828 {
829         do_exit((error_code&0xff)<<8);
830 }
831
832 task_t fastcall *next_thread(task_t *p)
833 {
834         struct pid_link *link = p->pids + PIDTYPE_TGID;
835         struct list_head *tmp, *head = &link->pidptr->task_list;
836
837 #ifdef CONFIG_SMP
838         if (!p->sighand)
839                 BUG();
840         if (!spin_is_locked(&p->sighand->siglock) &&
841                                 !rwlock_is_locked(&tasklist_lock))
842                 BUG();
843 #endif
844         tmp = link->pid_chain.next;
845         if (tmp == head)
846                 tmp = head->next;
847
848         return pid_task(tmp, PIDTYPE_TGID);
849 }
850
851 EXPORT_SYMBOL(next_thread);
852
853 /*
854  * Take down every thread in the group.  This is called by fatal signals
855  * as well as by sys_exit_group (below).
856  */
857 NORET_TYPE void
858 do_group_exit(int exit_code)
859 {
860         BUG_ON(exit_code & 0x80); /* core dumps don't get here */
861
862         if (current->signal->group_exit)
863                 exit_code = current->signal->group_exit_code;
864         else if (!thread_group_empty(current)) {
865                 struct signal_struct *const sig = current->signal;
866                 struct sighand_struct *const sighand = current->sighand;
867                 read_lock(&tasklist_lock);
868                 spin_lock_irq(&sighand->siglock);
869                 if (sig->group_exit)
870                         /* Another thread got here before we took the lock.  */
871                         exit_code = sig->group_exit_code;
872                 else {
873                         sig->group_exit = 1;
874                         sig->group_exit_code = exit_code;
875                         zap_other_threads(current);
876                 }
877                 spin_unlock_irq(&sighand->siglock);
878                 read_unlock(&tasklist_lock);
879         }
880
881         do_exit(exit_code);
882         /* NOTREACHED */
883 }
884
885 /*
886  * this kills every thread in the thread group. Note that any externally
887  * wait4()-ing process will get the correct exit code - even if this
888  * thread is not the thread group leader.
889  */
890 asmlinkage void sys_exit_group(int error_code)
891 {
892         do_group_exit((error_code & 0xff) << 8);
893 }
894
895 static int eligible_child(pid_t pid, int options, task_t *p)
896 {
897         if (pid > 0) {
898                 if (p->pid != pid)
899                         return 0;
900         } else if (!pid) {
901                 if (process_group(p) != process_group(current))
902                         return 0;
903         } else if (pid != -1) {
904                 if (process_group(p) != -pid)
905                         return 0;
906         }
907
908         /*
909          * Do not consider detached threads that are
910          * not ptraced:
911          */
912         if (p->exit_signal == -1 && !p->ptrace)
913                 return 0;
914
915         /* Wait for all children (clone and not) if __WALL is set;
916          * otherwise, wait for clone children *only* if __WCLONE is
917          * set; otherwise, wait for non-clone children *only*.  (Note:
918          * A "clone" child here is one that reports to its parent
919          * using a signal other than SIGCHLD.) */
920         if (((p->exit_signal != SIGCHLD) ^ ((options & __WCLONE) != 0))
921             && !(options & __WALL))
922                 return 0;
923         /*
924          * Do not consider thread group leaders that are
925          * in a non-empty thread group:
926          */
927         if (current->tgid != p->tgid && delay_group_leader(p))
928                 return 2;
929
930         if (security_task_wait(p))
931                 return 0;
932
933         return 1;
934 }
935
936 /*
937  * Handle sys_wait4 work for one task in state TASK_ZOMBIE.  We hold
938  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
939  * the lock and this task is uninteresting.  If we return nonzero, we have
940  * released the lock and the system call should return.
941  */
942 static int wait_task_zombie(task_t *p, unsigned int *stat_addr, struct rusage *ru)
943 {
944         unsigned long state;
945         int retval;
946
947         /*
948          * Try to move the task's state to DEAD
949          * only one thread is allowed to do this:
950          */
951         state = xchg(&p->state, TASK_DEAD);
952         if (state != TASK_ZOMBIE) {
953                 BUG_ON(state != TASK_DEAD);
954                 return 0;
955         }
956         if (unlikely(p->exit_signal == -1 && p->ptrace == 0))
957                 /*
958                  * This can only happen in a race with a ptraced thread
959                  * dying on another processor.
960                  */
961                 return 0;
962
963         /*
964          * Now we are sure this task is interesting, and no other
965          * thread can reap it because we set its state to TASK_DEAD.
966          */
967         read_unlock(&tasklist_lock);
968
969         retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
970         if (!retval && stat_addr) {
971                 if (p->signal->group_exit)
972                         retval = put_user(p->signal->group_exit_code, stat_addr);
973                 else
974                         retval = put_user(p->exit_code, stat_addr);
975         }
976         if (retval) {
977                 p->state = TASK_ZOMBIE;
978                 return retval;
979         }
980         retval = p->pid;
981         if (p->real_parent != p->parent) {
982                 write_lock_irq(&tasklist_lock);
983                 /* Double-check with lock held.  */
984                 if (p->real_parent != p->parent) {
985                         __ptrace_unlink(p);
986                         p->state = TASK_ZOMBIE;
987                         /* If this is a detached thread, this is where it goes away.  */
988                         if (p->exit_signal == -1) {
989                                 /* release_task takes the lock itself.  */
990                                 write_unlock_irq(&tasklist_lock);
991                                 release_task (p);
992                         }
993                         else {
994                                 do_notify_parent(p, p->exit_signal);
995                                 write_unlock_irq(&tasklist_lock);
996                         }
997                         p = NULL;
998                 }
999                 else
1000                         write_unlock_irq(&tasklist_lock);
1001         }
1002         if (p != NULL)
1003                 release_task(p);
1004         BUG_ON(!retval);
1005         return retval;
1006 }
1007
1008 /*
1009  * Handle sys_wait4 work for one task in state TASK_STOPPED.  We hold
1010  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1011  * the lock and this task is uninteresting.  If we return nonzero, we have
1012  * released the lock and the system call should return.
1013  */
1014 static int wait_task_stopped(task_t *p, int delayed_group_leader,
1015                              unsigned int *stat_addr, struct rusage *ru)
1016 {
1017         int retval, exit_code;
1018
1019         if (!p->exit_code)
1020                 return 0;
1021         if (delayed_group_leader && !(p->ptrace & PT_PTRACED) &&
1022             p->signal && p->signal->group_stop_count > 0)
1023                 /*
1024                  * A group stop is in progress and this is the group leader.
1025                  * We won't report until all threads have stopped.
1026                  */
1027                 return 0;
1028
1029         /*
1030          * Now we are pretty sure this task is interesting.
1031          * Make sure it doesn't get reaped out from under us while we
1032          * give up the lock and then examine it below.  We don't want to
1033          * keep holding onto the tasklist_lock while we call getrusage and
1034          * possibly take page faults for user memory.
1035          */
1036         get_task_struct(p);
1037         read_unlock(&tasklist_lock);
1038         write_lock_irq(&tasklist_lock);
1039
1040         /*
1041          * This uses xchg to be atomic with the thread resuming and setting
1042          * it.  It must also be done with the write lock held to prevent a
1043          * race with the TASK_ZOMBIE case.
1044          */
1045         exit_code = xchg(&p->exit_code, 0);
1046         if (unlikely(p->state > TASK_STOPPED)) {
1047                 /*
1048                  * The task resumed and then died.  Let the next iteration
1049                  * catch it in TASK_ZOMBIE.  Note that exit_code might
1050                  * already be zero here if it resumed and did _exit(0).
1051                  * The task itself is dead and won't touch exit_code again;
1052                  * other processors in this function are locked out.
1053                  */
1054                 p->exit_code = exit_code;
1055                 exit_code = 0;
1056         }
1057         if (unlikely(exit_code == 0)) {
1058                 /*
1059                  * Another thread in this function got to it first, or it
1060                  * resumed, or it resumed and then died.
1061                  */
1062                 write_unlock_irq(&tasklist_lock);
1063                 put_task_struct(p);
1064                 read_lock(&tasklist_lock);
1065                 return 0;
1066         }
1067
1068         /* move to end of parent's list to avoid starvation */
1069         remove_parent(p);
1070         add_parent(p, p->parent);
1071
1072         write_unlock_irq(&tasklist_lock);
1073
1074         retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
1075         if (!retval && stat_addr)
1076                 retval = put_user((exit_code << 8) | 0x7f, stat_addr);
1077         if (!retval)
1078                 retval = p->pid;
1079         put_task_struct(p);
1080
1081         BUG_ON(!retval);
1082         return retval;
1083 }
1084
1085 asmlinkage long sys_wait4(pid_t pid,unsigned int * stat_addr, int options, struct rusage * ru)
1086 {
1087         DECLARE_WAITQUEUE(wait, current);
1088         struct task_struct *tsk;
1089         int flag, retval;
1090
1091         if (options & ~(WNOHANG|WUNTRACED|__WNOTHREAD|__WCLONE|__WALL))
1092                 return -EINVAL;
1093
1094         add_wait_queue(&current->wait_chldexit,&wait);
1095 repeat:
1096         flag = 0;
1097         current->state = TASK_INTERRUPTIBLE;
1098         read_lock(&tasklist_lock);
1099         tsk = current;
1100         do {
1101                 struct task_struct *p;
1102                 struct list_head *_p;
1103                 int ret;
1104
1105                 list_for_each(_p,&tsk->children) {
1106                         p = list_entry(_p,struct task_struct,sibling);
1107
1108                         ret = eligible_child(pid, options, p);
1109                         if (!ret)
1110                                 continue;
1111                         flag = 1;
1112
1113                         switch (p->state) {
1114                         case TASK_STOPPED:
1115                                 if (!(options & WUNTRACED) &&
1116                                     !(p->ptrace & PT_PTRACED))
1117                                         continue;
1118                                 retval = wait_task_stopped(p, ret == 2,
1119                                                            stat_addr, ru);
1120                                 if (retval != 0) /* He released the lock.  */
1121                                         goto end_wait4;
1122                                 break;
1123                         case TASK_ZOMBIE:
1124                                 /*
1125                                  * Eligible but we cannot release it yet:
1126                                  */
1127                                 if (ret == 2)
1128                                         continue;
1129                                 retval = wait_task_zombie(p, stat_addr, ru);
1130                                 if (retval != 0) /* He released the lock.  */
1131                                         goto end_wait4;
1132                                 break;
1133                         }
1134                 }
1135                 if (!flag) {
1136                         list_for_each (_p,&tsk->ptrace_children) {
1137                                 p = list_entry(_p,struct task_struct,ptrace_list);
1138                                 if (!eligible_child(pid, options, p))
1139                                         continue;
1140                                 flag = 1;
1141                                 break;
1142                         }
1143                 }
1144                 if (options & __WNOTHREAD)
1145                         break;
1146                 tsk = next_thread(tsk);
1147                 if (tsk->signal != current->signal)
1148                         BUG();
1149         } while (tsk != current);
1150         read_unlock(&tasklist_lock);
1151         if (flag) {
1152                 retval = 0;
1153                 if (options & WNOHANG)
1154                         goto end_wait4;
1155                 retval = -ERESTARTSYS;
1156                 if (signal_pending(current))
1157                         goto end_wait4;
1158                 schedule();
1159                 goto repeat;
1160         }
1161         retval = -ECHILD;
1162 end_wait4:
1163         current->state = TASK_RUNNING;
1164         remove_wait_queue(&current->wait_chldexit,&wait);
1165         return retval;
1166 }
1167
1168 #if !defined(__alpha__) && !defined(__ia64__) && \
1169     !defined(__arm__) && !defined(__s390__)
1170
1171 /*
1172  * sys_waitpid() remains for compatibility. waitpid() should be
1173  * implemented by calling sys_wait4() from libc.a.
1174  */
1175 asmlinkage long sys_waitpid(pid_t pid,unsigned int * stat_addr, int options)
1176 {
1177         return sys_wait4(pid, stat_addr, options, NULL);
1178 }
1179
1180 #endif