xref: /linux/tools/testing/selftests/bpf/progs/iters_css.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (C) 2023 Chuyi Zhou <zhouchuyi@bytedance.com> */
3 
4 #include "vmlinux.h"
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_tracing.h>
7 #include "bpf_misc.h"
8 #include "bpf_experimental.h"
9 
10 char _license[] SEC("license") = "GPL";
11 
12 pid_t target_pid;
13 u64 root_cg_id, leaf_cg_id;
14 u64 first_cg_id, last_cg_id;
15 int pre_order_cnt, post_order_cnt, children_cnt, tree_high;
16 
17 struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;
18 void bpf_cgroup_release(struct cgroup *p) __ksym;
19 void bpf_rcu_read_lock(void) __ksym;
20 void bpf_rcu_read_unlock(void) __ksym;
21 
22 SEC("fentry.s/" SYS_PREFIX "sys_getpgid")
23 int iter_css_for_each(const void *ctx)
24 {
25 	struct task_struct *cur_task = bpf_get_current_task_btf();
26 	struct cgroup_subsys_state *root_css, *leaf_css, *pos;
27 	struct cgroup *root_cgrp, *leaf_cgrp, *cur_cgrp;
28 
29 	if (cur_task->pid != target_pid)
30 		return 0;
31 
32 	root_cgrp = bpf_cgroup_from_id(root_cg_id);
33 
34 	if (!root_cgrp)
35 		return 0;
36 
37 	leaf_cgrp = bpf_cgroup_from_id(leaf_cg_id);
38 
39 	if (!leaf_cgrp) {
40 		bpf_cgroup_release(root_cgrp);
41 		return 0;
42 	}
43 	root_css = &root_cgrp->self;
44 	leaf_css = &leaf_cgrp->self;
45 	pre_order_cnt = post_order_cnt = children_cnt = tree_high = 0;
46 	first_cg_id = last_cg_id = 0;
47 
48 	bpf_rcu_read_lock();
49 	bpf_for_each(css, pos, root_css, BPF_CGROUP_ITER_DESCENDANTS_POST) {
50 		cur_cgrp = pos->cgroup;
51 		post_order_cnt++;
52 		last_cg_id = cur_cgrp->kn->id;
53 	}
54 
55 	bpf_for_each(css, pos, root_css, BPF_CGROUP_ITER_DESCENDANTS_PRE) {
56 		cur_cgrp = pos->cgroup;
57 		pre_order_cnt++;
58 		if (!first_cg_id)
59 			first_cg_id = cur_cgrp->kn->id;
60 	}
61 
62 	bpf_for_each(css, pos, root_css, BPF_CGROUP_ITER_CHILDREN) {
63 		children_cnt++;
64 	}
65 
66 	bpf_for_each(css, pos, leaf_css, BPF_CGROUP_ITER_ANCESTORS_UP)
67 		tree_high++;
68 
69 	bpf_for_each(css, pos, root_css, BPF_CGROUP_ITER_ANCESTORS_UP)
70 		tree_high--;
71 	bpf_rcu_read_unlock();
72 	bpf_cgroup_release(root_cgrp);
73 	bpf_cgroup_release(leaf_cgrp);
74 	return 0;
75 }
76