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