OSDN Git Service

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