GNU Linux-libre 4.19.211-gnu1
[releases.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                 size_t this_len = min_t(size_t, 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         struct mm_struct *mm = NULL;
1039         struct task_struct *task;
1040         int err = 0;
1041
1042         task = get_proc_task(file_inode(file));
1043         if (!task)
1044                 return -ESRCH;
1045
1046         mutex_lock(&oom_adj_mutex);
1047         if (legacy) {
1048                 if (oom_adj < task->signal->oom_score_adj &&
1049                                 !capable(CAP_SYS_RESOURCE)) {
1050                         err = -EACCES;
1051                         goto err_unlock;
1052                 }
1053                 /*
1054                  * /proc/pid/oom_adj is provided for legacy purposes, ask users to use
1055                  * /proc/pid/oom_score_adj instead.
1056                  */
1057                 pr_warn_once("%s (%d): /proc/%d/oom_adj is deprecated, please use /proc/%d/oom_score_adj instead.\n",
1058                           current->comm, task_pid_nr(current), task_pid_nr(task),
1059                           task_pid_nr(task));
1060         } else {
1061                 if ((short)oom_adj < task->signal->oom_score_adj_min &&
1062                                 !capable(CAP_SYS_RESOURCE)) {
1063                         err = -EACCES;
1064                         goto err_unlock;
1065                 }
1066         }
1067
1068         /*
1069          * Make sure we will check other processes sharing the mm if this is
1070          * not vfrok which wants its own oom_score_adj.
1071          * pin the mm so it doesn't go away and get reused after task_unlock
1072          */
1073         if (!task->vfork_done) {
1074                 struct task_struct *p = find_lock_task_mm(task);
1075
1076                 if (p) {
1077                         if (test_bit(MMF_MULTIPROCESS, &p->mm->flags)) {
1078                                 mm = p->mm;
1079                                 mmgrab(mm);
1080                         }
1081                         task_unlock(p);
1082                 }
1083         }
1084
1085         task->signal->oom_score_adj = oom_adj;
1086         if (!legacy && has_capability_noaudit(current, CAP_SYS_RESOURCE))
1087                 task->signal->oom_score_adj_min = (short)oom_adj;
1088         trace_oom_score_adj_update(task);
1089
1090         if (mm) {
1091                 struct task_struct *p;
1092
1093                 rcu_read_lock();
1094                 for_each_process(p) {
1095                         if (same_thread_group(task, p))
1096                                 continue;
1097
1098                         /* do not touch kernel threads or the global init */
1099                         if (p->flags & PF_KTHREAD || is_global_init(p))
1100                                 continue;
1101
1102                         task_lock(p);
1103                         if (!p->vfork_done && process_shares_mm(p, mm)) {
1104                                 p->signal->oom_score_adj = oom_adj;
1105                                 if (!legacy && has_capability_noaudit(current, CAP_SYS_RESOURCE))
1106                                         p->signal->oom_score_adj_min = (short)oom_adj;
1107                         }
1108                         task_unlock(p);
1109                 }
1110                 rcu_read_unlock();
1111                 mmdrop(mm);
1112         }
1113 err_unlock:
1114         mutex_unlock(&oom_adj_mutex);
1115         put_task_struct(task);
1116         return err;
1117 }
1118
1119 /*
1120  * /proc/pid/oom_adj exists solely for backwards compatibility with previous
1121  * kernels.  The effective policy is defined by oom_score_adj, which has a
1122  * different scale: oom_adj grew exponentially and oom_score_adj grows linearly.
1123  * Values written to oom_adj are simply mapped linearly to oom_score_adj.
1124  * Processes that become oom disabled via oom_adj will still be oom disabled
1125  * with this implementation.
1126  *
1127  * oom_adj cannot be removed since existing userspace binaries use it.
1128  */
1129 static ssize_t oom_adj_write(struct file *file, const char __user *buf,
1130                              size_t count, loff_t *ppos)
1131 {
1132         char buffer[PROC_NUMBUF];
1133         int oom_adj;
1134         int err;
1135
1136         memset(buffer, 0, sizeof(buffer));
1137         if (count > sizeof(buffer) - 1)
1138                 count = sizeof(buffer) - 1;
1139         if (copy_from_user(buffer, buf, count)) {
1140                 err = -EFAULT;
1141                 goto out;
1142         }
1143
1144         err = kstrtoint(strstrip(buffer), 0, &oom_adj);
1145         if (err)
1146                 goto out;
1147         if ((oom_adj < OOM_ADJUST_MIN || oom_adj > OOM_ADJUST_MAX) &&
1148              oom_adj != OOM_DISABLE) {
1149                 err = -EINVAL;
1150                 goto out;
1151         }
1152
1153         /*
1154          * Scale /proc/pid/oom_score_adj appropriately ensuring that a maximum
1155          * value is always attainable.
1156          */
1157         if (oom_adj == OOM_ADJUST_MAX)
1158                 oom_adj = OOM_SCORE_ADJ_MAX;
1159         else
1160                 oom_adj = (oom_adj * OOM_SCORE_ADJ_MAX) / -OOM_DISABLE;
1161
1162         err = __set_oom_adj(file, oom_adj, true);
1163 out:
1164         return err < 0 ? err : count;
1165 }
1166
1167 static const struct file_operations proc_oom_adj_operations = {
1168         .read           = oom_adj_read,
1169         .write          = oom_adj_write,
1170         .llseek         = generic_file_llseek,
1171 };
1172
1173 static ssize_t oom_score_adj_read(struct file *file, char __user *buf,
1174                                         size_t count, loff_t *ppos)
1175 {
1176         struct task_struct *task = get_proc_task(file_inode(file));
1177         char buffer[PROC_NUMBUF];
1178         short oom_score_adj = OOM_SCORE_ADJ_MIN;
1179         size_t len;
1180
1181         if (!task)
1182                 return -ESRCH;
1183         oom_score_adj = task->signal->oom_score_adj;
1184         put_task_struct(task);
1185         len = snprintf(buffer, sizeof(buffer), "%hd\n", oom_score_adj);
1186         return simple_read_from_buffer(buf, count, ppos, buffer, len);
1187 }
1188
1189 static ssize_t oom_score_adj_write(struct file *file, const char __user *buf,
1190                                         size_t count, loff_t *ppos)
1191 {
1192         char buffer[PROC_NUMBUF];
1193         int oom_score_adj;
1194         int err;
1195
1196         memset(buffer, 0, sizeof(buffer));
1197         if (count > sizeof(buffer) - 1)
1198                 count = sizeof(buffer) - 1;
1199         if (copy_from_user(buffer, buf, count)) {
1200                 err = -EFAULT;
1201                 goto out;
1202         }
1203
1204         err = kstrtoint(strstrip(buffer), 0, &oom_score_adj);
1205         if (err)
1206                 goto out;
1207         if (oom_score_adj < OOM_SCORE_ADJ_MIN ||
1208                         oom_score_adj > OOM_SCORE_ADJ_MAX) {
1209                 err = -EINVAL;
1210                 goto out;
1211         }
1212
1213         err = __set_oom_adj(file, oom_score_adj, false);
1214 out:
1215         return err < 0 ? err : count;
1216 }
1217
1218 static const struct file_operations proc_oom_score_adj_operations = {
1219         .read           = oom_score_adj_read,
1220         .write          = oom_score_adj_write,
1221         .llseek         = default_llseek,
1222 };
1223
1224 #ifdef CONFIG_AUDITSYSCALL
1225 #define TMPBUFLEN 11
1226 static ssize_t proc_loginuid_read(struct file * file, char __user * buf,
1227                                   size_t count, loff_t *ppos)
1228 {
1229         struct inode * inode = file_inode(file);
1230         struct task_struct *task = get_proc_task(inode);
1231         ssize_t length;
1232         char tmpbuf[TMPBUFLEN];
1233
1234         if (!task)
1235                 return -ESRCH;
1236         length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1237                            from_kuid(file->f_cred->user_ns,
1238                                      audit_get_loginuid(task)));
1239         put_task_struct(task);
1240         return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1241 }
1242
1243 static ssize_t proc_loginuid_write(struct file * file, const char __user * buf,
1244                                    size_t count, loff_t *ppos)
1245 {
1246         struct inode * inode = file_inode(file);
1247         uid_t loginuid;
1248         kuid_t kloginuid;
1249         int rv;
1250
1251         rcu_read_lock();
1252         if (current != pid_task(proc_pid(inode), PIDTYPE_PID)) {
1253                 rcu_read_unlock();
1254                 return -EPERM;
1255         }
1256         rcu_read_unlock();
1257
1258         if (*ppos != 0) {
1259                 /* No partial writes. */
1260                 return -EINVAL;
1261         }
1262
1263         rv = kstrtou32_from_user(buf, count, 10, &loginuid);
1264         if (rv < 0)
1265                 return rv;
1266
1267         /* is userspace tring to explicitly UNSET the loginuid? */
1268         if (loginuid == AUDIT_UID_UNSET) {
1269                 kloginuid = INVALID_UID;
1270         } else {
1271                 kloginuid = make_kuid(file->f_cred->user_ns, loginuid);
1272                 if (!uid_valid(kloginuid))
1273                         return -EINVAL;
1274         }
1275
1276         rv = audit_set_loginuid(kloginuid);
1277         if (rv < 0)
1278                 return rv;
1279         return count;
1280 }
1281
1282 static const struct file_operations proc_loginuid_operations = {
1283         .read           = proc_loginuid_read,
1284         .write          = proc_loginuid_write,
1285         .llseek         = generic_file_llseek,
1286 };
1287
1288 static ssize_t proc_sessionid_read(struct file * file, char __user * buf,
1289                                   size_t count, loff_t *ppos)
1290 {
1291         struct inode * inode = file_inode(file);
1292         struct task_struct *task = get_proc_task(inode);
1293         ssize_t length;
1294         char tmpbuf[TMPBUFLEN];
1295
1296         if (!task)
1297                 return -ESRCH;
1298         length = scnprintf(tmpbuf, TMPBUFLEN, "%u",
1299                                 audit_get_sessionid(task));
1300         put_task_struct(task);
1301         return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
1302 }
1303
1304 static const struct file_operations proc_sessionid_operations = {
1305         .read           = proc_sessionid_read,
1306         .llseek         = generic_file_llseek,
1307 };
1308 #endif
1309
1310 #ifdef CONFIG_FAULT_INJECTION
1311 static ssize_t proc_fault_inject_read(struct file * file, char __user * buf,
1312                                       size_t count, loff_t *ppos)
1313 {
1314         struct task_struct *task = get_proc_task(file_inode(file));
1315         char buffer[PROC_NUMBUF];
1316         size_t len;
1317         int make_it_fail;
1318
1319         if (!task)
1320                 return -ESRCH;
1321         make_it_fail = task->make_it_fail;
1322         put_task_struct(task);
1323
1324         len = snprintf(buffer, sizeof(buffer), "%i\n", make_it_fail);
1325
1326         return simple_read_from_buffer(buf, count, ppos, buffer, len);
1327 }
1328
1329 static ssize_t proc_fault_inject_write(struct file * file,
1330                         const char __user * buf, size_t count, loff_t *ppos)
1331 {
1332         struct task_struct *task;
1333         char buffer[PROC_NUMBUF];
1334         int make_it_fail;
1335         int rv;
1336
1337         if (!capable(CAP_SYS_RESOURCE))
1338                 return -EPERM;
1339         memset(buffer, 0, sizeof(buffer));
1340         if (count > sizeof(buffer) - 1)
1341                 count = sizeof(buffer) - 1;
1342         if (copy_from_user(buffer, buf, count))
1343                 return -EFAULT;
1344         rv = kstrtoint(strstrip(buffer), 0, &make_it_fail);
1345         if (rv < 0)
1346                 return rv;
1347         if (make_it_fail < 0 || make_it_fail > 1)
1348                 return -EINVAL;
1349
1350         task = get_proc_task(file_inode(file));
1351         if (!task)
1352                 return -ESRCH;
1353         task->make_it_fail = make_it_fail;
1354         put_task_struct(task);
1355
1356         return count;
1357 }
1358
1359 static const struct file_operations proc_fault_inject_operations = {
1360         .read           = proc_fault_inject_read,
1361         .write          = proc_fault_inject_write,
1362         .llseek         = generic_file_llseek,
1363 };
1364
1365 static ssize_t proc_fail_nth_write(struct file *file, const char __user *buf,
1366                                    size_t count, loff_t *ppos)
1367 {
1368         struct task_struct *task;
1369         int err;
1370         unsigned int n;
1371
1372         err = kstrtouint_from_user(buf, count, 0, &n);
1373         if (err)
1374                 return err;
1375
1376         task = get_proc_task(file_inode(file));
1377         if (!task)
1378                 return -ESRCH;
1379         task->fail_nth = n;
1380         put_task_struct(task);
1381
1382         return count;
1383 }
1384
1385 static ssize_t proc_fail_nth_read(struct file *file, char __user *buf,
1386                                   size_t count, loff_t *ppos)
1387 {
1388         struct task_struct *task;
1389         char numbuf[PROC_NUMBUF];
1390         ssize_t len;
1391
1392         task = get_proc_task(file_inode(file));
1393         if (!task)
1394                 return -ESRCH;
1395         len = snprintf(numbuf, sizeof(numbuf), "%u\n", task->fail_nth);
1396         put_task_struct(task);
1397         return simple_read_from_buffer(buf, count, ppos, numbuf, len);
1398 }
1399
1400 static const struct file_operations proc_fail_nth_operations = {
1401         .read           = proc_fail_nth_read,
1402         .write          = proc_fail_nth_write,
1403 };
1404 #endif
1405
1406
1407 #ifdef CONFIG_SCHED_DEBUG
1408 /*
1409  * Print out various scheduling related per-task fields:
1410  */
1411 static int sched_show(struct seq_file *m, void *v)
1412 {
1413         struct inode *inode = m->private;
1414         struct pid_namespace *ns = proc_pid_ns(inode);
1415         struct task_struct *p;
1416
1417         p = get_proc_task(inode);
1418         if (!p)
1419                 return -ESRCH;
1420         proc_sched_show_task(p, ns, m);
1421
1422         put_task_struct(p);
1423
1424         return 0;
1425 }
1426
1427 static ssize_t
1428 sched_write(struct file *file, const char __user *buf,
1429             size_t count, loff_t *offset)
1430 {
1431         struct inode *inode = file_inode(file);
1432         struct task_struct *p;
1433
1434         p = get_proc_task(inode);
1435         if (!p)
1436                 return -ESRCH;
1437         proc_sched_set_task(p);
1438
1439         put_task_struct(p);
1440
1441         return count;
1442 }
1443
1444 static int sched_open(struct inode *inode, struct file *filp)
1445 {
1446         return single_open(filp, sched_show, inode);
1447 }
1448
1449 static const struct file_operations proc_pid_sched_operations = {
1450         .open           = sched_open,
1451         .read           = seq_read,
1452         .write          = sched_write,
1453         .llseek         = seq_lseek,
1454         .release        = single_release,
1455 };
1456
1457 #endif
1458
1459 #ifdef CONFIG_SCHED_AUTOGROUP
1460 /*
1461  * Print out autogroup related information:
1462  */
1463 static int sched_autogroup_show(struct seq_file *m, void *v)
1464 {
1465         struct inode *inode = m->private;
1466         struct task_struct *p;
1467
1468         p = get_proc_task(inode);
1469         if (!p)
1470                 return -ESRCH;
1471         proc_sched_autogroup_show_task(p, m);
1472
1473         put_task_struct(p);
1474
1475         return 0;
1476 }
1477
1478 static ssize_t
1479 sched_autogroup_write(struct file *file, const char __user *buf,
1480             size_t count, loff_t *offset)
1481 {
1482         struct inode *inode = file_inode(file);
1483         struct task_struct *p;
1484         char buffer[PROC_NUMBUF];
1485         int nice;
1486         int err;
1487
1488         memset(buffer, 0, sizeof(buffer));
1489         if (count > sizeof(buffer) - 1)
1490                 count = sizeof(buffer) - 1;
1491         if (copy_from_user(buffer, buf, count))
1492                 return -EFAULT;
1493
1494         err = kstrtoint(strstrip(buffer), 0, &nice);
1495         if (err < 0)
1496                 return err;
1497
1498         p = get_proc_task(inode);
1499         if (!p)
1500                 return -ESRCH;
1501
1502         err = proc_sched_autogroup_set_nice(p, nice);
1503         if (err)
1504                 count = err;
1505
1506         put_task_struct(p);
1507
1508         return count;
1509 }
1510
1511 static int sched_autogroup_open(struct inode *inode, struct file *filp)
1512 {
1513         int ret;
1514
1515         ret = single_open(filp, sched_autogroup_show, NULL);
1516         if (!ret) {
1517                 struct seq_file *m = filp->private_data;
1518
1519                 m->private = inode;
1520         }
1521         return ret;
1522 }
1523
1524 static const struct file_operations proc_pid_sched_autogroup_operations = {
1525         .open           = sched_autogroup_open,
1526         .read           = seq_read,
1527         .write          = sched_autogroup_write,
1528         .llseek         = seq_lseek,
1529         .release        = single_release,
1530 };
1531
1532 #endif /* CONFIG_SCHED_AUTOGROUP */
1533
1534 static ssize_t comm_write(struct file *file, const char __user *buf,
1535                                 size_t count, loff_t *offset)
1536 {
1537         struct inode *inode = file_inode(file);
1538         struct task_struct *p;
1539         char buffer[TASK_COMM_LEN];
1540         const size_t maxlen = sizeof(buffer) - 1;
1541
1542         memset(buffer, 0, sizeof(buffer));
1543         if (copy_from_user(buffer, buf, count > maxlen ? maxlen : count))
1544                 return -EFAULT;
1545
1546         p = get_proc_task(inode);
1547         if (!p)
1548                 return -ESRCH;
1549
1550         if (same_thread_group(current, p))
1551                 set_task_comm(p, buffer);
1552         else
1553                 count = -EINVAL;
1554
1555         put_task_struct(p);
1556
1557         return count;
1558 }
1559
1560 static int comm_show(struct seq_file *m, void *v)
1561 {
1562         struct inode *inode = m->private;
1563         struct task_struct *p;
1564
1565         p = get_proc_task(inode);
1566         if (!p)
1567                 return -ESRCH;
1568
1569         proc_task_name(m, p, false);
1570         seq_putc(m, '\n');
1571
1572         put_task_struct(p);
1573
1574         return 0;
1575 }
1576
1577 static int comm_open(struct inode *inode, struct file *filp)
1578 {
1579         return single_open(filp, comm_show, inode);
1580 }
1581
1582 static const struct file_operations proc_pid_set_comm_operations = {
1583         .open           = comm_open,
1584         .read           = seq_read,
1585         .write          = comm_write,
1586         .llseek         = seq_lseek,
1587         .release        = single_release,
1588 };
1589
1590 static int proc_exe_link(struct dentry *dentry, struct path *exe_path)
1591 {
1592         struct task_struct *task;
1593         struct file *exe_file;
1594
1595         task = get_proc_task(d_inode(dentry));
1596         if (!task)
1597                 return -ENOENT;
1598         exe_file = get_task_exe_file(task);
1599         put_task_struct(task);
1600         if (exe_file) {
1601                 *exe_path = exe_file->f_path;
1602                 path_get(&exe_file->f_path);
1603                 fput(exe_file);
1604                 return 0;
1605         } else
1606                 return -ENOENT;
1607 }
1608
1609 static const char *proc_pid_get_link(struct dentry *dentry,
1610                                      struct inode *inode,
1611                                      struct delayed_call *done)
1612 {
1613         struct path path;
1614         int error = -EACCES;
1615
1616         if (!dentry)
1617                 return ERR_PTR(-ECHILD);
1618
1619         /* Are we allowed to snoop on the tasks file descriptors? */
1620         if (!proc_fd_access_allowed(inode))
1621                 goto out;
1622
1623         error = PROC_I(inode)->op.proc_get_link(dentry, &path);
1624         if (error)
1625                 goto out;
1626
1627         nd_jump_link(&path);
1628         return NULL;
1629 out:
1630         return ERR_PTR(error);
1631 }
1632
1633 static int do_proc_readlink(struct path *path, char __user *buffer, int buflen)
1634 {
1635         char *tmp = (char *)__get_free_page(GFP_KERNEL);
1636         char *pathname;
1637         int len;
1638
1639         if (!tmp)
1640                 return -ENOMEM;
1641
1642         pathname = d_path(path, tmp, PAGE_SIZE);
1643         len = PTR_ERR(pathname);
1644         if (IS_ERR(pathname))
1645                 goto out;
1646         len = tmp + PAGE_SIZE - 1 - pathname;
1647
1648         if (len > buflen)
1649                 len = buflen;
1650         if (copy_to_user(buffer, pathname, len))
1651                 len = -EFAULT;
1652  out:
1653         free_page((unsigned long)tmp);
1654         return len;
1655 }
1656
1657 static int proc_pid_readlink(struct dentry * dentry, char __user * buffer, int buflen)
1658 {
1659         int error = -EACCES;
1660         struct inode *inode = d_inode(dentry);
1661         struct path path;
1662
1663         /* Are we allowed to snoop on the tasks file descriptors? */
1664         if (!proc_fd_access_allowed(inode))
1665                 goto out;
1666
1667         error = PROC_I(inode)->op.proc_get_link(dentry, &path);
1668         if (error)
1669                 goto out;
1670
1671         error = do_proc_readlink(&path, buffer, buflen);
1672         path_put(&path);
1673 out:
1674         return error;
1675 }
1676
1677 const struct inode_operations proc_pid_link_inode_operations = {
1678         .readlink       = proc_pid_readlink,
1679         .get_link       = proc_pid_get_link,
1680         .setattr        = proc_setattr,
1681 };
1682
1683
1684 /* building an inode */
1685
1686 void task_dump_owner(struct task_struct *task, umode_t mode,
1687                      kuid_t *ruid, kgid_t *rgid)
1688 {
1689         /* Depending on the state of dumpable compute who should own a
1690          * proc file for a task.
1691          */
1692         const struct cred *cred;
1693         kuid_t uid;
1694         kgid_t gid;
1695
1696         if (unlikely(task->flags & PF_KTHREAD)) {
1697                 *ruid = GLOBAL_ROOT_UID;
1698                 *rgid = GLOBAL_ROOT_GID;
1699                 return;
1700         }
1701
1702         /* Default to the tasks effective ownership */
1703         rcu_read_lock();
1704         cred = __task_cred(task);
1705         uid = cred->euid;
1706         gid = cred->egid;
1707         rcu_read_unlock();
1708
1709         /*
1710          * Before the /proc/pid/status file was created the only way to read
1711          * the effective uid of a /process was to stat /proc/pid.  Reading
1712          * /proc/pid/status is slow enough that procps and other packages
1713          * kept stating /proc/pid.  To keep the rules in /proc simple I have
1714          * made this apply to all per process world readable and executable
1715          * directories.
1716          */
1717         if (mode != (S_IFDIR|S_IRUGO|S_IXUGO)) {
1718                 struct mm_struct *mm;
1719                 task_lock(task);
1720                 mm = task->mm;
1721                 /* Make non-dumpable tasks owned by some root */
1722                 if (mm) {
1723                         if (get_dumpable(mm) != SUID_DUMP_USER) {
1724                                 struct user_namespace *user_ns = mm->user_ns;
1725
1726                                 uid = make_kuid(user_ns, 0);
1727                                 if (!uid_valid(uid))
1728                                         uid = GLOBAL_ROOT_UID;
1729
1730                                 gid = make_kgid(user_ns, 0);
1731                                 if (!gid_valid(gid))
1732                                         gid = GLOBAL_ROOT_GID;
1733                         }
1734                 } else {
1735                         uid = GLOBAL_ROOT_UID;
1736                         gid = GLOBAL_ROOT_GID;
1737                 }
1738                 task_unlock(task);
1739         }
1740         *ruid = uid;
1741         *rgid = gid;
1742 }
1743
1744 struct inode *proc_pid_make_inode(struct super_block * sb,
1745                                   struct task_struct *task, umode_t mode)
1746 {
1747         struct inode * inode;
1748         struct proc_inode *ei;
1749
1750         /* We need a new inode */
1751
1752         inode = new_inode(sb);
1753         if (!inode)
1754                 goto out;
1755
1756         /* Common stuff */
1757         ei = PROC_I(inode);
1758         inode->i_mode = mode;
1759         inode->i_ino = get_next_ino();
1760         inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode);
1761         inode->i_op = &proc_def_inode_operations;
1762
1763         /*
1764          * grab the reference to task.
1765          */
1766         ei->pid = get_task_pid(task, PIDTYPE_PID);
1767         if (!ei->pid)
1768                 goto out_unlock;
1769
1770         task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid);
1771         security_task_to_inode(task, inode);
1772
1773 out:
1774         return inode;
1775
1776 out_unlock:
1777         iput(inode);
1778         return NULL;
1779 }
1780
1781 int pid_getattr(const struct path *path, struct kstat *stat,
1782                 u32 request_mask, unsigned int query_flags)
1783 {
1784         struct inode *inode = d_inode(path->dentry);
1785         struct pid_namespace *pid = proc_pid_ns(inode);
1786         struct task_struct *task;
1787
1788         generic_fillattr(inode, stat);
1789
1790         stat->uid = GLOBAL_ROOT_UID;
1791         stat->gid = GLOBAL_ROOT_GID;
1792         rcu_read_lock();
1793         task = pid_task(proc_pid(inode), PIDTYPE_PID);
1794         if (task) {
1795                 if (!has_pid_permissions(pid, task, HIDEPID_INVISIBLE)) {
1796                         rcu_read_unlock();
1797                         /*
1798                          * This doesn't prevent learning whether PID exists,
1799                          * it only makes getattr() consistent with readdir().
1800                          */
1801                         return -ENOENT;
1802                 }
1803                 task_dump_owner(task, inode->i_mode, &stat->uid, &stat->gid);
1804         }
1805         rcu_read_unlock();
1806         return 0;
1807 }
1808
1809 /* dentry stuff */
1810
1811 /*
1812  * Set <pid>/... inode ownership (can change due to setuid(), etc.)
1813  */
1814 void pid_update_inode(struct task_struct *task, struct inode *inode)
1815 {
1816         task_dump_owner(task, inode->i_mode, &inode->i_uid, &inode->i_gid);
1817
1818         inode->i_mode &= ~(S_ISUID | S_ISGID);
1819         security_task_to_inode(task, inode);
1820 }
1821
1822 /*
1823  * Rewrite the inode's ownerships here because the owning task may have
1824  * performed a setuid(), etc.
1825  *
1826  */
1827 static int pid_revalidate(struct dentry *dentry, unsigned int flags)
1828 {
1829         struct inode *inode;
1830         struct task_struct *task;
1831
1832         if (flags & LOOKUP_RCU)
1833                 return -ECHILD;
1834
1835         inode = d_inode(dentry);
1836         task = get_proc_task(inode);
1837
1838         if (task) {
1839                 pid_update_inode(task, inode);
1840                 put_task_struct(task);
1841                 return 1;
1842         }
1843         return 0;
1844 }
1845
1846 static inline bool proc_inode_is_dead(struct inode *inode)
1847 {
1848         return !proc_pid(inode)->tasks[PIDTYPE_PID].first;
1849 }
1850
1851 int pid_delete_dentry(const struct dentry *dentry)
1852 {
1853         /* Is the task we represent dead?
1854          * If so, then don't put the dentry on the lru list,
1855          * kill it immediately.
1856          */
1857         return proc_inode_is_dead(d_inode(dentry));
1858 }
1859
1860 const struct dentry_operations pid_dentry_operations =
1861 {
1862         .d_revalidate   = pid_revalidate,
1863         .d_delete       = pid_delete_dentry,
1864 };
1865
1866 /* Lookups */
1867
1868 /*
1869  * Fill a directory entry.
1870  *
1871  * If possible create the dcache entry and derive our inode number and
1872  * file type from dcache entry.
1873  *
1874  * Since all of the proc inode numbers are dynamically generated, the inode
1875  * numbers do not exist until the inode is cache.  This means creating the
1876  * the dcache entry in readdir is necessary to keep the inode numbers
1877  * reported by readdir in sync with the inode numbers reported
1878  * by stat.
1879  */
1880 bool proc_fill_cache(struct file *file, struct dir_context *ctx,
1881         const char *name, unsigned int len,
1882         instantiate_t instantiate, struct task_struct *task, const void *ptr)
1883 {
1884         struct dentry *child, *dir = file->f_path.dentry;
1885         struct qstr qname = QSTR_INIT(name, len);
1886         struct inode *inode;
1887         unsigned type = DT_UNKNOWN;
1888         ino_t ino = 1;
1889
1890         child = d_hash_and_lookup(dir, &qname);
1891         if (!child) {
1892                 DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
1893                 child = d_alloc_parallel(dir, &qname, &wq);
1894                 if (IS_ERR(child))
1895                         goto end_instantiate;
1896                 if (d_in_lookup(child)) {
1897                         struct dentry *res;
1898                         res = instantiate(child, task, ptr);
1899                         d_lookup_done(child);
1900                         if (unlikely(res)) {
1901                                 dput(child);
1902                                 child = res;
1903                                 if (IS_ERR(child))
1904                                         goto end_instantiate;
1905                         }
1906                 }
1907         }
1908         inode = d_inode(child);
1909         ino = inode->i_ino;
1910         type = inode->i_mode >> 12;
1911         dput(child);
1912 end_instantiate:
1913         return dir_emit(ctx, name, len, ino, type);
1914 }
1915
1916 /*
1917  * dname_to_vma_addr - maps a dentry name into two unsigned longs
1918  * which represent vma start and end addresses.
1919  */
1920 static int dname_to_vma_addr(struct dentry *dentry,
1921                              unsigned long *start, unsigned long *end)
1922 {
1923         const char *str = dentry->d_name.name;
1924         unsigned long long sval, eval;
1925         unsigned int len;
1926
1927         if (str[0] == '0' && str[1] != '-')
1928                 return -EINVAL;
1929         len = _parse_integer(str, 16, &sval);
1930         if (len & KSTRTOX_OVERFLOW)
1931                 return -EINVAL;
1932         if (sval != (unsigned long)sval)
1933                 return -EINVAL;
1934         str += len;
1935
1936         if (*str != '-')
1937                 return -EINVAL;
1938         str++;
1939
1940         if (str[0] == '0' && str[1])
1941                 return -EINVAL;
1942         len = _parse_integer(str, 16, &eval);
1943         if (len & KSTRTOX_OVERFLOW)
1944                 return -EINVAL;
1945         if (eval != (unsigned long)eval)
1946                 return -EINVAL;
1947         str += len;
1948
1949         if (*str != '\0')
1950                 return -EINVAL;
1951
1952         *start = sval;
1953         *end = eval;
1954
1955         return 0;
1956 }
1957
1958 static int map_files_d_revalidate(struct dentry *dentry, unsigned int flags)
1959 {
1960         unsigned long vm_start, vm_end;
1961         bool exact_vma_exists = false;
1962         struct mm_struct *mm = NULL;
1963         struct task_struct *task;
1964         struct inode *inode;
1965         int status = 0;
1966
1967         if (flags & LOOKUP_RCU)
1968                 return -ECHILD;
1969
1970         inode = d_inode(dentry);
1971         task = get_proc_task(inode);
1972         if (!task)
1973                 goto out_notask;
1974
1975         mm = mm_access(task, PTRACE_MODE_READ_FSCREDS);
1976         if (IS_ERR_OR_NULL(mm))
1977                 goto out;
1978
1979         if (!dname_to_vma_addr(dentry, &vm_start, &vm_end)) {
1980                 status = down_read_killable(&mm->mmap_sem);
1981                 if (!status) {
1982                         exact_vma_exists = !!find_exact_vma(mm, vm_start,
1983                                                             vm_end);
1984                         up_read(&mm->mmap_sem);
1985                 }
1986         }
1987
1988         mmput(mm);
1989
1990         if (exact_vma_exists) {
1991                 task_dump_owner(task, 0, &inode->i_uid, &inode->i_gid);
1992
1993                 security_task_to_inode(task, inode);
1994                 status = 1;
1995         }
1996
1997 out:
1998         put_task_struct(task);
1999
2000 out_notask:
2001         return status;
2002 }
2003
2004 static const struct dentry_operations tid_map_files_dentry_operations = {
2005         .d_revalidate   = map_files_d_revalidate,
2006         .d_delete       = pid_delete_dentry,
2007 };
2008
2009 static int map_files_get_link(struct dentry *dentry, struct path *path)
2010 {
2011         unsigned long vm_start, vm_end;
2012         struct vm_area_struct *vma;
2013         struct task_struct *task;
2014         struct mm_struct *mm;
2015         int rc;
2016
2017         rc = -ENOENT;
2018         task = get_proc_task(d_inode(dentry));
2019         if (!task)
2020                 goto out;
2021
2022         mm = get_task_mm(task);
2023         put_task_struct(task);
2024         if (!mm)
2025                 goto out;
2026
2027         rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
2028         if (rc)
2029                 goto out_mmput;
2030
2031         rc = down_read_killable(&mm->mmap_sem);
2032         if (rc)
2033                 goto out_mmput;
2034
2035         rc = -ENOENT;
2036         vma = find_exact_vma(mm, vm_start, vm_end);
2037         if (vma && vma->vm_file) {
2038                 *path = vma->vm_file->f_path;
2039                 path_get(path);
2040                 rc = 0;
2041         }
2042         up_read(&mm->mmap_sem);
2043
2044 out_mmput:
2045         mmput(mm);
2046 out:
2047         return rc;
2048 }
2049
2050 struct map_files_info {
2051         unsigned long   start;
2052         unsigned long   end;
2053         fmode_t         mode;
2054 };
2055
2056 /*
2057  * Only allow CAP_SYS_ADMIN to follow the links, due to concerns about how the
2058  * symlinks may be used to bypass permissions on ancestor directories in the
2059  * path to the file in question.
2060  */
2061 static const char *
2062 proc_map_files_get_link(struct dentry *dentry,
2063                         struct inode *inode,
2064                         struct delayed_call *done)
2065 {
2066         if (!capable(CAP_SYS_ADMIN))
2067                 return ERR_PTR(-EPERM);
2068
2069         return proc_pid_get_link(dentry, inode, done);
2070 }
2071
2072 /*
2073  * Identical to proc_pid_link_inode_operations except for get_link()
2074  */
2075 static const struct inode_operations proc_map_files_link_inode_operations = {
2076         .readlink       = proc_pid_readlink,
2077         .get_link       = proc_map_files_get_link,
2078         .setattr        = proc_setattr,
2079 };
2080
2081 static struct dentry *
2082 proc_map_files_instantiate(struct dentry *dentry,
2083                            struct task_struct *task, const void *ptr)
2084 {
2085         fmode_t mode = (fmode_t)(unsigned long)ptr;
2086         struct proc_inode *ei;
2087         struct inode *inode;
2088
2089         inode = proc_pid_make_inode(dentry->d_sb, task, S_IFLNK |
2090                                     ((mode & FMODE_READ ) ? S_IRUSR : 0) |
2091                                     ((mode & FMODE_WRITE) ? S_IWUSR : 0));
2092         if (!inode)
2093                 return ERR_PTR(-ENOENT);
2094
2095         ei = PROC_I(inode);
2096         ei->op.proc_get_link = map_files_get_link;
2097
2098         inode->i_op = &proc_map_files_link_inode_operations;
2099         inode->i_size = 64;
2100
2101         d_set_d_op(dentry, &tid_map_files_dentry_operations);
2102         return d_splice_alias(inode, dentry);
2103 }
2104
2105 static struct dentry *proc_map_files_lookup(struct inode *dir,
2106                 struct dentry *dentry, unsigned int flags)
2107 {
2108         unsigned long vm_start, vm_end;
2109         struct vm_area_struct *vma;
2110         struct task_struct *task;
2111         struct dentry *result;
2112         struct mm_struct *mm;
2113
2114         result = ERR_PTR(-ENOENT);
2115         task = get_proc_task(dir);
2116         if (!task)
2117                 goto out;
2118
2119         result = ERR_PTR(-EACCES);
2120         if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
2121                 goto out_put_task;
2122
2123         result = ERR_PTR(-ENOENT);
2124         if (dname_to_vma_addr(dentry, &vm_start, &vm_end))
2125                 goto out_put_task;
2126
2127         mm = get_task_mm(task);
2128         if (!mm)
2129                 goto out_put_task;
2130
2131         result = ERR_PTR(-EINTR);
2132         if (down_read_killable(&mm->mmap_sem))
2133                 goto out_put_mm;
2134
2135         result = ERR_PTR(-ENOENT);
2136         vma = find_exact_vma(mm, vm_start, vm_end);
2137         if (!vma)
2138                 goto out_no_vma;
2139
2140         if (vma->vm_file)
2141                 result = proc_map_files_instantiate(dentry, task,
2142                                 (void *)(unsigned long)vma->vm_file->f_mode);
2143
2144 out_no_vma:
2145         up_read(&mm->mmap_sem);
2146 out_put_mm:
2147         mmput(mm);
2148 out_put_task:
2149         put_task_struct(task);
2150 out:
2151         return result;
2152 }
2153
2154 static const struct inode_operations proc_map_files_inode_operations = {
2155         .lookup         = proc_map_files_lookup,
2156         .permission     = proc_fd_permission,
2157         .setattr        = proc_setattr,
2158 };
2159
2160 static int
2161 proc_map_files_readdir(struct file *file, struct dir_context *ctx)
2162 {
2163         struct vm_area_struct *vma;
2164         struct task_struct *task;
2165         struct mm_struct *mm;
2166         unsigned long nr_files, pos, i;
2167         struct flex_array *fa = NULL;
2168         struct map_files_info info;
2169         struct map_files_info *p;
2170         int ret;
2171
2172         ret = -ENOENT;
2173         task = get_proc_task(file_inode(file));
2174         if (!task)
2175                 goto out;
2176
2177         ret = -EACCES;
2178         if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
2179                 goto out_put_task;
2180
2181         ret = 0;
2182         if (!dir_emit_dots(file, ctx))
2183                 goto out_put_task;
2184
2185         mm = get_task_mm(task);
2186         if (!mm)
2187                 goto out_put_task;
2188
2189         ret = down_read_killable(&mm->mmap_sem);
2190         if (ret) {
2191                 mmput(mm);
2192                 goto out_put_task;
2193         }
2194
2195         nr_files = 0;
2196
2197         /*
2198          * We need two passes here:
2199          *
2200          *  1) Collect vmas of mapped files with mmap_sem taken
2201          *  2) Release mmap_sem and instantiate entries
2202          *
2203          * otherwise we get lockdep complained, since filldir()
2204          * routine might require mmap_sem taken in might_fault().
2205          */
2206
2207         for (vma = mm->mmap, pos = 2; vma; vma = vma->vm_next) {
2208                 if (vma->vm_file && ++pos > ctx->pos)
2209                         nr_files++;
2210         }
2211
2212         if (nr_files) {
2213                 fa = flex_array_alloc(sizeof(info), nr_files,
2214                                         GFP_KERNEL);
2215                 if (!fa || flex_array_prealloc(fa, 0, nr_files,
2216                                                 GFP_KERNEL)) {
2217                         ret = -ENOMEM;
2218                         if (fa)
2219                                 flex_array_free(fa);
2220                         up_read(&mm->mmap_sem);
2221                         mmput(mm);
2222                         goto out_put_task;
2223                 }
2224                 for (i = 0, vma = mm->mmap, pos = 2; vma;
2225                                 vma = vma->vm_next) {
2226                         if (!vma->vm_file)
2227                                 continue;
2228                         if (++pos <= ctx->pos)
2229                                 continue;
2230
2231                         info.start = vma->vm_start;
2232                         info.end = vma->vm_end;
2233                         info.mode = vma->vm_file->f_mode;
2234                         if (flex_array_put(fa, i++, &info, GFP_KERNEL))
2235                                 BUG();
2236                 }
2237         }
2238         up_read(&mm->mmap_sem);
2239         mmput(mm);
2240
2241         for (i = 0; i < nr_files; i++) {
2242                 char buf[4 * sizeof(long) + 2]; /* max: %lx-%lx\0 */
2243                 unsigned int len;
2244
2245                 p = flex_array_get(fa, i);
2246                 len = snprintf(buf, sizeof(buf), "%lx-%lx", p->start, p->end);
2247                 if (!proc_fill_cache(file, ctx,
2248                                       buf, len,
2249                                       proc_map_files_instantiate,
2250                                       task,
2251                                       (void *)(unsigned long)p->mode))
2252                         break;
2253                 ctx->pos++;
2254         }
2255         if (fa)
2256                 flex_array_free(fa);
2257
2258 out_put_task:
2259         put_task_struct(task);
2260 out:
2261         return ret;
2262 }
2263
2264 static const struct file_operations proc_map_files_operations = {
2265         .read           = generic_read_dir,
2266         .iterate_shared = proc_map_files_readdir,
2267         .llseek         = generic_file_llseek,
2268 };
2269
2270 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS)
2271 struct timers_private {
2272         struct pid *pid;
2273         struct task_struct *task;
2274         struct sighand_struct *sighand;
2275         struct pid_namespace *ns;
2276         unsigned long flags;
2277 };
2278
2279 static void *timers_start(struct seq_file *m, loff_t *pos)
2280 {
2281         struct timers_private *tp = m->private;
2282
2283         tp->task = get_pid_task(tp->pid, PIDTYPE_PID);
2284         if (!tp->task)
2285                 return ERR_PTR(-ESRCH);
2286
2287         tp->sighand = lock_task_sighand(tp->task, &tp->flags);
2288         if (!tp->sighand)
2289                 return ERR_PTR(-ESRCH);
2290
2291         return seq_list_start(&tp->task->signal->posix_timers, *pos);
2292 }
2293
2294 static void *timers_next(struct seq_file *m, void *v, loff_t *pos)
2295 {
2296         struct timers_private *tp = m->private;
2297         return seq_list_next(v, &tp->task->signal->posix_timers, pos);
2298 }
2299
2300 static void timers_stop(struct seq_file *m, void *v)
2301 {
2302         struct timers_private *tp = m->private;
2303
2304         if (tp->sighand) {
2305                 unlock_task_sighand(tp->task, &tp->flags);
2306                 tp->sighand = NULL;
2307         }
2308
2309         if (tp->task) {
2310                 put_task_struct(tp->task);
2311                 tp->task = NULL;
2312         }
2313 }
2314
2315 static int show_timer(struct seq_file *m, void *v)
2316 {
2317         struct k_itimer *timer;
2318         struct timers_private *tp = m->private;
2319         int notify;
2320         static const char * const nstr[] = {
2321                 [SIGEV_SIGNAL] = "signal",
2322                 [SIGEV_NONE] = "none",
2323                 [SIGEV_THREAD] = "thread",
2324         };
2325
2326         timer = list_entry((struct list_head *)v, struct k_itimer, list);
2327         notify = timer->it_sigev_notify;
2328
2329         seq_printf(m, "ID: %d\n", timer->it_id);
2330         seq_printf(m, "signal: %d/%px\n",
2331                    timer->sigq->info.si_signo,
2332                    timer->sigq->info.si_value.sival_ptr);
2333         seq_printf(m, "notify: %s/%s.%d\n",
2334                    nstr[notify & ~SIGEV_THREAD_ID],
2335                    (notify & SIGEV_THREAD_ID) ? "tid" : "pid",
2336                    pid_nr_ns(timer->it_pid, tp->ns));
2337         seq_printf(m, "ClockID: %d\n", timer->it_clock);
2338
2339         return 0;
2340 }
2341
2342 static const struct seq_operations proc_timers_seq_ops = {
2343         .start  = timers_start,
2344         .next   = timers_next,
2345         .stop   = timers_stop,
2346         .show   = show_timer,
2347 };
2348
2349 static int proc_timers_open(struct inode *inode, struct file *file)
2350 {
2351         struct timers_private *tp;
2352
2353         tp = __seq_open_private(file, &proc_timers_seq_ops,
2354                         sizeof(struct timers_private));
2355         if (!tp)
2356                 return -ENOMEM;
2357
2358         tp->pid = proc_pid(inode);
2359         tp->ns = proc_pid_ns(inode);
2360         return 0;
2361 }
2362
2363 static const struct file_operations proc_timers_operations = {
2364         .open           = proc_timers_open,
2365         .read           = seq_read,
2366         .llseek         = seq_lseek,
2367         .release        = seq_release_private,
2368 };
2369 #endif
2370
2371 static ssize_t timerslack_ns_write(struct file *file, const char __user *buf,
2372                                         size_t count, loff_t *offset)
2373 {
2374         struct inode *inode = file_inode(file);
2375         struct task_struct *p;
2376         u64 slack_ns;
2377         int err;
2378
2379         err = kstrtoull_from_user(buf, count, 10, &slack_ns);
2380         if (err < 0)
2381                 return err;
2382
2383         p = get_proc_task(inode);
2384         if (!p)
2385                 return -ESRCH;
2386
2387         if (p != current) {
2388                 if (!capable(CAP_SYS_NICE)) {
2389                         count = -EPERM;
2390                         goto out;
2391                 }
2392
2393                 err = security_task_setscheduler(p);
2394                 if (err) {
2395                         count = err;
2396                         goto out;
2397                 }
2398         }
2399
2400         task_lock(p);
2401         if (slack_ns == 0)
2402                 p->timer_slack_ns = p->default_timer_slack_ns;
2403         else
2404                 p->timer_slack_ns = slack_ns;
2405         task_unlock(p);
2406
2407 out:
2408         put_task_struct(p);
2409
2410         return count;
2411 }
2412
2413 static int timerslack_ns_show(struct seq_file *m, void *v)
2414 {
2415         struct inode *inode = m->private;
2416         struct task_struct *p;
2417         int err = 0;
2418
2419         p = get_proc_task(inode);
2420         if (!p)
2421                 return -ESRCH;
2422
2423         if (p != current) {
2424
2425                 if (!capable(CAP_SYS_NICE)) {
2426                         err = -EPERM;
2427                         goto out;
2428                 }
2429                 err = security_task_getscheduler(p);
2430                 if (err)
2431                         goto out;
2432         }
2433
2434         task_lock(p);
2435         seq_printf(m, "%llu\n", p->timer_slack_ns);
2436         task_unlock(p);
2437
2438 out:
2439         put_task_struct(p);
2440
2441         return err;
2442 }
2443
2444 static int timerslack_ns_open(struct inode *inode, struct file *filp)
2445 {
2446         return single_open(filp, timerslack_ns_show, inode);
2447 }
2448
2449 static const struct file_operations proc_pid_set_timerslack_ns_operations = {
2450         .open           = timerslack_ns_open,
2451         .read           = seq_read,
2452         .write          = timerslack_ns_write,
2453         .llseek         = seq_lseek,
2454         .release        = single_release,
2455 };
2456
2457 static struct dentry *proc_pident_instantiate(struct dentry *dentry,
2458         struct task_struct *task, const void *ptr)
2459 {
2460         const struct pid_entry *p = ptr;
2461         struct inode *inode;
2462         struct proc_inode *ei;
2463
2464         inode = proc_pid_make_inode(dentry->d_sb, task, p->mode);
2465         if (!inode)
2466                 return ERR_PTR(-ENOENT);
2467
2468         ei = PROC_I(inode);
2469         if (S_ISDIR(inode->i_mode))
2470                 set_nlink(inode, 2);    /* Use getattr to fix if necessary */
2471         if (p->iop)
2472                 inode->i_op = p->iop;
2473         if (p->fop)
2474                 inode->i_fop = p->fop;
2475         ei->op = p->op;
2476         pid_update_inode(task, inode);
2477         d_set_d_op(dentry, &pid_dentry_operations);
2478         return d_splice_alias(inode, dentry);
2479 }
2480
2481 static struct dentry *proc_pident_lookup(struct inode *dir, 
2482                                          struct dentry *dentry,
2483                                          const struct pid_entry *ents,
2484                                          unsigned int nents)
2485 {
2486         struct task_struct *task = get_proc_task(dir);
2487         const struct pid_entry *p, *last;
2488         struct dentry *res = ERR_PTR(-ENOENT);
2489
2490         if (!task)
2491                 goto out_no_task;
2492
2493         /*
2494          * Yes, it does not scale. And it should not. Don't add
2495          * new entries into /proc/<tgid>/ without very good reasons.
2496          */
2497         last = &ents[nents];
2498         for (p = ents; p < last; p++) {
2499                 if (p->len != dentry->d_name.len)
2500                         continue;
2501                 if (!memcmp(dentry->d_name.name, p->name, p->len)) {
2502                         res = proc_pident_instantiate(dentry, task, p);
2503                         break;
2504                 }
2505         }
2506         put_task_struct(task);
2507 out_no_task:
2508         return res;
2509 }
2510
2511 static int proc_pident_readdir(struct file *file, struct dir_context *ctx,
2512                 const struct pid_entry *ents, unsigned int nents)
2513 {
2514         struct task_struct *task = get_proc_task(file_inode(file));
2515         const struct pid_entry *p;
2516
2517         if (!task)
2518                 return -ENOENT;
2519
2520         if (!dir_emit_dots(file, ctx))
2521                 goto out;
2522
2523         if (ctx->pos >= nents + 2)
2524                 goto out;
2525
2526         for (p = ents + (ctx->pos - 2); p < ents + nents; p++) {
2527                 if (!proc_fill_cache(file, ctx, p->name, p->len,
2528                                 proc_pident_instantiate, task, p))
2529                         break;
2530                 ctx->pos++;
2531         }
2532 out:
2533         put_task_struct(task);
2534         return 0;
2535 }
2536
2537 #ifdef CONFIG_SECURITY
2538 static int proc_pid_attr_open(struct inode *inode, struct file *file)
2539 {
2540         file->private_data = NULL;
2541         __mem_open(inode, file, PTRACE_MODE_READ_FSCREDS);
2542         return 0;
2543 }
2544
2545 static ssize_t proc_pid_attr_read(struct file * file, char __user * buf,
2546                                   size_t count, loff_t *ppos)
2547 {
2548         struct inode * inode = file_inode(file);
2549         char *p = NULL;
2550         ssize_t length;
2551         struct task_struct *task = get_proc_task(inode);
2552
2553         if (!task)
2554                 return -ESRCH;
2555
2556         length = security_getprocattr(task,
2557                                       (char*)file->f_path.dentry->d_name.name,
2558                                       &p);
2559         put_task_struct(task);
2560         if (length > 0)
2561                 length = simple_read_from_buffer(buf, count, ppos, p, length);
2562         kfree(p);
2563         return length;
2564 }
2565
2566 static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
2567                                    size_t count, loff_t *ppos)
2568 {
2569         struct inode * inode = file_inode(file);
2570         struct task_struct *task;
2571         void *page;
2572         int rv;
2573
2574         /* A task may only write when it was the opener. */
2575         if (file->private_data != current->mm)
2576                 return -EPERM;
2577
2578         rcu_read_lock();
2579         task = pid_task(proc_pid(inode), PIDTYPE_PID);
2580         if (!task) {
2581                 rcu_read_unlock();
2582                 return -ESRCH;
2583         }
2584         /* A task may only write its own attributes. */
2585         if (current != task) {
2586                 rcu_read_unlock();
2587                 return -EACCES;
2588         }
2589         /* Prevent changes to overridden credentials. */
2590         if (current_cred() != current_real_cred()) {
2591                 rcu_read_unlock();
2592                 return -EBUSY;
2593         }
2594         rcu_read_unlock();
2595
2596         if (count > PAGE_SIZE)
2597                 count = PAGE_SIZE;
2598
2599         /* No partial writes. */
2600         if (*ppos != 0)
2601                 return -EINVAL;
2602
2603         page = memdup_user(buf, count);
2604         if (IS_ERR(page)) {
2605                 rv = PTR_ERR(page);
2606                 goto out;
2607         }
2608
2609         /* Guard against adverse ptrace interaction */
2610         rv = mutex_lock_interruptible(&current->signal->cred_guard_mutex);
2611         if (rv < 0)
2612                 goto out_free;
2613
2614         rv = security_setprocattr(file->f_path.dentry->d_name.name, page, count);
2615         mutex_unlock(&current->signal->cred_guard_mutex);
2616 out_free:
2617         kfree(page);
2618 out:
2619         return rv;
2620 }
2621
2622 static const struct file_operations proc_pid_attr_operations = {
2623         .open           = proc_pid_attr_open,
2624         .read           = proc_pid_attr_read,
2625         .write          = proc_pid_attr_write,
2626         .llseek         = generic_file_llseek,
2627         .release        = mem_release,
2628 };
2629
2630 static const struct pid_entry attr_dir_stuff[] = {
2631         REG("current",    S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2632         REG("prev",       S_IRUGO,         proc_pid_attr_operations),
2633         REG("exec",       S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2634         REG("fscreate",   S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2635         REG("keycreate",  S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2636         REG("sockcreate", S_IRUGO|S_IWUGO, proc_pid_attr_operations),
2637 };
2638
2639 static int proc_attr_dir_readdir(struct file *file, struct dir_context *ctx)
2640 {
2641         return proc_pident_readdir(file, ctx, 
2642                                    attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
2643 }
2644
2645 static const struct file_operations proc_attr_dir_operations = {
2646         .read           = generic_read_dir,
2647         .iterate_shared = proc_attr_dir_readdir,
2648         .llseek         = generic_file_llseek,
2649 };
2650
2651 static struct dentry *proc_attr_dir_lookup(struct inode *dir,
2652                                 struct dentry *dentry, unsigned int flags)
2653 {
2654         return proc_pident_lookup(dir, dentry,
2655                                   attr_dir_stuff, ARRAY_SIZE(attr_dir_stuff));
2656 }
2657
2658 static const struct inode_operations proc_attr_dir_inode_operations = {
2659         .lookup         = proc_attr_dir_lookup,
2660         .getattr        = pid_getattr,
2661         .setattr        = proc_setattr,
2662 };
2663
2664 #endif
2665
2666 #ifdef CONFIG_ELF_CORE
2667 static ssize_t proc_coredump_filter_read(struct file *file, char __user *buf,
2668                                          size_t count, loff_t *ppos)
2669 {
2670         struct task_struct *task = get_proc_task(file_inode(file));
2671         struct mm_struct *mm;
2672         char buffer[PROC_NUMBUF];
2673         size_t len;
2674         int ret;
2675
2676         if (!task)
2677                 return -ESRCH;
2678
2679         ret = 0;
2680         mm = get_task_mm(task);
2681         if (mm) {
2682                 len = snprintf(buffer, sizeof(buffer), "%08lx\n",
2683                                ((mm->flags & MMF_DUMP_FILTER_MASK) >>
2684                                 MMF_DUMP_FILTER_SHIFT));
2685                 mmput(mm);
2686                 ret = simple_read_from_buffer(buf, count, ppos, buffer, len);
2687         }
2688
2689         put_task_struct(task);
2690
2691         return ret;
2692 }
2693
2694 static ssize_t proc_coredump_filter_write(struct file *file,
2695                                           const char __user *buf,
2696                                           size_t count,
2697                                           loff_t *ppos)
2698 {
2699         struct task_struct *task;
2700         struct mm_struct *mm;
2701         unsigned int val;
2702         int ret;
2703         int i;
2704         unsigned long mask;
2705
2706         ret = kstrtouint_from_user(buf, count, 0, &val);
2707         if (ret < 0)
2708                 return ret;
2709
2710         ret = -ESRCH;
2711         task = get_proc_task(file_inode(file));
2712         if (!task)
2713                 goto out_no_task;
2714
2715         mm = get_task_mm(task);
2716         if (!mm)
2717                 goto out_no_mm;
2718         ret = 0;
2719
2720         for (i = 0, mask = 1; i < MMF_DUMP_FILTER_BITS; i++, mask <<= 1) {
2721                 if (val & mask)
2722                         set_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2723                 else
2724                         clear_bit(i + MMF_DUMP_FILTER_SHIFT, &mm->flags);
2725         }
2726
2727         mmput(mm);
2728  out_no_mm:
2729         put_task_struct(task);
2730  out_no_task:
2731         if (ret < 0)
2732                 return ret;
2733         return count;
2734 }
2735
2736 static const struct file_operations proc_coredump_filter_operations = {
2737         .read           = proc_coredump_filter_read,
2738         .write          = proc_coredump_filter_write,
2739         .llseek         = generic_file_llseek,
2740 };
2741 #endif
2742
2743 #ifdef CONFIG_TASK_IO_ACCOUNTING
2744 static int do_io_accounting(struct task_struct *task, struct seq_file *m, int whole)
2745 {
2746         struct task_io_accounting acct = task->ioac;
2747         unsigned long flags;
2748         int result;
2749
2750         result = mutex_lock_killable(&task->signal->cred_guard_mutex);
2751         if (result)
2752                 return result;
2753
2754         if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS)) {
2755                 result = -EACCES;
2756                 goto out_unlock;
2757         }
2758
2759         if (whole && lock_task_sighand(task, &flags)) {
2760                 struct task_struct *t = task;
2761
2762                 task_io_accounting_add(&acct, &task->signal->ioac);
2763                 while_each_thread(task, t)
2764                         task_io_accounting_add(&acct, &t->ioac);
2765
2766                 unlock_task_sighand(task, &flags);
2767         }
2768         seq_printf(m,
2769                    "rchar: %llu\n"
2770                    "wchar: %llu\n"
2771                    "syscr: %llu\n"
2772                    "syscw: %llu\n"
2773                    "read_bytes: %llu\n"
2774                    "write_bytes: %llu\n"
2775                    "cancelled_write_bytes: %llu\n",
2776                    (unsigned long long)acct.rchar,
2777                    (unsigned long long)acct.wchar,
2778                    (unsigned long long)acct.syscr,
2779                    (unsigned long long)acct.syscw,
2780                    (unsigned long long)acct.read_bytes,
2781                    (unsigned long long)acct.write_bytes,
2782                    (unsigned long long)acct.cancelled_write_bytes);
2783         result = 0;
2784
2785 out_unlock:
2786         mutex_unlock(&task->signal->cred_guard_mutex);
2787         return result;
2788 }
2789
2790 static int proc_tid_io_accounting(struct seq_file *m, struct pid_namespace *ns,
2791                                   struct pid *pid, struct task_struct *task)
2792 {
2793         return do_io_accounting(task, m, 0);
2794 }
2795
2796 static int proc_tgid_io_accounting(struct seq_file *m, struct pid_namespace *ns,
2797                                    struct pid *pid, struct task_struct *task)
2798 {
2799         return do_io_accounting(task, m, 1);
2800 }
2801 #endif /* CONFIG_TASK_IO_ACCOUNTING */
2802
2803 #ifdef CONFIG_USER_NS
2804 static int proc_id_map_open(struct inode *inode, struct file *file,
2805         const struct seq_operations *seq_ops)
2806 {
2807         struct user_namespace *ns = NULL;
2808         struct task_struct *task;
2809         struct seq_file *seq;
2810         int ret = -EINVAL;
2811
2812         task = get_proc_task(inode);
2813         if (task) {
2814                 rcu_read_lock();
2815                 ns = get_user_ns(task_cred_xxx(task, user_ns));
2816                 rcu_read_unlock();
2817                 put_task_struct(task);
2818         }
2819         if (!ns)
2820                 goto err;
2821
2822         ret = seq_open(file, seq_ops);
2823         if (ret)
2824                 goto err_put_ns;
2825
2826         seq = file->private_data;
2827         seq->private = ns;
2828
2829         return 0;
2830 err_put_ns:
2831         put_user_ns(ns);
2832 err:
2833         return ret;
2834 }
2835
2836 static int proc_id_map_release(struct inode *inode, struct file *file)
2837 {
2838         struct seq_file *seq = file->private_data;
2839         struct user_namespace *ns = seq->private;
2840         put_user_ns(ns);
2841         return seq_release(inode, file);
2842 }
2843
2844 static int proc_uid_map_open(struct inode *inode, struct file *file)
2845 {
2846         return proc_id_map_open(inode, file, &proc_uid_seq_operations);
2847 }
2848
2849 static int proc_gid_map_open(struct inode *inode, struct file *file)
2850 {
2851         return proc_id_map_open(inode, file, &proc_gid_seq_operations);
2852 }
2853
2854 static int proc_projid_map_open(struct inode *inode, struct file *file)
2855 {
2856         return proc_id_map_open(inode, file, &proc_projid_seq_operations);
2857 }
2858
2859 static const struct file_operations proc_uid_map_operations = {
2860         .open           = proc_uid_map_open,
2861         .write          = proc_uid_map_write,
2862         .read           = seq_read,
2863         .llseek         = seq_lseek,
2864         .release        = proc_id_map_release,
2865 };
2866
2867 static const struct file_operations proc_gid_map_operations = {
2868         .open           = proc_gid_map_open,
2869         .write          = proc_gid_map_write,
2870         .read           = seq_read,
2871         .llseek         = seq_lseek,
2872         .release        = proc_id_map_release,
2873 };
2874
2875 static const struct file_operations proc_projid_map_operations = {
2876         .open           = proc_projid_map_open,
2877         .write          = proc_projid_map_write,
2878         .read           = seq_read,
2879         .llseek         = seq_lseek,
2880         .release        = proc_id_map_release,
2881 };
2882
2883 static int proc_setgroups_open(struct inode *inode, struct file *file)
2884 {
2885         struct user_namespace *ns = NULL;
2886         struct task_struct *task;
2887         int ret;
2888
2889         ret = -ESRCH;
2890         task = get_proc_task(inode);
2891         if (task) {
2892                 rcu_read_lock();
2893                 ns = get_user_ns(task_cred_xxx(task, user_ns));
2894                 rcu_read_unlock();
2895                 put_task_struct(task);
2896         }
2897         if (!ns)
2898                 goto err;
2899
2900         if (file->f_mode & FMODE_WRITE) {
2901                 ret = -EACCES;
2902                 if (!ns_capable(ns, CAP_SYS_ADMIN))
2903                         goto err_put_ns;
2904         }
2905
2906         ret = single_open(file, &proc_setgroups_show, ns);
2907         if (ret)
2908                 goto err_put_ns;
2909
2910         return 0;
2911 err_put_ns:
2912         put_user_ns(ns);
2913 err:
2914         return ret;
2915 }
2916
2917 static int proc_setgroups_release(struct inode *inode, struct file *file)
2918 {
2919         struct seq_file *seq = file->private_data;
2920         struct user_namespace *ns = seq->private;
2921         int ret = single_release(inode, file);
2922         put_user_ns(ns);
2923         return ret;
2924 }
2925
2926 static const struct file_operations proc_setgroups_operations = {
2927         .open           = proc_setgroups_open,
2928         .write          = proc_setgroups_write,
2929         .read           = seq_read,
2930         .llseek         = seq_lseek,
2931         .release        = proc_setgroups_release,
2932 };
2933 #endif /* CONFIG_USER_NS */
2934
2935 static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
2936                                 struct pid *pid, struct task_struct *task)
2937 {
2938         int err = lock_trace(task);
2939         if (!err) {
2940                 seq_printf(m, "%08x\n", task->personality);
2941                 unlock_trace(task);
2942         }
2943         return err;
2944 }
2945
2946 #ifdef CONFIG_LIVEPATCH
2947 static int proc_pid_patch_state(struct seq_file *m, struct pid_namespace *ns,
2948                                 struct pid *pid, struct task_struct *task)
2949 {
2950         seq_printf(m, "%d\n", task->patch_state);
2951         return 0;
2952 }
2953 #endif /* CONFIG_LIVEPATCH */
2954
2955 /*
2956  * Thread groups
2957  */
2958 static const struct file_operations proc_task_operations;
2959 static const struct inode_operations proc_task_inode_operations;
2960
2961 static const struct pid_entry tgid_base_stuff[] = {
2962         DIR("task",       S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
2963         DIR("fd",         S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
2964         DIR("map_files",  S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
2965         DIR("fdinfo",     S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
2966         DIR("ns",         S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
2967 #ifdef CONFIG_NET
2968         DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
2969 #endif
2970         REG("environ",    S_IRUSR, proc_environ_operations),
2971         REG("auxv",       S_IRUSR, proc_auxv_operations),
2972         ONE("status",     S_IRUGO, proc_pid_status),
2973         ONE("personality", S_IRUSR, proc_pid_personality),
2974         ONE("limits",     S_IRUGO, proc_pid_limits),
2975 #ifdef CONFIG_SCHED_DEBUG
2976         REG("sched",      S_IRUGO|S_IWUSR, proc_pid_sched_operations),
2977 #endif
2978 #ifdef CONFIG_SCHED_AUTOGROUP
2979         REG("autogroup",  S_IRUGO|S_IWUSR, proc_pid_sched_autogroup_operations),
2980 #endif
2981         REG("comm",      S_IRUGO|S_IWUSR, proc_pid_set_comm_operations),
2982 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
2983         ONE("syscall",    S_IRUSR, proc_pid_syscall),
2984 #endif
2985         REG("cmdline",    S_IRUGO, proc_pid_cmdline_ops),
2986         ONE("stat",       S_IRUGO, proc_tgid_stat),
2987         ONE("statm",      S_IRUGO, proc_pid_statm),
2988         REG("maps",       S_IRUGO, proc_pid_maps_operations),
2989 #ifdef CONFIG_NUMA
2990         REG("numa_maps",  S_IRUGO, proc_pid_numa_maps_operations),
2991 #endif
2992         REG("mem",        S_IRUSR|S_IWUSR, proc_mem_operations),
2993         LNK("cwd",        proc_cwd_link),
2994         LNK("root",       proc_root_link),
2995         LNK("exe",        proc_exe_link),
2996         REG("mounts",     S_IRUGO, proc_mounts_operations),
2997         REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
2998         REG("mountstats", S_IRUSR, proc_mountstats_operations),
2999 #ifdef CONFIG_PROC_PAGE_MONITOR
3000         REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3001         REG("smaps",      S_IRUGO, proc_pid_smaps_operations),
3002         REG("smaps_rollup", S_IRUGO, proc_pid_smaps_rollup_operations),
3003         REG("pagemap",    S_IRUSR, proc_pagemap_operations),
3004 #endif
3005 #ifdef CONFIG_SECURITY
3006         DIR("attr",       S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3007 #endif
3008 #ifdef CONFIG_KALLSYMS
3009         ONE("wchan",      S_IRUGO, proc_pid_wchan),
3010 #endif
3011 #ifdef CONFIG_STACKTRACE
3012         ONE("stack",      S_IRUSR, proc_pid_stack),
3013 #endif
3014 #ifdef CONFIG_SCHED_INFO
3015         ONE("schedstat",  S_IRUGO, proc_pid_schedstat),
3016 #endif
3017 #ifdef CONFIG_LATENCYTOP
3018         REG("latency",  S_IRUGO, proc_lstats_operations),
3019 #endif
3020 #ifdef CONFIG_PROC_PID_CPUSET
3021         ONE("cpuset",     S_IRUGO, proc_cpuset_show),
3022 #endif
3023 #ifdef CONFIG_CGROUPS
3024         ONE("cgroup",  S_IRUGO, proc_cgroup_show),
3025 #endif
3026         ONE("oom_score",  S_IRUGO, proc_oom_score),
3027         REG("oom_adj",    S_IRUGO|S_IWUSR, proc_oom_adj_operations),
3028         REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3029 #ifdef CONFIG_AUDITSYSCALL
3030         REG("loginuid",   S_IWUSR|S_IRUGO, proc_loginuid_operations),
3031         REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3032 #endif
3033 #ifdef CONFIG_FAULT_INJECTION
3034         REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3035         REG("fail-nth", 0644, proc_fail_nth_operations),
3036 #endif
3037 #ifdef CONFIG_ELF_CORE
3038         REG("coredump_filter", S_IRUGO|S_IWUSR, proc_coredump_filter_operations),
3039 #endif
3040 #ifdef CONFIG_TASK_IO_ACCOUNTING
3041         ONE("io",       S_IRUSR, proc_tgid_io_accounting),
3042 #endif
3043 #ifdef CONFIG_USER_NS
3044         REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3045         REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3046         REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
3047         REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
3048 #endif
3049 #if defined(CONFIG_CHECKPOINT_RESTORE) && defined(CONFIG_POSIX_TIMERS)
3050         REG("timers",     S_IRUGO, proc_timers_operations),
3051 #endif
3052         REG("timerslack_ns", S_IRUGO|S_IWUGO, proc_pid_set_timerslack_ns_operations),
3053 #ifdef CONFIG_LIVEPATCH
3054         ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
3055 #endif
3056 };
3057
3058 static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx)
3059 {
3060         return proc_pident_readdir(file, ctx,
3061                                    tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3062 }
3063
3064 static const struct file_operations proc_tgid_base_operations = {
3065         .read           = generic_read_dir,
3066         .iterate_shared = proc_tgid_base_readdir,
3067         .llseek         = generic_file_llseek,
3068 };
3069
3070 static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3071 {
3072         return proc_pident_lookup(dir, dentry,
3073                                   tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3074 }
3075
3076 static const struct inode_operations proc_tgid_base_inode_operations = {
3077         .lookup         = proc_tgid_base_lookup,
3078         .getattr        = pid_getattr,
3079         .setattr        = proc_setattr,
3080         .permission     = proc_pid_permission,
3081 };
3082
3083 static void proc_flush_task_mnt(struct vfsmount *mnt, pid_t pid, pid_t tgid)
3084 {
3085         struct dentry *dentry, *leader, *dir;
3086         char buf[10 + 1];
3087         struct qstr name;
3088
3089         name.name = buf;
3090         name.len = snprintf(buf, sizeof(buf), "%u", pid);
3091         /* no ->d_hash() rejects on procfs */
3092         dentry = d_hash_and_lookup(mnt->mnt_root, &name);
3093         if (dentry) {
3094                 d_invalidate(dentry);
3095                 dput(dentry);
3096         }
3097
3098         if (pid == tgid)
3099                 return;
3100
3101         name.name = buf;
3102         name.len = snprintf(buf, sizeof(buf), "%u", tgid);
3103         leader = d_hash_and_lookup(mnt->mnt_root, &name);
3104         if (!leader)
3105                 goto out;
3106
3107         name.name = "task";
3108         name.len = strlen(name.name);
3109         dir = d_hash_and_lookup(leader, &name);
3110         if (!dir)
3111                 goto out_put_leader;
3112
3113         name.name = buf;
3114         name.len = snprintf(buf, sizeof(buf), "%u", pid);
3115         dentry = d_hash_and_lookup(dir, &name);
3116         if (dentry) {
3117                 d_invalidate(dentry);
3118                 dput(dentry);
3119         }
3120
3121         dput(dir);
3122 out_put_leader:
3123         dput(leader);
3124 out:
3125         return;
3126 }
3127
3128 /**
3129  * proc_flush_task -  Remove dcache entries for @task from the /proc dcache.
3130  * @task: task that should be flushed.
3131  *
3132  * When flushing dentries from proc, one needs to flush them from global
3133  * proc (proc_mnt) and from all the namespaces' procs this task was seen
3134  * in. This call is supposed to do all of this job.
3135  *
3136  * Looks in the dcache for
3137  * /proc/@pid
3138  * /proc/@tgid/task/@pid
3139  * if either directory is present flushes it and all of it'ts children
3140  * from the dcache.
3141  *
3142  * It is safe and reasonable to cache /proc entries for a task until
3143  * that task exits.  After that they just clog up the dcache with
3144  * useless entries, possibly causing useful dcache entries to be
3145  * flushed instead.  This routine is proved to flush those useless
3146  * dcache entries at process exit time.
3147  *
3148  * NOTE: This routine is just an optimization so it does not guarantee
3149  *       that no dcache entries will exist at process exit time it
3150  *       just makes it very unlikely that any will persist.
3151  */
3152
3153 void proc_flush_task(struct task_struct *task)
3154 {
3155         int i;
3156         struct pid *pid, *tgid;
3157         struct upid *upid;
3158
3159         pid = task_pid(task);
3160         tgid = task_tgid(task);
3161
3162         for (i = 0; i <= pid->level; i++) {
3163                 upid = &pid->numbers[i];
3164                 proc_flush_task_mnt(upid->ns->proc_mnt, upid->nr,
3165                                         tgid->numbers[i].nr);
3166         }
3167 }
3168
3169 static struct dentry *proc_pid_instantiate(struct dentry * dentry,
3170                                    struct task_struct *task, const void *ptr)
3171 {
3172         struct inode *inode;
3173
3174         inode = proc_pid_make_inode(dentry->d_sb, task, S_IFDIR | S_IRUGO | S_IXUGO);
3175         if (!inode)
3176                 return ERR_PTR(-ENOENT);
3177
3178         inode->i_op = &proc_tgid_base_inode_operations;
3179         inode->i_fop = &proc_tgid_base_operations;
3180         inode->i_flags|=S_IMMUTABLE;
3181
3182         set_nlink(inode, nlink_tgid);
3183         pid_update_inode(task, inode);
3184
3185         d_set_d_op(dentry, &pid_dentry_operations);
3186         return d_splice_alias(inode, dentry);
3187 }
3188
3189 struct dentry *proc_pid_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
3190 {
3191         struct task_struct *task;
3192         unsigned tgid;
3193         struct pid_namespace *ns;
3194         struct dentry *result = ERR_PTR(-ENOENT);
3195
3196         tgid = name_to_int(&dentry->d_name);
3197         if (tgid == ~0U)
3198                 goto out;
3199
3200         ns = dentry->d_sb->s_fs_info;
3201         rcu_read_lock();
3202         task = find_task_by_pid_ns(tgid, ns);
3203         if (task)
3204                 get_task_struct(task);
3205         rcu_read_unlock();
3206         if (!task)
3207                 goto out;
3208
3209         result = proc_pid_instantiate(dentry, task, NULL);
3210         put_task_struct(task);
3211 out:
3212         return result;
3213 }
3214
3215 /*
3216  * Find the first task with tgid >= tgid
3217  *
3218  */
3219 struct tgid_iter {
3220         unsigned int tgid;
3221         struct task_struct *task;
3222 };
3223 static struct tgid_iter next_tgid(struct pid_namespace *ns, struct tgid_iter iter)
3224 {
3225         struct pid *pid;
3226
3227         if (iter.task)
3228                 put_task_struct(iter.task);
3229         rcu_read_lock();
3230 retry:
3231         iter.task = NULL;
3232         pid = find_ge_pid(iter.tgid, ns);
3233         if (pid) {
3234                 iter.tgid = pid_nr_ns(pid, ns);
3235                 iter.task = pid_task(pid, PIDTYPE_PID);
3236                 /* What we to know is if the pid we have find is the
3237                  * pid of a thread_group_leader.  Testing for task
3238                  * being a thread_group_leader is the obvious thing
3239                  * todo but there is a window when it fails, due to
3240                  * the pid transfer logic in de_thread.
3241                  *
3242                  * So we perform the straight forward test of seeing
3243                  * if the pid we have found is the pid of a thread
3244                  * group leader, and don't worry if the task we have
3245                  * found doesn't happen to be a thread group leader.
3246                  * As we don't care in the case of readdir.
3247                  */
3248                 if (!iter.task || !has_group_leader_pid(iter.task)) {
3249                         iter.tgid += 1;
3250                         goto retry;
3251                 }
3252                 get_task_struct(iter.task);
3253         }
3254         rcu_read_unlock();
3255         return iter;
3256 }
3257
3258 #define TGID_OFFSET (FIRST_PROCESS_ENTRY + 2)
3259
3260 /* for the /proc/ directory itself, after non-process stuff has been done */
3261 int proc_pid_readdir(struct file *file, struct dir_context *ctx)
3262 {
3263         struct tgid_iter iter;
3264         struct pid_namespace *ns = proc_pid_ns(file_inode(file));
3265         loff_t pos = ctx->pos;
3266
3267         if (pos >= PID_MAX_LIMIT + TGID_OFFSET)
3268                 return 0;
3269
3270         if (pos == TGID_OFFSET - 2) {
3271                 struct inode *inode = d_inode(ns->proc_self);
3272                 if (!dir_emit(ctx, "self", 4, inode->i_ino, DT_LNK))
3273                         return 0;
3274                 ctx->pos = pos = pos + 1;
3275         }
3276         if (pos == TGID_OFFSET - 1) {
3277                 struct inode *inode = d_inode(ns->proc_thread_self);
3278                 if (!dir_emit(ctx, "thread-self", 11, inode->i_ino, DT_LNK))
3279                         return 0;
3280                 ctx->pos = pos = pos + 1;
3281         }
3282         iter.tgid = pos - TGID_OFFSET;
3283         iter.task = NULL;
3284         for (iter = next_tgid(ns, iter);
3285              iter.task;
3286              iter.tgid += 1, iter = next_tgid(ns, iter)) {
3287                 char name[10 + 1];
3288                 unsigned int len;
3289
3290                 cond_resched();
3291                 if (!has_pid_permissions(ns, iter.task, HIDEPID_INVISIBLE))
3292                         continue;
3293
3294                 len = snprintf(name, sizeof(name), "%u", iter.tgid);
3295                 ctx->pos = iter.tgid + TGID_OFFSET;
3296                 if (!proc_fill_cache(file, ctx, name, len,
3297                                      proc_pid_instantiate, iter.task, NULL)) {
3298                         put_task_struct(iter.task);
3299                         return 0;
3300                 }
3301         }
3302         ctx->pos = PID_MAX_LIMIT + TGID_OFFSET;
3303         return 0;
3304 }
3305
3306 /*
3307  * proc_tid_comm_permission is a special permission function exclusively
3308  * used for the node /proc/<pid>/task/<tid>/comm.
3309  * It bypasses generic permission checks in the case where a task of the same
3310  * task group attempts to access the node.
3311  * The rationale behind this is that glibc and bionic access this node for
3312  * cross thread naming (pthread_set/getname_np(!self)). However, if
3313  * PR_SET_DUMPABLE gets set to 0 this node among others becomes uid=0 gid=0,
3314  * which locks out the cross thread naming implementation.
3315  * This function makes sure that the node is always accessible for members of
3316  * same thread group.
3317  */
3318 static int proc_tid_comm_permission(struct inode *inode, int mask)
3319 {
3320         bool is_same_tgroup;
3321         struct task_struct *task;
3322
3323         task = get_proc_task(inode);
3324         if (!task)
3325                 return -ESRCH;
3326         is_same_tgroup = same_thread_group(current, task);
3327         put_task_struct(task);
3328
3329         if (likely(is_same_tgroup && !(mask & MAY_EXEC))) {
3330                 /* This file (/proc/<pid>/task/<tid>/comm) can always be
3331                  * read or written by the members of the corresponding
3332                  * thread group.
3333                  */
3334                 return 0;
3335         }
3336
3337         return generic_permission(inode, mask);
3338 }
3339
3340 static const struct inode_operations proc_tid_comm_inode_operations = {
3341                 .permission = proc_tid_comm_permission,
3342 };
3343
3344 /*
3345  * Tasks
3346  */
3347 static const struct pid_entry tid_base_stuff[] = {
3348         DIR("fd",        S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
3349         DIR("fdinfo",    S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
3350         DIR("ns",        S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
3351 #ifdef CONFIG_NET
3352         DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
3353 #endif
3354         REG("environ",   S_IRUSR, proc_environ_operations),
3355         REG("auxv",      S_IRUSR, proc_auxv_operations),
3356         ONE("status",    S_IRUGO, proc_pid_status),
3357         ONE("personality", S_IRUSR, proc_pid_personality),
3358         ONE("limits",    S_IRUGO, proc_pid_limits),
3359 #ifdef CONFIG_SCHED_DEBUG
3360         REG("sched",     S_IRUGO|S_IWUSR, proc_pid_sched_operations),
3361 #endif
3362         NOD("comm",      S_IFREG|S_IRUGO|S_IWUSR,
3363                          &proc_tid_comm_inode_operations,
3364                          &proc_pid_set_comm_operations, {}),
3365 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
3366         ONE("syscall",   S_IRUSR, proc_pid_syscall),
3367 #endif
3368         REG("cmdline",   S_IRUGO, proc_pid_cmdline_ops),
3369         ONE("stat",      S_IRUGO, proc_tid_stat),
3370         ONE("statm",     S_IRUGO, proc_pid_statm),
3371         REG("maps",      S_IRUGO, proc_pid_maps_operations),
3372 #ifdef CONFIG_PROC_CHILDREN
3373         REG("children",  S_IRUGO, proc_tid_children_operations),
3374 #endif
3375 #ifdef CONFIG_NUMA
3376         REG("numa_maps", S_IRUGO, proc_pid_numa_maps_operations),
3377 #endif
3378         REG("mem",       S_IRUSR|S_IWUSR, proc_mem_operations),
3379         LNK("cwd",       proc_cwd_link),
3380         LNK("root",      proc_root_link),
3381         LNK("exe",       proc_exe_link),
3382         REG("mounts",    S_IRUGO, proc_mounts_operations),
3383         REG("mountinfo",  S_IRUGO, proc_mountinfo_operations),
3384 #ifdef CONFIG_PROC_PAGE_MONITOR
3385         REG("clear_refs", S_IWUSR, proc_clear_refs_operations),
3386         REG("smaps",     S_IRUGO, proc_pid_smaps_operations),
3387         REG("smaps_rollup", S_IRUGO, proc_pid_smaps_rollup_operations),
3388         REG("pagemap",    S_IRUSR, proc_pagemap_operations),
3389 #endif
3390 #ifdef CONFIG_SECURITY
3391         DIR("attr",      S_IRUGO|S_IXUGO, proc_attr_dir_inode_operations, proc_attr_dir_operations),
3392 #endif
3393 #ifdef CONFIG_KALLSYMS
3394         ONE("wchan",     S_IRUGO, proc_pid_wchan),
3395 #endif
3396 #ifdef CONFIG_STACKTRACE
3397         ONE("stack",      S_IRUSR, proc_pid_stack),
3398 #endif
3399 #ifdef CONFIG_SCHED_INFO
3400         ONE("schedstat", S_IRUGO, proc_pid_schedstat),
3401 #endif
3402 #ifdef CONFIG_LATENCYTOP
3403         REG("latency",  S_IRUGO, proc_lstats_operations),
3404 #endif
3405 #ifdef CONFIG_PROC_PID_CPUSET
3406         ONE("cpuset",    S_IRUGO, proc_cpuset_show),
3407 #endif
3408 #ifdef CONFIG_CGROUPS
3409         ONE("cgroup",  S_IRUGO, proc_cgroup_show),
3410 #endif
3411         ONE("oom_score", S_IRUGO, proc_oom_score),
3412         REG("oom_adj",   S_IRUGO|S_IWUSR, proc_oom_adj_operations),
3413         REG("oom_score_adj", S_IRUGO|S_IWUSR, proc_oom_score_adj_operations),
3414 #ifdef CONFIG_AUDITSYSCALL
3415         REG("loginuid",  S_IWUSR|S_IRUGO, proc_loginuid_operations),
3416         REG("sessionid",  S_IRUGO, proc_sessionid_operations),
3417 #endif
3418 #ifdef CONFIG_FAULT_INJECTION
3419         REG("make-it-fail", S_IRUGO|S_IWUSR, proc_fault_inject_operations),
3420         REG("fail-nth", 0644, proc_fail_nth_operations),
3421 #endif
3422 #ifdef CONFIG_TASK_IO_ACCOUNTING
3423         ONE("io",       S_IRUSR, proc_tid_io_accounting),
3424 #endif
3425 #ifdef CONFIG_USER_NS
3426         REG("uid_map",    S_IRUGO|S_IWUSR, proc_uid_map_operations),
3427         REG("gid_map",    S_IRUGO|S_IWUSR, proc_gid_map_operations),
3428         REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
3429         REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
3430 #endif
3431 #ifdef CONFIG_LIVEPATCH
3432         ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
3433 #endif
3434 };
3435
3436 static int proc_tid_base_readdir(struct file *file, struct dir_context *ctx)
3437 {
3438         return proc_pident_readdir(file, ctx,
3439                                    tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3440 }
3441
3442 static struct dentry *proc_tid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
3443 {
3444         return proc_pident_lookup(dir, dentry,
3445                                   tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3446 }
3447
3448 static const struct file_operations proc_tid_base_operations = {
3449         .read           = generic_read_dir,
3450         .iterate_shared = proc_tid_base_readdir,
3451         .llseek         = generic_file_llseek,
3452 };
3453
3454 static const struct inode_operations proc_tid_base_inode_operations = {
3455         .lookup         = proc_tid_base_lookup,
3456         .getattr        = pid_getattr,
3457         .setattr        = proc_setattr,
3458 };
3459
3460 static struct dentry *proc_task_instantiate(struct dentry *dentry,
3461         struct task_struct *task, const void *ptr)
3462 {
3463         struct inode *inode;
3464         inode = proc_pid_make_inode(dentry->d_sb, task, S_IFDIR | S_IRUGO | S_IXUGO);
3465         if (!inode)
3466                 return ERR_PTR(-ENOENT);
3467
3468         inode->i_op = &proc_tid_base_inode_operations;
3469         inode->i_fop = &proc_tid_base_operations;
3470         inode->i_flags |= S_IMMUTABLE;
3471
3472         set_nlink(inode, nlink_tid);
3473         pid_update_inode(task, inode);
3474
3475         d_set_d_op(dentry, &pid_dentry_operations);
3476         return d_splice_alias(inode, dentry);
3477 }
3478
3479 static struct dentry *proc_task_lookup(struct inode *dir, struct dentry * dentry, unsigned int flags)
3480 {
3481         struct task_struct *task;
3482         struct task_struct *leader = get_proc_task(dir);
3483         unsigned tid;
3484         struct pid_namespace *ns;
3485         struct dentry *result = ERR_PTR(-ENOENT);
3486
3487         if (!leader)
3488                 goto out_no_task;
3489
3490         tid = name_to_int(&dentry->d_name);
3491         if (tid == ~0U)
3492                 goto out;
3493
3494         ns = dentry->d_sb->s_fs_info;
3495         rcu_read_lock();
3496         task = find_task_by_pid_ns(tid, ns);
3497         if (task)
3498                 get_task_struct(task);
3499         rcu_read_unlock();
3500         if (!task)
3501                 goto out;
3502         if (!same_thread_group(leader, task))
3503                 goto out_drop_task;
3504
3505         result = proc_task_instantiate(dentry, task, NULL);
3506 out_drop_task:
3507         put_task_struct(task);
3508 out:
3509         put_task_struct(leader);
3510 out_no_task:
3511         return result;
3512 }
3513
3514 /*
3515  * Find the first tid of a thread group to return to user space.
3516  *
3517  * Usually this is just the thread group leader, but if the users
3518  * buffer was too small or there was a seek into the middle of the
3519  * directory we have more work todo.
3520  *
3521  * In the case of a short read we start with find_task_by_pid.
3522  *
3523  * In the case of a seek we start with the leader and walk nr
3524  * threads past it.
3525  */
3526 static struct task_struct *first_tid(struct pid *pid, int tid, loff_t f_pos,
3527                                         struct pid_namespace *ns)
3528 {
3529         struct task_struct *pos, *task;
3530         unsigned long nr = f_pos;
3531
3532         if (nr != f_pos)        /* 32bit overflow? */
3533                 return NULL;
3534
3535         rcu_read_lock();
3536         task = pid_task(pid, PIDTYPE_PID);
3537         if (!task)
3538                 goto fail;
3539
3540         /* Attempt to start with the tid of a thread */
3541         if (tid && nr) {
3542                 pos = find_task_by_pid_ns(tid, ns);
3543                 if (pos && same_thread_group(pos, task))
3544                         goto found;
3545         }
3546
3547         /* If nr exceeds the number of threads there is nothing todo */
3548         if (nr >= get_nr_threads(task))
3549                 goto fail;
3550
3551         /* If we haven't found our starting place yet start
3552          * with the leader and walk nr threads forward.
3553          */
3554         pos = task = task->group_leader;
3555         do {
3556                 if (!nr--)
3557                         goto found;
3558         } while_each_thread(task, pos);
3559 fail:
3560         pos = NULL;
3561         goto out;
3562 found:
3563         get_task_struct(pos);
3564 out:
3565         rcu_read_unlock();
3566         return pos;
3567 }
3568
3569 /*
3570  * Find the next thread in the thread list.
3571  * Return NULL if there is an error or no next thread.
3572  *
3573  * The reference to the input task_struct is released.
3574  */
3575 static struct task_struct *next_tid(struct task_struct *start)
3576 {
3577         struct task_struct *pos = NULL;
3578         rcu_read_lock();
3579         if (pid_alive(start)) {
3580                 pos = next_thread(start);
3581                 if (thread_group_leader(pos))
3582                         pos = NULL;
3583                 else
3584                         get_task_struct(pos);
3585         }
3586         rcu_read_unlock();
3587         put_task_struct(start);
3588         return pos;
3589 }
3590
3591 /* for the /proc/TGID/task/ directories */
3592 static int proc_task_readdir(struct file *file, struct dir_context *ctx)
3593 {
3594         struct inode *inode = file_inode(file);
3595         struct task_struct *task;
3596         struct pid_namespace *ns;
3597         int tid;
3598
3599         if (proc_inode_is_dead(inode))
3600                 return -ENOENT;
3601
3602         if (!dir_emit_dots(file, ctx))
3603                 return 0;
3604
3605         /* f_version caches the tgid value that the last readdir call couldn't
3606          * return. lseek aka telldir automagically resets f_version to 0.
3607          */
3608         ns = proc_pid_ns(inode);
3609         tid = (int)file->f_version;
3610         file->f_version = 0;
3611         for (task = first_tid(proc_pid(inode), tid, ctx->pos - 2, ns);
3612              task;
3613              task = next_tid(task), ctx->pos++) {
3614                 char name[10 + 1];
3615                 unsigned int len;
3616                 tid = task_pid_nr_ns(task, ns);
3617                 len = snprintf(name, sizeof(name), "%u", tid);
3618                 if (!proc_fill_cache(file, ctx, name, len,
3619                                 proc_task_instantiate, task, NULL)) {
3620                         /* returning this tgid failed, save it as the first
3621                          * pid for the next readir call */
3622                         file->f_version = (u64)tid;
3623                         put_task_struct(task);
3624                         break;
3625                 }
3626         }
3627
3628         return 0;
3629 }
3630
3631 static int proc_task_getattr(const struct path *path, struct kstat *stat,
3632                              u32 request_mask, unsigned int query_flags)
3633 {
3634         struct inode *inode = d_inode(path->dentry);
3635         struct task_struct *p = get_proc_task(inode);
3636         generic_fillattr(inode, stat);
3637
3638         if (p) {
3639                 stat->nlink += get_nr_threads(p);
3640                 put_task_struct(p);
3641         }
3642
3643         return 0;
3644 }
3645
3646 static const struct inode_operations proc_task_inode_operations = {
3647         .lookup         = proc_task_lookup,
3648         .getattr        = proc_task_getattr,
3649         .setattr        = proc_setattr,
3650         .permission     = proc_pid_permission,
3651 };
3652
3653 static const struct file_operations proc_task_operations = {
3654         .read           = generic_read_dir,
3655         .iterate_shared = proc_task_readdir,
3656         .llseek         = generic_file_llseek,
3657 };
3658
3659 void __init set_proc_pid_nlink(void)
3660 {
3661         nlink_tid = pid_entry_nlink(tid_base_stuff, ARRAY_SIZE(tid_base_stuff));
3662         nlink_tgid = pid_entry_nlink(tgid_base_stuff, ARRAY_SIZE(tgid_base_stuff));
3663 }