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