xref: /linux/tools/testing/selftests/bpf/progs/iters_task_failure.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
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 struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;
13 void bpf_cgroup_release(struct cgroup *p) __ksym;
14 void bpf_rcu_read_lock(void) __ksym;
15 void bpf_rcu_read_unlock(void) __ksym;
16 
17 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
18 __failure __msg("expected an RCU CS when using bpf_iter_task_next")
19 int BPF_PROG(iter_tasks_without_lock)
20 {
21 	struct task_struct *pos;
22 
23 	bpf_for_each(task, pos, NULL, BPF_TASK_ITER_ALL_PROCS) {
24 
25 	}
26 	return 0;
27 }
28 
29 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
30 __failure __msg("expected an RCU CS when using bpf_iter_css_next")
31 int BPF_PROG(iter_css_without_lock)
32 {
33 	u64 cg_id = bpf_get_current_cgroup_id();
34 	struct cgroup *cgrp = bpf_cgroup_from_id(cg_id);
35 	struct cgroup_subsys_state *root_css, *pos;
36 
37 	if (!cgrp)
38 		return 0;
39 	root_css = &cgrp->self;
40 
41 	bpf_for_each(css, pos, root_css, BPF_CGROUP_ITER_DESCENDANTS_POST) {
42 
43 	}
44 	bpf_cgroup_release(cgrp);
45 	return 0;
46 }
47 
48 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
49 __failure __msg("expected an RCU CS when using bpf_iter_task_next")
50 int BPF_PROG(iter_tasks_lock_and_unlock)
51 {
52 	struct task_struct *pos;
53 
54 	bpf_rcu_read_lock();
55 	bpf_for_each(task, pos, NULL, BPF_TASK_ITER_ALL_PROCS) {
56 		bpf_rcu_read_unlock();
57 
58 		bpf_rcu_read_lock();
59 	}
60 	bpf_rcu_read_unlock();
61 	return 0;
62 }
63 
64 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
65 __failure __msg("expected an RCU CS when using bpf_iter_css_next")
66 int BPF_PROG(iter_css_lock_and_unlock)
67 {
68 	u64 cg_id = bpf_get_current_cgroup_id();
69 	struct cgroup *cgrp = bpf_cgroup_from_id(cg_id);
70 	struct cgroup_subsys_state *root_css, *pos;
71 
72 	if (!cgrp)
73 		return 0;
74 	root_css = &cgrp->self;
75 
76 	bpf_rcu_read_lock();
77 	bpf_for_each(css, pos, root_css, BPF_CGROUP_ITER_DESCENDANTS_POST) {
78 		bpf_rcu_read_unlock();
79 
80 		bpf_rcu_read_lock();
81 	}
82 	bpf_rcu_read_unlock();
83 	bpf_cgroup_release(cgrp);
84 	return 0;
85 }
86 
87 SEC("?fentry/" SYS_PREFIX "sys_getpgid")
88 __failure __msg("css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs")
89 int BPF_PROG(iter_css_task_for_each)
90 {
91 	u64 cg_id = bpf_get_current_cgroup_id();
92 	struct cgroup *cgrp = bpf_cgroup_from_id(cg_id);
93 	struct cgroup_subsys_state *css;
94 	struct task_struct *task;
95 
96 	if (cgrp == NULL)
97 		return 0;
98 	css = &cgrp->self;
99 
100 	bpf_for_each(css_task, task, css, CSS_TASK_ITER_PROCS) {
101 
102 	}
103 	bpf_cgroup_release(cgrp);
104 	return 0;
105 }
106