sched/autogroup: Fix crash on reboot when autogroup is disabled
[cascardo/linux.git] / fs / proc / base.c
1 /*
2  *  linux/fs/proc/base.c
3  *
4  *  Copyright (C) 1991, 1992 Linus Torvalds
5  *
6  *  proc base directory handling functions
7  *
8  *  1999, Al Viro. Rewritten. Now it covers the whole per-process part.
9  *  Instead of using magical inumbers to determine the kind of object
10  *  we allocate and fill in-core inodes upon lookup. They don't even
11  *  go into icache. We cache the reference to task_struct upon lookup too.
12  *  Eventually it should become a filesystem in its own. We don't use the
13  *  rest of procfs anymore.
14  *
15  *
16  *  Changelog:
17  *  17-Jan-2005
18  *  Allan Bezerra
19  *  Bruna Moreira <bruna.moreira@indt.org.br>
20  *  Edjard Mota <edjard.mota@indt.org.br>
21  *  Ilias Biris <ilias.biris@indt.org.br>
22  *  Mauricio Lin <mauricio.lin@indt.org.br>
23  *
24  *  Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
25  *
26  *  A new process specific entry (smaps) included in /proc. It shows the
27  *  size of rss for each memory area. The maps entry lacks information
28  *  about physical memory size (rss) for each mapped file, i.e.,
29  *  rss information for executables and library files.
30  *  This additional information is useful for any tools that need to know
31  *  about physical memory consumption for a process specific library.
32  *
33  *  Changelog:
34  *  21-Feb-2005
35  *  Embedded Linux Lab - 10LE Instituto Nokia de Tecnologia - INdT
36  *  Pud inclusion in the page table walking.
37  *
38  *  ChangeLog:
39  *  10-Mar-2005
40  *  10LE Instituto Nokia de Tecnologia - INdT:
41  *  A better way to walks through the page table as suggested by Hugh Dickins.
42  *
43  *  Simo Piiroinen <simo.piiroinen@nokia.com>:
44  *  Smaps information related to shared, private, clean and dirty pages.
45  *
46  *  Paul Mundt <paul.mundt@nokia.com>:
47  *  Overall revision about smaps.
48  */
49
50 #include <asm/uaccess.h>
51
52 #include <linux/errno.h>
53 #include <linux/time.h>
54 #include <linux/proc_fs.h>
55 #include <linux/stat.h>
56 #include <linux/task_io_accounting_ops.h>
57 #include <linux/init.h>
58 #include <linux/capability.h>
59 #include <linux/file.h>
60 #include <linux/fdtable.h>
61 #include <linux/string.h>
62 #include <linux/seq_file.h>
63 #include <linux/namei.h>
64 #include <linux/mnt_namespace.h>
65 #include <linux/mm.h>
66 #include <linux/swap.h>
67 #include <linux/rcupdate.h>
68 #include <linux/kallsyms.h>
69 #include <linux/stacktrace.h>
70 #include <linux/resource.h>
71 #include <linux/module.h>
72 #include <linux/mount.h>
73 #include <linux/security.h>
74 #include <linux/ptrace.h>
75 #include <linux/tracehook.h>
76 #include <linux/cgroup.h>
77 #include <linux/cpuset.h>
78 #include <linux/audit.h>
79 #include <linux/poll.h>
80 #include <linux/nsproxy.h>
81 #include <linux/oom.h>
82 #include <linux/elf.h>
83 #include <linux/pid_namespace.h>
84 #include <linux/user_namespace.h>
85 #include <linux/fs_struct.h>
86 #include <linux/slab.h>
87 #include <linux/flex_array.h>
88 #ifdef CONFIG_HARDWALL
89 #include <asm/hardwall.h>
90 #endif
91 #include <trace/events/oom.h>
92 #include "internal.h"
93
94 /* NOTE:
95  *      Implementing inode permission operations in /proc is almost
96  *      certainly an error.  Permission checks need to happen during
97  *      each system call not at open time.  The reason is that most of
98  *      what we wish to check for permissions in /proc varies at runtime.
99  *
100  *      The classic example of a problem is opening file descriptors
101  *      in /proc for a task before it execs a suid executable.
102  */
103
104 struct pid_entry {
105         char *name;
106         int len;
107         umode_t mode;
108         const struct inode_operations *iop;
109         const struct file_operations *fop;
110         union proc_op op;
111 };
112
113 #define NOD(NAME, MODE, IOP, FOP, OP) {                 \
114         .name = (NAME),                                 \
115         .len  = sizeof(NAME) - 1,                       \
116         .mode = MODE,                                   \
117         .iop  = IOP,                                    \
118         .fop  = FOP,                                    \
119         .op   = OP,                                     \
120 }
121
122 #define DIR(NAME, MODE, iops, fops)     \
123         NOD(NAME, (S_IFDIR|(MODE)), &iops, &fops, {} )
124 #define LNK(NAME, get_link)                                     \
125         NOD(NAME, (S_IFLNK|S_IRWXUGO),                          \
126                 &proc_pid_link_inode_operations, NULL,          \
127                 { .proc_get_link = get_link } )
128 #define REG(NAME, MODE, fops)                           \
129         NOD(NAME, (S_IFREG|(MODE)), NULL, &fops, {})
130 #define INF(NAME, MODE, read)                           \
131         NOD(NAME, (S_IFREG|(MODE)),                     \
132                 NULL, &proc_info_file_operations,       \
133                 { .proc_read = read } )
134 #define ONE(NAME, MODE, show)                           \
135         NOD(NAME, (S_IFREG|(MODE)),                     \
136                 NULL, &proc_single_file_operations,     \
137                 { .proc_show = show } )
138
139 static int proc_fd_permission(struct inode *inode, int mask);
140
141 /*
142  * Count the number of hardlinks for the pid_entry table, excluding the .
143  * and .. links.
144  */
145 static unsigned int pid_entry_count_dirs(const struct pid_entry *entries,
146         unsigned int n)
147 {
148         unsigned int i;
149         unsigned int count;
150
151         count = 0;
152         for (i = 0; i < n; ++i) {
153                 if (S_ISDIR(entries[i].mode))
154                         ++count;
155         }
156
157         return count;
158 }
159
160 static int get_task_root(struct task_struct *task, struct path *root)
161 {
162         int result = -ENOENT;
163
164         task_lock(task);
165         if (task->fs) {
166                 get_fs_root(task->fs, root);
167                 result = 0;
168         }
169         task_unlock(task);
170         return result;
171 }
172
173 static int proc_cwd_link(struct dentry *dentry, struct path *path)
174 {
175         struct task_struct *task = get_proc_task(dentry->d_inode);
176         int result = -ENOENT;
177
178         if (task) {
179                 task_lock(task);
180                 if (task->fs) {
181                         get_fs_pwd(task->fs, path);
182                         result = 0;
183                 }
184                 task_unlock(task);
185                 put_task_struct(task);
186         }
187         return result;
188 }
189
190 static int proc_root_link(struct dentry *dentry, struct path *path)
191 {
192         struct task_struct *task = get_proc_task(dentry->d_inode);
193         int result = -ENOENT;
194
195         if (task) {
196                 result = get_task_root(task, path);
197                 put_task_struct(task);
198         }
199         return result;
200 }
201
202 static int proc_pid_cmdline(struct task_struct *task, char * buffer)
203 {
204         int res = 0;
205         unsigned int len;
206         struct mm_struct *mm = get_task_mm(task);
207         if (!mm)
208                 goto out;
209         if (!mm->arg_end)
210                 goto out_mm;    /* Shh! No looking before we're done */
211
212         len = mm->arg_end - mm->arg_start;
213  
214         if (len > PAGE_SIZE)
215                 len = PAGE_SIZE;
216  
217         res = access_process_vm(task, mm->arg_start, buffer, len, 0);
218
219         // If the nul at the end of args has been overwritten, then
220         // assume application is using setproctitle(3).
221         if (res > 0 && buffer[res-1] != '\0' && len < PAGE_SIZE) {
222                 len = strnlen(buffer, res);
223                 if (len < res) {
224                     res = len;
225                 } else {
226                         len = mm->env_end - mm->env_start;
227                         if (len > PAGE_SIZE - res)
228                                 len = PAGE_SIZE - res;
229                         res += access_process_vm(task, mm->env_start, buffer+res, len, 0);
230                         res = strnlen(buffer, res);
231                 }
232         }
233 out_mm:
234         mmput(mm);
235 out:
236         return res;
237 }
238
239 static int proc_pid_auxv(struct task_struct *task, char *buffer)
240 {
241         struct mm_struct *mm = mm_access(task, PTRACE_MODE_READ);
242         int res = PTR_ERR(mm);
243         if (mm && !IS_ERR(mm)) {
244                 unsigned int nwords = 0;
245                 do {
246                         nwords += 2;
247                 } while (mm->saved_auxv[nwords - 2] != 0); /* AT_NULL */
248                 res = nwords * sizeof(mm->saved_auxv[0]);
249                 if (res > PAGE_SIZE)
250                         res = PAGE_SIZE;
251                 memcpy(buffer, mm->saved_auxv, res);
252                 mmput(mm);
253         }
254         return res;
255 }
256
257
258 #ifdef CONFIG_KALLSYMS
259 /*
260  * Provides a wchan file via kallsyms in a proper one-value-per-file format.
261  * Returns the resolved symbol.  If that fails, simply return the address.
262  */
263 static int proc_pid_wchan(struct task_struct *task, char *buffer)
264 {
265         unsigned long wchan;
266         char symname[KSYM_NAME_LEN];
267
268         wchan = get_wchan(task);
269
270         if (lookup_symbol_name(wchan, symname) < 0)
271                 if (!ptrace_may_access(task, PTRACE_MODE_READ))
272                         return 0;
273                 else
274                         return sprintf(buffer, "%lu", wchan);
275         else
276                 return sprintf(buffer, "%s", symname);
277 }
278 #endif /* CONFIG_KALLSYMS */
279
280 static int lock_trace(struct task_struct *task)
281 {
282         int err = mutex_lock_killable(&task->signal->cred_guard_mutex);
283         if (err)
284                 return err;
285         if (!ptrace_may_access(task, PTRACE_MODE_ATTACH)) {
286                 mutex_unlock(&task->signal->cred_guard_mutex);
287                 return -EPERM;
288         }
289         return 0;
290 }
291
292 static void unlock_trace(struct task_struct *task)
293 {
294         mutex_unlock(&task->signal->cred_guard_mutex);
295 }
296
297 #ifdef CONFIG_STACKTRACE
298
299 #define MAX_STACK_TRACE_DEPTH   64
300
301 static int proc_pid_stack(struct seq_file *m, struct pid_namespace *ns,
302                           struct pid *pid, struct task_struct *task)
303 {
304         struct stack_trace trace;
305         unsigned long *entries;
306         int err;
307         int i;
308
309         entries = kmalloc(MAX_STACK_TRACE_DEPTH * sizeof(*entries), GFP_KERNEL);
310         if (!entries)
311                 return -ENOMEM;
312
313         trace.nr_entries        = 0;
314         trace.max_entries       = MAX_STACK_TRACE_DEPTH;
315         trace.entries           = entries;
316         trace.skip              = 0;
317
318         err = lock_trace(task);
319         if (!err) {
320                 save_stack_trace_tsk(task, &trace);
321
322                 for (i = 0; i < trace.nr_entries; i++) {
323                         seq_printf(m, "[<%pK>] %pS\n",
324                                    (void *)entries[i], (void *)entries[i]);
325                 }
326                 unlock_trace(task);
327         }
328         kfree(entries);
329
330         return err;
331 }
332 #endif
333
334 #ifdef CONFIG_SCHEDSTATS
335 /*
336  * Provides /proc/PID/schedstat
337  */
338 static int proc_pid_schedstat(struct task_struct *task, char *buffer)
339 {
340         return sprintf(buffer, "%llu %llu %lu\n",
341                         (unsigned long long)task->se.sum_exec_runtime,
342                         (unsigned long long)task->sched_info.run_delay,
343                         task->sched_info.pcount);
344 }
345 #endif
346
347 #ifdef CONFIG_LATENCYTOP
348 static int lstats_show_proc(struct seq_file *m, void *v)
349 {
350         int i;
351         struct inode *inode = m->private;
352         struct task_struct *task = get_proc_task(inode);
353
354         if (!task)
355                 return -ESRCH;
356         seq_puts(m, "Latency Top version : v0.1\n");
357         for (i = 0; i < 32; i++) {
358                 struct latency_record *lr = &task->latency_record[i];
359                 if (lr->backtrace[0]) {
360                         int q;
361                         seq_printf(m, "%i %li %li",
362                                    lr->count, lr->time, lr->max);
363                         for (q = 0; q < LT_BACKTRACEDEPTH; q++) {
364                                 unsigned long bt = lr->backtrace[q];
365                                 if (!bt)
366                                         break;
367                                 if (bt == ULONG_MAX)
368                                         break;
369                                 seq_printf(m, " %ps", (void *)bt);
370                         }
371                         seq_putc(m, '\n');
372                 }
373
374         }
375         put_task_struct(task);
376         return 0;
377 }
378
379 static int lstats_open(struct inode *inode, struct file *file)
380 {
381         return single_open(file, lstats_show_proc, inode);
382 }
383
384 static ssize_t lstats_write(struct file *file, const char __user *buf,
385                             size_t count, loff_t *offs)
386 {
387         struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
388
389         if (!task)
390                 return -ESRCH;
391         clear_all_latency_tracing(task);
392         put_task_struct(task);
393
394         return count;
395 }
396
397 static const struct file_operations proc_lstats_operations = {
398         .open           = lstats_open,
399         .read           = seq_read,
400         .write          = lstats_write,
401         .llseek         = seq_lseek,
402         .release        = single_release,
403 };
404
405 #endif
406
407 static int proc_oom_score(struct task_struct *task, char *buffer)
408 {
409         unsigned long totalpages = totalram_pages + total_swap_pages;
410         unsigned long points = 0;
411
412         read_lock(&tasklist_lock);
413         if (pid_alive(task))
414                 points = oom_badness(task, NULL, NULL, totalpages) *
415                                                 1000 / totalpages;
416         read_unlock(&tasklist_lock);
417         return sprintf(buffer, "%lu\n", points);
418 }
419
420 struct limit_names {
421         char *name;
422         char *unit;
423 };
424
425 static const struct limit_names lnames[RLIM_NLIMITS] = {
426         [RLIMIT_CPU] = {"Max cpu time", "seconds"},
427         [RLIMIT_FSIZE] = {"Max file size", "bytes"},
428         [RLIMIT_DATA] = {"Max data size", "bytes"},
429         [RLIMIT_STACK] = {"Max stack size", "bytes"},
430         [RLIMIT_CORE] = {"Max core file size", "bytes"},
431         [RLIMIT_RSS] = {"Max resident set", "bytes"},
432         [RLIMIT_NPROC] = {"Max processes", "processes"},
433         [RLIMIT_NOFILE] = {"Max open files", "files"},
434         [RLIMIT_MEMLOCK] = {"Max locked memory", "bytes"},
435         [RLIMIT_AS] = {"Max address space", "bytes"},
436         [RLIMIT_LOCKS] = {"Max file locks", "locks"},
437         [RLIMIT_SIGPENDING] = {"Max pending signals", "signals"},
438         [RLIMIT_MSGQUEUE] = {"Max msgqueue size", "bytes"},
439         [RLIMIT_NICE] = {"Max nice priority", NULL},
440         [RLIMIT_RTPRIO] = {"Max realtime priority", NULL},
441         [RLIMIT_RTTIME] = {"Max realtime timeout", "us"},
442 };
443
444 /* Display limits for a process */
445 static int proc_pid_limits(struct task_struct *task, char *buffer)
446 {
447         unsigned int i;
448         int count = 0;
449         unsigned long flags;
450         char *bufptr = buffer;
451
452         struct rlimit rlim[RLIM_NLIMITS];
453
454         if (!lock_task_sighand(task, &flags))
455                 return 0;
456         memcpy(rlim, task->signal->rlim, sizeof(struct rlimit) * RLIM_NLIMITS);
457         unlock_task_sighand(task, &flags);
458
459         /*
460          * print the file header
461          */
462         count += sprintf(&bufptr[count], "%-25s %-20s %-20s %-10s\n",
463                         "Limit", "Soft Limit", "Hard Limit", "Units");
464
465         for (i = 0; i < RLIM_NLIMITS; i++) {
466                 if (rlim[i].rlim_cur == RLIM_INFINITY)
467                         count += sprintf(&bufptr[count], "%-25s %-20s ",
468                                          lnames[i].name, "unlimited");
469                 else
470                         count += sprintf(&bufptr[count], "%-25s %-20lu ",
471                                          lnames[i].name, rlim[i].rlim_cur);
472
473                 if (rlim[i].rlim_max == RLIM_INFINITY)
474                         count += sprintf(&bufptr[count], "%-20s ", "unlimited");
475                 else
476                         count += sprintf(&bufptr[count], "%-20lu ",
477                                          rlim[i].rlim_max);
478
479                 if (lnames[i].unit)
480                         count += sprintf(&bufptr[count], "%-10s\n",
481                                          lnames[i].unit);
482                 else
483                         count += sprintf(&bufptr[count], "\n");
484         }
485
486         return count;
487 }
488
489 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
490 static int proc_pid_syscall(struct task_struct *task, char *buffer)
491 {
492         long nr;
493         unsigned long args[6], sp, pc;
494         int res = lock_trace(task);
495         if (res)
496                 return res;
497
498         if (task_current_syscall(task, &nr, args, 6, &sp, &pc))
499                 res = sprintf(buffer, "running\n");
500         else if (nr < 0)
501                 res = sprintf(buffer, "%ld 0x%lx 0x%lx\n", nr, sp, pc);
502         else
503                 res = sprintf(buffer,
504                        "%ld 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx\n",
505                        nr,
506                        args[0], args[1], args[2], args[3], args[4], args[5],
507                        sp, pc);
508         unlock_trace(task);
509         return res;
510 }
511 #endif /* CONFIG_HAVE_ARCH_TRACEHOOK */
512
513 /************************************************************************/
514 /*                       Here the fs part begins                        */
515 /************************************************************************/
516
517 /* permission checks */
518 static int proc_fd_access_allowed(struct inode *inode)
519 {
520         struct task_struct *task;
521         int allowed = 0;
522         /* Allow access to a task's file descriptors if it is us or we
523          * may use ptrace attach to the process and find out that
524          * information.
525          */
526         task = get_proc_task(inode);
527         if (task) {
528                 allowed = ptrace_may_access(task, PTRACE_MODE_READ);
529                 put_task_struct(task);
530         }
531         return allowed;
532 }
533
534 int proc_setattr(struct dentry *dentry, struct iattr *attr)
535 {
536         int error;
537         struct inode *inode = dentry->d_inode;
538
539         if (attr->ia_valid & ATTR_MODE)
540                 return -EPERM;
541
542         error = inode_change_ok(inode, attr);
543         if (error)
544                 return error;
545
546         if ((attr->ia_valid & ATTR_SIZE) &&
547             attr->ia_size != i_size_read(inode)) {
548                 error = vmtruncate(inode, attr->ia_size);
549                 if (error)
550                         return error;
551         }
552
553         setattr_copy(inode, attr);
554         mark_inode_dirty(inode);
555         return 0;
556 }
557
558 /*
559  * May current process learn task's sched/cmdline info (for hide_pid_min=1)
560  * or euid/egid (for hide_pid_min=2)?
561  */
562 static bool has_pid_permissions(struct pid_namespace *pid,
563                                  struct task_struct *task,
564                                  int hide_pid_min)
565 {
566         if (pid->hide_pid < hide_pid_min)
567                 return true;
568         if (in_group_p(pid->pid_gid))
569                 return true;
570         return ptrace_may_access(task, PTRACE_MODE_READ);
571 }
572
573
574 static int proc_pid_permission(struct inode *inode, int mask)
575 {
576         struct pid_namespace *pid = inode->i_sb->s_fs_info;
577         struct task_struct *task;
578         bool has_perms;
579
580         task = get_proc_task(inode);
581         if (!task)
582                 return -ESRCH;
583         has_perms = has_pid_permissions(pid, task, 1);
584         put_task_struct(task);
585
586         if (!has_perms) {
587                 if (pid->hide_pid == 2) {
588                         /*
589                          * Let's make getdents(), stat(), and open()
590                          * consistent with each other.  If a process
591                          * may not stat() a file, it shouldn't be seen
592                          * in procfs at all.
593                          */
594                         return -ENOENT;
595                 }
596
597                 return -EPERM;
598         }
599         return generic_permission(inode, mask);
600 }
601
602
603
604 static const struct inode_operations proc_def_inode_operations = {
605         .setattr        = proc_setattr,
606 };
607
608 #define PROC_BLOCK_SIZE (3*1024)                /* 4K page size but our output routines use some slack for overruns */
609
610 static ssize_t proc_info_read(struct file * file, char __user * buf,
611                           size_t count, loff_t *ppos)
612 {
613         struct inode * inode = file->f_path.dentry->d_inode;
614         unsigned long page;
615         ssize_t length;
616         struct task_struct *task = get_proc_task(inode);
617
618         length = -ESRCH;
619         if (!task)
620                 goto out_no_task;
621
622         if (count > PROC_BLOCK_SIZE)
623                 count = PROC_BLOCK_SIZE;
624
625         length = -ENOMEM;
626         if (!(page = __get_free_page(GFP_TEMPORARY)))
627                 goto out;
628
629         length = PROC_I(inode)->op.proc_read(task, (char*)page);
630
631         if (length >= 0)
632                 length = simple_read_from_buffer(buf, count, ppos, (char *)page, length);
633         free_page(page);
634 out:
635         put_task_struct(task);
636 out_no_task:
637         return length;
638 }
639
640 static const struct file_operations proc_info_file_operations = {
641         .read           = proc_info_read,
642         .llseek         = generic_file_llseek,
643 };
644
645 static int proc_single_show(struct seq_file *m, void *v)
646 {
647         struct inode *inode = m->private;
648         struct pid_namespace *ns;
649         struct pid *pid;
650         struct task_struct *task;
651         int ret;
652
653         ns = inode->i_sb->s_fs_info;
654         pid = proc_pid(inode);
655         task = get_pid_task(pid, PIDTYPE_PID);
656         if (!task)
657                 return -ESRCH;
658
659         ret = PROC_I(inode)->op.proc_show(m, ns, pid, task);
660
661         put_task_struct(task);
662         return ret;
663 }
664
665 static int proc_single_open(struct inode *inode, struct file *filp)
666 {
667         return single_open(filp, proc_single_show, inode);
668 }
669
670 static const struct file_operations proc_single_file_operations = {
671         .open           = proc_single_open,
672         .read           = seq_read,
673         .llseek         = seq_lseek,
674         .release        = single_release,
675 };
676
677 static int __mem_open(struct inode *inode, struct file *file, unsigned int mode)
678 {
679         struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
680         struct mm_struct *mm;
681
682         if (!task)
683                 return -ESRCH;
684
685         mm = mm_access(task, mode);
686         put_task_struct(task);
687
688         if (IS_ERR(mm))
689                 return PTR_ERR(mm);
690
691         if (mm) {
692                 /* ensure this mm_struct can't be freed */
693                 atomic_inc(&mm->mm_count);
694                 /* but do not pin its memory */
695                 mmput(mm);
696         }
697
698         file->private_data = mm;
699
700         return 0;
701 }
702
703 static int mem_open(struct inode *inode, struct file *file)
704 {
705         int ret = __mem_open(inode, file, PTRACE_MODE_ATTACH);
706
707         /* OK to pass negative loff_t, we can catch out-of-range */
708         file->f_mode |= FMODE_UNSIGNED_OFFSET;
709
710         return ret;
711 }
712
713 static ssize_t mem_rw(struct file *file, char __user *buf,
714                         size_t count, loff_t *ppos, int write)
715 {
716         struct mm_struct *mm = file->private_data;
717         unsigned long addr = *ppos;
718         ssize_t copied;
719         char *page;
720
721         if (!mm)
722                 return 0;
723
724         page = (char *)__get_free_page(GFP_TEMPORARY);
725         if (!page)
726                 return -ENOMEM;
727
728         copied = 0;
729         if (!atomic_inc_not_zero(&mm->mm_users))
730                 goto free;
731
732         while (count > 0) {
733                 int this_len = min_t(int, count, PAGE_SIZE);
734
735                 if (write && copy_from_user(page, buf, this_len)) {
736                         copied = -EFAULT;
737                         break;
738                 }
739
740                 this_len = access_remote_vm(mm, addr, page, this_len, write);
741                 if (!this_len) {
742                         if (!copied)
743                                 copied = -EIO;
744                         break;
745                 }
746
747                 if (!write && copy_to_user(buf, page, this_len)) {
748                         copied = -EFAULT;
749                         break;
750                 }
751
752                 buf += this_len;
753                 addr += this_len;
754                 copied += this_len;
755                 count -= this_len;
756         }
757         *ppos = addr;
758
759         mmput(mm);
760 free:
761         free_page((unsigned long) page);
762         return copied;
763 }
764
765 static ssize_t mem_read(struct file *file, char __user *buf,
766                         size_t count, loff_t *ppos)
767 {
768         return mem_rw(file, buf, count, ppos, 0);
769 }
770
771 static ssize_t mem_write(struct file *file, const char __user *buf,
772                          size_t count, loff_t *ppos)
773 {
774         return mem_rw(file, (char __user*)buf, count, ppos, 1);
775 }
776
777 loff_t mem_lseek(struct file *file, loff_t offset, int orig)
778 {
779         switch (orig) {
780         case 0:
781                 file->f_pos = offset;
782                 break;
783         case 1:
784                 file->f_pos += offset;
785                 break;
786         default:
787                 return -EINVAL;
788         }
789         force_successful_syscall_return();
790         return file->f_pos;
791 }
792
793 static int mem_release(struct inode *inode, struct file *file)
794 {
795         struct mm_struct *mm = file->private_data;
796         if (mm)
797                 mmdrop(mm);
798         return 0;
799 }
800
801 static const struct file_operations proc_mem_operations = {
802         .llseek         = mem_lseek,
803         .read           = mem_read,
804         .write          = mem_write,
805         .open           = mem_open,
806         .release        = mem_release,
807 };
808
809 static int environ_open(struct inode *inode, struct file *file)
810 {
811         return __mem_open(inode, file, PTRACE_MODE_READ);
812 }
813
814 static ssize_t environ_read(struct file *file, char __user *buf,
815                         size_t count, loff_t *ppos)
816 {
817         char *page;
818         unsigned long src = *ppos;
819         int ret = 0;
820         struct mm_struct *mm = file->private_data;
821
822         if (!mm)
823                 return 0;
824
825         page = (char *)__get_free_page(GFP_TEMPORARY);
826         if (!page)
827                 return -ENOMEM;
828
829         ret = 0;
830         if (!atomic_inc_not_zero(&mm->mm_users))
831                 goto free;
832         while (count > 0) {
833                 size_t this_len, max_len;
834                 int retval;
835
836                 if (src >= (mm->env_end - mm->env_start))
837                         break;
838
839                 this_len = mm->env_end - (mm->env_start + src);
840
841                 max_len = min_t(size_t, PAGE_SIZE, count);
842                 this_len = min(max_len, this_len);
843
844                 retval = access_remote_vm(mm, (mm->env_start + src),
845                         page, this_len, 0);
846
847                 if (retval <= 0) {
848                         ret = retval;
849                         break;
850                 }
851
852                 if (copy_to_user(buf, page, retval)) {
853                         ret = -EFAULT;
854                         break;
855                 }
856
857                 ret += retval;
858                 src += retval;
859                 buf += retval;
860                 count -= retval;
861         }
862         *ppos = src;
863         mmput(mm);
864
865 free:
866         free_page((unsigned long) page);
867         return ret;
868 }
869
870 static const struct file_operations proc_environ_operations = {
871         .open           = environ_open,
872         .read           = environ_read,
873         .llseek         = generic_file_llseek,
874         .release        = mem_release,
875 };
876
877 static ssize_t oom_adjust_read(struct file *file, char __user *buf,
878                                 size_t count, loff_t *ppos)
879 {
880         struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
881         char buffer[PROC_NUMBUF];
882         size_t len;
883         int oom_adjust = OOM_DISABLE;
884         unsigned long flags;
885
886         if (!task)
887                 return -ESRCH;
888
889         if (lock_task_sighand(task, &flags)) {
890                 oom_adjust = task->signal->oom_adj;
891                 unlock_task_sighand(task, &flags);
892         }
893
894         put_task_struct(task);
895
896         len = snprintf(buffer, sizeof(buffer), "%i\n", oom_adjust);
897
898         return simple_read_from_buffer(buf, count, ppos, buffer, len);
899 }
900
901 static ssize_t oom_adjust_write(struct file *file, const char __user *buf,
902                                 size_t count, loff_t *ppos)
903 {
904         struct task_struct *task;
905         char buffer[PROC_NUMBUF];
906         int oom_adjust;
907         unsigned long flags;
908         int err;
909
910         memset(buffer, 0, sizeof(buffer));
911         if (count > sizeof(buffer) - 1)
912                 count = sizeof(buffer) - 1;
913         if (copy_from_user(buffer, buf, count)) {
914                 err = -EFAULT;
915                 goto out;
916         }
917
918         err = kstrtoint(strstrip(buffer), 0, &oom_adjust);
919         if (err)
920                 goto out;
921         if ((oom_adjust < OOM_ADJUST_MIN || oom_adjust > OOM_ADJUST_MAX) &&
922              oom_adjust != OOM_DISABLE) {
923                 err = -EINVAL;
924                 goto out;
925         }
926
927         task = get_proc_task(file->f_path.dentry->d_inode);
928         if (!task) {
929                 err = -ESRCH;
930                 goto out;
931         }
932
933         task_lock(task);
934         if (!task->mm) {
935                 err = -EINVAL;
936                 goto err_task_lock;
937         }
938
939         if (!lock_task_sighand(task, &flags)) {
940                 err = -ESRCH;
941                 goto err_task_lock;
942         }
943
944         if (oom_adjust < task->signal->oom_adj && !capable(CAP_SYS_RESOURCE)) {
945                 err = -EACCES;
946                 goto err_sighand;
947         }
948
949         /*
950          * Warn that /proc/pid/oom_adj is deprecated, see
951          * Documentation/feature-removal-schedule.txt.
952          */
953         printk_once(KERN_WARNING "%s (%d): /proc/%d/oom_adj is deprecated, please use /proc/%d/oom_score_adj instead.\n",
954                   current->comm, task_pid_nr(current), task_pid_nr(task),
955                   task_pid_nr(task));
956         task->signal->oom_adj = oom_adjust;
957         /*
958          * Scale /proc/pid/oom_score_adj appropriately ensuring that a maximum
959          * value is always attainable.
960          */
961         if (task->signal->oom_adj == OOM_ADJUST_MAX)
962                 task->signal->oom_score_adj = OOM_SCORE_ADJ_MAX;
963         else
964                 task->signal->oom_score_adj = (oom_adjust * OOM_SCORE_ADJ_MAX) /
965                                                                 -OOM_DISABLE;
966         trace_oom_score_adj_update(task);
967 err_sighand:
968         unlock_task_sighand(task, &flags);
969 err_task_lock:
970         task_unlock(task);
971         put_task_struct(task);
972 out:
973         return err < 0 ? err : count;
974 }
975
976 static const struct file_operations proc_oom_adjust_operations = {
977         .read           = oom_adjust_read,
978         .write          = oom_adjust_write,
979         .llseek         = generic_file_llseek,
980 };
981
982 static ssize_t oom_score_adj_read(struct file *file, char __user *buf,
983                                         size_t count, loff_t *ppos)
984 {
985         struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
986         char buffer[PROC_NUMBUF];
987         int oom_score_adj = OOM_SCORE_ADJ_MIN;
988         unsigned long flags;
989         size_t len;
990
991         if (!task)
992                 return -ESRCH;
993         if (lock_task_sighand(task, &flags)) {
994                 oom_score_adj = task->signal->oom_score_adj;
995                 unlock_task_sighand(task, &flags);
996         }
997         put_task_struct(task);
998         len = snprintf(buffer, sizeof(buffer), "%d\n", oom_score_adj);
999         return simple_read_from_buffer(buf, count, ppos, buffer, len);
1000 }
1001
1002 static ssize_t oom_score_adj_write(struct file *file, const char __user *buf,
1003                                         size_t count, loff_t *ppos)
1004 {
1005         struct task_struct *task;
1006         char buffer[PROC_NUMBUF];
1007         unsigned long flags;
1008         int oom_score_adj;
1009         int err;
1010
1011         memset(buffer, 0, sizeof(buffer));
1012         if (count > sizeof(buffer) - 1)
1013                 count = sizeof(buffer) - 1;
1014         if (copy_from_user(buffer, buf, count)) {
1015                 err = -EFAULT;
1016                 goto out;
1017         }
1018
1019         err = kstrtoint(strstrip(buffer), 0, &oom_score_adj);
1020         if (err)
1021                 goto out;
1022         if (oom_score_adj < OOM_SCORE_ADJ_MIN ||
1023                         oom_score_adj > OOM_SCORE_ADJ_MAX) {
1024                 err = -EINVAL;
1025                 goto out;
1026         }
1027
1028         task = get_proc_task(file->f_path.dentry->d_inode);
1029         if (!task) {
1030                 err = -ESRCH;
1031                 goto out;
1032         }
1033
1034         task_lock(task);
1035         if (!task->mm) {
1036                 err = -EINVAL;
1037                 goto err_task_lock;
1038         }
1039
1040         if (!lock_task_sighand(task, &flags)) {
1041                 err = -ESRCH;
1042                 goto err_task_lock;
1043         }
1044
1045         if (oom_score_adj < task->signal->oom_score_adj_min &&
1046                         !capable(CAP_SYS_RESOURCE)) {
1047                 err = -EACCES;
1048                 goto err_sighand;
1049         }
1050
1051         task->signal->oom_score_adj = oom_score_adj;
1052         if (has_capability_noaudit(current, CAP_SYS_RESOURCE))
1053                 task->signal->oom_score_adj_min = oom_score_adj;
1054         trace_oom_score_adj_update(task);
1055         /*
1056          * Scale /proc/pid/oom_adj appropriately ensuring that OOM_DISABLE is
1057          * always attainable.
1058          */
1059         if (task->signal->oom_score_adj == OOM_SCORE_ADJ_MIN)
1060                 task->signal->oom_adj = OOM_DISABLE;
1061         else
1062                 task->signal->oom_adj = (oom_score_adj * OOM_ADJUST_MAX) /
1063                                                         OOM_SCORE_ADJ_MAX;
1064 err_sighand:
1065         unlock_task_sighand(task, &flags);
1066 err_task_lock:
1067         task_unlock(task);
1068         put_task_struct(task);
1069 out:
1070         return err < 0 ? err : count;
1071 }
1072
1073 static const struct file_operations proc_oom_score_adj_operations = {
1074         .read           = oom_score_adj_read,
1075         .write          = oom_score_adj_write,
1076         .llseek         = default_llseek,
1077 };
1078
1079 #ifdef CONFIG_AUDITSYSCALL
1080 #define TMPBUFLEN 21
1081 static ssize_t proc_loginuid_read(struct file * file, char __user * buf,
1082                                   size_t count, loff_t *ppos)
1083 {
1084         struct inode * inode = file->f_path.dentry->d_inode;
1085         struct task_struct *task = get_proc_task(inode);
1086         ssize_t length;
1087         char tmpbuf[TMPBUFLEN];
1088
1089         if (!task)
1090                 return -ESRCH;
1091         length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1092                                 audit_get_loginuid(task));
1093         put_task_struct(task);
1094         return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1095 }
1096
1097 static ssize_t proc_loginuid_write(struct file * file, const char __user * buf,
1098                                    size_t count, loff_t *ppos)
1099 {
1100         struct inode * inode = file->f_path.dentry->d_inode;
1101         char *page, *tmp;
1102         ssize_t length;
1103         uid_t loginuid;
1104
1105         rcu_read_lock();
1106         if (current != pid_task(proc_pid(inode), PIDTYPE_PID)) {
1107                 rcu_read_unlock();
1108                 return -EPERM;
1109         }
1110         rcu_read_unlock();
1111
1112         if (count >= PAGE_SIZE)
1113                 count = PAGE_SIZE - 1;
1114
1115         if (*ppos != 0) {
1116                 /* No partial writes. */
1117                 return -EINVAL;
1118         }
1119         page = (char*)__get_free_page(GFP_TEMPORARY);
1120         if (!page)
1121                 return -ENOMEM;
1122         length = -EFAULT;
1123         if (copy_from_user(page, buf, count))
1124                 goto out_free_page;
1125
1126         page[count] = '\0';
1127         loginuid = simple_strtoul(page, &tmp, 10);
1128         if (tmp == page) {
1129                 length = -EINVAL;
1130                 goto out_free_page;
1131
1132         }
1133         length = audit_set_loginuid(loginuid);
1134         if (likely(length == 0))
1135                 length = count;
1136
1137 out_free_page:
1138         free_page((unsigned long) page);
1139         return length;
1140 }
1141
1142 static const struct file_operations proc_loginuid_operations = {
1143         .read           = proc_loginuid_read,
1144         .write          = proc_loginuid_write,
1145         .llseek         = generic_file_llseek,
1146 };
1147
1148 static ssize_t proc_sessionid_read(struct file * file, char __user * buf,
1149                                   size_t count, loff_t *ppos)
1150 {
1151         struct inode * inode = file->f_path.dentry->d_inode;
1152         struct task_struct *task = get_proc_task(inode);
1153         ssize_t length;
1154         char tmpbuf[TMPBUFLEN];
1155
1156         if (!task)
1157                 return -ESRCH;
1158         length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1159                                 audit_get_sessionid(task));
1160         put_task_struct(task);
1161         return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1162 }
1163
1164 static const struct file_operations proc_sessionid_operations = {
1165         .read           = proc_sessionid_read,
1166         .llseek         = generic_file_llseek,
1167 };
1168 #endif
1169
1170 #ifdef CONFIG_FAULT_INJECTION
1171 static ssize_t proc_fault_inject_read(struct file * file, char __user * buf,
1172                                       size_t count, loff_t *ppos)
1173 {
1174         struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
1175         char buffer[PROC_NUMBUF];
1176         size_t len;
1177         int make_it_fail;
1178
1179         if (!task)
1180                 return -ESRCH;
1181         make_it_fail = task->make_it_fail;
1182         put_task_struct(task);
1183
1184         len = snprintf(buffer, sizeof(buffer), "%i\n", make_it_fail);
1185
1186         return simple_read_from_buffer(buf, count, ppos, buffer, len);
1187 }
1188
1189 static ssize_t proc_fault_inject_write(struct file * file,
1190                         const char __user * buf, size_t count, loff_t *ppos)
1191 {
1192         struct task_struct *task;
1193         char buffer[PROC_NUMBUF], *end;
1194         int make_it_fail;
1195
1196         if (!capable(CAP_SYS_RESOURCE))
1197                 return -EPERM;
1198         memset(buffer, 0, sizeof(buffer));
1199         if (count > sizeof(buffer) - 1)
1200                 count = sizeof(buffer) - 1;
1201         if (copy_from_user(buffer, buf, count))
1202                 return -EFAULT;
1203         make_it_fail = simple_strtol(strstrip(buffer), &end, 0);
1204         if (*end)
1205                 return -EINVAL;
1206         task = get_proc_task(file->f_dentry->d_inode);
1207         if (!task)
1208                 return -ESRCH;
1209         task->make_it_fail = make_it_fail;
1210         put_task_struct(task);
1211
1212         return count;
1213 }
1214
1215 static const struct file_operations proc_fault_inject_operations = {
1216         .read           = proc_fault_inject_read,
1217         .write          = proc_fault_inject_write,
1218         .llseek         = generic_file_llseek,
1219 };
1220 #endif
1221
1222
1223 #ifdef CONFIG_SCHED_DEBUG
1224 /*
1225  * Print out various scheduling related per-task fields:
1226  */
1227 static int sched_show(struct seq_file *m, void *v)
1228 {
1229         struct inode *inode = m->private;
1230         struct task_struct *p;
1231
1232         p = get_proc_task(inode);
1233         if (!p)
1234                 return -ESRCH;
1235         proc_sched_show_task(p, m);
1236
1237         put_task_struct(p);
1238
1239         return 0;
1240 }
1241
1242 static ssize_t
1243 sched_write(struct file *file, const char __user *buf,
1244             size_t count, loff_t *offset)
1245 {
1246         struct inode *inode = file->f_path.dentry->d_inode;
1247         struct task_struct *p;
1248
1249         p = get_proc_task(inode);
1250         if (!p)
1251                 return -ESRCH;
1252         proc_sched_set_task(p);
1253
1254         put_task_struct(p);
1255
1256         return count;
1257 }
1258
1259 static int sched_open(struct inode *inode, struct file *filp)
1260 {
1261         return single_open(filp, sched_show, inode);
1262 }
1263
1264 static const struct file_operations proc_pid_sched_operations = {
1265         .open           = sched_open,
1266         .read           = seq_read,
1267         .write          = sched_write,
1268         .llseek         = seq_lseek,
1269         .release        = single_release,
1270 };
1271
1272 #endif
1273
1274 static ssize_t comm_write(struct file *file, const char __user *buf,
1275                                 size_t count, loff_t *offset)
1276 {
1277         struct inode *inode = file->f_path.dentry->d_inode;
1278         struct task_struct *p;
1279         char buffer[TASK_COMM_LEN];
1280
1281         memset(buffer, 0, sizeof(buffer));
1282         if (count > sizeof(buffer) - 1)
1283                 count = sizeof(buffer) - 1;
1284         if (copy_from_user(buffer, buf, count))
1285                 return -EFAULT;
1286
1287         p = get_proc_task(inode);
1288         if (!p)
1289                 return -ESRCH;
1290
1291         if (same_thread_group(current, p))
1292                 set_task_comm(p, buffer);
1293         else
1294                 count = -EINVAL;
1295
1296         put_task_struct(p);
1297
1298         return count;
1299 }
1300
1301 static int comm_show(struct seq_file *m, void *v)
1302 {
1303         struct inode *inode = m->private;
1304         struct task_struct *p;
1305
1306         p = get_proc_task(inode);
1307         if (!p)
1308                 return -ESRCH;
1309
1310         task_lock(p);
1311         seq_printf(m, "%s\n", p->comm);
1312         task_unlock(p);
1313
1314         put_task_struct(p);
1315
1316         return 0;
1317 }
1318
1319 static int comm_open(struct inode *inode, struct file *filp)
1320 {
1321         return single_open(filp, comm_show, inode);
1322 }
1323
1324 static const struct file_operations proc_pid_set_comm_operations = {
1325         .open           = comm_open,
1326         .read           = seq_read,
1327         .write          = comm_write,
1328         .llseek         = seq_lseek,
1329         .release        = single_release,
1330 };
1331
1332 static int proc_exe_link(struct dentry *dentry, struct path *exe_path)
1333 {
1334         struct task_struct *task;
1335         struct mm_struct *mm;
1336         struct file *exe_file;
1337
1338         task = get_proc_task(dentry->d_inode);
1339         if (!task)
1340                 return -ENOENT;
1341         mm = get_task_mm(task);
1342         put_task_struct(task);
1343         if (!mm)
1344                 return -ENOENT;
1345         exe_file = get_mm_exe_file(mm);
1346         mmput(mm);
1347         if (exe_file) {
1348                 *exe_path = exe_file->f_path;
1349                 path_get(&exe_file->f_path);
1350                 fput(exe_file);
1351                 return 0;
1352         } else
1353                 return -ENOENT;
1354 }
1355
1356 static void *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd)
1357 {
1358         struct inode *inode = dentry->d_inode;
1359         struct path path;
1360         int error = -EACCES;
1361
1362         /* Are we allowed to snoop on the tasks file descriptors? */
1363         if (!proc_fd_access_allowed(inode))
1364                 goto out;
1365
1366         error = PROC_I(inode)->op.proc_get_link(dentry, &path);
1367         if (error)
1368                 goto out;
1369
1370         nd_jump_link(nd, &path);
1371         return NULL;
1372 out:
1373         return ERR_PTR(error);
1374 }
1375
1376 static int do_proc_readlink(struct path *path, char __user *buffer, int buflen)
1377 {
1378         char *tmp = (char*)__get_free_page(GFP_TEMPORARY);
1379         char *pathname;
1380         int len;
1381
1382         if (!tmp)
1383                 return -ENOMEM;
1384
1385         pathname = d_path(path, tmp, PAGE_SIZE);
1386         len = PTR_ERR(pathname);
1387         if (IS_ERR(pathname))
1388                 goto out;
1389         len = tmp + PAGE_SIZE - 1 - pathname;
1390
1391         if (len > buflen)
1392                 len = buflen;
1393         if (copy_to_user(buffer, pathname, len))
1394                 len = -EFAULT;
1395  out:
1396         free_page((unsigned long)tmp);
1397         return len;
1398 }
1399
1400 static int proc_pid_readlink(struct dentry * dentry, char __user * buffer, int buflen)
1401 {
1402         int error = -EACCES;
1403         struct inode *inode = dentry->d_inode;
1404         struct path path;
1405
1406         /* Are we allowed to snoop on the tasks file descriptors? */
1407         if (!proc_fd_access_allowed(inode))
1408                 goto out;
1409
1410         error = PROC_I(inode)->op.proc_get_link(dentry, &path);
1411         if (error)
1412                 goto out;
1413
1414         error = do_proc_readlink(&path, buffer, buflen);
1415         path_put(&path);
1416 out:
1417         return error;
1418 }
1419
1420 static const struct inode_operations proc_pid_link_inode_operations = {
1421         .readlink       = proc_pid_readlink,
1422         .follow_link    = proc_pid_follow_link,
1423         .setattr        = proc_setattr,
1424 };
1425
1426
1427 /* building an inode */
1428
1429 static int task_dumpable(struct task_struct *task)
1430 {
1431         int dumpable = 0;
1432         struct mm_struct *mm;
1433
1434         task_lock(task);
1435         mm = task->mm;
1436         if (mm)
1437                 dumpable = get_dumpable(mm);
1438         task_unlock(task);
1439         if(dumpable == 1)
1440                 return 1;
1441         return 0;
1442 }
1443
1444 struct inode *proc_pid_make_inode(struct super_block * sb, struct task_struct *task)
1445 {
1446         struct inode * inode;
1447         struct proc_inode *ei;
1448         const struct cred *cred;
1449
1450         /* We need a new inode */
1451
1452         inode = new_inode(sb);
1453         if (!inode)
1454                 goto out;
1455
1456         /* Common stuff */
1457         ei = PROC_I(inode);
1458         inode->i_ino = get_next_ino();
1459         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
1460         inode->i_op = &proc_def_inode_operations;
1461
1462         /*
1463          * grab the reference to task.
1464          */
1465         ei->pid = get_task_pid(task, PIDTYPE_PID);
1466         if (!ei->pid)
1467                 goto out_unlock;
1468
1469         if (task_dumpable(task)) {
1470                 rcu_read_lock();
1471                 cred = __task_cred(task);
1472                 inode->i_uid = cred->euid;
1473                 inode->i_gid = cred->egid;
1474                 rcu_read_unlock();
1475         }
1476         security_task_to_inode(task, inode);
1477
1478 out:
1479         return inode;
1480
1481 out_unlock:
1482         iput(inode);
1483         return NULL;
1484 }
1485
1486 int pid_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
1487 {
1488         struct inode *inode = dentry->d_inode;
1489         struct task_struct *task;
1490         const struct cred *cred;
1491         struct pid_namespace *pid = dentry->d_sb->s_fs_info;
1492
1493         generic_fillattr(inode, stat);
1494
1495         rcu_read_lock();
1496         stat->uid = GLOBAL_ROOT_UID;
1497         stat->gid = GLOBAL_ROOT_GID;
1498         task = pid_task(proc_pid(inode), PIDTYPE_PID);
1499         if (task) {
1500                 if (!has_pid_permissions(pid, task, 2)) {
1501                         rcu_read_unlock();
1502                         /*
1503                          * This doesn't prevent learning whether PID exists,
1504                          * it only makes getattr() consistent with readdir().
1505                          */
1506                         return -ENOENT;
1507                 }
1508                 if ((inode->i_mode == (S_IFDIR|S_IRUGO|S_IXUGO)) ||
1509                     task_dumpable(task)) {
1510                         cred = __task_cred(task);
1511                         stat->uid = cred->euid;
1512                         stat->gid = cred->egid;
1513                 }
1514         }
1515         rcu_read_unlock();
1516         return 0;
1517 }
1518
1519 /* dentry stuff */
1520
1521 /*
1522  *      Exceptional case: normally we are not allowed to unhash a busy
1523  * directory. In this case, however, we can do it - no aliasing problems
1524  * due to the way we treat inodes.
1525  *
1526  * Rewrite the inode's ownerships here because the owning task may have
1527  * performed a setuid(), etc.
1528  *
1529  * Before the /proc/pid/status file was created the only way to read
1530  * the effective uid of a /process was to stat /proc/pid.  Reading
1531  * /proc/pid/status is slow enough that procps and other packages
1532  * kept stating /proc/pid.  To keep the rules in /proc simple I have
1533  * made this apply to all per process world readable and executable
1534  * directories.
1535  */
1536 int pid_revalidate(struct dentry *dentry, unsigned int flags)
1537 {
1538         struct inode *inode;
1539         struct task_struct *task;
1540         const struct cred *cred;
1541
1542         if (flags & LOOKUP_RCU)
1543                 return -ECHILD;
1544
1545         inode = dentry->d_inode;
1546         task = get_proc_task(inode);
1547
1548         if (task) {
1549                 if ((inode->i_mode == (S_IFDIR|S_IRUGO|S_IXUGO)) ||
1550                     task_dumpable(task)) {
1551                         rcu_read_lock();
1552                         cred = __task_cred(task);
1553                         inode->i_uid = cred->euid;
1554                         inode->i_gid = cred->egid;
1555                         rcu_read_unlock();
1556                 } else {
1557                         inode->i_uid = GLOBAL_ROOT_UID;
1558                         inode->i_gid = GLOBAL_ROOT_GID;
1559                 }
1560                 inode->i_mode &= ~(S_ISUID | S_ISGID);
1561                 security_task_to_inode(task, inode);
1562                 put_task_struct(task);
1563                 return 1;
1564         }
1565         d_drop(dentry);
1566         return 0;
1567 }
1568
1569 static int pid_delete_dentry(const struct dentry * dentry)
1570 {
1571         /* Is the task we represent dead?
1572          * If so, then don't put the dentry on the lru list,
1573          * kill it immediately.
1574          */
1575         return !proc_pid(dentry->d_inode)->tasks[PIDTYPE_PID].first;
1576 }
1577
1578 const struct dentry_operations pid_dentry_operations =
1579 {
1580         .d_revalidate   = pid_revalidate,
1581         .d_delete       = pid_delete_dentry,
1582 };
1583
1584 /* Lookups */
1585
1586 /*
1587  * Fill a directory entry.
1588  *
1589  * If possible create the dcache entry and derive our inode number and
1590  * file type from dcache entry.
1591  *
1592  * Since all of the proc inode numbers are dynamically generated, the inode
1593  * numbers do not exist until the inode is cache.  This means creating the
1594  * the dcache entry in readdir is necessary to keep the inode numbers
1595  * reported by readdir in sync with the inode numbers reported
1596  * by stat.
1597  */
1598 int proc_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
1599         const char *name, int len,
1600         instantiate_t instantiate, struct task_struct *task, const void *ptr)
1601 {
1602         struct dentry *child, *dir = filp->f_path.dentry;
1603         struct inode *inode;
1604         struct qstr qname;
1605         ino_t ino = 0;
1606         unsigned type = DT_UNKNOWN;
1607
1608         qname.name = name;
1609         qname.len  = len;
1610         qname.hash = full_name_hash(name, len);
1611
1612         child = d_lookup(dir, &qname);
1613         if (!child) {
1614                 struct dentry *new;
1615                 new = d_alloc(dir, &qname);
1616                 if (new) {
1617                         child = instantiate(dir->d_inode, new, task, ptr);
1618                         if (child)
1619                                 dput(new);
1620                         else
1621                                 child = new;
1622                 }
1623         }
1624         if (!child || IS_ERR(child) || !child->d_inode)
1625                 goto end_instantiate;
1626         inode = child->d_inode;
1627         if (inode) {
1628                 ino = inode->i_ino;
1629                 type = inode->i_mode >> 12;
1630         }
1631         dput(child);
1632 end_instantiate:
1633         if (!ino)
1634                 ino = find_inode_number(dir, &qname);
1635         if (!ino)
1636                 ino = 1;
1637         return filldir(dirent, name, len, filp->f_pos, ino, type);
1638 }
1639
1640 static unsigned name_to_int(struct dentry *dentry)
1641 {
1642         const char *name = dentry->d_name.name;
1643         int len = dentry->d_name.len;
1644         unsigned n = 0;
1645
1646         if (len > 1 && *name == '0')
1647                 goto out;
1648         while (len-- > 0) {
1649                 unsigned c = *name++ - '0';
1650                 if (c > 9)
1651                         goto out;
1652                 if (n >= (~0U-9)/10)
1653                         goto out;
1654                 n *= 10;
1655                 n += c;
1656         }
1657         return n;
1658 out:
1659         return ~0U;
1660 }
1661
1662 #define PROC_FDINFO_MAX 64
1663
1664 static int proc_fd_info(struct inode *inode, struct path *path, char *info)
1665 {
1666         struct task_struct *task = get_proc_task(inode);
1667         struct files_struct *files = NULL;
1668         struct file *file;
1669         int fd = proc_fd(inode);
1670
1671         if (task) {
1672                 files = get_files_struct(task);
1673                 put_task_struct(task);
1674         }
1675         if (files) {
1676                 /*
1677                  * We are not taking a ref to the file structure, so we must
1678                  * hold ->file_lock.
1679                  */
1680                 spin_lock(&files->file_lock);
1681                 file = fcheck_files(files, fd);
1682                 if (file) {
1683                         unsigned int f_flags;
1684                         struct fdtable *fdt;
1685
1686                         fdt = files_fdtable(files);
1687                         f_flags = file->f_flags & ~O_CLOEXEC;
1688                         if (close_on_exec(fd, fdt))
1689                                 f_flags |= O_CLOEXEC;
1690
1691                         if (path) {
1692                                 *path = file->f_path;
1693                                 path_get(&file->f_path);
1694                         }
1695                         if (info)
1696                                 snprintf(info, PROC_FDINFO_MAX,
1697                                          "pos:\t%lli\n"
1698                                          "flags:\t0%o\n",
1699                                          (long long) file->f_pos,
1700                                          f_flags);
1701                         spin_unlock(&files->file_lock);
1702                         put_files_struct(files);
1703                         return 0;
1704                 }
1705                 spin_unlock(&files->file_lock);
1706                 put_files_struct(files);
1707         }
1708         return -ENOENT;
1709 }
1710
1711 static int proc_fd_link(struct dentry *dentry, struct path *path)
1712 {
1713         return proc_fd_info(dentry->d_inode, path, NULL);
1714 }
1715
1716 static int tid_fd_revalidate(struct dentry *dentry, unsigned int flags)
1717 {
1718         struct inode *inode;
1719         struct task_struct *task;
1720         int fd;
1721         struct files_struct *files;
1722         const struct cred *cred;
1723
1724         if (flags & LOOKUP_RCU)
1725                 return -ECHILD;
1726
1727         inode = dentry->d_inode;
1728         task = get_proc_task(inode);
1729         fd = proc_fd(inode);
1730
1731         if (task) {
1732                 files = get_files_struct(task);
1733                 if (files) {
1734                         struct file *file;
1735                         rcu_read_lock();
1736                         file = fcheck_files(files, fd);
1737                         if (file) {
1738                                 unsigned f_mode = file->f_mode;
1739
1740                                 rcu_read_unlock();
1741                                 put_files_struct(files);
1742
1743                                 if (task_dumpable(task)) {
1744                                         rcu_read_lock();
1745                                         cred = __task_cred(task);
1746                                         inode->i_uid = cred->euid;
1747                                         inode->i_gid = cred->egid;
1748                                         rcu_read_unlock();
1749                                 } else {
1750                                         inode->i_uid = GLOBAL_ROOT_UID;
1751                                         inode->i_gid = GLOBAL_ROOT_GID;
1752                                 }
1753
1754                                 if (S_ISLNK(inode->i_mode)) {
1755                                         unsigned i_mode = S_IFLNK;
1756                                         if (f_mode & FMODE_READ)
1757                                                 i_mode |= S_IRUSR | S_IXUSR;
1758                                         if (f_mode & FMODE_WRITE)
1759                                                 i_mode |= S_IWUSR | S_IXUSR;
1760                                         inode->i_mode = i_mode;
1761                                 }
1762
1763                                 security_task_to_inode(task, inode);
1764                                 put_task_struct(task);
1765                                 return 1;
1766                         }
1767                         rcu_read_unlock();
1768                         put_files_struct(files);
1769                 }
1770                 put_task_struct(task);
1771         }
1772         d_drop(dentry);
1773         return 0;
1774 }
1775
1776 static const struct dentry_operations tid_fd_dentry_operations =
1777 {
1778         .d_revalidate   = tid_fd_revalidate,
1779         .d_delete       = pid_delete_dentry,
1780 };
1781
1782 static struct dentry *proc_fd_instantiate(struct inode *dir,
1783         struct dentry *dentry, struct task_struct *task, const void *ptr)
1784 {
1785         unsigned fd = (unsigned long)ptr;
1786         struct inode *inode;
1787         struct proc_inode *ei;
1788         struct dentry *error = ERR_PTR(-ENOENT);
1789
1790         inode = proc_pid_make_inode(dir->i_sb, task);
1791         if (!inode)
1792                 goto out;
1793         ei = PROC_I(inode);
1794         ei->fd = fd;
1795
1796         inode->i_mode = S_IFLNK;
1797         inode->i_op = &proc_pid_link_inode_operations;
1798         inode->i_size = 64;
1799         ei->op.proc_get_link = proc_fd_link;
1800         d_set_d_op(dentry, &tid_fd_dentry_operations);
1801         d_add(dentry, inode);
1802         /* Close the race of the process dying before we return the dentry */
1803         if (tid_fd_revalidate(dentry, 0))
1804                 error = NULL;
1805
1806  out:
1807         return error;
1808 }
1809
1810 static struct dentry *proc_lookupfd_common(struct inode *dir,
1811                                            struct dentry *dentry,
1812                                            instantiate_t instantiate)
1813 {
1814         struct task_struct *task = get_proc_task(dir);
1815         unsigned fd = name_to_int(dentry);
1816         struct dentry *result = ERR_PTR(-ENOENT);
1817
1818         if (!task)
1819                 goto out_no_task;
1820         if (fd == ~0U)
1821                 goto out;
1822
1823         result = instantiate(dir, dentry, task, (void *)(unsigned long)fd);
1824 out:
1825         put_task_struct(task);
1826 out_no_task:
1827         return result;
1828 }
1829
1830 static int proc_readfd_common(struct file * filp, void * dirent,
1831                               filldir_t filldir, instantiate_t instantiate)
1832 {
1833         struct dentry *dentry = filp->f_path.dentry;
1834         struct inode *inode = dentry->d_inode;
1835         struct task_struct *p = get_proc_task(inode);
1836         unsigned int fd, ino;
1837         int retval;
1838         struct files_struct * files;
1839
1840         retval = -ENOENT;
1841         if (!p)
1842                 goto out_no_task;
1843         retval = 0;
1844
1845         fd = filp->f_pos;
1846         switch (fd) {
1847                 case 0:
1848                         if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR) < 0)
1849                                 goto out;
1850                         filp->f_pos++;
1851                 case 1:
1852                         ino = parent_ino(dentry);
1853                         if (filldir(dirent, "..", 2, 1, ino, DT_DIR) < 0)
1854                                 goto out;
1855                         filp->f_pos++;
1856                 default:
1857                         files = get_files_struct(p);
1858                         if (!files)
1859                                 goto out;
1860                         rcu_read_lock();
1861                         for (fd = filp->f_pos-2;
1862                              fd < files_fdtable(files)->max_fds;
1863                              fd++, filp->f_pos++) {
1864                                 char name[PROC_NUMBUF];
1865                                 int len;
1866                                 int rv;
1867
1868                                 if (!fcheck_files(files, fd))
1869                                         continue;
1870                                 rcu_read_unlock();
1871
1872                                 len = snprintf(name, sizeof(name), "%d", fd);
1873                                 rv = proc_fill_cache(filp, dirent, filldir,
1874                                                      name, len, instantiate, p,
1875                                                      (void *)(unsigned long)fd);
1876                                 if (rv < 0)
1877                                         goto out_fd_loop;
1878                                 rcu_read_lock();
1879                         }
1880                         rcu_read_unlock();
1881 out_fd_loop:
1882                         put_files_struct(files);
1883         }
1884 out:
1885         put_task_struct(p);
1886 out_no_task:
1887         return retval;
1888 }
1889
1890 static struct dentry *proc_lookupfd(struct inode *dir, struct dentry *dentry,
1891                                     unsigned int flags)
1892 {
1893         return proc_lookupfd_common(dir, dentry, proc_fd_instantiate);
1894 }
1895
1896 static int proc_readfd(struct file *filp, void *dirent, filldir_t filldir)
1897 {
1898         return proc_readfd_common(filp, dirent, filldir, proc_fd_instantiate);
1899 }
1900
1901 static ssize_t proc_fdinfo_read(struct file *file, char __user *buf,
1902                                       size_t len, loff_t *ppos)
1903 {
1904         char tmp[PROC_FDINFO_MAX];
1905         int err = proc_fd_info(file->f_path.dentry->d_inode, NULL, tmp);
1906         if (!err)
1907                 err = simple_read_from_buffer(buf, len, ppos, tmp, strlen(tmp));
1908         return err;
1909 }
1910
1911 static const struct file_operations proc_fdinfo_file_operations = {
1912         .open           = nonseekable_open,
1913         .read           = proc_fdinfo_read,
1914         .llseek         = no_llseek,
1915 };
1916
1917 static const struct file_operations proc_fd_operations = {
1918         .read           = generic_read_dir,
1919         .readdir        = proc_readfd,
1920         .llseek         = default_llseek,
1921 };
1922
1923 #ifdef CONFIG_CHECKPOINT_RESTORE
1924
1925 /*
1926  * dname_to_vma_addr - maps a dentry name into two unsigned longs
1927  * which represent vma start and end addresses.
1928  */
1929 static int dname_to_vma_addr(struct dentry *dentry,
1930                              unsigned long *start, unsigned long *end)
1931 {
1932         if (sscanf(dentry->d_name.name, "%lx-%lx", start, end) != 2)
1933                 return -EINVAL;
1934
1935         return 0;
1936 }
1937
1938 static int map_files_d_revalidate(struct dentry *dentry, unsigned int flags)
1939 {
1940         unsigned long vm_start, vm_end;
1941         bool exact_vma_exists = false;
1942         struct mm_struct *mm = NULL;
1943         struct task_struct *task;
1944         const struct cred *cred;
1945         struct inode *inode;
1946         int status = 0;
1947
1948         if (flags & LOOKUP_RCU)
1949                 return -ECHILD;
1950
1951         if (!capable(CAP_SYS_ADMIN)) {
1952                 status = -EACCES;
1953                 goto out_notask;
1954         }
1955
1956         inode = dentry->d_inode;
1957         task = get_proc_task(inode);
1958         if (!task)
1959                 goto out_notask;
1960
1961         mm = mm_access(task, PTRACE_MODE_READ);
1962         if (IS_ERR_OR_NULL(mm))
1963                 goto out;
1964
1965         if (!dname_to_vma_addr(dentry, &vm_start, &vm_end)) {
1966                 down_read(&mm->mmap_sem);
1967                 exact_vma_exists = !!find_exact_vma(mm, vm_start, vm_end);
1968                 up_read(&mm->mmap_sem);
1969         }
1970
1971         mmput(mm);
1972
1973         if (exact_vma_exists) {
1974                 if (task_dumpable(task)) {
1975                         rcu_read_lock();
1976                         cred = __task_cred(task);
1977                         inode->i_uid = cred->euid;
1978                         inode->i_gid = cred->egid;
1979                         rcu_read_unlock();
1980                 } else {
1981                         inode->i_uid = GLOBAL_ROOT_UID;
1982                         inode->i_gid = GLOBAL_ROOT_GID;
1983                 }
1984                 security_task_to_inode(task, inode);
1985                 status = 1;
1986         }
1987
1988 out:
1989         put_task_struct(task);
1990
1991 out_notask:
1992         if (status <= 0)
1993                 d_drop(dentry);
1994
1995         return status;
1996 }
1997
1998 static const struct dentry_operations tid_map_files_dentry_operations = {
1999         .d_revalidate   = map_files_d_revalidate,
2000         .d_delete       = pid_delete_dentry,
2001 };
2002
2003 static int proc_map_files_get_link(struct dentry *dentry, struct path *path)
2004 {
2005         unsigned long vm_start, vm_end;
2006         struct vm_area_struct *vma;
2007         struct task_struct *task;
2008         struct mm_struct *mm;
2009         int rc;
2010
2011         rc = -ENOENT;
2012         task = get_proc_task(dentry->d_inode);
2013         if (!task)
2014                 goto out;
2015
2016         mm = get_task_mm(task);
2017         put_task_struct(task);
2018         if (!mm)
2019                 goto out;
2020
2021         rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
2022         if (rc)
2023                 goto out_mmput;
2024
2025         down_read(&mm->mmap_sem);
2026         vma = find_exact_vma(mm, vm_start, vm_end);
2027         if (vma && vma->vm_file) {
2028                 *path = vma->vm_file->f_path;
2029                 path_get(path);
2030                 rc = 0;
2031         }
2032         up_read(&mm->mmap_sem);
2033
2034 out_mmput:
2035         mmput(mm);
2036 out:
2037         return rc;
2038 }
2039
2040 struct map_files_info {
2041         struct file     *file;
2042         unsigned long   len;
2043         unsigned char   name[4*sizeof(long)+2]; /* max: %lx-%lx\0 */
2044 };
2045
2046 static struct dentry *
2047 proc_map_files_instantiate(struct inode *dir, struct dentry *dentry,
2048                            struct task_struct *task, const void *ptr)
2049 {
2050         const struct file *file = ptr;
2051         struct proc_inode *ei;
2052         struct inode *inode;
2053
2054         if (!file)
2055                 return ERR_PTR(-ENOENT);
2056
2057         inode = proc_pid_make_inode(dir->i_sb, task);
2058         if (!inode)
2059                 return ERR_PTR(-ENOENT);
2060
2061         ei = PROC_I(inode);
2062         ei->op.proc_get_link = proc_map_files_get_link;
2063
2064         inode->i_op = &proc_pid_link_inode_operations;
2065         inode->i_size = 64;
2066         inode->i_mode = S_IFLNK;
2067
2068         if (file->f_mode & FMODE_READ)
2069                 inode->i_mode |= S_IRUSR;
2070         if (file->f_mode & FMODE_WRITE)
2071                 inode->i_mode |= S_IWUSR;
2072
2073         d_set_d_op(dentry, &tid_map_files_dentry_operations);
2074         d_add(dentry, inode);
2075
2076         return NULL;
2077 }
2078
2079 static struct dentry *proc_map_files_lookup(struct inode *dir,
2080                 struct dentry *dentry, unsigned int flags)
2081 {
2082         unsigned long vm_start, vm_end;
2083         struct vm_area_struct *vma;
2084         struct task_struct *task;
2085         struct dentry *result;
2086         struct mm_struct *mm;
2087
2088         result = ERR_PTR(-EACCES);
2089         if (!capable(CAP_SYS_ADMIN))
2090                 goto out;
2091
2092         result = ERR_PTR(-ENOENT);
2093         task = get_proc_task(dir);
2094         if (!task)
2095                 goto out;
2096
2097         result = ERR_PTR(-EACCES);
2098         if (!ptrace_may_access(task, PTRACE_MODE_READ))
2099                 goto out_put_task;
2100
2101         result = ERR_PTR(-ENOENT);
2102         if (dname_to_vma_addr(dentry, &vm_start, &vm_end))
2103                 goto out_put_task;
2104
2105         mm = get_task_mm(task);
2106         if (!mm)
2107                 goto out_put_task;
2108
2109         down_read(&mm->mmap_sem);
2110         vma = find_exact_vma(mm, vm_start, vm_end);
2111         if (!vma)
2112                 goto out_no_vma;
2113
2114         result = proc_map_files_instantiate(dir, dentry, task, vma->vm_file);
2115
2116 out_no_vma:
2117         up_read(&mm->mmap_sem);
2118         mmput(mm);
2119 out_put_task:
2120         put_task_struct(task);
2121 out:
2122         return result;
2123 }
2124
2125 static const struct inode_operations proc_map_files_inode_operations = {
2126         .lookup         = proc_map_files_lookup,
2127         .permission     = proc_fd_permission,
2128         .setattr        = proc_setattr,
2129 };
2130
2131 static int
2132 proc_map_files_readdir(struct file *filp, void *dirent, filldir_t filldir)
2133 {
2134         struct dentry *dentry = filp->f_path.dentry;
2135         struct inode *inode = dentry->d_inode;
2136         struct vm_area_struct *vma;
2137         struct task_struct *task;
2138         struct mm_struct *mm;
2139         ino_t ino;
2140         int ret;
2141
2142         ret = -EACCES;
2143         if (!capable(CAP_SYS_ADMIN))
2144                 goto out;
2145
2146         ret = -ENOENT;
2147         task = get_proc_task(inode);
2148         if (!task)
2149                 goto out;
2150
2151         ret = -EACCES;
2152         if (!ptrace_may_access(task, PTRACE_MODE_READ))
2153                 goto out_put_task;
2154
2155         ret = 0;
2156         switch (filp->f_pos) {
2157         case 0:
2158                 ino = inode->i_ino;
2159                 if (filldir(dirent, ".", 1, 0, ino, DT_DIR) < 0)
2160                         goto out_put_task;
2161                 filp->f_pos++;
2162         case 1:
2163                 ino = parent_ino(dentry);
2164                 if (filldir(dirent, "..", 2, 1, ino, DT_DIR) < 0)
2165                         goto out_put_task;
2166                 filp->f_pos++;
2167         default:
2168         {
2169                 unsigned long nr_files, pos, i;
2170                 struct flex_array *fa = NULL;
2171                 struct map_files_info info;
2172                 struct map_files_info *p;
2173
2174                 mm = get_task_mm(task);
2175                 if (!mm)
2176                         goto out_put_task;
2177                 down_read(&mm->mmap_sem);
2178
2179                 nr_files = 0;
2180
2181                 /*
2182                  * We need two passes here:
2183                  *
2184                  *  1) Collect vmas of mapped files with mmap_sem taken
2185                  *  2) Release mmap_sem and instantiate entries
2186                  *
2187                  * otherwise we get lockdep complained, since filldir()
2188                  * routine might require mmap_sem taken in might_fault().
2189                  */
2190
2191                 for (vma = mm->mmap, pos = 2; vma; vma = vma->vm_next) {
2192                         if (vma->vm_file && ++pos > filp->f_pos)
2193                                 nr_files++;
2194                 }
2195
2196                 if (nr_files) {
2197                         fa = flex_array_alloc(sizeof(info), nr_files,
2198                                                 GFP_KERNEL);
2199                         if (!fa || flex_array_prealloc(fa, 0, nr_files,
2200                                                         GFP_KERNEL)) {
2201                                 ret = -ENOMEM;
2202                                 if (fa)
2203                                         flex_array_free(fa);
2204                                 up_read(&mm->mmap_sem);
2205                                 mmput(mm);
2206                                 goto out_put_task;
2207                         }
2208                         for (i = 0, vma = mm->mmap, pos = 2; vma;
2209                                         vma = vma->vm_next) {
2210                                 if (!vma->vm_file)
2211                                         continue;
2212                                 if (++pos <= filp->f_pos)
2213                                         continue;
2214
2215                                 get_file(vma->vm_file);
2216                                 info.file = vma->vm_file;
2217                                 info.len = snprintf(info.name,
2218                                                 sizeof(info.name), "%lx-%lx",
2219                                                 vma->vm_start, vma->vm_end);
2220                                 if (flex_array_put(fa, i++, &info, GFP_KERNEL))
2221                                         BUG();
2222                         }
2223                 }
2224                 up_read(&mm->mmap_sem);
2225
2226                 for (i = 0; i < nr_files; i++) {
2227                         p = flex_array_get(fa, i);
2228                         ret = proc_fill_cache(filp, dirent, filldir,
2229                                               p->name, p->len,
2230                                               proc_map_files_instantiate,
2231                                               task, p->file);
2232                         if (ret)
2233                                 break;
2234                         filp->f_pos++;
2235                         fput(p->file);
2236                 }
2237                 for (; i < nr_files; i++) {
2238                         /*
2239                          * In case of error don't forget
2240                          * to put rest of file refs.
2241                          */
2242                         p = flex_array_get(fa, i);
2243                         fput(p->file);
2244                 }
2245                 if (fa)
2246                         flex_array_free(fa);
2247                 mmput(mm);
2248         }
2249         }
2250
2251 out_put_task:
2252         put_task_struct(task);
2253 out:
2254         return ret;
2255 }
2256
2257 static const struct file_operations proc_map_files_operations = {
2258         .read           = generic_read_dir,
2259         .readdir        = proc_map_files_readdir,
2260         .llseek         = default_llseek,
2261 };
2262
2263 #endif /* CONFIG_CHECKPOINT_RESTORE */
2264
2265 /*
2266  * /proc/pid/fd needs a special permission handler so that a process can still
2267  * access /proc/self/fd after it has executed a setuid().
2268  */
2269 static int proc_fd_permission(struct inode *inode, int mask)
2270 {
2271         int rv = generic_permission(inode, mask);
2272         if (rv == 0)
2273                 return 0;
2274         if (task_pid(current) == proc_pid(inode))
2275                 rv = 0;
2276         return rv;
2277 }
2278
2279 /*
2280  * proc directories can do almost nothing..
2281  */
2282 static const struct inode_operations proc_fd_inode_operations = {
2283         .lookup         = proc_lookupfd,
2284         .permission     = proc_fd_permission,
2285         .setattr        = proc_setattr,
2286 };
2287
2288 static struct dentry *proc_fdinfo_instantiate(struct inode *dir,
2289         struct dentry *dentry, struct task_struct *task, const void *ptr)
2290 {
2291         unsigned fd = (unsigned long)ptr;
2292         struct inode *inode;
2293         struct proc_inode *ei;
2294         struct dentry *error = ERR_PTR(-ENOENT);
2295
2296         inode = proc_pid_make_inode(dir->i_sb, task);
2297         if (!inode)
2298                 goto out;
2299         ei = PROC_I(inode);
2300         ei->fd = fd;
2301         inode->i_mode = S_IFREG | S_IRUSR;
2302         inode->i_fop = &proc_fdinfo_file_operations;
2303         d_set_d_op(dentry, &tid_fd_dentry_operations);
2304         d_add(dentry, inode);
2305         /* Close the race of the process dying before we return the dentry */
2306         if (tid_fd_revalidate(dentry, 0))
2307                 error = NULL;
2308
2309  out:
2310         return error;
2311 }
2312
2313 static struct dentry *proc_lookupfdinfo(struct inode *dir,
2314                                         struct dentry *dentry,
2315                                         unsigned int flags)
2316 {
2317         return proc_lookupfd_common(dir, dentry, proc_fdinfo_instantiate);
2318 }
2319
2320 static int proc_readfdinfo(struct file *filp, void *dirent, filldir_t filldir)
2321 {
2322         return proc_readfd_common(filp, dirent, filldir,
2323                                   proc_fdinfo_instantiate);
2324 }
2325
2326 static const struct file_operations proc_fdinfo_operations = {
2327         .read           = generic_read_dir,
2328         .readdir        = proc_readfdinfo,
2329         .llseek         = default_llseek,
2330 };
2331
2332 /*
2333  * proc directories can do almost nothing..
2334  */
2335 static const struct inode_operations proc_fdinfo_inode_operations = {
2336         .lookup         = proc_lookupfdinfo,
2337         .setattr        = proc_setattr,
2338 };
2339
2340
2341 static struct dentry *proc_pident_instantiate(struct inode *dir,
2342         struct dentry *dentry, struct task_struct *task, const void *ptr)
2343 {
2344         const struct pid_entry *p = ptr;
2345         struct inode *inode;
2346         struct proc_inode *ei;
2347         struct dentry *error = ERR_PTR(-ENOENT);
2348
2349         inode = proc_pid_make_inode(dir->i_sb, task);
2350         if (!inode)
2351                 goto out;
2352
2353         ei = PROC_I(inode);
2354         inode->i_mode = p->mode;
2355         if (S_ISDIR(inode->i_mode))
2356                 set_nlink(inode, 2);    /* Use getattr to fix if necessary */
2357         if (p->iop)
2358                 inode->i_op = p->iop;
2359         if (p->fop)
2360                 inode->i_fop = p->fop;
2361         ei->op = p->op;
2362         d_set_d_op(dentry, &pid_dentry_operations);
2363         d_add(dentry, inode);
2364         /* Close the race of the process dying before we return the dentry */
2365         if (pid_revalidate(dentry, 0))
2366                 error = NULL;
2367 out:
2368         return error;
2369 }
2370
2371 static struct dentry *proc_pident_lookup(struct inode *dir, 
2372                                          struct dentry *dentry,
2373                                          const struct pid_entry *ents,
2374                                          unsigned int nents)
2375 {
2376         struct dentry *error;
2377         struct task_struct *task = get_proc_task(dir);
2378         const struct pid_entry *p, *last;
2379
2380         error = ERR_PTR(-ENOENT);
2381
2382         if (!task)
2383                 goto out_no_task;
2384
2385         /*
2386          * Yes, it does not scale. And it should not. Don't add
2387          * new entries into /proc/<tgid>/ without very good reasons.
2388          */
2389         last = &ents[nents - 1];
2390         for (p = ents; p <= last; p++) {
2391                 if (p->len != dentry->d_name.len)
2392                         continue;
2393                 if (!memcmp(dentry->d_name.name, p->name, p->len))
2394                         break;
2395         }
2396         if (p > last)
2397                 goto out;
2398
2399         error = proc_pident_instantiate(dir, dentry, task, p);
2400 out:
2401         put_task_struct(task);
2402 out_no_task:
2403         return error;
2404 }
2405
2406 static int proc_pident_fill_cache(struct file *filp, void *dirent,
2407         filldir_t filldir, struct task_struct *task, const struct pid_entry *p)
2408 {
2409         return proc_fill_cache(filp, dirent, filldir, p->name, p->len,
2410                                 proc_pident_instantiate, task, p);
2411 }
2412
2413 static int proc_pident_readdir(struct file *filp,
2414                 void *dirent, filldir_t filldir,
2415                 const struct pid_entry *ents, unsigned int nents)
2416 {
2417         int i;
2418         struct dentry *dentry = filp->f_path.dentry;
2419         struct inode *inode = dentry->d_inode;
2420         struct task_struct *task = get_proc_task(inode);
2421         const struct pid_entry *p, *last;
2422         ino_t ino;
2423         int ret;
2424
2425         ret = -ENOENT;
2426         if (!task)
2427                 goto out_no_task;
2428
2429         ret = 0;
2430         i = filp->f_pos;
2431         switch (i) {
2432         case 0:
2433                 ino = inode->i_ino;
2434                 if (filldir(dirent, ".", 1, i, ino, DT_DIR) < 0)
2435                         goto out;
2436                 i++;
2437                 filp->f_pos++;
2438                 /* fall through */
2439         case 1:
2440                 ino = parent_ino(dentry);
2441                 if (filldir(dirent, "..", 2, i, ino, DT_DIR) < 0)
2442                         goto out;
2443                 i++;
2444                 filp->f_pos++;
2445                 /* fall through */
2446         default:
2447                 i -= 2;
2448                 if (i >= nents) {
2449                         ret = 1;
2450                         goto out;
2451                 }
2452                 p = ents + i;
2453                 last = &ents[nents - 1];
2454                 while (p <= last) {
2455                         if (proc_pident_fill_cache(filp, dirent, filldir, task, p) < 0)
2456                                 goto out;
2457                         filp->f_pos++;
2458                         p++;
2459                 }
2460         }
2461
2462         ret = 1;
2463 out:
2464         put_task_struct(task);
2465 out_no_task:
2466         return ret;
2467 }
2468
2469 #ifdef CONFIG_SECURITY
2470 static ssize_t proc_pid_attr_read(struct file * file, char __user * buf,
2471                                   size_t count, loff_t *ppos)
2472 {
2473         struct inode * inode = file->f_path.dentry->d_inode;
2474         char *p = NULL;
2475         ssize_t length;
2476         struct task_struct *task = get_proc_task(inode);
2477
2478         if (!task)
2479                 return -ESRCH;
2480
2481         length = security_getprocattr(task,
2482                                       (char*)file->f_path.dentry->d_name.name,
2483                                       &p);
2484         put_task_struct(task);
2485         if (length > 0)
2486                 length = simple_read_from_buffer(buf, count, ppos, p, length);
2487         kfree(p);
2488         return length;
2489 }
2490
2491 static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
2492                                    size_t count, loff_t *ppos)
2493 {
2494         struct inode * inode = file->f_path.dentry->d_inode;
2495         char *page;
2496         ssize_t length;
2497         struct task_struct *task = get_proc_task(inode);
2498
2499         length = -ESRCH;
2500         if (!task)
2501                 goto out_no_task;
2502         if (count > PAGE_SIZE)
2503                 count = PAGE_SIZE;
2504
2505         /* No partial writes. */
2506         length = -EINVAL;
2507         if (*ppos != 0)
2508                 goto out;
2509
2510         length = -ENOMEM;
2511         page = (char*)__get_free_page(GFP_TEMPORARY);
2512         if (!page)
2513                 goto out;
2514
2515         length = -EFAULT;
2516         if (copy_from_user(page, buf, count))
2517                 goto out_free;
2518
2519         /* Guard against adverse ptrace interaction */
2520         length = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
2521         if (length < 0)
2522                 goto out_free;
2523
2524         length = security_setprocattr(task,
2525                                       (char*)file->f_path.dentry->d_name.name,
2526                                       (void*)page, count);
2527         mutex_unlock(&task->signal->cred_guard_mutex);
2528 out_free:
2529         free_page((unsigned long) page);
2530 out:
2531         put_task_struct(task);
2532 out_no_task:
2533         return length;
2534 }
2535
2536 static const struct file_operations proc_pid_attr_operations = {
2537         .read           = proc_pid_attr_read,
2538         .write          = proc_pid_attr_write,
2539         .llseek         = generic_file_llseek,
2540 };
2541
2542 static const struct pid_entry attr_dir_stuff[] = {
2543         REG("current",    S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2544         REG("prev",       S_IRUGO,         proc_pid_attr_operations),
2545         REG("exec",       S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2546         REG("fscreate",   S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2547         REG("keycreate",  S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2548         REG("sockcreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2549 };
2550
2551 static int proc_attr_dir_readdir(struct file * filp,
2552                              void * dirent, filldir_t filldir)
2553 {
2554         return proc_pident_readdir(filp,dirent,filldir,
2555                                    attr_dir_stuff,ARRAY_SIZE(attr_dir_stuff));
2556 }
2557
2558 static const struct file_operations proc_attr_dir_operations = {
2559         .read           = generic_read_dir,
2560         .readdir        = proc_attr_dir_readdir,
2561         .llseek         = default_llseek,
2562 };
2563
2564 static struct dentry *proc_attr_dir_lookup(struct inode *dir,
2565                                 struct dentry *dentry, unsigned int flags)
2566 {
2567         return proc_pident_lookup(dir, dentry,
2568                                   attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
2569 }
2570
2571 static const struct inode_operations proc_attr_dir_inode_operations = {
2572         .lookup         = proc_attr_dir_lookup,
2573         .getattr        = pid_getattr,
2574         .setattr        = proc_setattr,
2575 };
2576
2577 #endif
2578
2579 #ifdef CONFIG_ELF_CORE
2580 static ssize_t proc_coredump_filter_read(struct file *file, char __user *buf,
2581                                          size_t count, loff_t *ppos)
2582 {
2583         struct task_struct *task = get_proc_task(file->f_dentry->d_inode);
2584         struct mm_struct *mm;
2585         char buffer[PROC_NUMBUF];
2586         size_t len;
2587         int ret;
2588
2589         if (!task)
2590                 return -ESRCH;
2591
2592         ret = 0;
2593         mm = get_task_mm(task);
2594         if (mm) {
2595                 len = snprintf(buffer, sizeof(buffer), "%08lx\n",
2596                                ((mm->flags & MMF_DUMP_FILTER_MASK) >>
2597                                 MMF_DUMP_FILTER_SHIFT));
2598                 mmput(mm);
2599                 ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
2600         }
2601
2602         put_task_struct(task);
2603
2604         return ret;
2605 }
2606
2607 static ssize_t proc_coredump_filter_write(struct file *file,
2608                                           const char __user *buf,
2609                                           size_t count,
2610                                           loff_t *ppos)
2611 {
2612         struct task_struct *task;
2613         struct mm_struct *mm;
2614         char buffer[PROC_NUMBUF], *end;
2615         unsigned int val;
2616         int ret;
2617         int i;
2618         unsigned long mask;
2619
2620         ret = -EFAULT;
2621         memset(buffer, 0, sizeof(buffer));
2622         if (count > sizeof(buffer) - 1)
2623                 count = sizeof(buffer) - 1;
2624         if (copy_from_user(buffer, buf, count))
2625                 goto out_no_task;
2626
2627         ret = -EINVAL;
2628         val = (unsigned int)simple_strtoul(buffer, &end, 0);
2629         if (*end == '\n')
2630                 end++;
2631         if (end - buffer == 0)
2632                 goto out_no_task;
2633
2634         ret = -ESRCH;
2635         task = get_proc_task(file->f_dentry->d_inode);
2636         if (!task)
2637                 goto out_no_task;
2638
2639         ret = end - buffer;
2640         mm = get_task_mm(task);
2641         if (!mm)
2642                 goto out_no_mm;
2643
2644         for (i = 0, mask = 1; i < MMF_DUMP_FILTER_BITS; i++, mask <<= 1) {
2645                 if (val & mask)
2646                         set_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2647                 else
2648                         clear_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2649         }
2650
2651         mmput(mm);
2652  out_no_mm:
2653         put_task_struct(task);
2654  out_no_task:
2655         return ret;
2656 }
2657
2658 static const struct file_operations proc_coredump_filter_operations = {
2659         .read           = proc_coredump_filter_read,
2660         .write          = proc_coredump_filter_write,
2661         .llseek         = generic_file_llseek,
2662 };
2663 #endif
2664
2665 /*
2666  * /proc/self:
2667  */
2668 static int proc_self_readlink(struct dentry *dentry, char __user *buffer,
2669                               int buflen)
2670 {
2671         struct pid_namespace *ns = dentry->d_sb->s_fs_info;
2672         pid_t tgid = task_tgid_nr_ns(current, ns);
2673         char tmp[PROC_NUMBUF];
2674         if (!tgid)
2675                 return -ENOENT;
2676         sprintf(tmp, "%d", tgid);
2677         return vfs_readlink(dentry,buffer,buflen,tmp);
2678 }
2679
2680 static void *proc_self_follow_link(struct dentry *dentry, struct nameidata *nd)
2681 {
2682         struct pid_namespace *ns = dentry->d_sb->s_fs_info;
2683         pid_t tgid = task_tgid_nr_ns(current, ns);
2684         char *name = ERR_PTR(-ENOENT);
2685         if (tgid) {
2686                 name = __getname();
2687                 if (!name)
2688                         name = ERR_PTR(-ENOMEM);
2689                 else
2690                         sprintf(name, "%d", tgid);
2691         }
2692         nd_set_link(nd, name);
2693         return NULL;
2694 }
2695
2696 static void proc_self_put_link(struct dentry *dentry, struct nameidata *nd,
2697                                 void *cookie)
2698 {
2699         char *s = nd_get_link(nd);
2700         if (!IS_ERR(s))
2701                 __putname(s);
2702 }
2703
2704 static const struct inode_operations proc_self_inode_operations = {
2705         .readlink       = proc_self_readlink,
2706         .follow_link    = proc_self_follow_link,
2707         .put_link       = proc_self_put_link,
2708 };
2709
2710 /*
2711  * proc base
2712  *
2713  * These are the directory entries in the root directory of /proc
2714  * that properly belong to the /proc filesystem, as they describe
2715  * describe something that is process related.
2716  */
2717 static const struct pid_entry proc_base_stuff[] = {
2718         NOD("self", S_IFLNK|S_IRWXUGO,
2719                 &proc_self_inode_operations, NULL, {}),
2720 };
2721
2722 static struct dentry *proc_base_instantiate(struct inode *dir,
2723         struct dentry *dentry, struct task_struct *task, const void *ptr)
2724 {
2725         const struct pid_entry *p = ptr;
2726         struct inode *inode;
2727         struct proc_inode *ei;
2728         struct dentry *error;
2729
2730         /* Allocate the inode */
2731         error = ERR_PTR(-ENOMEM);
2732         inode = new_inode(dir->i_sb);
2733         if (!inode)
2734                 goto out;
2735
2736         /* Initialize the inode */
2737         ei = PROC_I(inode);
2738         inode->i_ino = get_next_ino();
2739         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
2740
2741         /*
2742          * grab the reference to the task.
2743          */
2744         ei->pid = get_task_pid(task, PIDTYPE_PID);
2745         if (!ei->pid)
2746                 goto out_iput;
2747
2748         inode->i_mode = p->mode;
2749         if (S_ISDIR(inode->i_mode))
2750                 set_nlink(inode, 2);
2751         if (S_ISLNK(inode->i_mode))
2752                 inode->i_size = 64;
2753         if (p->iop)
2754                 inode->i_op = p->iop;
2755         if (p->fop)
2756                 inode->i_fop = p->fop;
2757         ei->op = p->op;
2758         d_add(dentry, inode);
2759         error = NULL;
2760 out:
2761         return error;
2762 out_iput:
2763         iput(inode);
2764         goto out;
2765 }
2766
2767 static struct dentry *proc_base_lookup(struct inode *dir, struct dentry *dentry)
2768 {
2769         struct dentry *error;
2770         struct task_struct *task = get_proc_task(dir);
2771         const struct pid_entry *p, *last;
2772
2773         error = ERR_PTR(-ENOENT);
2774
2775         if (!task)
2776                 goto out_no_task;
2777
2778         /* Lookup the directory entry */
2779         last = &proc_base_stuff[ARRAY_SIZE(proc_base_stuff) - 1];
2780         for (p = proc_base_stuff; p <= last; p++) {
2781                 if (p->len != dentry->d_name.len)
2782                         continue;
2783                 if (!memcmp(dentry->d_name.name, p->name, p->len))
2784                         break;
2785         }
2786         if (p > last)
2787                 goto out;
2788
2789         error = proc_base_instantiate(dir, dentry, task, p);
2790
2791 out:
2792         put_task_struct(task);
2793 out_no_task:
2794         return error;
2795 }
2796
2797 static int proc_base_fill_cache(struct file *filp, void *dirent,
2798         filldir_t filldir, struct task_struct *task, const struct pid_entry *p)
2799 {
2800         return proc_fill_cache(filp, dirent, filldir, p->name, p->len,
2801                                 proc_base_instantiate, task, p);
2802 }
2803
2804 #ifdef CONFIG_TASK_IO_ACCOUNTING
2805 static int do_io_accounting(struct task_struct *task, char *buffer, int whole)
2806 {
2807         struct task_io_accounting acct = task->ioac;
2808         unsigned long flags;
2809         int result;
2810
2811         result = mutex_lock_killable(&task->signal->cred_guard_mutex);
2812         if (result)
2813                 return result;
2814
2815         if (!ptrace_may_access(task, PTRACE_MODE_READ)) {
2816                 result = -EACCES;
2817                 goto out_unlock;
2818         }
2819
2820         if (whole && lock_task_sighand(task, &flags)) {
2821                 struct task_struct *t = task;
2822
2823                 task_io_accounting_add(&acct, &task->signal->ioac);
2824                 while_each_thread(task, t)
2825                         task_io_accounting_add(&acct, &t->ioac);
2826
2827                 unlock_task_sighand(task, &flags);
2828         }
2829         result = sprintf(buffer,
2830                         "rchar: %llu\n"
2831                         "wchar: %llu\n"
2832                         "syscr: %llu\n"
2833                         "syscw: %llu\n"
2834                         "read_bytes: %llu\n"
2835                         "write_bytes: %llu\n"
2836                         "cancelled_write_bytes: %llu\n",
2837                         (unsigned long long)acct.rchar,
2838                         (unsigned long long)acct.wchar,
2839                         (unsigned long long)acct.syscr,
2840                         (unsigned long long)acct.syscw,
2841                         (unsigned long long)acct.read_bytes,
2842                         (unsigned long long)acct.write_bytes,
2843                         (unsigned long long)acct.cancelled_write_bytes);
2844 out_unlock:
2845         mutex_unlock(&task->signal->cred_guard_mutex);
2846         return result;
2847 }
2848
2849 static int proc_tid_io_accounting(struct task_struct *task, char *buffer)
2850 {
2851         return do_io_accounting(task, buffer, 0);
2852 }
2853
2854 static int proc_tgid_io_accounting(struct task_struct *task, char *buffer)
2855 {
2856         return do_io_accounting(task, buffer, 1);
2857 }
2858 #endif /* CONFIG_TASK_IO_ACCOUNTING */
2859
2860 #ifdef CONFIG_USER_NS
2861 static int proc_id_map_open(struct inode *inode, struct file *file,
2862         struct seq_operations *seq_ops)
2863 {
2864         struct user_namespace *ns = NULL;
2865         struct task_struct *task;
2866         struct seq_file *seq;
2867         int ret = -EINVAL;
2868
2869         task = get_proc_task(inode);
2870         if (task) {
2871                 rcu_read_lock();
2872                 ns = get_user_ns(task_cred_xxx(task, user_ns));
2873                 rcu_read_unlock();
2874                 put_task_struct(task);
2875         }
2876         if (!ns)
2877                 goto err;
2878
2879         ret = seq_open(file, seq_ops);
2880         if (ret)
2881                 goto err_put_ns;
2882
2883         seq = file->private_data;
2884         seq->private = ns;
2885
2886         return 0;
2887 err_put_ns:
2888         put_user_ns(ns);
2889 err:
2890         return ret;
2891 }
2892
2893 static int proc_id_map_release(struct inode *inode, struct file *file)
2894 {
2895         struct seq_file *seq = file->private_data;
2896         struct user_namespace *ns = seq->private;
2897         put_user_ns(ns);
2898         return seq_release(inode, file);
2899 }
2900
2901 static int proc_uid_map_open(struct inode *inode, struct file *file)
2902 {
2903         return proc_id_map_open(inode, file, &proc_uid_seq_operations);
2904 }
2905
2906 static int proc_gid_map_open(struct inode *inode, struct file *file)
2907 {
2908         return proc_id_map_open(inode, file, &proc_gid_seq_operations);
2909 }
2910
2911 static const struct file_operations proc_uid_map_operations = {
2912         .open           = proc_uid_map_open,
2913         .write          = proc_uid_map_write,
2914         .read           = seq_read,
2915         .llseek         = seq_lseek,
2916         .release        = proc_id_map_release,
2917 };
2918
2919 static const struct file_operations proc_gid_map_operations = {
2920         .open           = proc_gid_map_open,
2921         .write          = proc_gid_map_write,
2922         .read           = seq_read,
2923         .llseek         = seq_lseek,
2924         .release        = proc_id_map_release,
2925 };
2926 #endif /* CONFIG_USER_NS */
2927
2928 static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
2929                                 struct pid *pid, struct task_struct *task)
2930 {
2931         int err = lock_trace(task);
2932         if (!err) {
2933                 seq_printf(m, "%08x\n", task->personality);
2934                 unlock_trace(task);
2935         }
2936         return err;
2937 }
2938
2939 /*
2940  * Thread groups
2941  */
2942 static const struct file_operations proc_task_operations;
2943 static const struct inode_operations proc_task_inode_operations;
2944
2945 static const struct pid_entry tgid_base_stuff[] = {
2946         DIR("task",       S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
2947         DIR("fd",         S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
2948 #ifdef CONFIG_CHECKPOINT_RESTORE
2949         DIR("map_files",  S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
2950 #endif
2951         DIR("fdinfo",     S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
2952         DIR("ns",         S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
2953 #ifdef CONFIG_NET
2954         DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
2955 #endif
2956         REG("environ",    S_IRUSR, proc_environ_operations),
2957         INF("auxv",       S_IRUSR, proc_pid_auxv),
2958         ONE("status",     S_IRUGO, proc_pid_status),
2959         ONE("personality", S_IRUGO, proc_pid_personality),
2960         INF("limits",     S_IRUGO, proc_pid_limits),
2961 #ifdef CONFIG_SCHED_DEBUG
2962         REG("sched",      S_IRUGO|S_IWUSR, proc_pid_sched_operations),
2963 #endif
2964         REG("comm",      S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
2965 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
2966         INF("syscall",    S_IRUGO, proc_pid_syscall),
2967 #endif
2968         INF("cmdline",    S_IRUGO, proc_pid_cmdline),
2969         ONE("stat",       S_IRUGO, proc_tgid_stat),
2970         ONE("statm",      S_IRUGO, proc_pid_statm),
2971         REG("maps",       S_IRUGO, proc_pid_maps_operations),
2972 #ifdef CONFIG_NUMA
2973         REG("numa_maps",  S_IRUGO, proc_pid_numa_maps_operations),
2974 #endif
2975         REG("mem",        S_IRUSR|S_IWUSR, proc_mem_operations),
2976         LNK("cwd",        proc_cwd_link),
2977         LNK("root",       proc_root_link),
2978         LNK("exe",        proc_exe_link),
2979         REG("mounts",     S_IRUGO, proc_mounts_operations),
2980         REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
2981         REG("mountstats", S_IRUSR, proc_mountstats_operations),
2982 #ifdef CONFIG_PROC_PAGE_MONITOR
2983         REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
2984         REG("smaps",      S_IRUGO, proc_pid_smaps_operations),
2985         REG("pagemap",    S_IRUGO, proc_pagemap_operations),
2986 #endif
2987 #ifdef CONFIG_SECURITY
2988         DIR("attr",       S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
2989 #endif
2990 #ifdef CONFIG_KALLSYMS
2991         INF("wchan",      S_IRUGO, proc_pid_wchan),
2992 #endif
2993 #ifdef CONFIG_STACKTRACE
2994         ONE("stack",      S_IRUGO, proc_pid_stack),
2995 #endif
2996 #ifdef CONFIG_SCHEDSTATS
2997         INF("schedstat",  S_IRUGO, proc_pid_schedstat),
2998 #endif
2999 #ifdef CONFIG_LATENCYTOP
3000         REG("latency",  S_IRUGO, proc_lstats_operations),
3001 #endif
3002 #ifdef CONFIG_PROC_PID_CPUSET
3003         REG("cpuset",     S_IRUGO, proc_cpuset_operations),
3004 #endif
3005 #ifdef CONFIG_CGROUPS
3006         REG("cgroup",  S_IRUGO, proc_cgroup_operations),
3007 #endif
3008         INF("oom_score",  S_IRUGO, proc_oom_score),
3009         REG("oom_adj",    S_IRUGO|S_IWUSR, proc_oom_adjust_operations),
3010         REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3011 #ifdef CONFIG_AUDITSYSCALL
3012         REG("loginuid",   S_IWUSR|S_IRUGO, proc_loginuid_operations),
3013         REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3014 #endif
3015 #ifdef CONFIG_FAULT_INJECTION
3016         REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3017 #endif
3018 #ifdef CONFIG_ELF_CORE
3019         REG("coredump_filter", S_IRUGO|S_IWUSR, proc_coredump_filter_operations),
3020 #endif
3021 #ifdef CONFIG_TASK_IO_ACCOUNTING
3022         INF("io",       S_IRUSR, proc_tgid_io_accounting),
3023 #endif
3024 #ifdef CONFIG_HARDWALL
3025         INF("hardwall",   S_IRUGO, proc_pid_hardwall),
3026 #endif
3027 #ifdef CONFIG_USER_NS
3028         REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3029         REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3030 #endif
3031 };
3032
3033 static int proc_tgid_base_readdir(struct file * filp,
3034                              void * dirent, filldir_t filldir)
3035 {
3036         return proc_pident_readdir(filp,dirent,filldir,
3037                                    tgid_base_stuff,ARRAY_SIZE(tgid_base_stuff));
3038 }
3039
3040 static const struct file_operations proc_tgid_base_operations = {
3041         .read           = generic_read_dir,
3042         .readdir        = proc_tgid_base_readdir,
3043         .llseek         = default_llseek,
3044 };
3045
3046 static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3047 {
3048         return proc_pident_lookup(dir, dentry,
3049                                   tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3050 }
3051
3052 static const struct inode_operations proc_tgid_base_inode_operations = {
3053         .lookup         = proc_tgid_base_lookup,
3054         .getattr        = pid_getattr,
3055         .setattr        = proc_setattr,
3056         .permission     = proc_pid_permission,
3057 };
3058
3059 static void proc_flush_task_mnt(struct vfsmount *mnt, pid_t pid, pid_t tgid)
3060 {
3061         struct dentry *dentry, *leader, *dir;
3062         char buf[PROC_NUMBUF];
3063         struct qstr name;
3064
3065         name.name = buf;
3066         name.len = snprintf(buf, sizeof(buf), "%d", pid);
3067         dentry = d_hash_and_lookup(mnt->mnt_root, &name);
3068         if (dentry) {
3069                 shrink_dcache_parent(dentry);
3070                 d_drop(dentry);
3071                 dput(dentry);
3072         }
3073
3074         name.name = buf;
3075         name.len = snprintf(buf, sizeof(buf), "%d", tgid);
3076         leader = d_hash_and_lookup(mnt->mnt_root, &name);
3077         if (!leader)
3078                 goto out;
3079
3080         name.name = "task";
3081         name.len = strlen(name.name);
3082         dir = d_hash_and_lookup(leader, &name);
3083         if (!dir)
3084                 goto out_put_leader;
3085
3086         name.name = buf;
3087         name.len = snprintf(buf, sizeof(buf), "%d", pid);
3088         dentry = d_hash_and_lookup(dir, &name);
3089         if (dentry) {
3090                 shrink_dcache_parent(dentry);
3091                 d_drop(dentry);
3092                 dput(dentry);
3093         }
3094
3095         dput(dir);
3096 out_put_leader:
3097         dput(leader);
3098 out:
3099         return;
3100 }
3101
3102 /**
3103  * proc_flush_task -  Remove dcache entries for @task from the /proc dcache.
3104  * @task: task that should be flushed.
3105  *
3106  * When flushing dentries from proc, one needs to flush them from global
3107  * proc (proc_mnt) and from all the namespaces' procs this task was seen
3108  * in. This call is supposed to do all of this job.
3109  *
3110  * Looks in the dcache for
3111  * /proc/@pid
3112  * /proc/@tgid/task/@pid
3113  * if either directory is present flushes it and all of it'ts children
3114  * from the dcache.
3115  *
3116  * It is safe and reasonable to cache /proc entries for a task until
3117  * that task exits.  After that they just clog up the dcache with
3118  * useless entries, possibly causing useful dcache entries to be
3119  * flushed instead.  This routine is proved to flush those useless
3120  * dcache entries at process exit time.
3121  *
3122  * NOTE: This routine is just an optimization so it does not guarantee
3123  *       that no dcache entries will exist at process exit time it
3124  *       just makes it very unlikely that any will persist.
3125  */
3126
3127 void proc_flush_task(struct task_struct *task)
3128 {
3129         int i;
3130         struct pid *pid, *tgid;
3131         struct upid *upid;
3132
3133         pid = task_pid(task);
3134         tgid = task_tgid(task);
3135
3136         for (i = 0; i <= pid->level; i++) {
3137                 upid = &pid->numbers[i];
3138                 proc_flush_task_mnt(upid->ns->proc_mnt, upid->nr,
3139                                         tgid->numbers[i].nr);
3140         }
3141
3142         upid = &pid->numbers[pid->level];
3143         if (upid->nr == 1)
3144                 pid_ns_release_proc(upid->ns);
3145 }
3146
3147 static struct dentry *proc_pid_instantiate(struct inode *dir,
3148                                            struct dentry * dentry,
3149                                            struct task_struct *task, const void *ptr)
3150 {
3151         struct dentry *error = ERR_PTR(-ENOENT);
3152         struct inode *inode;
3153
3154         inode = proc_pid_make_inode(dir->i_sb, task);
3155         if (!inode)
3156                 goto out;
3157
3158         inode->i_mode = S_IFDIR|S_IRUGO|S_IXUGO;
3159         inode->i_op = &proc_tgid_base_inode_operations;
3160         inode->i_fop = &proc_tgid_base_operations;
3161         inode->i_flags|=S_IMMUTABLE;
3162
3163         set_nlink(inode, 2 + pid_entry_count_dirs(tgid_base_stuff,
3164                                                   ARRAY_SIZE(tgid_base_stuff)));
3165
3166         d_set_d_op(dentry, &pid_dentry_operations);
3167
3168         d_add(dentry, inode);
3169         /* Close the race of the process dying before we return the dentry */
3170         if (pid_revalidate(dentry, 0))
3171                 error = NULL;
3172 out:
3173         return error;
3174 }
3175
3176 struct dentry *proc_pid_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
3177 {
3178         struct dentry *result;
3179         struct task_struct *task;
3180         unsigned tgid;
3181         struct pid_namespace *ns;
3182
3183         result = proc_base_lookup(dir, dentry);
3184         if (!IS_ERR(result) || PTR_ERR(result) != -ENOENT)
3185                 goto out;
3186
3187         tgid = name_to_int(dentry);
3188         if (tgid == ~0U)
3189                 goto out;
3190
3191         ns = dentry->d_sb->s_fs_info;
3192         rcu_read_lock();
3193         task = find_task_by_pid_ns(tgid, ns);
3194         if (task)
3195                 get_task_struct(task);
3196         rcu_read_unlock();
3197         if (!task)
3198                 goto out;
3199
3200         result = proc_pid_instantiate(dir, dentry, task, NULL);
3201         put_task_struct(task);
3202 out:
3203         return result;
3204 }
3205
3206 /*
3207  * Find the first task with tgid >= tgid
3208  *
3209  */
3210 struct tgid_iter {
3211         unsigned int tgid;
3212         struct task_struct *task;
3213 };
3214 static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
3215 {
3216         struct pid *pid;
3217
3218         if (iter.task)
3219                 put_task_struct(iter.task);
3220         rcu_read_lock();
3221 retry:
3222         iter.task = NULL;
3223         pid = find_ge_pid(iter.tgid, ns);
3224         if (pid) {
3225                 iter.tgid = pid_nr_ns(pid, ns);
3226                 iter.task = pid_task(pid, PIDTYPE_PID);
3227                 /* What we to know is if the pid we have find is the
3228                  * pid of a thread_group_leader.  Testing for task
3229                  * being a thread_group_leader is the obvious thing
3230                  * todo but there is a window when it fails, due to
3231                  * the pid transfer logic in de_thread.
3232                  *
3233                  * So we perform the straight forward test of seeing
3234                  * if the pid we have found is the pid of a thread
3235                  * group leader, and don't worry if the task we have
3236                  * found doesn't happen to be a thread group leader.
3237                  * As we don't care in the case of readdir.
3238                  */
3239                 if (!iter.task || !has_group_leader_pid(iter.task)) {
3240                         iter.tgid += 1;
3241                         goto retry;
3242                 }
3243                 get_task_struct(iter.task);
3244         }
3245         rcu_read_unlock();
3246         return iter;
3247 }
3248
3249 #define TGID_OFFSET (FIRST_PROCESS_ENTRY + ARRAY_SIZE(proc_base_stuff))
3250
3251 static int proc_pid_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
3252         struct tgid_iter iter)
3253 {
3254         char name[PROC_NUMBUF];
3255         int len = snprintf(name, sizeof(name), "%d", iter.tgid);
3256         return proc_fill_cache(filp, dirent, filldir, name, len,
3257                                 proc_pid_instantiate, iter.task, NULL);
3258 }
3259
3260 static int fake_filldir(void *buf, const char *name, int namelen,
3261                         loff_t offset, u64 ino, unsigned d_type)
3262 {
3263         return 0;
3264 }
3265
3266 /* for the /proc/ directory itself, after non-process stuff has been done */
3267 int proc_pid_readdir(struct file * filp, void * dirent, filldir_t filldir)
3268 {
3269         unsigned int nr;
3270         struct task_struct *reaper;
3271         struct tgid_iter iter;
3272         struct pid_namespace *ns;
3273         filldir_t __filldir;
3274
3275         if (filp->f_pos >= PID_MAX_LIMIT + TGID_OFFSET)
3276                 goto out_no_task;
3277         nr = filp->f_pos - FIRST_PROCESS_ENTRY;
3278
3279         reaper = get_proc_task(filp->f_path.dentry->d_inode);
3280         if (!reaper)
3281                 goto out_no_task;
3282
3283         for (; nr < ARRAY_SIZE(proc_base_stuff); filp->f_pos++, nr++) {
3284                 const struct pid_entry *p = &proc_base_stuff[nr];
3285                 if (proc_base_fill_cache(filp, dirent, filldir, reaper, p) < 0)
3286                         goto out;
3287         }
3288
3289         ns = filp->f_dentry->d_sb->s_fs_info;
3290         iter.task = NULL;
3291         iter.tgid = filp->f_pos - TGID_OFFSET;
3292         for (iter = next_tgid(ns, iter);
3293              iter.task;
3294              iter.tgid += 1, iter = next_tgid(ns, iter)) {
3295                 if (has_pid_permissions(ns, iter.task, 2))
3296                         __filldir = filldir;
3297                 else
3298                         __filldir = fake_filldir;
3299
3300                 filp->f_pos = iter.tgid + TGID_OFFSET;
3301                 if (proc_pid_fill_cache(filp, dirent, __filldir, iter) < 0) {
3302                         put_task_struct(iter.task);
3303                         goto out;
3304                 }
3305         }
3306         filp->f_pos = PID_MAX_LIMIT + TGID_OFFSET;
3307 out:
3308         put_task_struct(reaper);
3309 out_no_task:
3310         return 0;
3311 }
3312
3313 /*
3314  * Tasks
3315  */
3316 static const struct pid_entry tid_base_stuff[] = {
3317         DIR("fd",        S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
3318         DIR("fdinfo",    S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
3319         DIR("ns",        S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
3320         REG("environ",   S_IRUSR, proc_environ_operations),
3321         INF("auxv",      S_IRUSR, proc_pid_auxv),
3322         ONE("status",    S_IRUGO, proc_pid_status),
3323         ONE("personality", S_IRUGO, proc_pid_personality),
3324         INF("limits",    S_IRUGO, proc_pid_limits),
3325 #ifdef CONFIG_SCHED_DEBUG
3326         REG("sched",     S_IRUGO|S_IWUSR, proc_pid_sched_operations),
3327 #endif
3328         REG("comm",      S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
3329 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
3330         INF("syscall",   S_IRUGO, proc_pid_syscall),
3331 #endif
3332         INF("cmdline",   S_IRUGO, proc_pid_cmdline),
3333         ONE("stat",      S_IRUGO, proc_tid_stat),
3334         ONE("statm",     S_IRUGO, proc_pid_statm),
3335         REG("maps",      S_IRUGO, proc_tid_maps_operations),
3336 #ifdef CONFIG_CHECKPOINT_RESTORE
3337         REG("children",  S_IRUGO, proc_tid_children_operations),
3338 #endif
3339 #ifdef CONFIG_NUMA
3340         REG("numa_maps", S_IRUGO, proc_tid_numa_maps_operations),
3341 #endif
3342         REG("mem",       S_IRUSR|S_IWUSR, proc_mem_operations),
3343         LNK("cwd",       proc_cwd_link),
3344         LNK("root",      proc_root_link),
3345         LNK("exe",       proc_exe_link),
3346         REG("mounts",    S_IRUGO, proc_mounts_operations),
3347         REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
3348 #ifdef CONFIG_PROC_PAGE_MONITOR
3349         REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3350         REG("smaps",     S_IRUGO, proc_tid_smaps_operations),
3351         REG("pagemap",    S_IRUGO, proc_pagemap_operations),
3352 #endif
3353 #ifdef CONFIG_SECURITY
3354         DIR("attr",      S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3355 #endif
3356 #ifdef CONFIG_KALLSYMS
3357         INF("wchan",     S_IRUGO, proc_pid_wchan),
3358 #endif
3359 #ifdef CONFIG_STACKTRACE
3360         ONE("stack",      S_IRUGO, proc_pid_stack),
3361 #endif
3362 #ifdef CONFIG_SCHEDSTATS
3363         INF("schedstat", S_IRUGO, proc_pid_schedstat),
3364 #endif
3365 #ifdef CONFIG_LATENCYTOP
3366         REG("latency",  S_IRUGO, proc_lstats_operations),
3367 #endif
3368 #ifdef CONFIG_PROC_PID_CPUSET
3369         REG("cpuset",    S_IRUGO, proc_cpuset_operations),
3370 #endif
3371 #ifdef CONFIG_CGROUPS
3372         REG("cgroup",  S_IRUGO, proc_cgroup_operations),
3373 #endif
3374         INF("oom_score", S_IRUGO, proc_oom_score),
3375         REG("oom_adj",   S_IRUGO|S_IWUSR, proc_oom_adjust_operations),
3376         REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3377 #ifdef CONFIG_AUDITSYSCALL
3378         REG("loginuid",  S_IWUSR|S_IRUGO, proc_loginuid_operations),
3379         REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3380 #endif
3381 #ifdef CONFIG_FAULT_INJECTION
3382         REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3383 #endif
3384 #ifdef CONFIG_TASK_IO_ACCOUNTING
3385         INF("io",       S_IRUSR, proc_tid_io_accounting),
3386 #endif
3387 #ifdef CONFIG_HARDWALL
3388         INF("hardwall",   S_IRUGO, proc_pid_hardwall),
3389 #endif
3390 #ifdef CONFIG_USER_NS
3391         REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3392         REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3393 #endif
3394 };
3395
3396 static int proc_tid_base_readdir(struct file * filp,
3397                              void * dirent, filldir_t filldir)
3398 {
3399         return proc_pident_readdir(filp,dirent,filldir,
3400                                    tid_base_stuff,ARRAY_SIZE(tid_base_stuff));
3401 }
3402
3403 static struct dentry *proc_tid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3404 {
3405         return proc_pident_lookup(dir, dentry,
3406                                   tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3407 }
3408
3409 static const struct file_operations proc_tid_base_operations = {
3410         .read           = generic_read_dir,
3411         .readdir        = proc_tid_base_readdir,
3412         .llseek         = default_llseek,
3413 };
3414
3415 static const struct inode_operations proc_tid_base_inode_operations = {
3416         .lookup         = proc_tid_base_lookup,
3417         .getattr        = pid_getattr,
3418         .setattr        = proc_setattr,
3419 };
3420
3421 static struct dentry *proc_task_instantiate(struct inode *dir,
3422         struct dentry *dentry, struct task_struct *task, const void *ptr)
3423 {
3424         struct dentry *error = ERR_PTR(-ENOENT);
3425         struct inode *inode;
3426         inode = proc_pid_make_inode(dir->i_sb, task);
3427
3428         if (!inode)
3429                 goto out;
3430         inode->i_mode = S_IFDIR|S_IRUGO|S_IXUGO;
3431         inode->i_op = &proc_tid_base_inode_operations;
3432         inode->i_fop = &proc_tid_base_operations;
3433         inode->i_flags|=S_IMMUTABLE;
3434
3435         set_nlink(inode, 2 + pid_entry_count_dirs(tid_base_stuff,
3436                                                   ARRAY_SIZE(tid_base_stuff)));
3437
3438         d_set_d_op(dentry, &pid_dentry_operations);
3439
3440         d_add(dentry, inode);
3441         /* Close the race of the process dying before we return the dentry */
3442         if (pid_revalidate(dentry, 0))
3443                 error = NULL;
3444 out:
3445         return error;
3446 }
3447
3448 static struct dentry *proc_task_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
3449 {
3450         struct dentry *result = ERR_PTR(-ENOENT);
3451         struct task_struct *task;
3452         struct task_struct *leader = get_proc_task(dir);
3453         unsigned tid;
3454         struct pid_namespace *ns;
3455
3456         if (!leader)
3457                 goto out_no_task;
3458
3459         tid = name_to_int(dentry);
3460         if (tid == ~0U)
3461                 goto out;
3462
3463         ns = dentry->d_sb->s_fs_info;
3464         rcu_read_lock();
3465         task = find_task_by_pid_ns(tid, ns);
3466         if (task)
3467                 get_task_struct(task);
3468         rcu_read_unlock();
3469         if (!task)
3470                 goto out;
3471         if (!same_thread_group(leader, task))
3472                 goto out_drop_task;
3473
3474         result = proc_task_instantiate(dir, dentry, task, NULL);
3475 out_drop_task:
3476         put_task_struct(task);
3477 out:
3478         put_task_struct(leader);
3479 out_no_task:
3480         return result;
3481 }
3482
3483 /*
3484  * Find the first tid of a thread group to return to user space.
3485  *
3486  * Usually this is just the thread group leader, but if the users
3487  * buffer was too small or there was a seek into the middle of the
3488  * directory we have more work todo.
3489  *
3490  * In the case of a short read we start with find_task_by_pid.
3491  *
3492  * In the case of a seek we start with the leader and walk nr
3493  * threads past it.
3494  */
3495 static struct task_struct *first_tid(struct task_struct *leader,
3496                 int tid, int nr, struct pid_namespace *ns)
3497 {
3498         struct task_struct *pos;
3499
3500         rcu_read_lock();
3501         /* Attempt to start with the pid of a thread */
3502         if (tid && (nr > 0)) {
3503                 pos = find_task_by_pid_ns(tid, ns);
3504                 if (pos && (pos->group_leader == leader))
3505                         goto found;
3506         }
3507
3508         /* If nr exceeds the number of threads there is nothing todo */
3509         pos = NULL;
3510         if (nr && nr >= get_nr_threads(leader))
3511                 goto out;
3512
3513         /* If we haven't found our starting place yet start
3514          * with the leader and walk nr threads forward.
3515          */
3516         for (pos = leader; nr > 0; --nr) {
3517                 pos = next_thread(pos);
3518                 if (pos == leader) {
3519                         pos = NULL;
3520                         goto out;
3521                 }
3522         }
3523 found:
3524         get_task_struct(pos);
3525 out:
3526         rcu_read_unlock();
3527         return pos;
3528 }
3529
3530 /*
3531  * Find the next thread in the thread list.
3532  * Return NULL if there is an error or no next thread.
3533  *
3534  * The reference to the input task_struct is released.
3535  */
3536 static struct task_struct *next_tid(struct task_struct *start)
3537 {
3538         struct task_struct *pos = NULL;
3539         rcu_read_lock();
3540         if (pid_alive(start)) {
3541                 pos = next_thread(start);
3542                 if (thread_group_leader(pos))
3543                         pos = NULL;
3544                 else
3545                         get_task_struct(pos);
3546         }
3547         rcu_read_unlock();
3548         put_task_struct(start);
3549         return pos;
3550 }
3551
3552 static int proc_task_fill_cache(struct file *filp, void *dirent, filldir_t filldir,
3553         struct task_struct *task, int tid)
3554 {
3555         char name[PROC_NUMBUF];
3556         int len = snprintf(name, sizeof(name), "%d", tid);
3557         return proc_fill_cache(filp, dirent, filldir, name, len,
3558                                 proc_task_instantiate, task, NULL);
3559 }
3560
3561 /* for the /proc/TGID/task/ directories */
3562 static int proc_task_readdir(struct file * filp, void * dirent, filldir_t filldir)
3563 {
3564         struct dentry *dentry = filp->f_path.dentry;
3565         struct inode *inode = dentry->d_inode;
3566         struct task_struct *leader = NULL;
3567         struct task_struct *task;
3568         int retval = -ENOENT;
3569         ino_t ino;
3570         int tid;
3571         struct pid_namespace *ns;
3572
3573         task = get_proc_task(inode);
3574         if (!task)
3575                 goto out_no_task;
3576         rcu_read_lock();
3577         if (pid_alive(task)) {
3578                 leader = task->group_leader;
3579                 get_task_struct(leader);
3580         }
3581         rcu_read_unlock();
3582         put_task_struct(task);
3583         if (!leader)
3584                 goto out_no_task;
3585         retval = 0;
3586
3587         switch ((unsigned long)filp->f_pos) {
3588         case 0:
3589                 ino = inode->i_ino;
3590                 if (filldir(dirent, ".", 1, filp->f_pos, ino, DT_DIR) < 0)
3591                         goto out;
3592                 filp->f_pos++;
3593                 /* fall through */
3594         case 1:
3595                 ino = parent_ino(dentry);
3596                 if (filldir(dirent, "..", 2, filp->f_pos, ino, DT_DIR) < 0)
3597                         goto out;
3598                 filp->f_pos++;
3599                 /* fall through */
3600         }
3601
3602         /* f_version caches the tgid value that the last readdir call couldn't
3603          * return. lseek aka telldir automagically resets f_version to 0.
3604          */
3605         ns = filp->f_dentry->d_sb->s_fs_info;
3606         tid = (int)filp->f_version;
3607         filp->f_version = 0;
3608         for (task = first_tid(leader, tid, filp->f_pos - 2, ns);
3609              task;
3610              task = next_tid(task), filp->f_pos++) {
3611                 tid = task_pid_nr_ns(task, ns);
3612                 if (proc_task_fill_cache(filp, dirent, filldir, task, tid) < 0) {
3613                         /* returning this tgid failed, save it as the first
3614                          * pid for the next readir call */
3615                         filp->f_version = (u64)tid;
3616                         put_task_struct(task);
3617                         break;
3618                 }
3619         }
3620 out:
3621         put_task_struct(leader);
3622 out_no_task:
3623         return retval;
3624 }
3625
3626 static int proc_task_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
3627 {
3628         struct inode *inode = dentry->d_inode;
3629         struct task_struct *p = get_proc_task(inode);
3630         generic_fillattr(inode, stat);
3631
3632         if (p) {
3633                 stat->nlink += get_nr_threads(p);
3634                 put_task_struct(p);
3635         }
3636
3637         return 0;
3638 }
3639
3640 static const struct inode_operations proc_task_inode_operations = {
3641         .lookup         = proc_task_lookup,
3642         .getattr        = proc_task_getattr,
3643         .setattr        = proc_setattr,
3644         .permission     = proc_pid_permission,
3645 };
3646
3647 static const struct file_operations proc_task_operations = {
3648         .read           = generic_read_dir,
3649         .readdir        = proc_task_readdir,
3650         .llseek         = default_llseek,
3651 };