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