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_ref * 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 28 static inline struct __cgrps_kfunc_map_value *cgrps_kfunc_map_value_lookup(struct cgroup *cgrp) 29 { 30 s32 id; 31 long status; 32 33 status = bpf_probe_read_kernel(&id, sizeof(id), &cgrp->self.id); 34 if (status) 35 return NULL; 36 37 return bpf_map_lookup_elem(&__cgrps_kfunc_map, &id); 38 } 39 40 static inline int cgrps_kfunc_map_insert(struct cgroup *cgrp) 41 { 42 struct __cgrps_kfunc_map_value local, *v; 43 long status; 44 struct cgroup *acquired, *old; 45 s32 id; 46 47 status = bpf_probe_read_kernel(&id, sizeof(id), &cgrp->self.id); 48 if (status) 49 return status; 50 51 local.cgrp = NULL; 52 status = bpf_map_update_elem(&__cgrps_kfunc_map, &id, &local, BPF_NOEXIST); 53 if (status) 54 return status; 55 56 v = bpf_map_lookup_elem(&__cgrps_kfunc_map, &id); 57 if (!v) { 58 bpf_map_delete_elem(&__cgrps_kfunc_map, &id); 59 return -ENOENT; 60 } 61 62 acquired = bpf_cgroup_acquire(cgrp); 63 old = bpf_kptr_xchg(&v->cgrp, acquired); 64 if (old) { 65 bpf_cgroup_release(old); 66 return -EEXIST; 67 } 68 69 return 0; 70 } 71 72 #endif /* _CGRP_KFUNC_COMMON_H */ 73