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