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