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