xref: /linux/fs/pidfs.c (revision a945535dfd21fb74be516ded5c8d053e922f0729)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/anon_inodes.h>
3 #include <linux/exportfs.h>
4 #include <linux/file.h>
5 #include <linux/fs.h>
6 #include <linux/cgroup.h>
7 #include <linux/magic.h>
8 #include <linux/mount.h>
9 #include <linux/pid.h>
10 #include <linux/pidfs.h>
11 #include <linux/pid_namespace.h>
12 #include <linux/poll.h>
13 #include <linux/proc_fs.h>
14 #include <linux/proc_ns.h>
15 #include <linux/pseudo_fs.h>
16 #include <linux/ptrace.h>
17 #include <linux/seq_file.h>
18 #include <uapi/linux/pidfd.h>
19 #include <linux/ipc_namespace.h>
20 #include <linux/time_namespace.h>
21 #include <linux/utsname.h>
22 #include <net/net_namespace.h>
23 #include <linux/coredump.h>
24 #include <linux/xattr.h>
25 
26 #include "internal.h"
27 #include "mount.h"
28 
29 #define PIDFS_PID_DEAD ERR_PTR(-ESRCH)
30 
31 static struct kmem_cache *pidfs_attr_cachep __ro_after_init;
32 static struct kmem_cache *pidfs_xattr_cachep __ro_after_init;
33 
34 static struct path pidfs_root_path = {};
35 
36 void pidfs_get_root(struct path *path)
37 {
38 	*path = pidfs_root_path;
39 	path_get(path);
40 }
41 
42 enum pidfs_attr_mask_bits {
43 	PIDFS_ATTR_BIT_EXIT	= 0,
44 	PIDFS_ATTR_BIT_COREDUMP	= 1,
45 };
46 
47 struct pidfs_attr {
48 	unsigned long attr_mask;
49 	struct simple_xattrs *xattrs;
50 	struct /* exit info */ {
51 		__u64 cgroupid;
52 		__s32 exit_code;
53 	};
54 	__u32 coredump_mask;
55 	__u32 coredump_signal;
56 };
57 
58 static struct rb_root pidfs_ino_tree = RB_ROOT;
59 
60 #if BITS_PER_LONG == 32
61 static inline unsigned long pidfs_ino(u64 ino)
62 {
63 	return lower_32_bits(ino);
64 }
65 
66 /* On 32 bit the generation number are the upper 32 bits. */
67 static inline u32 pidfs_gen(u64 ino)
68 {
69 	return upper_32_bits(ino);
70 }
71 
72 #else
73 
74 /* On 64 bit simply return ino. */
75 static inline unsigned long pidfs_ino(u64 ino)
76 {
77 	return ino;
78 }
79 
80 /* On 64 bit the generation number is 0. */
81 static inline u32 pidfs_gen(u64 ino)
82 {
83 	return 0;
84 }
85 #endif
86 
87 static int pidfs_ino_cmp(struct rb_node *a, const struct rb_node *b)
88 {
89 	struct pid *pid_a = rb_entry(a, struct pid, pidfs_node);
90 	struct pid *pid_b = rb_entry(b, struct pid, pidfs_node);
91 	u64 pid_ino_a = pid_a->ino;
92 	u64 pid_ino_b = pid_b->ino;
93 
94 	if (pid_ino_a < pid_ino_b)
95 		return -1;
96 	if (pid_ino_a > pid_ino_b)
97 		return 1;
98 	return 0;
99 }
100 
101 void pidfs_add_pid(struct pid *pid)
102 {
103 	static u64 pidfs_ino_nr = 2;
104 
105 	/*
106 	 * On 64 bit nothing special happens. The 64bit number assigned
107 	 * to struct pid is the inode number.
108 	 *
109 	 * On 32 bit the 64 bit number assigned to struct pid is split
110 	 * into two 32 bit numbers. The lower 32 bits are used as the
111 	 * inode number and the upper 32 bits are used as the inode
112 	 * generation number.
113 	 *
114 	 * On 32 bit pidfs_ino() will return the lower 32 bit. When
115 	 * pidfs_ino() returns zero a wrap around happened. When a
116 	 * wraparound happens the 64 bit number will be incremented by 2
117 	 * so inode numbering starts at 2 again.
118 	 *
119 	 * On 64 bit comparing two pidfds is as simple as comparing
120 	 * inode numbers.
121 	 *
122 	 * When a wraparound happens on 32 bit multiple pidfds with the
123 	 * same inode number are likely to exist (This isn't a problem
124 	 * since before pidfs pidfds used the anonymous inode meaning
125 	 * all pidfds had the same inode number.). Userspace can
126 	 * reconstruct the 64 bit identifier by retrieving both the
127 	 * inode number and the inode generation number to compare or
128 	 * use file handles.
129 	 */
130 	if (pidfs_ino(pidfs_ino_nr) == 0)
131 		pidfs_ino_nr += 2;
132 
133 	pid->ino = pidfs_ino_nr;
134 	pid->stashed = NULL;
135 	pid->attr = NULL;
136 	pidfs_ino_nr++;
137 
138 	write_seqcount_begin(&pidmap_lock_seq);
139 	rb_find_add_rcu(&pid->pidfs_node, &pidfs_ino_tree, pidfs_ino_cmp);
140 	write_seqcount_end(&pidmap_lock_seq);
141 }
142 
143 void pidfs_remove_pid(struct pid *pid)
144 {
145 	write_seqcount_begin(&pidmap_lock_seq);
146 	rb_erase(&pid->pidfs_node, &pidfs_ino_tree);
147 	write_seqcount_end(&pidmap_lock_seq);
148 }
149 
150 void pidfs_free_pid(struct pid *pid)
151 {
152 	struct pidfs_attr *attr __free(kfree) = no_free_ptr(pid->attr);
153 	struct simple_xattrs *xattrs __free(kfree) = NULL;
154 
155 	/*
156 	 * Any dentry must've been wiped from the pid by now.
157 	 * Otherwise there's a reference count bug.
158 	 */
159 	VFS_WARN_ON_ONCE(pid->stashed);
160 
161 	/*
162 	 * This if an error occurred during e.g., task creation that
163 	 * causes us to never go through the exit path.
164 	 */
165 	if (unlikely(!attr))
166 		return;
167 
168 	/* This never had a pidfd created. */
169 	if (IS_ERR(attr))
170 		return;
171 
172 	xattrs = no_free_ptr(attr->xattrs);
173 	if (xattrs)
174 		simple_xattrs_free(xattrs, NULL);
175 }
176 
177 #ifdef CONFIG_PROC_FS
178 /**
179  * pidfd_show_fdinfo - print information about a pidfd
180  * @m: proc fdinfo file
181  * @f: file referencing a pidfd
182  *
183  * Pid:
184  * This function will print the pid that a given pidfd refers to in the
185  * pid namespace of the procfs instance.
186  * If the pid namespace of the process is not a descendant of the pid
187  * namespace of the procfs instance 0 will be shown as its pid. This is
188  * similar to calling getppid() on a process whose parent is outside of
189  * its pid namespace.
190  *
191  * NSpid:
192  * If pid namespaces are supported then this function will also print
193  * the pid of a given pidfd refers to for all descendant pid namespaces
194  * starting from the current pid namespace of the instance, i.e. the
195  * Pid field and the first entry in the NSpid field will be identical.
196  * If the pid namespace of the process is not a descendant of the pid
197  * namespace of the procfs instance 0 will be shown as its first NSpid
198  * entry and no others will be shown.
199  * Note that this differs from the Pid and NSpid fields in
200  * /proc/<pid>/status where Pid and NSpid are always shown relative to
201  * the  pid namespace of the procfs instance. The difference becomes
202  * obvious when sending around a pidfd between pid namespaces from a
203  * different branch of the tree, i.e. where no ancestral relation is
204  * present between the pid namespaces:
205  * - create two new pid namespaces ns1 and ns2 in the initial pid
206  *   namespace (also take care to create new mount namespaces in the
207  *   new pid namespace and mount procfs)
208  * - create a process with a pidfd in ns1
209  * - send pidfd from ns1 to ns2
210  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
211  *   have exactly one entry, which is 0
212  */
213 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
214 {
215 	struct pid *pid = pidfd_pid(f);
216 	struct pid_namespace *ns;
217 	pid_t nr = -1;
218 
219 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
220 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
221 		nr = pid_nr_ns(pid, ns);
222 	}
223 
224 	seq_put_decimal_ll(m, "Pid:\t", nr);
225 
226 #ifdef CONFIG_PID_NS
227 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
228 	if (nr > 0) {
229 		int i;
230 
231 		/* If nr is non-zero it means that 'pid' is valid and that
232 		 * ns, i.e. the pid namespace associated with the procfs
233 		 * instance, is in the pid namespace hierarchy of pid.
234 		 * Start at one below the already printed level.
235 		 */
236 		for (i = ns->level + 1; i <= pid->level; i++)
237 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
238 	}
239 #endif
240 	seq_putc(m, '\n');
241 }
242 #endif
243 
244 /*
245  * Poll support for process exit notification.
246  */
247 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
248 {
249 	struct pid *pid = pidfd_pid(file);
250 	struct task_struct *task;
251 	__poll_t poll_flags = 0;
252 
253 	poll_wait(file, &pid->wait_pidfd, pts);
254 	/*
255 	 * Don't wake waiters if the thread-group leader exited
256 	 * prematurely. They either get notified when the last subthread
257 	 * exits or not at all if one of the remaining subthreads execs
258 	 * and assumes the struct pid of the old thread-group leader.
259 	 */
260 	guard(rcu)();
261 	task = pid_task(pid, PIDTYPE_PID);
262 	if (!task)
263 		poll_flags = EPOLLIN | EPOLLRDNORM | EPOLLHUP;
264 	else if (task->exit_state && !delay_group_leader(task))
265 		poll_flags = EPOLLIN | EPOLLRDNORM;
266 
267 	return poll_flags;
268 }
269 
270 static inline bool pid_in_current_pidns(const struct pid *pid)
271 {
272 	const struct pid_namespace *ns = task_active_pid_ns(current);
273 
274 	if (ns->level <= pid->level)
275 		return pid->numbers[ns->level].ns == ns;
276 
277 	return false;
278 }
279 
280 static __u32 pidfs_coredump_mask(unsigned long mm_flags)
281 {
282 	switch (__get_dumpable(mm_flags)) {
283 	case SUID_DUMP_USER:
284 		return PIDFD_COREDUMP_USER;
285 	case SUID_DUMP_ROOT:
286 		return PIDFD_COREDUMP_ROOT;
287 	case SUID_DUMP_DISABLE:
288 		return PIDFD_COREDUMP_SKIP;
289 	default:
290 		WARN_ON_ONCE(true);
291 	}
292 
293 	return 0;
294 }
295 
296 /* This must be updated whenever a new flag is added */
297 #define PIDFD_INFO_SUPPORTED (PIDFD_INFO_PID | \
298 			      PIDFD_INFO_CREDS | \
299 			      PIDFD_INFO_CGROUPID | \
300 			      PIDFD_INFO_EXIT | \
301 			      PIDFD_INFO_COREDUMP | \
302 			      PIDFD_INFO_SUPPORTED_MASK | \
303 			      PIDFD_INFO_COREDUMP_SIGNAL)
304 
305 static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg)
306 {
307 	struct pidfd_info __user *uinfo = (struct pidfd_info __user *)arg;
308 	struct task_struct *task __free(put_task) = NULL;
309 	struct pid *pid = pidfd_pid(file);
310 	size_t usize = _IOC_SIZE(cmd);
311 	struct pidfd_info kinfo = {};
312 	struct user_namespace *user_ns;
313 	struct pidfs_attr *attr;
314 	const struct cred *c;
315 	__u64 mask;
316 
317 	BUILD_BUG_ON(sizeof(struct pidfd_info) != PIDFD_INFO_SIZE_VER2);
318 
319 	if (!uinfo)
320 		return -EINVAL;
321 	if (usize < PIDFD_INFO_SIZE_VER0)
322 		return -EINVAL; /* First version, no smaller struct possible */
323 
324 	if (copy_from_user(&mask, &uinfo->mask, sizeof(mask)))
325 		return -EFAULT;
326 
327 	/*
328 	 * Restrict information retrieval to tasks within the caller's pid
329 	 * namespace hierarchy.
330 	 */
331 	if (!pid_in_current_pidns(pid))
332 		return -ESRCH;
333 
334 	attr = READ_ONCE(pid->attr);
335 	if (mask & PIDFD_INFO_EXIT) {
336 		if (test_bit(PIDFS_ATTR_BIT_EXIT, &attr->attr_mask)) {
337 			smp_rmb();
338 			kinfo.mask |= PIDFD_INFO_EXIT;
339 #ifdef CONFIG_CGROUPS
340 			kinfo.cgroupid = attr->cgroupid;
341 			kinfo.mask |= PIDFD_INFO_CGROUPID;
342 #endif
343 			kinfo.exit_code = attr->exit_code;
344 		}
345 	}
346 
347 	if (mask & PIDFD_INFO_COREDUMP) {
348 		if (test_bit(PIDFS_ATTR_BIT_COREDUMP, &attr->attr_mask)) {
349 			smp_rmb();
350 			kinfo.mask |= PIDFD_INFO_COREDUMP | PIDFD_INFO_COREDUMP_SIGNAL;
351 			kinfo.coredump_mask = attr->coredump_mask;
352 			kinfo.coredump_signal = attr->coredump_signal;
353 		}
354 	}
355 
356 	task = get_pid_task(pid, PIDTYPE_PID);
357 	if (!task) {
358 		/*
359 		 * If the task has already been reaped, only exit
360 		 * information is available
361 		 */
362 		if (!(mask & PIDFD_INFO_EXIT))
363 			return -ESRCH;
364 
365 		goto copy_out;
366 	}
367 
368 	c = get_task_cred(task);
369 	if (!c)
370 		return -ESRCH;
371 
372 	if ((mask & PIDFD_INFO_COREDUMP) && !kinfo.coredump_mask) {
373 		guard(task_lock)(task);
374 		if (task->mm) {
375 			unsigned long flags = __mm_flags_get_dumpable(task->mm);
376 
377 			kinfo.coredump_mask = pidfs_coredump_mask(flags);
378 			kinfo.mask |= PIDFD_INFO_COREDUMP;
379 			/* No coredump actually took place, so no coredump signal. */
380 		}
381 	}
382 
383 	/* Unconditionally return identifiers and credentials, the rest only on request */
384 
385 	user_ns = current_user_ns();
386 	kinfo.ruid = from_kuid_munged(user_ns, c->uid);
387 	kinfo.rgid = from_kgid_munged(user_ns, c->gid);
388 	kinfo.euid = from_kuid_munged(user_ns, c->euid);
389 	kinfo.egid = from_kgid_munged(user_ns, c->egid);
390 	kinfo.suid = from_kuid_munged(user_ns, c->suid);
391 	kinfo.sgid = from_kgid_munged(user_ns, c->sgid);
392 	kinfo.fsuid = from_kuid_munged(user_ns, c->fsuid);
393 	kinfo.fsgid = from_kgid_munged(user_ns, c->fsgid);
394 	kinfo.mask |= PIDFD_INFO_CREDS;
395 	put_cred(c);
396 
397 #ifdef CONFIG_CGROUPS
398 	if (!kinfo.cgroupid) {
399 		struct cgroup *cgrp;
400 
401 		rcu_read_lock();
402 		cgrp = task_dfl_cgroup(task);
403 		kinfo.cgroupid = cgroup_id(cgrp);
404 		kinfo.mask |= PIDFD_INFO_CGROUPID;
405 		rcu_read_unlock();
406 	}
407 #endif
408 
409 	/*
410 	 * Copy pid/tgid last, to reduce the chances the information might be
411 	 * stale. Note that it is not possible to ensure it will be valid as the
412 	 * task might return as soon as the copy_to_user finishes, but that's ok
413 	 * and userspace expects that might happen and can act accordingly, so
414 	 * this is just best-effort. What we can do however is checking that all
415 	 * the fields are set correctly, or return ESRCH to avoid providing
416 	 * incomplete information. */
417 
418 	kinfo.ppid = task_ppid_nr_ns(task, NULL);
419 	kinfo.tgid = task_tgid_vnr(task);
420 	kinfo.pid = task_pid_vnr(task);
421 	kinfo.mask |= PIDFD_INFO_PID;
422 
423 	if (kinfo.pid == 0 || kinfo.tgid == 0)
424 		return -ESRCH;
425 
426 copy_out:
427 	if (mask & PIDFD_INFO_SUPPORTED_MASK) {
428 		kinfo.mask |= PIDFD_INFO_SUPPORTED_MASK;
429 		kinfo.supported_mask = PIDFD_INFO_SUPPORTED;
430 	}
431 
432 	/* Are there bits in the return mask not present in PIDFD_INFO_SUPPORTED? */
433 	WARN_ON_ONCE(~PIDFD_INFO_SUPPORTED & kinfo.mask);
434 	/*
435 	 * If userspace and the kernel have the same struct size it can just
436 	 * be copied. If userspace provides an older struct, only the bits that
437 	 * userspace knows about will be copied. If userspace provides a new
438 	 * struct, only the bits that the kernel knows about will be copied.
439 	 */
440 	return copy_struct_to_user(uinfo, usize, &kinfo, sizeof(kinfo), NULL);
441 }
442 
443 static bool pidfs_ioctl_valid(unsigned int cmd)
444 {
445 	switch (cmd) {
446 	case FS_IOC_GETVERSION:
447 	case PIDFD_GET_CGROUP_NAMESPACE:
448 	case PIDFD_GET_IPC_NAMESPACE:
449 	case PIDFD_GET_MNT_NAMESPACE:
450 	case PIDFD_GET_NET_NAMESPACE:
451 	case PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE:
452 	case PIDFD_GET_TIME_NAMESPACE:
453 	case PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE:
454 	case PIDFD_GET_UTS_NAMESPACE:
455 	case PIDFD_GET_USER_NAMESPACE:
456 	case PIDFD_GET_PID_NAMESPACE:
457 		return true;
458 	}
459 
460 	/* Extensible ioctls require some more careful checks. */
461 	switch (_IOC_NR(cmd)) {
462 	case _IOC_NR(PIDFD_GET_INFO):
463 		/*
464 		 * Try to prevent performing a pidfd ioctl when someone
465 		 * erronously mistook the file descriptor for a pidfd.
466 		 * This is not perfect but will catch most cases.
467 		 */
468 		return extensible_ioctl_valid(cmd, PIDFD_GET_INFO, PIDFD_INFO_SIZE_VER0);
469 	}
470 
471 	return false;
472 }
473 
474 static long pidfd_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
475 {
476 	struct task_struct *task __free(put_task) = NULL;
477 	struct nsproxy *nsp __free(put_nsproxy) = NULL;
478 	struct ns_common *ns_common = NULL;
479 	struct pid_namespace *pid_ns;
480 
481 	if (!pidfs_ioctl_valid(cmd))
482 		return -ENOIOCTLCMD;
483 
484 	if (cmd == FS_IOC_GETVERSION) {
485 		if (!arg)
486 			return -EINVAL;
487 
488 		__u32 __user *argp = (__u32 __user *)arg;
489 		return put_user(file_inode(file)->i_generation, argp);
490 	}
491 
492 	/* Extensible IOCTL that does not open namespace FDs, take a shortcut */
493 	if (_IOC_NR(cmd) == _IOC_NR(PIDFD_GET_INFO))
494 		return pidfd_info(file, cmd, arg);
495 
496 	task = get_pid_task(pidfd_pid(file), PIDTYPE_PID);
497 	if (!task)
498 		return -ESRCH;
499 
500 	if (arg)
501 		return -EINVAL;
502 
503 	scoped_guard(task_lock, task) {
504 		nsp = task->nsproxy;
505 		if (nsp)
506 			get_nsproxy(nsp);
507 	}
508 	if (!nsp)
509 		return -ESRCH; /* just pretend it didn't exist */
510 
511 	/*
512 	 * We're trying to open a file descriptor to the namespace so perform a
513 	 * filesystem cred ptrace check. Also, we mirror nsfs behavior.
514 	 */
515 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
516 		return -EACCES;
517 
518 	switch (cmd) {
519 	/* Namespaces that hang of nsproxy. */
520 	case PIDFD_GET_CGROUP_NAMESPACE:
521 		if (IS_ENABLED(CONFIG_CGROUPS)) {
522 			get_cgroup_ns(nsp->cgroup_ns);
523 			ns_common = to_ns_common(nsp->cgroup_ns);
524 		}
525 		break;
526 	case PIDFD_GET_IPC_NAMESPACE:
527 		if (IS_ENABLED(CONFIG_IPC_NS)) {
528 			get_ipc_ns(nsp->ipc_ns);
529 			ns_common = to_ns_common(nsp->ipc_ns);
530 		}
531 		break;
532 	case PIDFD_GET_MNT_NAMESPACE:
533 		get_mnt_ns(nsp->mnt_ns);
534 		ns_common = to_ns_common(nsp->mnt_ns);
535 		break;
536 	case PIDFD_GET_NET_NAMESPACE:
537 		if (IS_ENABLED(CONFIG_NET_NS)) {
538 			ns_common = to_ns_common(nsp->net_ns);
539 			get_net_ns(ns_common);
540 		}
541 		break;
542 	case PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE:
543 		if (IS_ENABLED(CONFIG_PID_NS)) {
544 			get_pid_ns(nsp->pid_ns_for_children);
545 			ns_common = to_ns_common(nsp->pid_ns_for_children);
546 		}
547 		break;
548 	case PIDFD_GET_TIME_NAMESPACE:
549 		if (IS_ENABLED(CONFIG_TIME_NS)) {
550 			get_time_ns(nsp->time_ns);
551 			ns_common = to_ns_common(nsp->time_ns);
552 		}
553 		break;
554 	case PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE:
555 		if (IS_ENABLED(CONFIG_TIME_NS)) {
556 			get_time_ns(nsp->time_ns_for_children);
557 			ns_common = to_ns_common(nsp->time_ns_for_children);
558 		}
559 		break;
560 	case PIDFD_GET_UTS_NAMESPACE:
561 		if (IS_ENABLED(CONFIG_UTS_NS)) {
562 			get_uts_ns(nsp->uts_ns);
563 			ns_common = to_ns_common(nsp->uts_ns);
564 		}
565 		break;
566 	/* Namespaces that don't hang of nsproxy. */
567 	case PIDFD_GET_USER_NAMESPACE:
568 		if (IS_ENABLED(CONFIG_USER_NS)) {
569 			rcu_read_lock();
570 			ns_common = to_ns_common(get_user_ns(task_cred_xxx(task, user_ns)));
571 			rcu_read_unlock();
572 		}
573 		break;
574 	case PIDFD_GET_PID_NAMESPACE:
575 		if (IS_ENABLED(CONFIG_PID_NS)) {
576 			rcu_read_lock();
577 			pid_ns = task_active_pid_ns(task);
578 			if (pid_ns)
579 				ns_common = to_ns_common(get_pid_ns(pid_ns));
580 			rcu_read_unlock();
581 		}
582 		break;
583 	default:
584 		return -ENOIOCTLCMD;
585 	}
586 
587 	if (!ns_common)
588 		return -EOPNOTSUPP;
589 
590 	/* open_namespace() unconditionally consumes the reference */
591 	return open_namespace(ns_common);
592 }
593 
594 static const struct file_operations pidfs_file_operations = {
595 	.poll		= pidfd_poll,
596 #ifdef CONFIG_PROC_FS
597 	.show_fdinfo	= pidfd_show_fdinfo,
598 #endif
599 	.unlocked_ioctl	= pidfd_ioctl,
600 	.compat_ioctl   = compat_ptr_ioctl,
601 };
602 
603 struct pid *pidfd_pid(const struct file *file)
604 {
605 	if (file->f_op != &pidfs_file_operations)
606 		return ERR_PTR(-EBADF);
607 	return file_inode(file)->i_private;
608 }
609 
610 /*
611  * We're called from release_task(). We know there's at least one
612  * reference to struct pid being held that won't be released until the
613  * task has been reaped which cannot happen until we're out of
614  * release_task().
615  *
616  * If this struct pid has at least once been referred to by a pidfd then
617  * pid->attr will be allocated. If not we mark the struct pid as dead so
618  * anyone who is trying to register it with pidfs will fail to do so.
619  * Otherwise we would hand out pidfs for reaped tasks without having
620  * exit information available.
621  *
622  * Worst case is that we've filled in the info and the pid gets freed
623  * right away in free_pid() when no one holds a pidfd anymore. Since
624  * pidfs_exit() currently is placed after exit_task_work() we know that
625  * it cannot be us aka the exiting task holding a pidfd to itself.
626  */
627 void pidfs_exit(struct task_struct *tsk)
628 {
629 	struct pid *pid = task_pid(tsk);
630 	struct pidfs_attr *attr;
631 #ifdef CONFIG_CGROUPS
632 	struct cgroup *cgrp;
633 #endif
634 
635 	might_sleep();
636 
637 	guard(spinlock_irq)(&pid->wait_pidfd.lock);
638 	attr = pid->attr;
639 	if (!attr) {
640 		/*
641 		 * No one ever held a pidfd for this struct pid.
642 		 * Mark it as dead so no one can add a pidfs
643 		 * entry anymore. We're about to be reaped and
644 		 * so no exit information would be available.
645 		 */
646 		pid->attr = PIDFS_PID_DEAD;
647 		return;
648 	}
649 
650 	/*
651 	 * If @pid->attr is set someone might still legitimately hold a
652 	 * pidfd to @pid or someone might concurrently still be getting
653 	 * a reference to an already stashed dentry from @pid->stashed.
654 	 * So defer cleaning @pid->attr until the last reference to @pid
655 	 * is put
656 	 */
657 
658 #ifdef CONFIG_CGROUPS
659 	rcu_read_lock();
660 	cgrp = task_dfl_cgroup(tsk);
661 	attr->cgroupid = cgroup_id(cgrp);
662 	rcu_read_unlock();
663 #endif
664 	attr->exit_code = tsk->exit_code;
665 
666 	/* Ensure that PIDFD_GET_INFO sees either all or nothing. */
667 	smp_wmb();
668 	set_bit(PIDFS_ATTR_BIT_EXIT, &attr->attr_mask);
669 }
670 
671 #ifdef CONFIG_COREDUMP
672 void pidfs_coredump(const struct coredump_params *cprm)
673 {
674 	struct pid *pid = cprm->pid;
675 	struct pidfs_attr *attr;
676 
677 	attr = READ_ONCE(pid->attr);
678 
679 	VFS_WARN_ON_ONCE(!attr);
680 	VFS_WARN_ON_ONCE(attr == PIDFS_PID_DEAD);
681 
682 	/* Note how we were coredumped and that we coredumped. */
683 	attr->coredump_mask = pidfs_coredump_mask(cprm->mm_flags) |
684 			      PIDFD_COREDUMPED;
685 	/* If coredumping is set to skip we should never end up here. */
686 	VFS_WARN_ON_ONCE(attr->coredump_mask & PIDFD_COREDUMP_SKIP);
687 	/* Expose the signal number that caused the coredump. */
688 	attr->coredump_signal = cprm->siginfo->si_signo;
689 	smp_wmb();
690 	set_bit(PIDFS_ATTR_BIT_COREDUMP, &attr->attr_mask);
691 }
692 #endif
693 
694 static struct vfsmount *pidfs_mnt __ro_after_init;
695 
696 /*
697  * The vfs falls back to simple_setattr() if i_op->setattr() isn't
698  * implemented. Let's reject it completely until we have a clean
699  * permission concept for pidfds.
700  */
701 static int pidfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
702 			 struct iattr *attr)
703 {
704 	return anon_inode_setattr(idmap, dentry, attr);
705 }
706 
707 static int pidfs_getattr(struct mnt_idmap *idmap, const struct path *path,
708 			 struct kstat *stat, u32 request_mask,
709 			 unsigned int query_flags)
710 {
711 	return anon_inode_getattr(idmap, path, stat, request_mask, query_flags);
712 }
713 
714 static ssize_t pidfs_listxattr(struct dentry *dentry, char *buf, size_t size)
715 {
716 	struct inode *inode = d_inode(dentry);
717 	struct pid *pid = inode->i_private;
718 	struct pidfs_attr *attr = pid->attr;
719 	struct simple_xattrs *xattrs;
720 
721 	xattrs = READ_ONCE(attr->xattrs);
722 	if (!xattrs)
723 		return 0;
724 
725 	return simple_xattr_list(inode, xattrs, buf, size);
726 }
727 
728 static const struct inode_operations pidfs_inode_operations = {
729 	.getattr	= pidfs_getattr,
730 	.setattr	= pidfs_setattr,
731 	.listxattr	= pidfs_listxattr,
732 };
733 
734 static void pidfs_evict_inode(struct inode *inode)
735 {
736 	struct pid *pid = inode->i_private;
737 
738 	clear_inode(inode);
739 	put_pid(pid);
740 }
741 
742 static const struct super_operations pidfs_sops = {
743 	.drop_inode	= inode_just_drop,
744 	.evict_inode	= pidfs_evict_inode,
745 	.statfs		= simple_statfs,
746 };
747 
748 /*
749  * 'lsof' has knowledge of out historical anon_inode use, and expects
750  * the pidfs dentry name to start with 'anon_inode'.
751  */
752 static char *pidfs_dname(struct dentry *dentry, char *buffer, int buflen)
753 {
754 	return dynamic_dname(buffer, buflen, "anon_inode:[pidfd]");
755 }
756 
757 const struct dentry_operations pidfs_dentry_operations = {
758 	.d_dname	= pidfs_dname,
759 	.d_prune	= stashed_dentry_prune,
760 };
761 
762 static int pidfs_encode_fh(struct inode *inode, u32 *fh, int *max_len,
763 			   struct inode *parent)
764 {
765 	const struct pid *pid = inode->i_private;
766 
767 	if (*max_len < 2) {
768 		*max_len = 2;
769 		return FILEID_INVALID;
770 	}
771 
772 	*max_len = 2;
773 	*(u64 *)fh = pid->ino;
774 	return FILEID_KERNFS;
775 }
776 
777 static int pidfs_ino_find(const void *key, const struct rb_node *node)
778 {
779 	const u64 pid_ino = *(u64 *)key;
780 	const struct pid *pid = rb_entry(node, struct pid, pidfs_node);
781 
782 	if (pid_ino < pid->ino)
783 		return -1;
784 	if (pid_ino > pid->ino)
785 		return 1;
786 	return 0;
787 }
788 
789 /* Find a struct pid based on the inode number. */
790 static struct pid *pidfs_ino_get_pid(u64 ino)
791 {
792 	struct pid *pid;
793 	struct rb_node *node;
794 	unsigned int seq;
795 
796 	guard(rcu)();
797 	do {
798 		seq = read_seqcount_begin(&pidmap_lock_seq);
799 		node = rb_find_rcu(&ino, &pidfs_ino_tree, pidfs_ino_find);
800 		if (node)
801 			break;
802 	} while (read_seqcount_retry(&pidmap_lock_seq, seq));
803 
804 	if (!node)
805 		return NULL;
806 
807 	pid = rb_entry(node, struct pid, pidfs_node);
808 
809 	/* Within our pid namespace hierarchy? */
810 	if (pid_vnr(pid) == 0)
811 		return NULL;
812 
813 	return get_pid(pid);
814 }
815 
816 static struct dentry *pidfs_fh_to_dentry(struct super_block *sb,
817 					 struct fid *fid, int fh_len,
818 					 int fh_type)
819 {
820 	int ret;
821 	u64 pid_ino;
822 	struct path path;
823 	struct pid *pid;
824 
825 	if (fh_len < 2)
826 		return NULL;
827 
828 	switch (fh_type) {
829 	case FILEID_KERNFS:
830 		pid_ino = *(u64 *)fid;
831 		break;
832 	default:
833 		return NULL;
834 	}
835 
836 	pid = pidfs_ino_get_pid(pid_ino);
837 	if (!pid)
838 		return NULL;
839 
840 	ret = path_from_stashed(&pid->stashed, pidfs_mnt, pid, &path);
841 	if (ret < 0)
842 		return ERR_PTR(ret);
843 
844 	VFS_WARN_ON_ONCE(!pid->attr);
845 
846 	mntput(path.mnt);
847 	return path.dentry;
848 }
849 
850 /*
851  * Make sure that we reject any nonsensical flags that users pass via
852  * open_by_handle_at(). Note that PIDFD_THREAD is defined as O_EXCL, and
853  * PIDFD_NONBLOCK as O_NONBLOCK.
854  */
855 #define VALID_FILE_HANDLE_OPEN_FLAGS \
856 	(O_RDONLY | O_WRONLY | O_RDWR | O_NONBLOCK | O_CLOEXEC | O_EXCL)
857 
858 static int pidfs_export_permission(struct handle_to_path_ctx *ctx,
859 				   unsigned int oflags)
860 {
861 	if (oflags & ~(VALID_FILE_HANDLE_OPEN_FLAGS | O_LARGEFILE))
862 		return -EINVAL;
863 
864 	/*
865 	 * pidfd_ino_get_pid() will verify that the struct pid is part
866 	 * of the caller's pid namespace hierarchy. No further
867 	 * permission checks are needed.
868 	 */
869 	return 0;
870 }
871 
872 static struct file *pidfs_export_open(const struct path *path, unsigned int oflags)
873 {
874 	/*
875 	 * Clear O_LARGEFILE as open_by_handle_at() forces it and raise
876 	 * O_RDWR as pidfds always are.
877 	 */
878 	oflags &= ~O_LARGEFILE;
879 	return dentry_open(path, oflags | O_RDWR, current_cred());
880 }
881 
882 static const struct export_operations pidfs_export_operations = {
883 	.encode_fh	= pidfs_encode_fh,
884 	.fh_to_dentry	= pidfs_fh_to_dentry,
885 	.open		= pidfs_export_open,
886 	.permission	= pidfs_export_permission,
887 };
888 
889 static int pidfs_init_inode(struct inode *inode, void *data)
890 {
891 	const struct pid *pid = data;
892 
893 	inode->i_private = data;
894 	inode->i_flags |= S_PRIVATE | S_ANON_INODE;
895 	/* We allow to set xattrs. */
896 	inode->i_flags &= ~S_IMMUTABLE;
897 	inode->i_mode |= S_IRWXU;
898 	inode->i_op = &pidfs_inode_operations;
899 	inode->i_fop = &pidfs_file_operations;
900 	inode->i_ino = pidfs_ino(pid->ino);
901 	inode->i_generation = pidfs_gen(pid->ino);
902 	return 0;
903 }
904 
905 static void pidfs_put_data(void *data)
906 {
907 	struct pid *pid = data;
908 	put_pid(pid);
909 }
910 
911 /**
912  * pidfs_register_pid - register a struct pid in pidfs
913  * @pid: pid to pin
914  *
915  * Register a struct pid in pidfs.
916  *
917  * Return: On success zero, on error a negative error code is returned.
918  */
919 int pidfs_register_pid(struct pid *pid)
920 {
921 	struct pidfs_attr *new_attr __free(kfree) = NULL;
922 	struct pidfs_attr *attr;
923 
924 	might_sleep();
925 
926 	if (!pid)
927 		return 0;
928 
929 	attr = READ_ONCE(pid->attr);
930 	if (unlikely(attr == PIDFS_PID_DEAD))
931 		return PTR_ERR(PIDFS_PID_DEAD);
932 	if (attr)
933 		return 0;
934 
935 	new_attr = kmem_cache_zalloc(pidfs_attr_cachep, GFP_KERNEL);
936 	if (!new_attr)
937 		return -ENOMEM;
938 
939 	/* Synchronize with pidfs_exit(). */
940 	guard(spinlock_irq)(&pid->wait_pidfd.lock);
941 
942 	attr = pid->attr;
943 	if (unlikely(attr == PIDFS_PID_DEAD))
944 		return PTR_ERR(PIDFS_PID_DEAD);
945 	if (unlikely(attr))
946 		return 0;
947 
948 	pid->attr = no_free_ptr(new_attr);
949 	return 0;
950 }
951 
952 static struct dentry *pidfs_stash_dentry(struct dentry **stashed,
953 					 struct dentry *dentry)
954 {
955 	int ret;
956 	struct pid *pid = d_inode(dentry)->i_private;
957 
958 	VFS_WARN_ON_ONCE(stashed != &pid->stashed);
959 
960 	ret = pidfs_register_pid(pid);
961 	if (ret)
962 		return ERR_PTR(ret);
963 
964 	return stash_dentry(stashed, dentry);
965 }
966 
967 static const struct stashed_operations pidfs_stashed_ops = {
968 	.stash_dentry	= pidfs_stash_dentry,
969 	.init_inode	= pidfs_init_inode,
970 	.put_data	= pidfs_put_data,
971 };
972 
973 static int pidfs_xattr_get(const struct xattr_handler *handler,
974 			   struct dentry *unused, struct inode *inode,
975 			   const char *suffix, void *value, size_t size)
976 {
977 	struct pid *pid = inode->i_private;
978 	struct pidfs_attr *attr = pid->attr;
979 	const char *name;
980 	struct simple_xattrs *xattrs;
981 
982 	xattrs = READ_ONCE(attr->xattrs);
983 	if (!xattrs)
984 		return 0;
985 
986 	name = xattr_full_name(handler, suffix);
987 	return simple_xattr_get(xattrs, name, value, size);
988 }
989 
990 static int pidfs_xattr_set(const struct xattr_handler *handler,
991 			   struct mnt_idmap *idmap, struct dentry *unused,
992 			   struct inode *inode, const char *suffix,
993 			   const void *value, size_t size, int flags)
994 {
995 	struct pid *pid = inode->i_private;
996 	struct pidfs_attr *attr = pid->attr;
997 	const char *name;
998 	struct simple_xattrs *xattrs;
999 	struct simple_xattr *old_xattr;
1000 
1001 	/* Ensure we're the only one to set @attr->xattrs. */
1002 	WARN_ON_ONCE(!inode_is_locked(inode));
1003 
1004 	xattrs = READ_ONCE(attr->xattrs);
1005 	if (!xattrs) {
1006 		xattrs = kmem_cache_zalloc(pidfs_xattr_cachep, GFP_KERNEL);
1007 		if (!xattrs)
1008 			return -ENOMEM;
1009 
1010 		simple_xattrs_init(xattrs);
1011 		smp_store_release(&pid->attr->xattrs, xattrs);
1012 	}
1013 
1014 	name = xattr_full_name(handler, suffix);
1015 	old_xattr = simple_xattr_set(xattrs, name, value, size, flags);
1016 	if (IS_ERR(old_xattr))
1017 		return PTR_ERR(old_xattr);
1018 
1019 	simple_xattr_free(old_xattr);
1020 	return 0;
1021 }
1022 
1023 static const struct xattr_handler pidfs_trusted_xattr_handler = {
1024 	.prefix = XATTR_TRUSTED_PREFIX,
1025 	.get	= pidfs_xattr_get,
1026 	.set	= pidfs_xattr_set,
1027 };
1028 
1029 static const struct xattr_handler *const pidfs_xattr_handlers[] = {
1030 	&pidfs_trusted_xattr_handler,
1031 	NULL
1032 };
1033 
1034 static int pidfs_init_fs_context(struct fs_context *fc)
1035 {
1036 	struct pseudo_fs_context *ctx;
1037 
1038 	ctx = init_pseudo(fc, PID_FS_MAGIC);
1039 	if (!ctx)
1040 		return -ENOMEM;
1041 
1042 	fc->s_iflags |= SB_I_NOEXEC;
1043 	fc->s_iflags |= SB_I_NODEV;
1044 	ctx->ops = &pidfs_sops;
1045 	ctx->eops = &pidfs_export_operations;
1046 	ctx->dops = &pidfs_dentry_operations;
1047 	ctx->xattr = pidfs_xattr_handlers;
1048 	fc->s_fs_info = (void *)&pidfs_stashed_ops;
1049 	return 0;
1050 }
1051 
1052 static struct file_system_type pidfs_type = {
1053 	.name			= "pidfs",
1054 	.init_fs_context	= pidfs_init_fs_context,
1055 	.kill_sb		= kill_anon_super,
1056 };
1057 
1058 struct file *pidfs_alloc_file(struct pid *pid, unsigned int flags)
1059 {
1060 	struct file *pidfd_file;
1061 	struct path path __free(path_put) = {};
1062 	int ret;
1063 
1064 	/*
1065 	 * Ensure that PIDFD_STALE can be passed as a flag without
1066 	 * overloading other uapi pidfd flags.
1067 	 */
1068 	BUILD_BUG_ON(PIDFD_STALE == PIDFD_THREAD);
1069 	BUILD_BUG_ON(PIDFD_STALE == PIDFD_NONBLOCK);
1070 
1071 	ret = path_from_stashed(&pid->stashed, pidfs_mnt, get_pid(pid), &path);
1072 	if (ret < 0)
1073 		return ERR_PTR(ret);
1074 
1075 	VFS_WARN_ON_ONCE(!pid->attr);
1076 
1077 	flags &= ~PIDFD_STALE;
1078 	flags |= O_RDWR;
1079 	pidfd_file = dentry_open(&path, flags, current_cred());
1080 	/* Raise PIDFD_THREAD explicitly as do_dentry_open() strips it. */
1081 	if (!IS_ERR(pidfd_file))
1082 		pidfd_file->f_flags |= (flags & PIDFD_THREAD);
1083 
1084 	return pidfd_file;
1085 }
1086 
1087 void __init pidfs_init(void)
1088 {
1089 	pidfs_attr_cachep = kmem_cache_create("pidfs_attr_cache", sizeof(struct pidfs_attr), 0,
1090 					 (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT |
1091 					  SLAB_ACCOUNT | SLAB_PANIC), NULL);
1092 
1093 	pidfs_xattr_cachep = kmem_cache_create("pidfs_xattr_cache",
1094 					       sizeof(struct simple_xattrs), 0,
1095 					       (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT |
1096 						SLAB_ACCOUNT | SLAB_PANIC), NULL);
1097 
1098 	pidfs_mnt = kern_mount(&pidfs_type);
1099 	if (IS_ERR(pidfs_mnt))
1100 		panic("Failed to mount pidfs pseudo filesystem");
1101 
1102 	pidfs_root_path.mnt = pidfs_mnt;
1103 	pidfs_root_path.dentry = pidfs_mnt->mnt_root;
1104 }
1105