xref: /openbmc/linux/tools/testing/selftests/bpf/progs/cgrp_kfunc_common.h (revision 9df839a711aee437390b16ee39cf0b5c1620be6a)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 
4 #ifndef _CGRP_KFUNC_COMMON_H
5 #define _CGRP_KFUNC_COMMON_H
6 
7 #include <errno.h>
8 #include <vmlinux.h>
9 #include <bpf/bpf_helpers.h>
10 #include <bpf/bpf_tracing.h>
11 
12 struct __cgrps_kfunc_map_value {
13 	struct cgroup __kptr * cgrp;
14 };
15 
16 struct hash_map {
17 	__uint(type, BPF_MAP_TYPE_HASH);
18 	__type(key, int);
19 	__type(value, struct __cgrps_kfunc_map_value);
20 	__uint(max_entries, 1);
21 } __cgrps_kfunc_map SEC(".maps");
22 
23 struct cgroup *bpf_cgroup_acquire(struct cgroup *p) __ksym;
24 struct cgroup *bpf_cgroup_kptr_get(struct cgroup **pp) __ksym;
25 void bpf_cgroup_release(struct cgroup *p) __ksym;
26 struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level) __ksym;
27 struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;
28 
29 static inline struct __cgrps_kfunc_map_value *cgrps_kfunc_map_value_lookup(struct cgroup *cgrp)
30 {
31 	s32 id;
32 	long status;
33 
34 	status = bpf_probe_read_kernel(&id, sizeof(id), &cgrp->self.id);
35 	if (status)
36 		return NULL;
37 
38 	return bpf_map_lookup_elem(&__cgrps_kfunc_map, &id);
39 }
40 
41 static inline int cgrps_kfunc_map_insert(struct cgroup *cgrp)
42 {
43 	struct __cgrps_kfunc_map_value local, *v;
44 	long status;
45 	struct cgroup *acquired, *old;
46 	s32 id;
47 
48 	status = bpf_probe_read_kernel(&id, sizeof(id), &cgrp->self.id);
49 	if (status)
50 		return status;
51 
52 	local.cgrp = NULL;
53 	status = bpf_map_update_elem(&__cgrps_kfunc_map, &id, &local, BPF_NOEXIST);
54 	if (status)
55 		return status;
56 
57 	v = bpf_map_lookup_elem(&__cgrps_kfunc_map, &id);
58 	if (!v) {
59 		bpf_map_delete_elem(&__cgrps_kfunc_map, &id);
60 		return -ENOENT;
61 	}
62 
63 	acquired = bpf_cgroup_acquire(cgrp);
64 	old = bpf_kptr_xchg(&v->cgrp, acquired);
65 	if (old) {
66 		bpf_cgroup_release(old);
67 		return -EEXIST;
68 	}
69 
70 	return 0;
71 }
72 
73 #endif /* _CGRP_KFUNC_COMMON_H */
74