1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 /* Copyright (c) 2022 Hengqi Chen */
3
4 #ifndef __COMPAT_BPF_H
5 #define __COMPAT_BPF_H
6
7 #include <vmlinux.h>
8 #include <bpf/bpf_helpers.h>
9
10 #define MAX_EVENT_SIZE 10240
11 #define RINGBUF_SIZE (1024 * 256)
12
13 struct {
14 __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
15 __uint(max_entries, 1);
16 __uint(key_size, sizeof(__u32));
17 __uint(value_size, MAX_EVENT_SIZE);
18 } heap SEC(".maps");
19
20 struct {
21 __uint(type, BPF_MAP_TYPE_RINGBUF);
22 __uint(max_entries, RINGBUF_SIZE);
23 } events SEC(".maps");
24
reserve_buf(__u64 size)25 static __always_inline void *reserve_buf(__u64 size)
26 {
27 static const int zero = 0;
28
29 if (bpf_core_type_exists(struct bpf_ringbuf))
30 return bpf_ringbuf_reserve(&events, size, 0);
31
32 return bpf_map_lookup_elem(&heap, &zero);
33 }
34
submit_buf(void * ctx,void * buf,__u64 size)35 static __always_inline long submit_buf(void *ctx, void *buf, __u64 size)
36 {
37 if (bpf_core_type_exists(struct bpf_ringbuf)) {
38 bpf_ringbuf_submit(buf, 0);
39 return 0;
40 }
41
42 return bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, buf, size);
43 }
44
45 #endif /* __COMPAT_BPF_H */
46