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