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