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