xref: /linux/tools/perf/util/bpf-utils.h (revision 8dc364fa484df22d301a16148d1b356931d0cbb0)
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 #ifndef __PERF_BPF_UTILS_H
4 #define __PERF_BPF_UTILS_H
5 
6 #define ptr_to_u64(ptr)    ((__u64)(unsigned long)(ptr))
7 
8 #ifdef HAVE_LIBBPF_SUPPORT
9 
10 #include <bpf/libbpf.h>
11 #include <bpf/libbpf_version.h>
12 
13 #define LIBBPF_CURRENT_VERSION_GEQ(major, minor)                       \
14        (LIBBPF_MAJOR_VERSION > (major) ||                              \
15         (LIBBPF_MAJOR_VERSION == (major) && LIBBPF_MINOR_VERSION >= (minor)))
16 
17 /*
18  * Get bpf_prog_info in continuous memory
19  *
20  * struct bpf_prog_info has multiple arrays. The user has option to choose
21  * arrays to fetch from kernel. The following APIs provide an uniform way to
22  * fetch these data. All arrays in bpf_prog_info are stored in a single
23  * continuous memory region. This makes it easy to store the info in a
24  * file.
25  *
26  * Before writing perf_bpil to files, it is necessary to
27  * translate pointers in bpf_prog_info to offsets. Helper functions
28  * bpil_addr_to_offs() and bpil_offs_to_addr()
29  * are introduced to switch between pointers and offsets.
30  *
31  * Examples:
32  *   # To fetch map_ids and prog_tags:
33  *   __u64 arrays = (1UL << PERF_BPIL_MAP_IDS) |
34  *           (1UL << PERF_BPIL_PROG_TAGS);
35  *   struct perf_bpil *info_linear =
36  *           get_bpf_prog_info_linear(fd, arrays);
37  *
38  *   # To save data in file
39  *   bpil_addr_to_offs(info_linear);
40  *   write(f, info_linear, sizeof(*info_linear) + info_linear->data_len);
41  *
42  *   # To read data from file
43  *   read(f, info_linear, <proper_size>);
44  *   bpil_offs_to_addr(info_linear);
45  */
46 enum perf_bpil_array_types {
47 	PERF_BPIL_FIRST_ARRAY = 0,
48 	PERF_BPIL_JITED_INSNS = 0,
49 	PERF_BPIL_XLATED_INSNS,
50 	PERF_BPIL_MAP_IDS,
51 	PERF_BPIL_JITED_KSYMS,
52 	PERF_BPIL_JITED_FUNC_LENS,
53 	PERF_BPIL_FUNC_INFO,
54 	PERF_BPIL_LINE_INFO,
55 	PERF_BPIL_JITED_LINE_INFO,
56 	PERF_BPIL_PROG_TAGS,
57 	PERF_BPIL_LAST_ARRAY,
58 };
59 
60 struct perf_bpil {
61 	/* size of struct bpf_prog_info, when the tool is compiled */
62 	__u32			info_len;
63 	/* total bytes allocated for data, round up to 8 bytes */
64 	__u32			data_len;
65 	/* which arrays are included in data */
66 	__u64			arrays;
67 	struct bpf_prog_info	info;
68 	__u8			data[];
69 };
70 
71 struct perf_bpil *
72 get_bpf_prog_info_linear(int fd, __u64 arrays);
73 
74 void
75 bpil_addr_to_offs(struct perf_bpil *info_linear);
76 
77 void
78 bpil_offs_to_addr(struct perf_bpil *info_linear);
79 
80 #endif /* HAVE_LIBBPF_SUPPORT */
81 #endif /* __PERF_BPF_UTILS_H */
82