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