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