xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/bpf/bpf_common.h (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3  * Copyright (c) 2019-2020 Linux Test Project
4  */
5 
6 #ifndef LTP_BPF_COMMON_H
7 #define LTP_BPF_COMMON_H
8 
9 #include <sys/types.h>
10 #include <inttypes.h>
11 
12 #include "lapi/bpf.h"
13 #include "lapi/socket.h"
14 
15 #define BPF_MEMLOCK_ADD (2*1024*1024)
16 #define BUFSIZE 8192
17 
18 /* map[array_indx] = reg_to_save
19  *
20  * Inserts the following instructions
21  *
22  * r1 = map_fd
23  * r2 = fp
24  * r2 = r2 - 4
25  * r2 = array_indx
26  * call map_lookup_elem(r1, r2)
27  * if r0 != 0 goto pc+1
28  * exit
29  * *r0 = reg_to_save
30  *
31  */
32 #define BPF_MAP_ARRAY_STX(map_fd, array_indx, reg_to_save)\
33 	BPF_LD_MAP_FD(BPF_REG_1, map_fd),		\
34 	BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),		\
35 	BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4),		\
36 	BPF_ST_MEM(BPF_W, BPF_REG_2, 0, array_indx),	\
37 	BPF_EMIT_CALL(BPF_FUNC_map_lookup_elem),	\
38 	BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 1),		\
39 	BPF_EXIT_INSN(),				\
40 	BPF_STX_MEM(BPF_DW, BPF_REG_0, reg_to_save, 0)
41 
42 void rlimit_bump_memlock(void);
43 
44 int bpf_map_create(union bpf_attr *const attr)
45 	__attribute__((nonnull, warn_unused_result));
46 int bpf_map_array_create(const uint32_t max_entries)
47 	__attribute__((warn_unused_result));
48 void bpf_map_array_get(const int map_fd,
49 		       const uint32_t *const array_indx,
50 		       uint64_t *const array_val)
51 	__attribute__((nonnull));
52 
53 void bpf_init_prog_attr(union bpf_attr *const attr,
54 			const struct bpf_insn *const prog,
55 			const size_t prog_size,
56 			char *const log_buf, const size_t log_size)
57 	__attribute__((nonnull));
58 int bpf_load_prog(union bpf_attr *const attr, const char *const log)
59 	__attribute__((nonnull, warn_unused_result));
60 void bpf_run_prog(const int prog_fd,
61 		  const char *const msg, const size_t msg_len)
62 	__attribute__((nonnull));
63 
64 #endif
65