xref: /linux/fs/pidfs.c (revision db7ce91e226df0fec200bd2a0eb87eed7c5d3adb)
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 
24 #include "internal.h"
25 #include "mount.h"
26 
27 static struct kmem_cache *pidfs_cachep __ro_after_init;
28 
29 /*
30  * Stashes information that userspace needs to access even after the
31  * process has been reaped.
32  */
33 struct pidfs_exit_info {
34 	__u64 cgroupid;
35 	__s32 exit_code;
36 };
37 
38 struct pidfs_inode {
39 	struct pidfs_exit_info __pei;
40 	struct pidfs_exit_info *exit_info;
41 	struct inode vfs_inode;
42 };
43 
44 static inline struct pidfs_inode *pidfs_i(struct inode *inode)
45 {
46 	return container_of(inode, struct pidfs_inode, vfs_inode);
47 }
48 
49 static struct rb_root pidfs_ino_tree = RB_ROOT;
50 
51 #if BITS_PER_LONG == 32
52 static inline unsigned long pidfs_ino(u64 ino)
53 {
54 	return lower_32_bits(ino);
55 }
56 
57 /* On 32 bit the generation number are the upper 32 bits. */
58 static inline u32 pidfs_gen(u64 ino)
59 {
60 	return upper_32_bits(ino);
61 }
62 
63 #else
64 
65 /* On 64 bit simply return ino. */
66 static inline unsigned long pidfs_ino(u64 ino)
67 {
68 	return ino;
69 }
70 
71 /* On 64 bit the generation number is 0. */
72 static inline u32 pidfs_gen(u64 ino)
73 {
74 	return 0;
75 }
76 #endif
77 
78 static int pidfs_ino_cmp(struct rb_node *a, const struct rb_node *b)
79 {
80 	struct pid *pid_a = rb_entry(a, struct pid, pidfs_node);
81 	struct pid *pid_b = rb_entry(b, struct pid, pidfs_node);
82 	u64 pid_ino_a = pid_a->ino;
83 	u64 pid_ino_b = pid_b->ino;
84 
85 	if (pid_ino_a < pid_ino_b)
86 		return -1;
87 	if (pid_ino_a > pid_ino_b)
88 		return 1;
89 	return 0;
90 }
91 
92 void pidfs_add_pid(struct pid *pid)
93 {
94 	static u64 pidfs_ino_nr = 2;
95 
96 	/*
97 	 * On 64 bit nothing special happens. The 64bit number assigned
98 	 * to struct pid is the inode number.
99 	 *
100 	 * On 32 bit the 64 bit number assigned to struct pid is split
101 	 * into two 32 bit numbers. The lower 32 bits are used as the
102 	 * inode number and the upper 32 bits are used as the inode
103 	 * generation number.
104 	 *
105 	 * On 32 bit pidfs_ino() will return the lower 32 bit. When
106 	 * pidfs_ino() returns zero a wrap around happened. When a
107 	 * wraparound happens the 64 bit number will be incremented by 2
108 	 * so inode numbering starts at 2 again.
109 	 *
110 	 * On 64 bit comparing two pidfds is as simple as comparing
111 	 * inode numbers.
112 	 *
113 	 * When a wraparound happens on 32 bit multiple pidfds with the
114 	 * same inode number are likely to exist (This isn't a problem
115 	 * since before pidfs pidfds used the anonymous inode meaning
116 	 * all pidfds had the same inode number.). Userspace can
117 	 * reconstruct the 64 bit identifier by retrieving both the
118 	 * inode number and the inode generation number to compare or
119 	 * use file handles.
120 	 */
121 	if (pidfs_ino(pidfs_ino_nr) == 0)
122 		pidfs_ino_nr += 2;
123 
124 	pid->ino = pidfs_ino_nr;
125 	pid->stashed = NULL;
126 	pidfs_ino_nr++;
127 
128 	write_seqcount_begin(&pidmap_lock_seq);
129 	rb_find_add_rcu(&pid->pidfs_node, &pidfs_ino_tree, pidfs_ino_cmp);
130 	write_seqcount_end(&pidmap_lock_seq);
131 }
132 
133 void pidfs_remove_pid(struct pid *pid)
134 {
135 	write_seqcount_begin(&pidmap_lock_seq);
136 	rb_erase(&pid->pidfs_node, &pidfs_ino_tree);
137 	write_seqcount_end(&pidmap_lock_seq);
138 }
139 
140 #ifdef CONFIG_PROC_FS
141 /**
142  * pidfd_show_fdinfo - print information about a pidfd
143  * @m: proc fdinfo file
144  * @f: file referencing a pidfd
145  *
146  * Pid:
147  * This function will print the pid that a given pidfd refers to in the
148  * pid namespace of the procfs instance.
149  * If the pid namespace of the process is not a descendant of the pid
150  * namespace of the procfs instance 0 will be shown as its pid. This is
151  * similar to calling getppid() on a process whose parent is outside of
152  * its pid namespace.
153  *
154  * NSpid:
155  * If pid namespaces are supported then this function will also print
156  * the pid of a given pidfd refers to for all descendant pid namespaces
157  * starting from the current pid namespace of the instance, i.e. the
158  * Pid field and the first entry in the NSpid field will be identical.
159  * If the pid namespace of the process is not a descendant of the pid
160  * namespace of the procfs instance 0 will be shown as its first NSpid
161  * entry and no others will be shown.
162  * Note that this differs from the Pid and NSpid fields in
163  * /proc/<pid>/status where Pid and NSpid are always shown relative to
164  * the  pid namespace of the procfs instance. The difference becomes
165  * obvious when sending around a pidfd between pid namespaces from a
166  * different branch of the tree, i.e. where no ancestral relation is
167  * present between the pid namespaces:
168  * - create two new pid namespaces ns1 and ns2 in the initial pid
169  *   namespace (also take care to create new mount namespaces in the
170  *   new pid namespace and mount procfs)
171  * - create a process with a pidfd in ns1
172  * - send pidfd from ns1 to ns2
173  * - read /proc/self/fdinfo/<pidfd> and observe that both Pid and NSpid
174  *   have exactly one entry, which is 0
175  */
176 static void pidfd_show_fdinfo(struct seq_file *m, struct file *f)
177 {
178 	struct pid *pid = pidfd_pid(f);
179 	struct pid_namespace *ns;
180 	pid_t nr = -1;
181 
182 	if (likely(pid_has_task(pid, PIDTYPE_PID))) {
183 		ns = proc_pid_ns(file_inode(m->file)->i_sb);
184 		nr = pid_nr_ns(pid, ns);
185 	}
186 
187 	seq_put_decimal_ll(m, "Pid:\t", nr);
188 
189 #ifdef CONFIG_PID_NS
190 	seq_put_decimal_ll(m, "\nNSpid:\t", nr);
191 	if (nr > 0) {
192 		int i;
193 
194 		/* If nr is non-zero it means that 'pid' is valid and that
195 		 * ns, i.e. the pid namespace associated with the procfs
196 		 * instance, is in the pid namespace hierarchy of pid.
197 		 * Start at one below the already printed level.
198 		 */
199 		for (i = ns->level + 1; i <= pid->level; i++)
200 			seq_put_decimal_ll(m, "\t", pid->numbers[i].nr);
201 	}
202 #endif
203 	seq_putc(m, '\n');
204 }
205 #endif
206 
207 /*
208  * Poll support for process exit notification.
209  */
210 static __poll_t pidfd_poll(struct file *file, struct poll_table_struct *pts)
211 {
212 	struct pid *pid = pidfd_pid(file);
213 	struct task_struct *task;
214 	__poll_t poll_flags = 0;
215 
216 	poll_wait(file, &pid->wait_pidfd, pts);
217 	/*
218 	 * Don't wake waiters if the thread-group leader exited
219 	 * prematurely. They either get notified when the last subthread
220 	 * exits or not at all if one of the remaining subthreads execs
221 	 * and assumes the struct pid of the old thread-group leader.
222 	 */
223 	guard(rcu)();
224 	task = pid_task(pid, PIDTYPE_PID);
225 	if (!task)
226 		poll_flags = EPOLLIN | EPOLLRDNORM | EPOLLHUP;
227 	else if (task->exit_state && !delay_group_leader(task))
228 		poll_flags = EPOLLIN | EPOLLRDNORM;
229 
230 	return poll_flags;
231 }
232 
233 static inline bool pid_in_current_pidns(const struct pid *pid)
234 {
235 	const struct pid_namespace *ns = task_active_pid_ns(current);
236 
237 	if (ns->level <= pid->level)
238 		return pid->numbers[ns->level].ns == ns;
239 
240 	return false;
241 }
242 
243 static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg)
244 {
245 	struct pidfd_info __user *uinfo = (struct pidfd_info __user *)arg;
246 	struct inode *inode = file_inode(file);
247 	struct pid *pid = pidfd_pid(file);
248 	size_t usize = _IOC_SIZE(cmd);
249 	struct pidfd_info kinfo = {};
250 	struct pidfs_exit_info *exit_info;
251 	struct user_namespace *user_ns;
252 	struct task_struct *task;
253 	const struct cred *c;
254 	__u64 mask;
255 
256 	if (!uinfo)
257 		return -EINVAL;
258 	if (usize < PIDFD_INFO_SIZE_VER0)
259 		return -EINVAL; /* First version, no smaller struct possible */
260 
261 	if (copy_from_user(&mask, &uinfo->mask, sizeof(mask)))
262 		return -EFAULT;
263 
264 	/*
265 	 * Restrict information retrieval to tasks within the caller's pid
266 	 * namespace hierarchy.
267 	 */
268 	if (!pid_in_current_pidns(pid))
269 		return -ESRCH;
270 
271 	if (mask & PIDFD_INFO_EXIT) {
272 		exit_info = READ_ONCE(pidfs_i(inode)->exit_info);
273 		if (exit_info) {
274 			kinfo.mask |= PIDFD_INFO_EXIT;
275 #ifdef CONFIG_CGROUPS
276 			kinfo.cgroupid = exit_info->cgroupid;
277 			kinfo.mask |= PIDFD_INFO_CGROUPID;
278 #endif
279 			kinfo.exit_code = exit_info->exit_code;
280 		}
281 	}
282 
283 	task = get_pid_task(pid, PIDTYPE_PID);
284 	if (!task) {
285 		/*
286 		 * If the task has already been reaped, only exit
287 		 * information is available
288 		 */
289 		if (!(mask & PIDFD_INFO_EXIT))
290 			return -ESRCH;
291 
292 		goto copy_out;
293 	}
294 
295 	c = get_task_cred(task);
296 	if (!c)
297 		return -ESRCH;
298 
299 	/* Unconditionally return identifiers and credentials, the rest only on request */
300 
301 	user_ns = current_user_ns();
302 	kinfo.ruid = from_kuid_munged(user_ns, c->uid);
303 	kinfo.rgid = from_kgid_munged(user_ns, c->gid);
304 	kinfo.euid = from_kuid_munged(user_ns, c->euid);
305 	kinfo.egid = from_kgid_munged(user_ns, c->egid);
306 	kinfo.suid = from_kuid_munged(user_ns, c->suid);
307 	kinfo.sgid = from_kgid_munged(user_ns, c->sgid);
308 	kinfo.fsuid = from_kuid_munged(user_ns, c->fsuid);
309 	kinfo.fsgid = from_kgid_munged(user_ns, c->fsgid);
310 	kinfo.mask |= PIDFD_INFO_CREDS;
311 	put_cred(c);
312 
313 #ifdef CONFIG_CGROUPS
314 	if (!kinfo.cgroupid) {
315 		struct cgroup *cgrp;
316 
317 		rcu_read_lock();
318 		cgrp = task_dfl_cgroup(task);
319 		kinfo.cgroupid = cgroup_id(cgrp);
320 		kinfo.mask |= PIDFD_INFO_CGROUPID;
321 		rcu_read_unlock();
322 	}
323 #endif
324 
325 	/*
326 	 * Copy pid/tgid last, to reduce the chances the information might be
327 	 * stale. Note that it is not possible to ensure it will be valid as the
328 	 * task might return as soon as the copy_to_user finishes, but that's ok
329 	 * and userspace expects that might happen and can act accordingly, so
330 	 * this is just best-effort. What we can do however is checking that all
331 	 * the fields are set correctly, or return ESRCH to avoid providing
332 	 * incomplete information. */
333 
334 	kinfo.ppid = task_ppid_nr_ns(task, NULL);
335 	kinfo.tgid = task_tgid_vnr(task);
336 	kinfo.pid = task_pid_vnr(task);
337 	kinfo.mask |= PIDFD_INFO_PID;
338 
339 	if (kinfo.pid == 0 || kinfo.tgid == 0 || (kinfo.ppid == 0 && kinfo.pid != 1))
340 		return -ESRCH;
341 
342 copy_out:
343 	/*
344 	 * If userspace and the kernel have the same struct size it can just
345 	 * be copied. If userspace provides an older struct, only the bits that
346 	 * userspace knows about will be copied. If userspace provides a new
347 	 * struct, only the bits that the kernel knows about will be copied.
348 	 */
349 	return copy_struct_to_user(uinfo, usize, &kinfo, sizeof(kinfo), NULL);
350 }
351 
352 static bool pidfs_ioctl_valid(unsigned int cmd)
353 {
354 	switch (cmd) {
355 	case FS_IOC_GETVERSION:
356 	case PIDFD_GET_CGROUP_NAMESPACE:
357 	case PIDFD_GET_INFO:
358 	case PIDFD_GET_IPC_NAMESPACE:
359 	case PIDFD_GET_MNT_NAMESPACE:
360 	case PIDFD_GET_NET_NAMESPACE:
361 	case PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE:
362 	case PIDFD_GET_TIME_NAMESPACE:
363 	case PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE:
364 	case PIDFD_GET_UTS_NAMESPACE:
365 	case PIDFD_GET_USER_NAMESPACE:
366 	case PIDFD_GET_PID_NAMESPACE:
367 		return true;
368 	}
369 
370 	return false;
371 }
372 
373 static long pidfd_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
374 {
375 	struct task_struct *task __free(put_task) = NULL;
376 	struct nsproxy *nsp __free(put_nsproxy) = NULL;
377 	struct ns_common *ns_common = NULL;
378 	struct pid_namespace *pid_ns;
379 
380 	if (!pidfs_ioctl_valid(cmd))
381 		return -ENOIOCTLCMD;
382 
383 	if (cmd == FS_IOC_GETVERSION) {
384 		if (!arg)
385 			return -EINVAL;
386 
387 		__u32 __user *argp = (__u32 __user *)arg;
388 		return put_user(file_inode(file)->i_generation, argp);
389 	}
390 
391 	/* Extensible IOCTL that does not open namespace FDs, take a shortcut */
392 	if (_IOC_NR(cmd) == _IOC_NR(PIDFD_GET_INFO))
393 		return pidfd_info(file, cmd, arg);
394 
395 	task = get_pid_task(pidfd_pid(file), PIDTYPE_PID);
396 	if (!task)
397 		return -ESRCH;
398 
399 	if (arg)
400 		return -EINVAL;
401 
402 	scoped_guard(task_lock, task) {
403 		nsp = task->nsproxy;
404 		if (nsp)
405 			get_nsproxy(nsp);
406 	}
407 	if (!nsp)
408 		return -ESRCH; /* just pretend it didn't exist */
409 
410 	/*
411 	 * We're trying to open a file descriptor to the namespace so perform a
412 	 * filesystem cred ptrace check. Also, we mirror nsfs behavior.
413 	 */
414 	if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
415 		return -EACCES;
416 
417 	switch (cmd) {
418 	/* Namespaces that hang of nsproxy. */
419 	case PIDFD_GET_CGROUP_NAMESPACE:
420 		if (IS_ENABLED(CONFIG_CGROUPS)) {
421 			get_cgroup_ns(nsp->cgroup_ns);
422 			ns_common = to_ns_common(nsp->cgroup_ns);
423 		}
424 		break;
425 	case PIDFD_GET_IPC_NAMESPACE:
426 		if (IS_ENABLED(CONFIG_IPC_NS)) {
427 			get_ipc_ns(nsp->ipc_ns);
428 			ns_common = to_ns_common(nsp->ipc_ns);
429 		}
430 		break;
431 	case PIDFD_GET_MNT_NAMESPACE:
432 		get_mnt_ns(nsp->mnt_ns);
433 		ns_common = to_ns_common(nsp->mnt_ns);
434 		break;
435 	case PIDFD_GET_NET_NAMESPACE:
436 		if (IS_ENABLED(CONFIG_NET_NS)) {
437 			ns_common = to_ns_common(nsp->net_ns);
438 			get_net_ns(ns_common);
439 		}
440 		break;
441 	case PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE:
442 		if (IS_ENABLED(CONFIG_PID_NS)) {
443 			get_pid_ns(nsp->pid_ns_for_children);
444 			ns_common = to_ns_common(nsp->pid_ns_for_children);
445 		}
446 		break;
447 	case PIDFD_GET_TIME_NAMESPACE:
448 		if (IS_ENABLED(CONFIG_TIME_NS)) {
449 			get_time_ns(nsp->time_ns);
450 			ns_common = to_ns_common(nsp->time_ns);
451 		}
452 		break;
453 	case PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE:
454 		if (IS_ENABLED(CONFIG_TIME_NS)) {
455 			get_time_ns(nsp->time_ns_for_children);
456 			ns_common = to_ns_common(nsp->time_ns_for_children);
457 		}
458 		break;
459 	case PIDFD_GET_UTS_NAMESPACE:
460 		if (IS_ENABLED(CONFIG_UTS_NS)) {
461 			get_uts_ns(nsp->uts_ns);
462 			ns_common = to_ns_common(nsp->uts_ns);
463 		}
464 		break;
465 	/* Namespaces that don't hang of nsproxy. */
466 	case PIDFD_GET_USER_NAMESPACE:
467 		if (IS_ENABLED(CONFIG_USER_NS)) {
468 			rcu_read_lock();
469 			ns_common = to_ns_common(get_user_ns(task_cred_xxx(task, user_ns)));
470 			rcu_read_unlock();
471 		}
472 		break;
473 	case PIDFD_GET_PID_NAMESPACE:
474 		if (IS_ENABLED(CONFIG_PID_NS)) {
475 			rcu_read_lock();
476 			pid_ns = task_active_pid_ns(task);
477 			if (pid_ns)
478 				ns_common = to_ns_common(get_pid_ns(pid_ns));
479 			rcu_read_unlock();
480 		}
481 		break;
482 	default:
483 		return -ENOIOCTLCMD;
484 	}
485 
486 	if (!ns_common)
487 		return -EOPNOTSUPP;
488 
489 	/* open_namespace() unconditionally consumes the reference */
490 	return open_namespace(ns_common);
491 }
492 
493 static const struct file_operations pidfs_file_operations = {
494 	.poll		= pidfd_poll,
495 #ifdef CONFIG_PROC_FS
496 	.show_fdinfo	= pidfd_show_fdinfo,
497 #endif
498 	.unlocked_ioctl	= pidfd_ioctl,
499 	.compat_ioctl   = compat_ptr_ioctl,
500 };
501 
502 struct pid *pidfd_pid(const struct file *file)
503 {
504 	if (file->f_op != &pidfs_file_operations)
505 		return ERR_PTR(-EBADF);
506 	return file_inode(file)->i_private;
507 }
508 
509 /*
510  * We're called from release_task(). We know there's at least one
511  * reference to struct pid being held that won't be released until the
512  * task has been reaped which cannot happen until we're out of
513  * release_task().
514  *
515  * If this struct pid is referred to by a pidfd then
516  * stashed_dentry_get() will return the dentry and inode for that struct
517  * pid. Since we've taken a reference on it there's now an additional
518  * reference from the exit path on it. Which is fine. We're going to put
519  * it again in a second and we know that the pid is kept alive anyway.
520  *
521  * Worst case is that we've filled in the info and immediately free the
522  * dentry and inode afterwards since the pidfd has been closed. Since
523  * pidfs_exit() currently is placed after exit_task_work() we know that
524  * it cannot be us aka the exiting task holding a pidfd to ourselves.
525  */
526 void pidfs_exit(struct task_struct *tsk)
527 {
528 	struct dentry *dentry;
529 
530 	might_sleep();
531 
532 	dentry = stashed_dentry_get(&task_pid(tsk)->stashed);
533 	if (dentry) {
534 		struct inode *inode = d_inode(dentry);
535 		struct pidfs_exit_info *exit_info = &pidfs_i(inode)->__pei;
536 #ifdef CONFIG_CGROUPS
537 		struct cgroup *cgrp;
538 
539 		rcu_read_lock();
540 		cgrp = task_dfl_cgroup(tsk);
541 		exit_info->cgroupid = cgroup_id(cgrp);
542 		rcu_read_unlock();
543 #endif
544 		exit_info->exit_code = tsk->exit_code;
545 
546 		/* Ensure that PIDFD_GET_INFO sees either all or nothing. */
547 		smp_store_release(&pidfs_i(inode)->exit_info, &pidfs_i(inode)->__pei);
548 		dput(dentry);
549 	}
550 }
551 
552 static struct vfsmount *pidfs_mnt __ro_after_init;
553 
554 /*
555  * The vfs falls back to simple_setattr() if i_op->setattr() isn't
556  * implemented. Let's reject it completely until we have a clean
557  * permission concept for pidfds.
558  */
559 static int pidfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
560 			 struct iattr *attr)
561 {
562 	return -EOPNOTSUPP;
563 }
564 
565 
566 /*
567  * User space expects pidfs inodes to have no file type in st_mode.
568  *
569  * In particular, 'lsof' has this legacy logic:
570  *
571  *	type = s->st_mode & S_IFMT;
572  *	switch (type) {
573  *	  ...
574  *	case 0:
575  *		if (!strcmp(p, "anon_inode"))
576  *			Lf->ntype = Ntype = N_ANON_INODE;
577  *
578  * to detect our old anon_inode logic.
579  *
580  * Rather than mess with our internal sane inode data, just fix it
581  * up here in getattr() by masking off the format bits.
582  */
583 static int pidfs_getattr(struct mnt_idmap *idmap, const struct path *path,
584 			 struct kstat *stat, u32 request_mask,
585 			 unsigned int query_flags)
586 {
587 	struct inode *inode = d_inode(path->dentry);
588 
589 	generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
590 	stat->mode &= ~S_IFMT;
591 	return 0;
592 }
593 
594 static const struct inode_operations pidfs_inode_operations = {
595 	.getattr = pidfs_getattr,
596 	.setattr = pidfs_setattr,
597 };
598 
599 static void pidfs_evict_inode(struct inode *inode)
600 {
601 	struct pid *pid = inode->i_private;
602 
603 	clear_inode(inode);
604 	put_pid(pid);
605 }
606 
607 static struct inode *pidfs_alloc_inode(struct super_block *sb)
608 {
609 	struct pidfs_inode *pi;
610 
611 	pi = alloc_inode_sb(sb, pidfs_cachep, GFP_KERNEL);
612 	if (!pi)
613 		return NULL;
614 
615 	memset(&pi->__pei, 0, sizeof(pi->__pei));
616 	pi->exit_info = NULL;
617 
618 	return &pi->vfs_inode;
619 }
620 
621 static void pidfs_free_inode(struct inode *inode)
622 {
623 	kmem_cache_free(pidfs_cachep, pidfs_i(inode));
624 }
625 
626 static const struct super_operations pidfs_sops = {
627 	.alloc_inode	= pidfs_alloc_inode,
628 	.drop_inode	= generic_delete_inode,
629 	.evict_inode	= pidfs_evict_inode,
630 	.free_inode	= pidfs_free_inode,
631 	.statfs		= simple_statfs,
632 };
633 
634 /*
635  * 'lsof' has knowledge of out historical anon_inode use, and expects
636  * the pidfs dentry name to start with 'anon_inode'.
637  */
638 static char *pidfs_dname(struct dentry *dentry, char *buffer, int buflen)
639 {
640 	return dynamic_dname(buffer, buflen, "anon_inode:[pidfd]");
641 }
642 
643 const struct dentry_operations pidfs_dentry_operations = {
644 	.d_delete	= always_delete_dentry,
645 	.d_dname	= pidfs_dname,
646 	.d_prune	= stashed_dentry_prune,
647 };
648 
649 static int pidfs_encode_fh(struct inode *inode, u32 *fh, int *max_len,
650 			   struct inode *parent)
651 {
652 	const struct pid *pid = inode->i_private;
653 
654 	if (*max_len < 2) {
655 		*max_len = 2;
656 		return FILEID_INVALID;
657 	}
658 
659 	*max_len = 2;
660 	*(u64 *)fh = pid->ino;
661 	return FILEID_KERNFS;
662 }
663 
664 static int pidfs_ino_find(const void *key, const struct rb_node *node)
665 {
666 	const u64 pid_ino = *(u64 *)key;
667 	const struct pid *pid = rb_entry(node, struct pid, pidfs_node);
668 
669 	if (pid_ino < pid->ino)
670 		return -1;
671 	if (pid_ino > pid->ino)
672 		return 1;
673 	return 0;
674 }
675 
676 /* Find a struct pid based on the inode number. */
677 static struct pid *pidfs_ino_get_pid(u64 ino)
678 {
679 	struct pid *pid;
680 	struct rb_node *node;
681 	unsigned int seq;
682 
683 	guard(rcu)();
684 	do {
685 		seq = read_seqcount_begin(&pidmap_lock_seq);
686 		node = rb_find_rcu(&ino, &pidfs_ino_tree, pidfs_ino_find);
687 		if (node)
688 			break;
689 	} while (read_seqcount_retry(&pidmap_lock_seq, seq));
690 
691 	if (!node)
692 		return NULL;
693 
694 	pid = rb_entry(node, struct pid, pidfs_node);
695 
696 	/* Within our pid namespace hierarchy? */
697 	if (pid_vnr(pid) == 0)
698 		return NULL;
699 
700 	return get_pid(pid);
701 }
702 
703 static struct dentry *pidfs_fh_to_dentry(struct super_block *sb,
704 					 struct fid *fid, int fh_len,
705 					 int fh_type)
706 {
707 	int ret;
708 	u64 pid_ino;
709 	struct path path;
710 	struct pid *pid;
711 
712 	if (fh_len < 2)
713 		return NULL;
714 
715 	switch (fh_type) {
716 	case FILEID_KERNFS:
717 		pid_ino = *(u64 *)fid;
718 		break;
719 	default:
720 		return NULL;
721 	}
722 
723 	pid = pidfs_ino_get_pid(pid_ino);
724 	if (!pid)
725 		return NULL;
726 
727 	ret = path_from_stashed(&pid->stashed, pidfs_mnt, pid, &path);
728 	if (ret < 0)
729 		return ERR_PTR(ret);
730 
731 	mntput(path.mnt);
732 	return path.dentry;
733 }
734 
735 /*
736  * Make sure that we reject any nonsensical flags that users pass via
737  * open_by_handle_at(). Note that PIDFD_THREAD is defined as O_EXCL, and
738  * PIDFD_NONBLOCK as O_NONBLOCK.
739  */
740 #define VALID_FILE_HANDLE_OPEN_FLAGS \
741 	(O_RDONLY | O_WRONLY | O_RDWR | O_NONBLOCK | O_CLOEXEC | O_EXCL)
742 
743 static int pidfs_export_permission(struct handle_to_path_ctx *ctx,
744 				   unsigned int oflags)
745 {
746 	if (oflags & ~(VALID_FILE_HANDLE_OPEN_FLAGS | O_LARGEFILE))
747 		return -EINVAL;
748 
749 	/*
750 	 * pidfd_ino_get_pid() will verify that the struct pid is part
751 	 * of the caller's pid namespace hierarchy. No further
752 	 * permission checks are needed.
753 	 */
754 	return 0;
755 }
756 
757 static inline bool pidfs_pid_valid(struct pid *pid, const struct path *path,
758 				   unsigned int flags)
759 {
760 	enum pid_type type;
761 
762 	if (flags & PIDFD_CLONE)
763 		return true;
764 
765 	/*
766 	 * Make sure that if a pidfd is created PIDFD_INFO_EXIT
767 	 * information will be available. So after an inode for the
768 	 * pidfd has been allocated perform another check that the pid
769 	 * is still alive. If it is exit information is available even
770 	 * if the task gets reaped before the pidfd is returned to
771 	 * userspace. The only exception is PIDFD_CLONE where no task
772 	 * linkage has been established for @pid yet and the kernel is
773 	 * in the middle of process creation so there's nothing for
774 	 * pidfs to miss.
775 	 */
776 	if (flags & PIDFD_THREAD)
777 		type = PIDTYPE_PID;
778 	else
779 		type = PIDTYPE_TGID;
780 
781 	/*
782 	 * Since pidfs_exit() is called before struct pid's task linkage
783 	 * is removed the case where the task got reaped but a dentry
784 	 * was already attached to struct pid and exit information was
785 	 * recorded and published can be handled correctly.
786 	 */
787 	if (unlikely(!pid_has_task(pid, type))) {
788 		struct inode *inode = d_inode(path->dentry);
789 		return !!READ_ONCE(pidfs_i(inode)->exit_info);
790 	}
791 
792 	return true;
793 }
794 
795 static struct file *pidfs_export_open(struct path *path, unsigned int oflags)
796 {
797 	if (!pidfs_pid_valid(d_inode(path->dentry)->i_private, path, oflags))
798 		return ERR_PTR(-ESRCH);
799 
800 	/*
801 	 * Clear O_LARGEFILE as open_by_handle_at() forces it and raise
802 	 * O_RDWR as pidfds always are.
803 	 */
804 	oflags &= ~O_LARGEFILE;
805 	return dentry_open(path, oflags | O_RDWR, current_cred());
806 }
807 
808 static const struct export_operations pidfs_export_operations = {
809 	.encode_fh	= pidfs_encode_fh,
810 	.fh_to_dentry	= pidfs_fh_to_dentry,
811 	.open		= pidfs_export_open,
812 	.permission	= pidfs_export_permission,
813 };
814 
815 static int pidfs_init_inode(struct inode *inode, void *data)
816 {
817 	const struct pid *pid = data;
818 
819 	inode->i_private = data;
820 	inode->i_flags |= S_PRIVATE;
821 	inode->i_mode |= S_IRWXU;
822 	inode->i_op = &pidfs_inode_operations;
823 	inode->i_fop = &pidfs_file_operations;
824 	inode->i_ino = pidfs_ino(pid->ino);
825 	inode->i_generation = pidfs_gen(pid->ino);
826 	return 0;
827 }
828 
829 static void pidfs_put_data(void *data)
830 {
831 	struct pid *pid = data;
832 	put_pid(pid);
833 }
834 
835 static const struct stashed_operations pidfs_stashed_ops = {
836 	.init_inode = pidfs_init_inode,
837 	.put_data = pidfs_put_data,
838 };
839 
840 static int pidfs_init_fs_context(struct fs_context *fc)
841 {
842 	struct pseudo_fs_context *ctx;
843 
844 	ctx = init_pseudo(fc, PID_FS_MAGIC);
845 	if (!ctx)
846 		return -ENOMEM;
847 
848 	ctx->ops = &pidfs_sops;
849 	ctx->eops = &pidfs_export_operations;
850 	ctx->dops = &pidfs_dentry_operations;
851 	fc->s_fs_info = (void *)&pidfs_stashed_ops;
852 	return 0;
853 }
854 
855 static struct file_system_type pidfs_type = {
856 	.name			= "pidfs",
857 	.init_fs_context	= pidfs_init_fs_context,
858 	.kill_sb		= kill_anon_super,
859 };
860 
861 struct file *pidfs_alloc_file(struct pid *pid, unsigned int flags)
862 {
863 	struct file *pidfd_file;
864 	struct path path __free(path_put) = {};
865 	int ret;
866 
867 	/*
868 	 * Ensure that PIDFD_CLONE can be passed as a flag without
869 	 * overloading other uapi pidfd flags.
870 	 */
871 	BUILD_BUG_ON(PIDFD_CLONE == PIDFD_THREAD);
872 	BUILD_BUG_ON(PIDFD_CLONE == PIDFD_NONBLOCK);
873 
874 	ret = path_from_stashed(&pid->stashed, pidfs_mnt, get_pid(pid), &path);
875 	if (ret < 0)
876 		return ERR_PTR(ret);
877 
878 	if (!pidfs_pid_valid(pid, &path, flags))
879 		return ERR_PTR(-ESRCH);
880 
881 	flags &= ~PIDFD_CLONE;
882 	pidfd_file = dentry_open(&path, flags, current_cred());
883 	/* Raise PIDFD_THREAD explicitly as do_dentry_open() strips it. */
884 	if (!IS_ERR(pidfd_file))
885 		pidfd_file->f_flags |= (flags & PIDFD_THREAD);
886 
887 	return pidfd_file;
888 }
889 
890 static void pidfs_inode_init_once(void *data)
891 {
892 	struct pidfs_inode *pi = data;
893 
894 	inode_init_once(&pi->vfs_inode);
895 }
896 
897 void __init pidfs_init(void)
898 {
899 	pidfs_cachep = kmem_cache_create("pidfs_cache", sizeof(struct pidfs_inode), 0,
900 					 (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT |
901 					  SLAB_ACCOUNT | SLAB_PANIC),
902 					 pidfs_inode_init_once);
903 	pidfs_mnt = kern_mount(&pidfs_type);
904 	if (IS_ERR(pidfs_mnt))
905 		panic("Failed to mount pidfs pseudo filesystem");
906 }
907