[RFC PATCH bpf-next RESEND 05/16] bpf/crib: Add struct file related CRIB kfuncs

From: Juntong Deng
Date: Thu Jul 11 2024 - 07:26:32 EST


This patch adds struct file related CRIB kfuncs.

bpf_file_from_task_fd() is used to get a pointer to the struct file
corresponding to the task file descriptor. Note that this function
acquires a reference to struct file.

bpf_file_release() is used to release the reference acquired on
struct file.

Signed-off-by: Juntong Deng <juntong.deng@xxxxxxxxxxx>
---
kernel/bpf/crib/bpf_crib.c | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)

diff --git a/kernel/bpf/crib/bpf_crib.c b/kernel/bpf/crib/bpf_crib.c
index 9ef2d61955bf..1c1729ddf233 100644
--- a/kernel/bpf/crib/bpf_crib.c
+++ b/kernel/bpf/crib/bpf_crib.c
@@ -8,13 +8,50 @@

#include <linux/bpf_crib.h>
#include <linux/init.h>
+#include <linux/fdtable.h>

__bpf_kfunc_start_defs();

+/**
+ * bpf_file_from_task_fd() - Get a pointer to the struct file
+ * corresponding to the task file descriptor.
+ *
+ * Note that this function acquires a reference to struct file.
+ *
+ * @task: specified struct task_struct
+ * @fd: file descriptor
+ *
+ * @returns the corresponding struct file pointer if found,
+ * otherwise returns NULL.
+ */
+__bpf_kfunc struct file *bpf_file_from_task_fd(struct task_struct *task, int fd)
+{
+ struct file *file;
+
+ rcu_read_lock();
+ file = task_lookup_fdget_rcu(task, fd);
+ rcu_read_unlock();
+
+ return file;
+}
+
+/**
+ * bpf_file_release() - Release the reference acquired on struct file.
+ *
+ * @file: struct file that has acquired the reference
+ */
+__bpf_kfunc void bpf_file_release(struct file *file)
+{
+ fput(file);
+}
+
__bpf_kfunc_end_defs();

BTF_KFUNCS_START(bpf_crib_kfuncs)

+BTF_ID_FLAGS(func, bpf_file_from_task_fd, KF_ACQUIRE | KF_TRUSTED_ARGS | KF_RET_NULL)
+BTF_ID_FLAGS(func, bpf_file_release, KF_RELEASE)
+
BTF_KFUNCS_END(bpf_crib_kfuncs)

static int bpf_prog_run_crib(struct bpf_prog *prog,
--
2.39.2