• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 #ifndef __BPF_HELPERS__
3 #define __BPF_HELPERS__
4 
5 /*
6  * Note that bpf programs need to include either
7  * vmlinux.h (auto-generated from BTF) or linux/types.h
8  * in advance since bpf_helper_defs.h uses such types
9  * as __u64.
10  */
11 #include "bpf_helper_defs.h"
12 
13 #define __uint(name, val) int (*name)[val]
14 #define __type(name, val) typeof(val) *name
15 #define __array(name, val) typeof(val) *name[]
16 
17 /* Helper macro to print out debug messages */
18 #define bpf_printk(fmt, ...)				\
19 ({							\
20 	char ____fmt[] = fmt;				\
21 	bpf_trace_printk(____fmt, sizeof(____fmt),	\
22 			 ##__VA_ARGS__);		\
23 })
24 
25 /*
26  * Helper macro to place programs, maps, license in
27  * different sections in elf_bpf file. Section names
28  * are interpreted by libbpf depending on the context (BPF programs, BPF maps,
29  * extern variables, etc).
30  * To allow use of SEC() with externs (e.g., for extern .maps declarations),
31  * make sure __attribute__((unused)) doesn't trigger compilation warning.
32  */
33 #define SEC(name) \
34 	_Pragma("GCC diagnostic push")					    \
35 	_Pragma("GCC diagnostic ignored \"-Wignored-attributes\"")	    \
36 	__attribute__((section(name), used))				    \
37 	_Pragma("GCC diagnostic pop")					    \
38 
39 /* Avoid 'linux/stddef.h' definition of '__always_inline'. */
40 #undef __always_inline
41 #define __always_inline inline __attribute__((always_inline))
42 
43 #ifndef __noinline
44 #define __noinline __attribute__((noinline))
45 #endif
46 #ifndef __weak
47 #define __weak __attribute__((weak))
48 #endif
49 
50 /*
51  * Use __hidden attribute to mark a non-static BPF subprogram effectively
52  * static for BPF verifier's verification algorithm purposes, allowing more
53  * extensive and permissive BPF verification process, taking into account
54  * subprogram's caller context.
55  */
56 #define __hidden __attribute__((visibility("hidden")))
57 
58 /* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
59  * any system-level headers (such as stddef.h, linux/version.h, etc), and
60  * commonly-used macros like NULL and KERNEL_VERSION aren't available through
61  * vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
62  * them on their own. So as a convenience, provide such definitions here.
63  */
64 #ifndef NULL
65 #define NULL ((void *)0)
66 #endif
67 
68 #ifndef KERNEL_VERSION
69 #define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
70 #endif
71 
72 /*
73  * Helper macros to manipulate data structures
74  */
75 
76 /* offsetof() definition that uses __builtin_offset() might not preserve field
77  * offset CO-RE relocation properly, so force-redefine offsetof() using
78  * old-school approach which works with CO-RE correctly
79  */
80 #undef offsetof
81 #define offsetof(type, member)	((unsigned long)&((type *)0)->member)
82 
83 /* redefined container_of() to ensure we use the above offsetof() macro */
84 #undef container_of
85 #define container_of(ptr, type, member)				\
86 	({							\
87 		void *__mptr = (void *)(ptr);			\
88 		((type *)(__mptr - offsetof(type, member)));	\
89 	})
90 
91 /*
92  * Helper macro to throw a compilation error if __bpf_unreachable() gets
93  * built into the resulting code. This works given BPF back end does not
94  * implement __builtin_trap(). This is useful to assert that certain paths
95  * of the program code are never used and hence eliminated by the compiler.
96  *
97  * For example, consider a switch statement that covers known cases used by
98  * the program. __bpf_unreachable() can then reside in the default case. If
99  * the program gets extended such that a case is not covered in the switch
100  * statement, then it will throw a build error due to the default case not
101  * being compiled out.
102  */
103 #ifndef __bpf_unreachable
104 # define __bpf_unreachable()	__builtin_trap()
105 #endif
106 
107 /*
108  * Helper function to perform a tail call with a constant/immediate map slot.
109  */
110 #if __clang_major__ >= 8 && defined(__bpf__)
111 static __always_inline void
bpf_tail_call_static(void * ctx,const void * map,const __u32 slot)112 bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
113 {
114 	if (!__builtin_constant_p(slot))
115 		__bpf_unreachable();
116 
117 	/*
118 	 * Provide a hard guarantee that LLVM won't optimize setting r2 (map
119 	 * pointer) and r3 (constant map index) from _different paths_ ending
120 	 * up at the _same_ call insn as otherwise we won't be able to use the
121 	 * jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
122 	 * given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
123 	 * tracking for prog array pokes") for details on verifier tracking.
124 	 *
125 	 * Note on clobber list: we need to stay in-line with BPF calling
126 	 * convention, so even if we don't end up using r0, r4, r5, we need
127 	 * to mark them as clobber so that LLVM doesn't end up using them
128 	 * before / after the call.
129 	 */
130 	asm volatile("r1 = %[ctx]\n\t"
131 		     "r2 = %[map]\n\t"
132 		     "r3 = %[slot]\n\t"
133 		     "call 12"
134 		     :: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
135 		     : "r0", "r1", "r2", "r3", "r4", "r5");
136 }
137 #endif
138 
139 /*
140  * Helper structure used by eBPF C program
141  * to describe BPF map attributes to libbpf loader
142  */
143 struct bpf_map_def {
144 	unsigned int type;
145 	unsigned int key_size;
146 	unsigned int value_size;
147 	unsigned int max_entries;
148 	unsigned int map_flags;
149 };
150 
151 enum libbpf_pin_type {
152 	LIBBPF_PIN_NONE,
153 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
154 	LIBBPF_PIN_BY_NAME,
155 };
156 
157 enum libbpf_tristate {
158 	TRI_NO = 0,
159 	TRI_YES = 1,
160 	TRI_MODULE = 2,
161 };
162 
163 #define __kconfig __attribute__((section(".kconfig")))
164 #define __ksym __attribute__((section(".ksyms")))
165 
166 #ifndef ___bpf_concat
167 #define ___bpf_concat(a, b) a ## b
168 #endif
169 #ifndef ___bpf_apply
170 #define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
171 #endif
172 #ifndef ___bpf_nth
173 #define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
174 #endif
175 #ifndef ___bpf_narg
176 #define ___bpf_narg(...) \
177 	___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
178 #endif
179 
180 #define ___bpf_fill0(arr, p, x) do {} while (0)
181 #define ___bpf_fill1(arr, p, x) arr[p] = x
182 #define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
183 #define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
184 #define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
185 #define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
186 #define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
187 #define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
188 #define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
189 #define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
190 #define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
191 #define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
192 #define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
193 #define ___bpf_fill(arr, args...) \
194 	___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
195 
196 /*
197  * BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
198  * in a structure.
199  */
200 #define BPF_SEQ_PRINTF(seq, fmt, args...)			\
201 ({								\
202 	static const char ___fmt[] = fmt;			\
203 	unsigned long long ___param[___bpf_narg(args)];		\
204 								\
205 	_Pragma("GCC diagnostic push")				\
206 	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
207 	___bpf_fill(___param, args);				\
208 	_Pragma("GCC diagnostic pop")				\
209 								\
210 	bpf_seq_printf(seq, ___fmt, sizeof(___fmt),		\
211 		       ___param, sizeof(___param));		\
212 })
213 
214 /*
215  * BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
216  * an array of u64.
217  */
218 #define BPF_SNPRINTF(out, out_size, fmt, args...)		\
219 ({								\
220 	static const char ___fmt[] = fmt;			\
221 	unsigned long long ___param[___bpf_narg(args)];		\
222 								\
223 	_Pragma("GCC diagnostic push")				\
224 	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
225 	___bpf_fill(___param, args);				\
226 	_Pragma("GCC diagnostic pop")				\
227 								\
228 	bpf_snprintf(out, out_size, ___fmt,			\
229 		     ___param, sizeof(___param));		\
230 })
231 
232 #endif
233