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