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