Merge branch 'master' into next
[safe/jmp/linux-2.6] / kernel / exit.c
1 /*
2  *  linux/kernel/exit.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 #include <linux/mm.h>
8 #include <linux/slab.h>
9 #include <linux/interrupt.h>
10 #include <linux/module.h>
11 #include <linux/capability.h>
12 #include <linux/completion.h>
13 #include <linux/personality.h>
14 #include <linux/tty.h>
15 #include <linux/mnt_namespace.h>
16 #include <linux/iocontext.h>
17 #include <linux/key.h>
18 #include <linux/security.h>
19 #include <linux/cpu.h>
20 #include <linux/acct.h>
21 #include <linux/tsacct_kern.h>
22 #include <linux/file.h>
23 #include <linux/fdtable.h>
24 #include <linux/binfmts.h>
25 #include <linux/nsproxy.h>
26 #include <linux/pid_namespace.h>
27 #include <linux/ptrace.h>
28 #include <linux/profile.h>
29 #include <linux/mount.h>
30 #include <linux/proc_fs.h>
31 #include <linux/kthread.h>
32 #include <linux/mempolicy.h>
33 #include <linux/taskstats_kern.h>
34 #include <linux/delayacct.h>
35 #include <linux/freezer.h>
36 #include <linux/cgroup.h>
37 #include <linux/syscalls.h>
38 #include <linux/signal.h>
39 #include <linux/posix-timers.h>
40 #include <linux/cn_proc.h>
41 #include <linux/mutex.h>
42 #include <linux/futex.h>
43 #include <linux/compat.h>
44 #include <linux/pipe_fs_i.h>
45 #include <linux/audit.h> /* for audit_free() */
46 #include <linux/resource.h>
47 #include <linux/blkdev.h>
48 #include <linux/task_io_accounting_ops.h>
49 #include <linux/tracehook.h>
50 #include <linux/init_task.h>
51 #include <trace/sched.h>
52
53 #include <asm/uaccess.h>
54 #include <asm/unistd.h>
55 #include <asm/pgtable.h>
56 #include <asm/mmu_context.h>
57 #include "cred-internals.h"
58
59 static void exit_mm(struct task_struct * tsk);
60
61 static inline int task_detached(struct task_struct *p)
62 {
63         return p->exit_signal == -1;
64 }
65
66 static void __unhash_process(struct task_struct *p)
67 {
68         nr_threads--;
69         detach_pid(p, PIDTYPE_PID);
70         if (thread_group_leader(p)) {
71                 detach_pid(p, PIDTYPE_PGID);
72                 detach_pid(p, PIDTYPE_SID);
73
74                 list_del_rcu(&p->tasks);
75                 __get_cpu_var(process_counts)--;
76         }
77         list_del_rcu(&p->thread_group);
78         list_del_init(&p->sibling);
79 }
80
81 /*
82  * This function expects the tasklist_lock write-locked.
83  */
84 static void __exit_signal(struct task_struct *tsk)
85 {
86         struct signal_struct *sig = tsk->signal;
87         struct sighand_struct *sighand;
88
89         BUG_ON(!sig);
90         BUG_ON(!atomic_read(&sig->count));
91
92         sighand = rcu_dereference(tsk->sighand);
93         spin_lock(&sighand->siglock);
94
95         posix_cpu_timers_exit(tsk);
96         if (atomic_dec_and_test(&sig->count))
97                 posix_cpu_timers_exit_group(tsk);
98         else {
99                 /*
100                  * If there is any task waiting for the group exit
101                  * then notify it:
102                  */
103                 if (sig->group_exit_task && atomic_read(&sig->count) == sig->notify_count)
104                         wake_up_process(sig->group_exit_task);
105
106                 if (tsk == sig->curr_target)
107                         sig->curr_target = next_thread(tsk);
108                 /*
109                  * Accumulate here the counters for all threads but the
110                  * group leader as they die, so they can be added into
111                  * the process-wide totals when those are taken.
112                  * The group leader stays around as a zombie as long
113                  * as there are other threads.  When it gets reaped,
114                  * the exit.c code will add its counts into these totals.
115                  * We won't ever get here for the group leader, since it
116                  * will have been the last reference on the signal_struct.
117                  */
118                 sig->gtime = cputime_add(sig->gtime, task_gtime(tsk));
119                 sig->min_flt += tsk->min_flt;
120                 sig->maj_flt += tsk->maj_flt;
121                 sig->nvcsw += tsk->nvcsw;
122                 sig->nivcsw += tsk->nivcsw;
123                 sig->inblock += task_io_get_inblock(tsk);
124                 sig->oublock += task_io_get_oublock(tsk);
125                 task_io_accounting_add(&sig->ioac, &tsk->ioac);
126                 sig = NULL; /* Marker for below. */
127         }
128
129         __unhash_process(tsk);
130
131         /*
132          * Do this under ->siglock, we can race with another thread
133          * doing sigqueue_free() if we have SIGQUEUE_PREALLOC signals.
134          */
135         flush_sigqueue(&tsk->pending);
136
137         tsk->signal = NULL;
138         tsk->sighand = NULL;
139         spin_unlock(&sighand->siglock);
140
141         __cleanup_sighand(sighand);
142         clear_tsk_thread_flag(tsk,TIF_SIGPENDING);
143         if (sig) {
144                 flush_sigqueue(&sig->shared_pending);
145                 taskstats_tgid_free(sig);
146                 /*
147                  * Make sure ->signal can't go away under rq->lock,
148                  * see account_group_exec_runtime().
149                  */
150                 task_rq_unlock_wait(tsk);
151                 __cleanup_signal(sig);
152         }
153 }
154
155 static void delayed_put_task_struct(struct rcu_head *rhp)
156 {
157         struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
158
159         trace_sched_process_free(tsk);
160         put_task_struct(tsk);
161 }
162
163
164 void release_task(struct task_struct * p)
165 {
166         struct task_struct *leader;
167         int zap_leader;
168 repeat:
169         tracehook_prepare_release_task(p);
170         /* don't need to get the RCU readlock here - the process is dead and
171          * can't be modifying its own credentials */
172         atomic_dec(&__task_cred(p)->user->processes);
173
174         proc_flush_task(p);
175         write_lock_irq(&tasklist_lock);
176         tracehook_finish_release_task(p);
177         __exit_signal(p);
178
179         /*
180          * If we are the last non-leader member of the thread
181          * group, and the leader is zombie, then notify the
182          * group leader's parent process. (if it wants notification.)
183          */
184         zap_leader = 0;
185         leader = p->group_leader;
186         if (leader != p && thread_group_empty(leader) && leader->exit_state == EXIT_ZOMBIE) {
187                 BUG_ON(task_detached(leader));
188                 do_notify_parent(leader, leader->exit_signal);
189                 /*
190                  * If we were the last child thread and the leader has
191                  * exited already, and the leader's parent ignores SIGCHLD,
192                  * then we are the one who should release the leader.
193                  *
194                  * do_notify_parent() will have marked it self-reaping in
195                  * that case.
196                  */
197                 zap_leader = task_detached(leader);
198
199                 /*
200                  * This maintains the invariant that release_task()
201                  * only runs on a task in EXIT_DEAD, just for sanity.
202                  */
203                 if (zap_leader)
204                         leader->exit_state = EXIT_DEAD;
205         }
206
207         write_unlock_irq(&tasklist_lock);
208         release_thread(p);
209         call_rcu(&p->rcu, delayed_put_task_struct);
210
211         p = leader;
212         if (unlikely(zap_leader))
213                 goto repeat;
214 }
215
216 /*
217  * This checks not only the pgrp, but falls back on the pid if no
218  * satisfactory pgrp is found. I dunno - gdb doesn't work correctly
219  * without this...
220  *
221  * The caller must hold rcu lock or the tasklist lock.
222  */
223 struct pid *session_of_pgrp(struct pid *pgrp)
224 {
225         struct task_struct *p;
226         struct pid *sid = NULL;
227
228         p = pid_task(pgrp, PIDTYPE_PGID);
229         if (p == NULL)
230                 p = pid_task(pgrp, PIDTYPE_PID);
231         if (p != NULL)
232                 sid = task_session(p);
233
234         return sid;
235 }
236
237 /*
238  * Determine if a process group is "orphaned", according to the POSIX
239  * definition in 2.2.2.52.  Orphaned process groups are not to be affected
240  * by terminal-generated stop signals.  Newly orphaned process groups are
241  * to receive a SIGHUP and a SIGCONT.
242  *
243  * "I ask you, have you ever known what it is to be an orphan?"
244  */
245 static int will_become_orphaned_pgrp(struct pid *pgrp, struct task_struct *ignored_task)
246 {
247         struct task_struct *p;
248
249         do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
250                 if ((p == ignored_task) ||
251                     (p->exit_state && thread_group_empty(p)) ||
252                     is_global_init(p->real_parent))
253                         continue;
254
255                 if (task_pgrp(p->real_parent) != pgrp &&
256                     task_session(p->real_parent) == task_session(p))
257                         return 0;
258         } while_each_pid_task(pgrp, PIDTYPE_PGID, p);
259
260         return 1;
261 }
262
263 int is_current_pgrp_orphaned(void)
264 {
265         int retval;
266
267         read_lock(&tasklist_lock);
268         retval = will_become_orphaned_pgrp(task_pgrp(current), NULL);
269         read_unlock(&tasklist_lock);
270
271         return retval;
272 }
273
274 static int has_stopped_jobs(struct pid *pgrp)
275 {
276         int retval = 0;
277         struct task_struct *p;
278
279         do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
280                 if (!task_is_stopped(p))
281                         continue;
282                 retval = 1;
283                 break;
284         } while_each_pid_task(pgrp, PIDTYPE_PGID, p);
285         return retval;
286 }
287
288 /*
289  * Check to see if any process groups have become orphaned as
290  * a result of our exiting, and if they have any stopped jobs,
291  * send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2)
292  */
293 static void
294 kill_orphaned_pgrp(struct task_struct *tsk, struct task_struct *parent)
295 {
296         struct pid *pgrp = task_pgrp(tsk);
297         struct task_struct *ignored_task = tsk;
298
299         if (!parent)
300                  /* exit: our father is in a different pgrp than
301                   * we are and we were the only connection outside.
302                   */
303                 parent = tsk->real_parent;
304         else
305                 /* reparent: our child is in a different pgrp than
306                  * we are, and it was the only connection outside.
307                  */
308                 ignored_task = NULL;
309
310         if (task_pgrp(parent) != pgrp &&
311             task_session(parent) == task_session(tsk) &&
312             will_become_orphaned_pgrp(pgrp, ignored_task) &&
313             has_stopped_jobs(pgrp)) {
314                 __kill_pgrp_info(SIGHUP, SEND_SIG_PRIV, pgrp);
315                 __kill_pgrp_info(SIGCONT, SEND_SIG_PRIV, pgrp);
316         }
317 }
318
319 /**
320  * reparent_to_kthreadd - Reparent the calling kernel thread to kthreadd
321  *
322  * If a kernel thread is launched as a result of a system call, or if
323  * it ever exits, it should generally reparent itself to kthreadd so it
324  * isn't in the way of other processes and is correctly cleaned up on exit.
325  *
326  * The various task state such as scheduling policy and priority may have
327  * been inherited from a user process, so we reset them to sane values here.
328  *
329  * NOTE that reparent_to_kthreadd() gives the caller full capabilities.
330  */
331 static void reparent_to_kthreadd(void)
332 {
333         write_lock_irq(&tasklist_lock);
334
335         ptrace_unlink(current);
336         /* Reparent to init */
337         current->real_parent = current->parent = kthreadd_task;
338         list_move_tail(&current->sibling, &current->real_parent->children);
339
340         /* Set the exit signal to SIGCHLD so we signal init on exit */
341         current->exit_signal = SIGCHLD;
342
343         if (task_nice(current) < 0)
344                 set_user_nice(current, 0);
345         /* cpus_allowed? */
346         /* rt_priority? */
347         /* signals? */
348         memcpy(current->signal->rlim, init_task.signal->rlim,
349                sizeof(current->signal->rlim));
350
351         atomic_inc(&init_cred.usage);
352         commit_creds(&init_cred);
353         write_unlock_irq(&tasklist_lock);
354 }
355
356 void __set_special_pids(struct pid *pid)
357 {
358         struct task_struct *curr = current->group_leader;
359         pid_t nr = pid_nr(pid);
360
361         if (task_session(curr) != pid) {
362                 change_pid(curr, PIDTYPE_SID, pid);
363                 set_task_session(curr, nr);
364         }
365         if (task_pgrp(curr) != pid) {
366                 change_pid(curr, PIDTYPE_PGID, pid);
367                 set_task_pgrp(curr, nr);
368         }
369 }
370
371 static void set_special_pids(struct pid *pid)
372 {
373         write_lock_irq(&tasklist_lock);
374         __set_special_pids(pid);
375         write_unlock_irq(&tasklist_lock);
376 }
377
378 /*
379  * Let kernel threads use this to say that they
380  * allow a certain signal (since daemonize() will
381  * have disabled all of them by default).
382  */
383 int allow_signal(int sig)
384 {
385         if (!valid_signal(sig) || sig < 1)
386                 return -EINVAL;
387
388         spin_lock_irq(&current->sighand->siglock);
389         sigdelset(&current->blocked, sig);
390         if (!current->mm) {
391                 /* Kernel threads handle their own signals.
392                    Let the signal code know it'll be handled, so
393                    that they don't get converted to SIGKILL or
394                    just silently dropped */
395                 current->sighand->action[(sig)-1].sa.sa_handler = (void __user *)2;
396         }
397         recalc_sigpending();
398         spin_unlock_irq(&current->sighand->siglock);
399         return 0;
400 }
401
402 EXPORT_SYMBOL(allow_signal);
403
404 int disallow_signal(int sig)
405 {
406         if (!valid_signal(sig) || sig < 1)
407                 return -EINVAL;
408
409         spin_lock_irq(&current->sighand->siglock);
410         current->sighand->action[(sig)-1].sa.sa_handler = SIG_IGN;
411         recalc_sigpending();
412         spin_unlock_irq(&current->sighand->siglock);
413         return 0;
414 }
415
416 EXPORT_SYMBOL(disallow_signal);
417
418 /*
419  *      Put all the gunge required to become a kernel thread without
420  *      attached user resources in one place where it belongs.
421  */
422
423 void daemonize(const char *name, ...)
424 {
425         va_list args;
426         struct fs_struct *fs;
427         sigset_t blocked;
428
429         va_start(args, name);
430         vsnprintf(current->comm, sizeof(current->comm), name, args);
431         va_end(args);
432
433         /*
434          * If we were started as result of loading a module, close all of the
435          * user space pages.  We don't need them, and if we didn't close them
436          * they would be locked into memory.
437          */
438         exit_mm(current);
439         /*
440          * We don't want to have TIF_FREEZE set if the system-wide hibernation
441          * or suspend transition begins right now.
442          */
443         current->flags |= (PF_NOFREEZE | PF_KTHREAD);
444
445         if (current->nsproxy != &init_nsproxy) {
446                 get_nsproxy(&init_nsproxy);
447                 switch_task_namespaces(current, &init_nsproxy);
448         }
449         set_special_pids(&init_struct_pid);
450         proc_clear_tty(current);
451
452         /* Block and flush all signals */
453         sigfillset(&blocked);
454         sigprocmask(SIG_BLOCK, &blocked, NULL);
455         flush_signals(current);
456
457         /* Become as one with the init task */
458
459         exit_fs(current);       /* current->fs->count--; */
460         fs = init_task.fs;
461         current->fs = fs;
462         atomic_inc(&fs->count);
463
464         exit_files(current);
465         current->files = init_task.files;
466         atomic_inc(&current->files->count);
467
468         reparent_to_kthreadd();
469 }
470
471 EXPORT_SYMBOL(daemonize);
472
473 static void close_files(struct files_struct * files)
474 {
475         int i, j;
476         struct fdtable *fdt;
477
478         j = 0;
479
480         /*
481          * It is safe to dereference the fd table without RCU or
482          * ->file_lock because this is the last reference to the
483          * files structure.
484          */
485         fdt = files_fdtable(files);
486         for (;;) {
487                 unsigned long set;
488                 i = j * __NFDBITS;
489                 if (i >= fdt->max_fds)
490                         break;
491                 set = fdt->open_fds->fds_bits[j++];
492                 while (set) {
493                         if (set & 1) {
494                                 struct file * file = xchg(&fdt->fd[i], NULL);
495                                 if (file) {
496                                         filp_close(file, files);
497                                         cond_resched();
498                                 }
499                         }
500                         i++;
501                         set >>= 1;
502                 }
503         }
504 }
505
506 struct files_struct *get_files_struct(struct task_struct *task)
507 {
508         struct files_struct *files;
509
510         task_lock(task);
511         files = task->files;
512         if (files)
513                 atomic_inc(&files->count);
514         task_unlock(task);
515
516         return files;
517 }
518
519 void put_files_struct(struct files_struct *files)
520 {
521         struct fdtable *fdt;
522
523         if (atomic_dec_and_test(&files->count)) {
524                 close_files(files);
525                 /*
526                  * Free the fd and fdset arrays if we expanded them.
527                  * If the fdtable was embedded, pass files for freeing
528                  * at the end of the RCU grace period. Otherwise,
529                  * you can free files immediately.
530                  */
531                 fdt = files_fdtable(files);
532                 if (fdt != &files->fdtab)
533                         kmem_cache_free(files_cachep, files);
534                 free_fdtable(fdt);
535         }
536 }
537
538 void reset_files_struct(struct files_struct *files)
539 {
540         struct task_struct *tsk = current;
541         struct files_struct *old;
542
543         old = tsk->files;
544         task_lock(tsk);
545         tsk->files = files;
546         task_unlock(tsk);
547         put_files_struct(old);
548 }
549
550 void exit_files(struct task_struct *tsk)
551 {
552         struct files_struct * files = tsk->files;
553
554         if (files) {
555                 task_lock(tsk);
556                 tsk->files = NULL;
557                 task_unlock(tsk);
558                 put_files_struct(files);
559         }
560 }
561
562 void put_fs_struct(struct fs_struct *fs)
563 {
564         /* No need to hold fs->lock if we are killing it */
565         if (atomic_dec_and_test(&fs->count)) {
566                 path_put(&fs->root);
567                 path_put(&fs->pwd);
568                 kmem_cache_free(fs_cachep, fs);
569         }
570 }
571
572 void exit_fs(struct task_struct *tsk)
573 {
574         struct fs_struct * fs = tsk->fs;
575
576         if (fs) {
577                 task_lock(tsk);
578                 tsk->fs = NULL;
579                 task_unlock(tsk);
580                 put_fs_struct(fs);
581         }
582 }
583
584 EXPORT_SYMBOL_GPL(exit_fs);
585
586 #ifdef CONFIG_MM_OWNER
587 /*
588  * Task p is exiting and it owned mm, lets find a new owner for it
589  */
590 static inline int
591 mm_need_new_owner(struct mm_struct *mm, struct task_struct *p)
592 {
593         /*
594          * If there are other users of the mm and the owner (us) is exiting
595          * we need to find a new owner to take on the responsibility.
596          */
597         if (atomic_read(&mm->mm_users) <= 1)
598                 return 0;
599         if (mm->owner != p)
600                 return 0;
601         return 1;
602 }
603
604 void mm_update_next_owner(struct mm_struct *mm)
605 {
606         struct task_struct *c, *g, *p = current;
607
608 retry:
609         if (!mm_need_new_owner(mm, p))
610                 return;
611
612         read_lock(&tasklist_lock);
613         /*
614          * Search in the children
615          */
616         list_for_each_entry(c, &p->children, sibling) {
617                 if (c->mm == mm)
618                         goto assign_new_owner;
619         }
620
621         /*
622          * Search in the siblings
623          */
624         list_for_each_entry(c, &p->parent->children, sibling) {
625                 if (c->mm == mm)
626                         goto assign_new_owner;
627         }
628
629         /*
630          * Search through everything else. We should not get
631          * here often
632          */
633         do_each_thread(g, c) {
634                 if (c->mm == mm)
635                         goto assign_new_owner;
636         } while_each_thread(g, c);
637
638         read_unlock(&tasklist_lock);
639         /*
640          * We found no owner yet mm_users > 1: this implies that we are
641          * most likely racing with swapoff (try_to_unuse()) or /proc or
642          * ptrace or page migration (get_task_mm()).  Mark owner as NULL,
643          * so that subsystems can understand the callback and take action.
644          */
645         down_write(&mm->mmap_sem);
646         cgroup_mm_owner_callbacks(mm->owner, NULL);
647         mm->owner = NULL;
648         up_write(&mm->mmap_sem);
649         return;
650
651 assign_new_owner:
652         BUG_ON(c == p);
653         get_task_struct(c);
654         read_unlock(&tasklist_lock);
655         down_write(&mm->mmap_sem);
656         /*
657          * The task_lock protects c->mm from changing.
658          * We always want mm->owner->mm == mm
659          */
660         task_lock(c);
661         if (c->mm != mm) {
662                 task_unlock(c);
663                 up_write(&mm->mmap_sem);
664                 put_task_struct(c);
665                 goto retry;
666         }
667         cgroup_mm_owner_callbacks(mm->owner, c);
668         mm->owner = c;
669         task_unlock(c);
670         up_write(&mm->mmap_sem);
671         put_task_struct(c);
672 }
673 #endif /* CONFIG_MM_OWNER */
674
675 /*
676  * Turn us into a lazy TLB process if we
677  * aren't already..
678  */
679 static void exit_mm(struct task_struct * tsk)
680 {
681         struct mm_struct *mm = tsk->mm;
682         struct core_state *core_state;
683
684         mm_release(tsk, mm);
685         if (!mm)
686                 return;
687         /*
688          * Serialize with any possible pending coredump.
689          * We must hold mmap_sem around checking core_state
690          * and clearing tsk->mm.  The core-inducing thread
691          * will increment ->nr_threads for each thread in the
692          * group with ->mm != NULL.
693          */
694         down_read(&mm->mmap_sem);
695         core_state = mm->core_state;
696         if (core_state) {
697                 struct core_thread self;
698                 up_read(&mm->mmap_sem);
699
700                 self.task = tsk;
701                 self.next = xchg(&core_state->dumper.next, &self);
702                 /*
703                  * Implies mb(), the result of xchg() must be visible
704                  * to core_state->dumper.
705                  */
706                 if (atomic_dec_and_test(&core_state->nr_threads))
707                         complete(&core_state->startup);
708
709                 for (;;) {
710                         set_task_state(tsk, TASK_UNINTERRUPTIBLE);
711                         if (!self.task) /* see coredump_finish() */
712                                 break;
713                         schedule();
714                 }
715                 __set_task_state(tsk, TASK_RUNNING);
716                 down_read(&mm->mmap_sem);
717         }
718         atomic_inc(&mm->mm_count);
719         BUG_ON(mm != tsk->active_mm);
720         /* more a memory barrier than a real lock */
721         task_lock(tsk);
722         tsk->mm = NULL;
723         up_read(&mm->mmap_sem);
724         enter_lazy_tlb(mm, current);
725         /* We don't want this task to be frozen prematurely */
726         clear_freeze_flag(tsk);
727         task_unlock(tsk);
728         mm_update_next_owner(mm);
729         mmput(mm);
730 }
731
732 /*
733  * Return nonzero if @parent's children should reap themselves.
734  *
735  * Called with write_lock_irq(&tasklist_lock) held.
736  */
737 static int ignoring_children(struct task_struct *parent)
738 {
739         int ret;
740         struct sighand_struct *psig = parent->sighand;
741         unsigned long flags;
742         spin_lock_irqsave(&psig->siglock, flags);
743         ret = (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||
744                (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT));
745         spin_unlock_irqrestore(&psig->siglock, flags);
746         return ret;
747 }
748
749 /*
750  * Detach all tasks we were using ptrace on.
751  * Any that need to be release_task'd are put on the @dead list.
752  *
753  * Called with write_lock(&tasklist_lock) held.
754  */
755 static void ptrace_exit(struct task_struct *parent, struct list_head *dead)
756 {
757         struct task_struct *p, *n;
758         int ign = -1;
759
760         list_for_each_entry_safe(p, n, &parent->ptraced, ptrace_entry) {
761                 __ptrace_unlink(p);
762
763                 if (p->exit_state != EXIT_ZOMBIE)
764                         continue;
765
766                 /*
767                  * If it's a zombie, our attachedness prevented normal
768                  * parent notification or self-reaping.  Do notification
769                  * now if it would have happened earlier.  If it should
770                  * reap itself, add it to the @dead list.  We can't call
771                  * release_task() here because we already hold tasklist_lock.
772                  *
773                  * If it's our own child, there is no notification to do.
774                  * But if our normal children self-reap, then this child
775                  * was prevented by ptrace and we must reap it now.
776                  */
777                 if (!task_detached(p) && thread_group_empty(p)) {
778                         if (!same_thread_group(p->real_parent, parent))
779                                 do_notify_parent(p, p->exit_signal);
780                         else {
781                                 if (ign < 0)
782                                         ign = ignoring_children(parent);
783                                 if (ign)
784                                         p->exit_signal = -1;
785                         }
786                 }
787
788                 if (task_detached(p)) {
789                         /*
790                          * Mark it as in the process of being reaped.
791                          */
792                         p->exit_state = EXIT_DEAD;
793                         list_add(&p->ptrace_entry, dead);
794                 }
795         }
796 }
797
798 /*
799  * Finish up exit-time ptrace cleanup.
800  *
801  * Called without locks.
802  */
803 static void ptrace_exit_finish(struct task_struct *parent,
804                                struct list_head *dead)
805 {
806         struct task_struct *p, *n;
807
808         BUG_ON(!list_empty(&parent->ptraced));
809
810         list_for_each_entry_safe(p, n, dead, ptrace_entry) {
811                 list_del_init(&p->ptrace_entry);
812                 release_task(p);
813         }
814 }
815
816 static void reparent_thread(struct task_struct *p, struct task_struct *father)
817 {
818         if (p->pdeath_signal)
819                 /* We already hold the tasklist_lock here.  */
820                 group_send_sig_info(p->pdeath_signal, SEND_SIG_NOINFO, p);
821
822         list_move_tail(&p->sibling, &p->real_parent->children);
823
824         /* If this is a threaded reparent there is no need to
825          * notify anyone anything has happened.
826          */
827         if (same_thread_group(p->real_parent, father))
828                 return;
829
830         /* We don't want people slaying init.  */
831         if (!task_detached(p))
832                 p->exit_signal = SIGCHLD;
833
834         /* If we'd notified the old parent about this child's death,
835          * also notify the new parent.
836          */
837         if (!ptrace_reparented(p) &&
838             p->exit_state == EXIT_ZOMBIE &&
839             !task_detached(p) && thread_group_empty(p))
840                 do_notify_parent(p, p->exit_signal);
841
842         kill_orphaned_pgrp(p, father);
843 }
844
845 /*
846  * When we die, we re-parent all our children.
847  * Try to give them to another thread in our thread
848  * group, and if no such member exists, give it to
849  * the child reaper process (ie "init") in our pid
850  * space.
851  */
852 static struct task_struct *find_new_reaper(struct task_struct *father)
853 {
854         struct pid_namespace *pid_ns = task_active_pid_ns(father);
855         struct task_struct *thread;
856
857         thread = father;
858         while_each_thread(father, thread) {
859                 if (thread->flags & PF_EXITING)
860                         continue;
861                 if (unlikely(pid_ns->child_reaper == father))
862                         pid_ns->child_reaper = thread;
863                 return thread;
864         }
865
866         if (unlikely(pid_ns->child_reaper == father)) {
867                 write_unlock_irq(&tasklist_lock);
868                 if (unlikely(pid_ns == &init_pid_ns))
869                         panic("Attempted to kill init!");
870
871                 zap_pid_ns_processes(pid_ns);
872                 write_lock_irq(&tasklist_lock);
873                 /*
874                  * We can not clear ->child_reaper or leave it alone.
875                  * There may by stealth EXIT_DEAD tasks on ->children,
876                  * forget_original_parent() must move them somewhere.
877                  */
878                 pid_ns->child_reaper = init_pid_ns.child_reaper;
879         }
880
881         return pid_ns->child_reaper;
882 }
883
884 static void forget_original_parent(struct task_struct *father)
885 {
886         struct task_struct *p, *n, *reaper;
887         LIST_HEAD(ptrace_dead);
888
889         write_lock_irq(&tasklist_lock);
890         reaper = find_new_reaper(father);
891         /*
892          * First clean up ptrace if we were using it.
893          */
894         ptrace_exit(father, &ptrace_dead);
895
896         list_for_each_entry_safe(p, n, &father->children, sibling) {
897                 p->real_parent = reaper;
898                 if (p->parent == father) {
899                         BUG_ON(p->ptrace);
900                         p->parent = p->real_parent;
901                 }
902                 reparent_thread(p, father);
903         }
904
905         write_unlock_irq(&tasklist_lock);
906         BUG_ON(!list_empty(&father->children));
907
908         ptrace_exit_finish(father, &ptrace_dead);
909 }
910
911 /*
912  * Send signals to all our closest relatives so that they know
913  * to properly mourn us..
914  */
915 static void exit_notify(struct task_struct *tsk, int group_dead)
916 {
917         int signal;
918         void *cookie;
919
920         /*
921          * This does two things:
922          *
923          * A.  Make init inherit all the child processes
924          * B.  Check to see if any process groups have become orphaned
925          *      as a result of our exiting, and if they have any stopped
926          *      jobs, send them a SIGHUP and then a SIGCONT.  (POSIX 3.2.2.2)
927          */
928         forget_original_parent(tsk);
929         exit_task_namespaces(tsk);
930
931         write_lock_irq(&tasklist_lock);
932         if (group_dead)
933                 kill_orphaned_pgrp(tsk->group_leader, NULL);
934
935         /* Let father know we died
936          *
937          * Thread signals are configurable, but you aren't going to use
938          * that to send signals to arbitary processes.
939          * That stops right now.
940          *
941          * If the parent exec id doesn't match the exec id we saved
942          * when we started then we know the parent has changed security
943          * domain.
944          *
945          * If our self_exec id doesn't match our parent_exec_id then
946          * we have changed execution domain as these two values started
947          * the same after a fork.
948          */
949         if (tsk->exit_signal != SIGCHLD && !task_detached(tsk) &&
950             (tsk->parent_exec_id != tsk->real_parent->self_exec_id ||
951              tsk->self_exec_id != tsk->parent_exec_id) &&
952             !capable(CAP_KILL))
953                 tsk->exit_signal = SIGCHLD;
954
955         signal = tracehook_notify_death(tsk, &cookie, group_dead);
956         if (signal >= 0)
957                 signal = do_notify_parent(tsk, signal);
958
959         tsk->exit_state = signal == DEATH_REAP ? EXIT_DEAD : EXIT_ZOMBIE;
960
961         /* mt-exec, de_thread() is waiting for us */
962         if (thread_group_leader(tsk) &&
963             tsk->signal->group_exit_task &&
964             tsk->signal->notify_count < 0)
965                 wake_up_process(tsk->signal->group_exit_task);
966
967         write_unlock_irq(&tasklist_lock);
968
969         tracehook_report_death(tsk, signal, cookie, group_dead);
970
971         /* If the process is dead, release it - nobody will wait for it */
972         if (signal == DEATH_REAP)
973                 release_task(tsk);
974 }
975
976 #ifdef CONFIG_DEBUG_STACK_USAGE
977 static void check_stack_usage(void)
978 {
979         static DEFINE_SPINLOCK(low_water_lock);
980         static int lowest_to_date = THREAD_SIZE;
981         unsigned long *n = end_of_stack(current);
982         unsigned long free;
983
984         while (*n == 0)
985                 n++;
986         free = (unsigned long)n - (unsigned long)end_of_stack(current);
987
988         if (free >= lowest_to_date)
989                 return;
990
991         spin_lock(&low_water_lock);
992         if (free < lowest_to_date) {
993                 printk(KERN_WARNING "%s used greatest stack depth: %lu bytes "
994                                 "left\n",
995                                 current->comm, free);
996                 lowest_to_date = free;
997         }
998         spin_unlock(&low_water_lock);
999 }
1000 #else
1001 static inline void check_stack_usage(void) {}
1002 #endif
1003
1004 NORET_TYPE void do_exit(long code)
1005 {
1006         struct task_struct *tsk = current;
1007         int group_dead;
1008
1009         profile_task_exit(tsk);
1010
1011         WARN_ON(atomic_read(&tsk->fs_excl));
1012
1013         if (unlikely(in_interrupt()))
1014                 panic("Aiee, killing interrupt handler!");
1015         if (unlikely(!tsk->pid))
1016                 panic("Attempted to kill the idle task!");
1017
1018         tracehook_report_exit(&code);
1019
1020         /*
1021          * We're taking recursive faults here in do_exit. Safest is to just
1022          * leave this task alone and wait for reboot.
1023          */
1024         if (unlikely(tsk->flags & PF_EXITING)) {
1025                 printk(KERN_ALERT
1026                         "Fixing recursive fault but reboot is needed!\n");
1027                 /*
1028                  * We can do this unlocked here. The futex code uses
1029                  * this flag just to verify whether the pi state
1030                  * cleanup has been done or not. In the worst case it
1031                  * loops once more. We pretend that the cleanup was
1032                  * done as there is no way to return. Either the
1033                  * OWNER_DIED bit is set by now or we push the blocked
1034                  * task into the wait for ever nirwana as well.
1035                  */
1036                 tsk->flags |= PF_EXITPIDONE;
1037                 if (tsk->io_context)
1038                         exit_io_context();
1039                 set_current_state(TASK_UNINTERRUPTIBLE);
1040                 schedule();
1041         }
1042
1043         exit_signals(tsk);  /* sets PF_EXITING */
1044         /*
1045          * tsk->flags are checked in the futex code to protect against
1046          * an exiting task cleaning up the robust pi futexes.
1047          */
1048         smp_mb();
1049         spin_unlock_wait(&tsk->pi_lock);
1050
1051         if (unlikely(in_atomic()))
1052                 printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n",
1053                                 current->comm, task_pid_nr(current),
1054                                 preempt_count());
1055
1056         acct_update_integrals(tsk);
1057         if (tsk->mm) {
1058                 update_hiwater_rss(tsk->mm);
1059                 update_hiwater_vm(tsk->mm);
1060         }
1061         group_dead = atomic_dec_and_test(&tsk->signal->live);
1062         if (group_dead) {
1063                 hrtimer_cancel(&tsk->signal->real_timer);
1064                 exit_itimers(tsk->signal);
1065         }
1066         acct_collect(code, group_dead);
1067 #ifdef CONFIG_FUTEX
1068         if (unlikely(tsk->robust_list))
1069                 exit_robust_list(tsk);
1070 #ifdef CONFIG_COMPAT
1071         if (unlikely(tsk->compat_robust_list))
1072                 compat_exit_robust_list(tsk);
1073 #endif
1074 #endif
1075         if (group_dead)
1076                 tty_audit_exit();
1077         if (unlikely(tsk->audit_context))
1078                 audit_free(tsk);
1079
1080         tsk->exit_code = code;
1081         taskstats_exit(tsk, group_dead);
1082
1083         exit_mm(tsk);
1084
1085         if (group_dead)
1086                 acct_process();
1087         trace_sched_process_exit(tsk);
1088
1089         exit_sem(tsk);
1090         exit_files(tsk);
1091         exit_fs(tsk);
1092         check_stack_usage();
1093         exit_thread();
1094         cgroup_exit(tsk, 1);
1095
1096         if (group_dead && tsk->signal->leader)
1097                 disassociate_ctty(1);
1098
1099         module_put(task_thread_info(tsk)->exec_domain->module);
1100         if (tsk->binfmt)
1101                 module_put(tsk->binfmt->module);
1102
1103         proc_exit_connector(tsk);
1104         exit_notify(tsk, group_dead);
1105 #ifdef CONFIG_NUMA
1106         mpol_put(tsk->mempolicy);
1107         tsk->mempolicy = NULL;
1108 #endif
1109 #ifdef CONFIG_FUTEX
1110         /*
1111          * This must happen late, after the PID is not
1112          * hashed anymore:
1113          */
1114         if (unlikely(!list_empty(&tsk->pi_state_list)))
1115                 exit_pi_state_list(tsk);
1116         if (unlikely(current->pi_state_cache))
1117                 kfree(current->pi_state_cache);
1118 #endif
1119         /*
1120          * Make sure we are holding no locks:
1121          */
1122         debug_check_no_locks_held(tsk);
1123         /*
1124          * We can do this unlocked here. The futex code uses this flag
1125          * just to verify whether the pi state cleanup has been done
1126          * or not. In the worst case it loops once more.
1127          */
1128         tsk->flags |= PF_EXITPIDONE;
1129
1130         if (tsk->io_context)
1131                 exit_io_context();
1132
1133         if (tsk->splice_pipe)
1134                 __free_pipe_info(tsk->splice_pipe);
1135
1136         preempt_disable();
1137         /* causes final put_task_struct in finish_task_switch(). */
1138         tsk->state = TASK_DEAD;
1139
1140         schedule();
1141         BUG();
1142         /* Avoid "noreturn function does return".  */
1143         for (;;)
1144                 cpu_relax();    /* For when BUG is null */
1145 }
1146
1147 EXPORT_SYMBOL_GPL(do_exit);
1148
1149 NORET_TYPE void complete_and_exit(struct completion *comp, long code)
1150 {
1151         if (comp)
1152                 complete(comp);
1153
1154         do_exit(code);
1155 }
1156
1157 EXPORT_SYMBOL(complete_and_exit);
1158
1159 asmlinkage long sys_exit(int error_code)
1160 {
1161         do_exit((error_code&0xff)<<8);
1162 }
1163
1164 /*
1165  * Take down every thread in the group.  This is called by fatal signals
1166  * as well as by sys_exit_group (below).
1167  */
1168 NORET_TYPE void
1169 do_group_exit(int exit_code)
1170 {
1171         struct signal_struct *sig = current->signal;
1172
1173         BUG_ON(exit_code & 0x80); /* core dumps don't get here */
1174
1175         if (signal_group_exit(sig))
1176                 exit_code = sig->group_exit_code;
1177         else if (!thread_group_empty(current)) {
1178                 struct sighand_struct *const sighand = current->sighand;
1179                 spin_lock_irq(&sighand->siglock);
1180                 if (signal_group_exit(sig))
1181                         /* Another thread got here before we took the lock.  */
1182                         exit_code = sig->group_exit_code;
1183                 else {
1184                         sig->group_exit_code = exit_code;
1185                         sig->flags = SIGNAL_GROUP_EXIT;
1186                         zap_other_threads(current);
1187                 }
1188                 spin_unlock_irq(&sighand->siglock);
1189         }
1190
1191         do_exit(exit_code);
1192         /* NOTREACHED */
1193 }
1194
1195 /*
1196  * this kills every thread in the thread group. Note that any externally
1197  * wait4()-ing process will get the correct exit code - even if this
1198  * thread is not the thread group leader.
1199  */
1200 asmlinkage void sys_exit_group(int error_code)
1201 {
1202         do_group_exit((error_code & 0xff) << 8);
1203 }
1204
1205 static struct pid *task_pid_type(struct task_struct *task, enum pid_type type)
1206 {
1207         struct pid *pid = NULL;
1208         if (type == PIDTYPE_PID)
1209                 pid = task->pids[type].pid;
1210         else if (type < PIDTYPE_MAX)
1211                 pid = task->group_leader->pids[type].pid;
1212         return pid;
1213 }
1214
1215 static int eligible_child(enum pid_type type, struct pid *pid, int options,
1216                           struct task_struct *p)
1217 {
1218         int err;
1219
1220         if (type < PIDTYPE_MAX) {
1221                 if (task_pid_type(p, type) != pid)
1222                         return 0;
1223         }
1224
1225         /* Wait for all children (clone and not) if __WALL is set;
1226          * otherwise, wait for clone children *only* if __WCLONE is
1227          * set; otherwise, wait for non-clone children *only*.  (Note:
1228          * A "clone" child here is one that reports to its parent
1229          * using a signal other than SIGCHLD.) */
1230         if (((p->exit_signal != SIGCHLD) ^ ((options & __WCLONE) != 0))
1231             && !(options & __WALL))
1232                 return 0;
1233
1234         err = security_task_wait(p);
1235         if (err)
1236                 return err;
1237
1238         return 1;
1239 }
1240
1241 static int wait_noreap_copyout(struct task_struct *p, pid_t pid, uid_t uid,
1242                                int why, int status,
1243                                struct siginfo __user *infop,
1244                                struct rusage __user *rusagep)
1245 {
1246         int retval = rusagep ? getrusage(p, RUSAGE_BOTH, rusagep) : 0;
1247
1248         put_task_struct(p);
1249         if (!retval)
1250                 retval = put_user(SIGCHLD, &infop->si_signo);
1251         if (!retval)
1252                 retval = put_user(0, &infop->si_errno);
1253         if (!retval)
1254                 retval = put_user((short)why, &infop->si_code);
1255         if (!retval)
1256                 retval = put_user(pid, &infop->si_pid);
1257         if (!retval)
1258                 retval = put_user(uid, &infop->si_uid);
1259         if (!retval)
1260                 retval = put_user(status, &infop->si_status);
1261         if (!retval)
1262                 retval = pid;
1263         return retval;
1264 }
1265
1266 /*
1267  * Handle sys_wait4 work for one task in state EXIT_ZOMBIE.  We hold
1268  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1269  * the lock and this task is uninteresting.  If we return nonzero, we have
1270  * released the lock and the system call should return.
1271  */
1272 static int wait_task_zombie(struct task_struct *p, int options,
1273                             struct siginfo __user *infop,
1274                             int __user *stat_addr, struct rusage __user *ru)
1275 {
1276         unsigned long state;
1277         int retval, status, traced;
1278         pid_t pid = task_pid_vnr(p);
1279         uid_t uid = __task_cred(p)->uid;
1280
1281         if (!likely(options & WEXITED))
1282                 return 0;
1283
1284         if (unlikely(options & WNOWAIT)) {
1285                 int exit_code = p->exit_code;
1286                 int why, status;
1287
1288                 get_task_struct(p);
1289                 read_unlock(&tasklist_lock);
1290                 if ((exit_code & 0x7f) == 0) {
1291                         why = CLD_EXITED;
1292                         status = exit_code >> 8;
1293                 } else {
1294                         why = (exit_code & 0x80) ? CLD_DUMPED : CLD_KILLED;
1295                         status = exit_code & 0x7f;
1296                 }
1297                 return wait_noreap_copyout(p, pid, uid, why,
1298                                            status, infop, ru);
1299         }
1300
1301         /*
1302          * Try to move the task's state to DEAD
1303          * only one thread is allowed to do this:
1304          */
1305         state = xchg(&p->exit_state, EXIT_DEAD);
1306         if (state != EXIT_ZOMBIE) {
1307                 BUG_ON(state != EXIT_DEAD);
1308                 return 0;
1309         }
1310
1311         traced = ptrace_reparented(p);
1312
1313         if (likely(!traced)) {
1314                 struct signal_struct *psig;
1315                 struct signal_struct *sig;
1316                 struct task_cputime cputime;
1317
1318                 /*
1319                  * The resource counters for the group leader are in its
1320                  * own task_struct.  Those for dead threads in the group
1321                  * are in its signal_struct, as are those for the child
1322                  * processes it has previously reaped.  All these
1323                  * accumulate in the parent's signal_struct c* fields.
1324                  *
1325                  * We don't bother to take a lock here to protect these
1326                  * p->signal fields, because they are only touched by
1327                  * __exit_signal, which runs with tasklist_lock
1328                  * write-locked anyway, and so is excluded here.  We do
1329                  * need to protect the access to p->parent->signal fields,
1330                  * as other threads in the parent group can be right
1331                  * here reaping other children at the same time.
1332                  *
1333                  * We use thread_group_cputime() to get times for the thread
1334                  * group, which consolidates times for all threads in the
1335                  * group including the group leader.
1336                  */
1337                 spin_lock_irq(&p->parent->sighand->siglock);
1338                 psig = p->parent->signal;
1339                 sig = p->signal;
1340                 thread_group_cputime(p, &cputime);
1341                 psig->cutime =
1342                         cputime_add(psig->cutime,
1343                         cputime_add(cputime.utime,
1344                                     sig->cutime));
1345                 psig->cstime =
1346                         cputime_add(psig->cstime,
1347                         cputime_add(cputime.stime,
1348                                     sig->cstime));
1349                 psig->cgtime =
1350                         cputime_add(psig->cgtime,
1351                         cputime_add(p->gtime,
1352                         cputime_add(sig->gtime,
1353                                     sig->cgtime)));
1354                 psig->cmin_flt +=
1355                         p->min_flt + sig->min_flt + sig->cmin_flt;
1356                 psig->cmaj_flt +=
1357                         p->maj_flt + sig->maj_flt + sig->cmaj_flt;
1358                 psig->cnvcsw +=
1359                         p->nvcsw + sig->nvcsw + sig->cnvcsw;
1360                 psig->cnivcsw +=
1361                         p->nivcsw + sig->nivcsw + sig->cnivcsw;
1362                 psig->cinblock +=
1363                         task_io_get_inblock(p) +
1364                         sig->inblock + sig->cinblock;
1365                 psig->coublock +=
1366                         task_io_get_oublock(p) +
1367                         sig->oublock + sig->coublock;
1368                 task_io_accounting_add(&psig->ioac, &p->ioac);
1369                 task_io_accounting_add(&psig->ioac, &sig->ioac);
1370                 spin_unlock_irq(&p->parent->sighand->siglock);
1371         }
1372
1373         /*
1374          * Now we are sure this task is interesting, and no other
1375          * thread can reap it because we set its state to EXIT_DEAD.
1376          */
1377         read_unlock(&tasklist_lock);
1378
1379         retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
1380         status = (p->signal->flags & SIGNAL_GROUP_EXIT)
1381                 ? p->signal->group_exit_code : p->exit_code;
1382         if (!retval && stat_addr)
1383                 retval = put_user(status, stat_addr);
1384         if (!retval && infop)
1385                 retval = put_user(SIGCHLD, &infop->si_signo);
1386         if (!retval && infop)
1387                 retval = put_user(0, &infop->si_errno);
1388         if (!retval && infop) {
1389                 int why;
1390
1391                 if ((status & 0x7f) == 0) {
1392                         why = CLD_EXITED;
1393                         status >>= 8;
1394                 } else {
1395                         why = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
1396                         status &= 0x7f;
1397                 }
1398                 retval = put_user((short)why, &infop->si_code);
1399                 if (!retval)
1400                         retval = put_user(status, &infop->si_status);
1401         }
1402         if (!retval && infop)
1403                 retval = put_user(pid, &infop->si_pid);
1404         if (!retval && infop)
1405                 retval = put_user(uid, &infop->si_uid);
1406         if (!retval)
1407                 retval = pid;
1408
1409         if (traced) {
1410                 write_lock_irq(&tasklist_lock);
1411                 /* We dropped tasklist, ptracer could die and untrace */
1412                 ptrace_unlink(p);
1413                 /*
1414                  * If this is not a detached task, notify the parent.
1415                  * If it's still not detached after that, don't release
1416                  * it now.
1417                  */
1418                 if (!task_detached(p)) {
1419                         do_notify_parent(p, p->exit_signal);
1420                         if (!task_detached(p)) {
1421                                 p->exit_state = EXIT_ZOMBIE;
1422                                 p = NULL;
1423                         }
1424                 }
1425                 write_unlock_irq(&tasklist_lock);
1426         }
1427         if (p != NULL)
1428                 release_task(p);
1429
1430         return retval;
1431 }
1432
1433 /*
1434  * Handle sys_wait4 work for one task in state TASK_STOPPED.  We hold
1435  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1436  * the lock and this task is uninteresting.  If we return nonzero, we have
1437  * released the lock and the system call should return.
1438  */
1439 static int wait_task_stopped(int ptrace, struct task_struct *p,
1440                              int options, struct siginfo __user *infop,
1441                              int __user *stat_addr, struct rusage __user *ru)
1442 {
1443         int retval, exit_code, why;
1444         uid_t uid = 0; /* unneeded, required by compiler */
1445         pid_t pid;
1446
1447         if (!(options & WUNTRACED))
1448                 return 0;
1449
1450         exit_code = 0;
1451         spin_lock_irq(&p->sighand->siglock);
1452
1453         if (unlikely(!task_is_stopped_or_traced(p)))
1454                 goto unlock_sig;
1455
1456         if (!ptrace && p->signal->group_stop_count > 0)
1457                 /*
1458                  * A group stop is in progress and this is the group leader.
1459                  * We won't report until all threads have stopped.
1460                  */
1461                 goto unlock_sig;
1462
1463         exit_code = p->exit_code;
1464         if (!exit_code)
1465                 goto unlock_sig;
1466
1467         if (!unlikely(options & WNOWAIT))
1468                 p->exit_code = 0;
1469
1470         /* don't need the RCU readlock here as we're holding a spinlock */
1471         uid = __task_cred(p)->uid;
1472 unlock_sig:
1473         spin_unlock_irq(&p->sighand->siglock);
1474         if (!exit_code)
1475                 return 0;
1476
1477         /*
1478          * Now we are pretty sure this task is interesting.
1479          * Make sure it doesn't get reaped out from under us while we
1480          * give up the lock and then examine it below.  We don't want to
1481          * keep holding onto the tasklist_lock while we call getrusage and
1482          * possibly take page faults for user memory.
1483          */
1484         get_task_struct(p);
1485         pid = task_pid_vnr(p);
1486         why = ptrace ? CLD_TRAPPED : CLD_STOPPED;
1487         read_unlock(&tasklist_lock);
1488
1489         if (unlikely(options & WNOWAIT))
1490                 return wait_noreap_copyout(p, pid, uid,
1491                                            why, exit_code,
1492                                            infop, ru);
1493
1494         retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
1495         if (!retval && stat_addr)
1496                 retval = put_user((exit_code << 8) | 0x7f, stat_addr);
1497         if (!retval && infop)
1498                 retval = put_user(SIGCHLD, &infop->si_signo);
1499         if (!retval && infop)
1500                 retval = put_user(0, &infop->si_errno);
1501         if (!retval && infop)
1502                 retval = put_user((short)why, &infop->si_code);
1503         if (!retval && infop)
1504                 retval = put_user(exit_code, &infop->si_status);
1505         if (!retval && infop)
1506                 retval = put_user(pid, &infop->si_pid);
1507         if (!retval && infop)
1508                 retval = put_user(uid, &infop->si_uid);
1509         if (!retval)
1510                 retval = pid;
1511         put_task_struct(p);
1512
1513         BUG_ON(!retval);
1514         return retval;
1515 }
1516
1517 /*
1518  * Handle do_wait work for one task in a live, non-stopped state.
1519  * read_lock(&tasklist_lock) on entry.  If we return zero, we still hold
1520  * the lock and this task is uninteresting.  If we return nonzero, we have
1521  * released the lock and the system call should return.
1522  */
1523 static int wait_task_continued(struct task_struct *p, int options,
1524                                struct siginfo __user *infop,
1525                                int __user *stat_addr, struct rusage __user *ru)
1526 {
1527         int retval;
1528         pid_t pid;
1529         uid_t uid;
1530
1531         if (!unlikely(options & WCONTINUED))
1532                 return 0;
1533
1534         if (!(p->signal->flags & SIGNAL_STOP_CONTINUED))
1535                 return 0;
1536
1537         spin_lock_irq(&p->sighand->siglock);
1538         /* Re-check with the lock held.  */
1539         if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) {
1540                 spin_unlock_irq(&p->sighand->siglock);
1541                 return 0;
1542         }
1543         if (!unlikely(options & WNOWAIT))
1544                 p->signal->flags &= ~SIGNAL_STOP_CONTINUED;
1545         uid = __task_cred(p)->uid;
1546         spin_unlock_irq(&p->sighand->siglock);
1547
1548         pid = task_pid_vnr(p);
1549         get_task_struct(p);
1550         read_unlock(&tasklist_lock);
1551
1552         if (!infop) {
1553                 retval = ru ? getrusage(p, RUSAGE_BOTH, ru) : 0;
1554                 put_task_struct(p);
1555                 if (!retval && stat_addr)
1556                         retval = put_user(0xffff, stat_addr);
1557                 if (!retval)
1558                         retval = pid;
1559         } else {
1560                 retval = wait_noreap_copyout(p, pid, uid,
1561                                              CLD_CONTINUED, SIGCONT,
1562                                              infop, ru);
1563                 BUG_ON(retval == 0);
1564         }
1565
1566         return retval;
1567 }
1568
1569 /*
1570  * Consider @p for a wait by @parent.
1571  *
1572  * -ECHILD should be in *@notask_error before the first call.
1573  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1574  * Returns zero if the search for a child should continue;
1575  * then *@notask_error is 0 if @p is an eligible child,
1576  * or another error from security_task_wait(), or still -ECHILD.
1577  */
1578 static int wait_consider_task(struct task_struct *parent, int ptrace,
1579                               struct task_struct *p, int *notask_error,
1580                               enum pid_type type, struct pid *pid, int options,
1581                               struct siginfo __user *infop,
1582                               int __user *stat_addr, struct rusage __user *ru)
1583 {
1584         int ret = eligible_child(type, pid, options, p);
1585         if (!ret)
1586                 return ret;
1587
1588         if (unlikely(ret < 0)) {
1589                 /*
1590                  * If we have not yet seen any eligible child,
1591                  * then let this error code replace -ECHILD.
1592                  * A permission error will give the user a clue
1593                  * to look for security policy problems, rather
1594                  * than for mysterious wait bugs.
1595                  */
1596                 if (*notask_error)
1597                         *notask_error = ret;
1598         }
1599
1600         if (likely(!ptrace) && unlikely(p->ptrace)) {
1601                 /*
1602                  * This child is hidden by ptrace.
1603                  * We aren't allowed to see it now, but eventually we will.
1604                  */
1605                 *notask_error = 0;
1606                 return 0;
1607         }
1608
1609         if (p->exit_state == EXIT_DEAD)
1610                 return 0;
1611
1612         /*
1613          * We don't reap group leaders with subthreads.
1614          */
1615         if (p->exit_state == EXIT_ZOMBIE && !delay_group_leader(p))
1616                 return wait_task_zombie(p, options, infop, stat_addr, ru);
1617
1618         /*
1619          * It's stopped or running now, so it might
1620          * later continue, exit, or stop again.
1621          */
1622         *notask_error = 0;
1623
1624         if (task_is_stopped_or_traced(p))
1625                 return wait_task_stopped(ptrace, p, options,
1626                                          infop, stat_addr, ru);
1627
1628         return wait_task_continued(p, options, infop, stat_addr, ru);
1629 }
1630
1631 /*
1632  * Do the work of do_wait() for one thread in the group, @tsk.
1633  *
1634  * -ECHILD should be in *@notask_error before the first call.
1635  * Returns nonzero for a final return, when we have unlocked tasklist_lock.
1636  * Returns zero if the search for a child should continue; then
1637  * *@notask_error is 0 if there were any eligible children,
1638  * or another error from security_task_wait(), or still -ECHILD.
1639  */
1640 static int do_wait_thread(struct task_struct *tsk, int *notask_error,
1641                           enum pid_type type, struct pid *pid, int options,
1642                           struct siginfo __user *infop, int __user *stat_addr,
1643                           struct rusage __user *ru)
1644 {
1645         struct task_struct *p;
1646
1647         list_for_each_entry(p, &tsk->children, sibling) {
1648                 /*
1649                  * Do not consider detached threads.
1650                  */
1651                 if (!task_detached(p)) {
1652                         int ret = wait_consider_task(tsk, 0, p, notask_error,
1653                                                      type, pid, options,
1654                                                      infop, stat_addr, ru);
1655                         if (ret)
1656                                 return ret;
1657                 }
1658         }
1659
1660         return 0;
1661 }
1662
1663 static int ptrace_do_wait(struct task_struct *tsk, int *notask_error,
1664                           enum pid_type type, struct pid *pid, int options,
1665                           struct siginfo __user *infop, int __user *stat_addr,
1666                           struct rusage __user *ru)
1667 {
1668         struct task_struct *p;
1669
1670         /*
1671          * Traditionally we see ptrace'd stopped tasks regardless of options.
1672          */
1673         options |= WUNTRACED;
1674
1675         list_for_each_entry(p, &tsk->ptraced, ptrace_entry) {
1676                 int ret = wait_consider_task(tsk, 1, p, notask_error,
1677                                              type, pid, options,
1678                                              infop, stat_addr, ru);
1679                 if (ret)
1680                         return ret;
1681         }
1682
1683         return 0;
1684 }
1685
1686 static long do_wait(enum pid_type type, struct pid *pid, int options,
1687                     struct siginfo __user *infop, int __user *stat_addr,
1688                     struct rusage __user *ru)
1689 {
1690         DECLARE_WAITQUEUE(wait, current);
1691         struct task_struct *tsk;
1692         int retval;
1693
1694         trace_sched_process_wait(pid);
1695
1696         add_wait_queue(&current->signal->wait_chldexit,&wait);
1697 repeat:
1698         /*
1699          * If there is nothing that can match our critiera just get out.
1700          * We will clear @retval to zero if we see any child that might later
1701          * match our criteria, even if we are not able to reap it yet.
1702          */
1703         retval = -ECHILD;
1704         if ((type < PIDTYPE_MAX) && (!pid || hlist_empty(&pid->tasks[type])))
1705                 goto end;
1706
1707         current->state = TASK_INTERRUPTIBLE;
1708         read_lock(&tasklist_lock);
1709         tsk = current;
1710         do {
1711                 int tsk_result = do_wait_thread(tsk, &retval,
1712                                                 type, pid, options,
1713                                                 infop, stat_addr, ru);
1714                 if (!tsk_result)
1715                         tsk_result = ptrace_do_wait(tsk, &retval,
1716                                                     type, pid, options,
1717                                                     infop, stat_addr, ru);
1718                 if (tsk_result) {
1719                         /*
1720                          * tasklist_lock is unlocked and we have a final result.
1721                          */
1722                         retval = tsk_result;
1723                         goto end;
1724                 }
1725
1726                 if (options & __WNOTHREAD)
1727                         break;
1728                 tsk = next_thread(tsk);
1729                 BUG_ON(tsk->signal != current->signal);
1730         } while (tsk != current);
1731         read_unlock(&tasklist_lock);
1732
1733         if (!retval && !(options & WNOHANG)) {
1734                 retval = -ERESTARTSYS;
1735                 if (!signal_pending(current)) {
1736                         schedule();
1737                         goto repeat;
1738                 }
1739         }
1740
1741 end:
1742         current->state = TASK_RUNNING;
1743         remove_wait_queue(&current->signal->wait_chldexit,&wait);
1744         if (infop) {
1745                 if (retval > 0)
1746                         retval = 0;
1747                 else {
1748                         /*
1749                          * For a WNOHANG return, clear out all the fields
1750                          * we would set so the user can easily tell the
1751                          * difference.
1752                          */
1753                         if (!retval)
1754                                 retval = put_user(0, &infop->si_signo);
1755                         if (!retval)
1756                                 retval = put_user(0, &infop->si_errno);
1757                         if (!retval)
1758                                 retval = put_user(0, &infop->si_code);
1759                         if (!retval)
1760                                 retval = put_user(0, &infop->si_pid);
1761                         if (!retval)
1762                                 retval = put_user(0, &infop->si_uid);
1763                         if (!retval)
1764                                 retval = put_user(0, &infop->si_status);
1765                 }
1766         }
1767         return retval;
1768 }
1769
1770 asmlinkage long sys_waitid(int which, pid_t upid,
1771                            struct siginfo __user *infop, int options,
1772                            struct rusage __user *ru)
1773 {
1774         struct pid *pid = NULL;
1775         enum pid_type type;
1776         long ret;
1777
1778         if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED))
1779                 return -EINVAL;
1780         if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
1781                 return -EINVAL;
1782
1783         switch (which) {
1784         case P_ALL:
1785                 type = PIDTYPE_MAX;
1786                 break;
1787         case P_PID:
1788                 type = PIDTYPE_PID;
1789                 if (upid <= 0)
1790                         return -EINVAL;
1791                 break;
1792         case P_PGID:
1793                 type = PIDTYPE_PGID;
1794                 if (upid <= 0)
1795                         return -EINVAL;
1796                 break;
1797         default:
1798                 return -EINVAL;
1799         }
1800
1801         if (type < PIDTYPE_MAX)
1802                 pid = find_get_pid(upid);
1803         ret = do_wait(type, pid, options, infop, NULL, ru);
1804         put_pid(pid);
1805
1806         /* avoid REGPARM breakage on x86: */
1807         asmlinkage_protect(5, ret, which, upid, infop, options, ru);
1808         return ret;
1809 }
1810
1811 asmlinkage long sys_wait4(pid_t upid, int __user *stat_addr,
1812                           int options, struct rusage __user *ru)
1813 {
1814         struct pid *pid = NULL;
1815         enum pid_type type;
1816         long ret;
1817
1818         if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
1819                         __WNOTHREAD|__WCLONE|__WALL))
1820                 return -EINVAL;
1821
1822         if (upid == -1)
1823                 type = PIDTYPE_MAX;
1824         else if (upid < 0) {
1825                 type = PIDTYPE_PGID;
1826                 pid = find_get_pid(-upid);
1827         } else if (upid == 0) {
1828                 type = PIDTYPE_PGID;
1829                 pid = get_pid(task_pgrp(current));
1830         } else /* upid > 0 */ {
1831                 type = PIDTYPE_PID;
1832                 pid = find_get_pid(upid);
1833         }
1834
1835         ret = do_wait(type, pid, options | WEXITED, NULL, stat_addr, ru);
1836         put_pid(pid);
1837
1838         /* avoid REGPARM breakage on x86: */
1839         asmlinkage_protect(4, ret, upid, stat_addr, options, ru);
1840         return ret;
1841 }
1842
1843 #ifdef __ARCH_WANT_SYS_WAITPID
1844
1845 /*
1846  * sys_waitpid() remains for compatibility. waitpid() should be
1847  * implemented by calling sys_wait4() from libc.a.
1848  */
1849 asmlinkage long sys_waitpid(pid_t pid, int __user *stat_addr, int options)
1850 {
1851         return sys_wait4(pid, stat_addr, options, NULL);
1852 }
1853
1854 #endif