[RFC PATCH bpf-next 3/8] bpf: Add kfuncs for cgroup1 hierarchy

Yafang Shao
2023-10-07T14:03:23Z

Two new kfuncs are added to retrieve the cgroup1 IDs.

- bpf_task_cgroup1_id_within_hierarchy
Retrieves the associated cgroup ID of a task whithin a specific
cgroup1 hierarchy. The cgroup1 hierarchy is identified by its
hierarchy ID.
- bpf_task_ancestor_cgroup1_id_within_hierarchy
Retrieves the associated ancestor cgroup ID of a task whithin a
specific cgroup1 hierarchy. he specific ancestor cgroup is determined by
the ancestor level within the cgroup1 hierarchy.

These two new kfuncs enable the tracing of tasks within a designated
container or cgroup directory in BPF programs.

Signed-off-by: Yafang Shao <laoar.shao@gmail.com>
---
kernel/bpf/helpers.c | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)

diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index dd1c69ee3375..39ec6f9f2027 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -2214,6 +2214,30 @@ __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
{
return task_under_cgroup_hierarchy(task, ancestor);
}
+
+/**
+ * bpf_task_cgroup_id_within_hierarchy - Retrieves the associated cgroup ID of a
+ * task within a specific cgroup1 hierarchy.
+ * @task: The target task
+ * @hierarchy_id: The ID of a cgroup1 hierarchy
+ */
+__bpf_kfunc u64 bpf_task_cgroup1_id_within_hierarchy(struct task_struct *task, int hierarchy_id)
+{
+ return task_cgroup1_id_within_hierarchy(task, hierarchy_id);
+}
+
+/**
+ * bpf_task_ancestor_cgroup_id_within_hierarchy - Retrieves the associated
+ * ancestor cgroup ID of a task within a specific cgroup1 hierarchy.
+ * @task: The target task
+ * @hierarchy_id: The ID of a cgroup1 hierarchy
+ * @ancestor_level: The cgroup level of the ancestor in the cgroup1 hierarchy
+ */
+__bpf_kfunc u64 bpf_task_ancestor_cgroup1_id_within_hierarchy(struct task_struct *task,
+ int hierarchy_id, int ancestor_level)
+{
+ return task_ancestor_cgroup1_id_within_hierarchy(task, hierarchy_id, ancestor_level);
+}
#endif /* CONFIG_CGROUPS */

/**
@@ -2520,6 +2544,8 @@ BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_cgroup_from_id, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_task_under_cgroup, KF_RCU)
+BTF_ID_FLAGS(func, bpf_task_cgroup1_id_within_hierarchy, KF_RCU)
+BTF_ID_FLAGS(func, bpf_task_ancestor_cgroup1_id_within_hierarchy, KF_RCU)
#endif
BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_throw)
--
2.30.1 (Apple Git-130)