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