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