Linux Audio

Check our new training course

Loading...
v6.2
  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/*
 18 * Helper macro to place programs, maps, license in
 19 * different sections in elf_bpf file. Section names
 20 * are interpreted by libbpf depending on the context (BPF programs, BPF maps,
 21 * extern variables, etc).
 22 * To allow use of SEC() with externs (e.g., for extern .maps declarations),
 23 * make sure __attribute__((unused)) doesn't trigger compilation warning.
 24 */
 25#if __GNUC__ && !__clang__
 26
 27/*
 28 * Pragma macros are broken on GCC
 29 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55578
 30 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90400
 31 */
 32#define SEC(name) __attribute__((section(name), used))
 33
 34#else
 35
 36#define SEC(name) \
 37	_Pragma("GCC diagnostic push")					    \
 38	_Pragma("GCC diagnostic ignored \"-Wignored-attributes\"")	    \
 39	__attribute__((section(name), used))				    \
 40	_Pragma("GCC diagnostic pop")					    \
 41
 42#endif
 43
 44/* Avoid 'linux/stddef.h' definition of '__always_inline'. */
 45#undef __always_inline
 46#define __always_inline inline __attribute__((always_inline))
 47
 48#ifndef __noinline
 49#define __noinline __attribute__((noinline))
 50#endif
 51#ifndef __weak
 52#define __weak __attribute__((weak))
 53#endif
 54
 55/*
 56 * Use __hidden attribute to mark a non-static BPF subprogram effectively
 57 * static for BPF verifier's verification algorithm purposes, allowing more
 58 * extensive and permissive BPF verification process, taking into account
 59 * subprogram's caller context.
 60 */
 61#define __hidden __attribute__((visibility("hidden")))
 62
 63/* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
 64 * any system-level headers (such as stddef.h, linux/version.h, etc), and
 65 * commonly-used macros like NULL and KERNEL_VERSION aren't available through
 66 * vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
 67 * them on their own. So as a convenience, provide such definitions here.
 68 */
 69#ifndef NULL
 70#define NULL ((void *)0)
 71#endif
 72
 73#ifndef KERNEL_VERSION
 74#define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
 75#endif
 76
 77/*
 78 * Helper macros to manipulate data structures
 79 */
 80#ifndef offsetof
 81#define offsetof(TYPE, MEMBER)	((unsigned long)&((TYPE *)0)->MEMBER)
 82#endif
 83#ifndef container_of
 
 
 
 
 
 
 84#define container_of(ptr, type, member)				\
 85	({							\
 86		void *__mptr = (void *)(ptr);			\
 87		((type *)(__mptr - offsetof(type, member)));	\
 88	})
 89#endif
 90
 91/*
 92 * Compiler (optimization) barrier.
 93 */
 94#ifndef barrier
 95#define barrier() asm volatile("" ::: "memory")
 96#endif
 97
 98/* Variable-specific compiler (optimization) barrier. It's a no-op which makes
 99 * compiler believe that there is some black box modification of a given
100 * variable and thus prevents compiler from making extra assumption about its
101 * value and potential simplifications and optimizations on this variable.
102 *
103 * E.g., compiler might often delay or even omit 32-bit to 64-bit casting of
104 * a variable, making some code patterns unverifiable. Putting barrier_var()
105 * in place will ensure that cast is performed before the barrier_var()
106 * invocation, because compiler has to pessimistically assume that embedded
107 * asm section might perform some extra operations on that variable.
108 *
109 * This is a variable-specific variant of more global barrier().
110 */
111#ifndef barrier_var
112#define barrier_var(var) asm volatile("" : "=r"(var) : "0"(var))
113#endif
114
115/*
116 * Helper macro to throw a compilation error if __bpf_unreachable() gets
117 * built into the resulting code. This works given BPF back end does not
118 * implement __builtin_trap(). This is useful to assert that certain paths
119 * of the program code are never used and hence eliminated by the compiler.
120 *
121 * For example, consider a switch statement that covers known cases used by
122 * the program. __bpf_unreachable() can then reside in the default case. If
123 * the program gets extended such that a case is not covered in the switch
124 * statement, then it will throw a build error due to the default case not
125 * being compiled out.
126 */
127#ifndef __bpf_unreachable
128# define __bpf_unreachable()	__builtin_trap()
129#endif
130
131/*
132 * Helper function to perform a tail call with a constant/immediate map slot.
133 */
134#if __clang_major__ >= 8 && defined(__bpf__)
 
135static __always_inline void
136bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
137{
138	if (!__builtin_constant_p(slot))
139		__bpf_unreachable();
140
141	/*
142	 * Provide a hard guarantee that LLVM won't optimize setting r2 (map
143	 * pointer) and r3 (constant map index) from _different paths_ ending
144	 * up at the _same_ call insn as otherwise we won't be able to use the
145	 * jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
146	 * given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
147	 * tracking for prog array pokes") for details on verifier tracking.
148	 *
149	 * Note on clobber list: we need to stay in-line with BPF calling
150	 * convention, so even if we don't end up using r0, r4, r5, we need
151	 * to mark them as clobber so that LLVM doesn't end up using them
152	 * before / after the call.
153	 */
154	asm volatile("r1 = %[ctx]\n\t"
155		     "r2 = %[map]\n\t"
156		     "r3 = %[slot]\n\t"
157		     "call 12"
158		     :: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
159		     : "r0", "r1", "r2", "r3", "r4", "r5");
160}
161#endif
 
162
163enum libbpf_pin_type {
164	LIBBPF_PIN_NONE,
165	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
166	LIBBPF_PIN_BY_NAME,
167};
168
169enum libbpf_tristate {
170	TRI_NO = 0,
171	TRI_YES = 1,
172	TRI_MODULE = 2,
173};
174
175#define __kconfig __attribute__((section(".kconfig")))
176#define __ksym __attribute__((section(".ksyms")))
 
177#define __kptr __attribute__((btf_type_tag("kptr")))
178#define __kptr_ref __attribute__((btf_type_tag("kptr_ref")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
180#ifndef ___bpf_concat
181#define ___bpf_concat(a, b) a ## b
182#endif
183#ifndef ___bpf_apply
184#define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
185#endif
186#ifndef ___bpf_nth
187#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
188#endif
189#ifndef ___bpf_narg
190#define ___bpf_narg(...) \
191	___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
192#endif
193
194#define ___bpf_fill0(arr, p, x) do {} while (0)
195#define ___bpf_fill1(arr, p, x) arr[p] = x
196#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
197#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
198#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
199#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
200#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
201#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
202#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
203#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
204#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
205#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
206#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
207#define ___bpf_fill(arr, args...) \
208	___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
209
210/*
211 * BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
212 * in a structure.
213 */
214#define BPF_SEQ_PRINTF(seq, fmt, args...)			\
215({								\
216	static const char ___fmt[] = fmt;			\
217	unsigned long long ___param[___bpf_narg(args)];		\
218								\
219	_Pragma("GCC diagnostic push")				\
220	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
221	___bpf_fill(___param, args);				\
222	_Pragma("GCC diagnostic pop")				\
223								\
224	bpf_seq_printf(seq, ___fmt, sizeof(___fmt),		\
225		       ___param, sizeof(___param));		\
226})
227
228/*
229 * BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
230 * an array of u64.
231 */
232#define BPF_SNPRINTF(out, out_size, fmt, args...)		\
233({								\
234	static const char ___fmt[] = fmt;			\
235	unsigned long long ___param[___bpf_narg(args)];		\
236								\
237	_Pragma("GCC diagnostic push")				\
238	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
239	___bpf_fill(___param, args);				\
240	_Pragma("GCC diagnostic pop")				\
241								\
242	bpf_snprintf(out, out_size, ___fmt,			\
243		     ___param, sizeof(___param));		\
244})
245
246#ifdef BPF_NO_GLOBAL_DATA
247#define BPF_PRINTK_FMT_MOD
248#else
249#define BPF_PRINTK_FMT_MOD static const
250#endif
251
252#define __bpf_printk(fmt, ...)				\
253({							\
254	BPF_PRINTK_FMT_MOD char ____fmt[] = fmt;	\
255	bpf_trace_printk(____fmt, sizeof(____fmt),	\
256			 ##__VA_ARGS__);		\
257})
258
259/*
260 * __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments
261 * instead of an array of u64.
262 */
263#define __bpf_vprintk(fmt, args...)				\
264({								\
265	static const char ___fmt[] = fmt;			\
266	unsigned long long ___param[___bpf_narg(args)];		\
267								\
268	_Pragma("GCC diagnostic push")				\
269	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
270	___bpf_fill(___param, args);				\
271	_Pragma("GCC diagnostic pop")				\
272								\
273	bpf_trace_vprintk(___fmt, sizeof(___fmt),		\
274			  ___param, sizeof(___param));		\
275})
276
277/* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args
278 * Otherwise use __bpf_vprintk
279 */
280#define ___bpf_pick_printk(...) \
281	___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk,	\
282		   __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk,		\
283		   __bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\
284		   __bpf_printk /*1*/, __bpf_printk /*0*/)
285
286/* Helper macro to print out debug messages */
287#define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
289#endif
v6.13.7
  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#define __ulong(name, val) enum { ___bpf_concat(__unique_value, __COUNTER__) = val } name
 17
 18/*
 19 * Helper macro to place programs, maps, license in
 20 * different sections in elf_bpf file. Section names
 21 * are interpreted by libbpf depending on the context (BPF programs, BPF maps,
 22 * extern variables, etc).
 23 * To allow use of SEC() with externs (e.g., for extern .maps declarations),
 24 * make sure __attribute__((unused)) doesn't trigger compilation warning.
 25 */
 26#if __GNUC__ && !__clang__
 27
 28/*
 29 * Pragma macros are broken on GCC
 30 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55578
 31 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90400
 32 */
 33#define SEC(name) __attribute__((section(name), used))
 34
 35#else
 36
 37#define SEC(name) \
 38	_Pragma("GCC diagnostic push")					    \
 39	_Pragma("GCC diagnostic ignored \"-Wignored-attributes\"")	    \
 40	__attribute__((section(name), used))				    \
 41	_Pragma("GCC diagnostic pop")					    \
 42
 43#endif
 44
 45/* Avoid 'linux/stddef.h' definition of '__always_inline'. */
 46#undef __always_inline
 47#define __always_inline inline __attribute__((always_inline))
 48
 49#ifndef __noinline
 50#define __noinline __attribute__((noinline))
 51#endif
 52#ifndef __weak
 53#define __weak __attribute__((weak))
 54#endif
 55
 56/*
 57 * Use __hidden attribute to mark a non-static BPF subprogram effectively
 58 * static for BPF verifier's verification algorithm purposes, allowing more
 59 * extensive and permissive BPF verification process, taking into account
 60 * subprogram's caller context.
 61 */
 62#define __hidden __attribute__((visibility("hidden")))
 63
 64/* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
 65 * any system-level headers (such as stddef.h, linux/version.h, etc), and
 66 * commonly-used macros like NULL and KERNEL_VERSION aren't available through
 67 * vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
 68 * them on their own. So as a convenience, provide such definitions here.
 69 */
 70#ifndef NULL
 71#define NULL ((void *)0)
 72#endif
 73
 74#ifndef KERNEL_VERSION
 75#define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
 76#endif
 77
 78/*
 79 * Helper macros to manipulate data structures
 80 */
 81
 82/* offsetof() definition that uses __builtin_offset() might not preserve field
 83 * offset CO-RE relocation properly, so force-redefine offsetof() using
 84 * old-school approach which works with CO-RE correctly
 85 */
 86#undef offsetof
 87#define offsetof(type, member)	((unsigned long)&((type *)0)->member)
 88
 89/* redefined container_of() to ensure we use the above offsetof() macro */
 90#undef container_of
 91#define container_of(ptr, type, member)				\
 92	({							\
 93		void *__mptr = (void *)(ptr);			\
 94		((type *)(__mptr - offsetof(type, member)));	\
 95	})
 
 96
 97/*
 98 * Compiler (optimization) barrier.
 99 */
100#ifndef barrier
101#define barrier() asm volatile("" ::: "memory")
102#endif
103
104/* Variable-specific compiler (optimization) barrier. It's a no-op which makes
105 * compiler believe that there is some black box modification of a given
106 * variable and thus prevents compiler from making extra assumption about its
107 * value and potential simplifications and optimizations on this variable.
108 *
109 * E.g., compiler might often delay or even omit 32-bit to 64-bit casting of
110 * a variable, making some code patterns unverifiable. Putting barrier_var()
111 * in place will ensure that cast is performed before the barrier_var()
112 * invocation, because compiler has to pessimistically assume that embedded
113 * asm section might perform some extra operations on that variable.
114 *
115 * This is a variable-specific variant of more global barrier().
116 */
117#ifndef barrier_var
118#define barrier_var(var) asm volatile("" : "+r"(var))
119#endif
120
121/*
122 * Helper macro to throw a compilation error if __bpf_unreachable() gets
123 * built into the resulting code. This works given BPF back end does not
124 * implement __builtin_trap(). This is useful to assert that certain paths
125 * of the program code are never used and hence eliminated by the compiler.
126 *
127 * For example, consider a switch statement that covers known cases used by
128 * the program. __bpf_unreachable() can then reside in the default case. If
129 * the program gets extended such that a case is not covered in the switch
130 * statement, then it will throw a build error due to the default case not
131 * being compiled out.
132 */
133#ifndef __bpf_unreachable
134# define __bpf_unreachable()	__builtin_trap()
135#endif
136
137/*
138 * Helper function to perform a tail call with a constant/immediate map slot.
139 */
140#if (defined(__clang__) && __clang_major__ >= 8) || (!defined(__clang__) && __GNUC__ > 12)
141#if defined(__bpf__)
142static __always_inline void
143bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
144{
145	if (!__builtin_constant_p(slot))
146		__bpf_unreachable();
147
148	/*
149	 * Provide a hard guarantee that LLVM won't optimize setting r2 (map
150	 * pointer) and r3 (constant map index) from _different paths_ ending
151	 * up at the _same_ call insn as otherwise we won't be able to use the
152	 * jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
153	 * given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
154	 * tracking for prog array pokes") for details on verifier tracking.
155	 *
156	 * Note on clobber list: we need to stay in-line with BPF calling
157	 * convention, so even if we don't end up using r0, r4, r5, we need
158	 * to mark them as clobber so that LLVM doesn't end up using them
159	 * before / after the call.
160	 */
161	asm volatile("r1 = %[ctx]\n\t"
162		     "r2 = %[map]\n\t"
163		     "r3 = %[slot]\n\t"
164		     "call 12"
165		     :: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
166		     : "r0", "r1", "r2", "r3", "r4", "r5");
167}
168#endif
169#endif
170
171enum libbpf_pin_type {
172	LIBBPF_PIN_NONE,
173	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
174	LIBBPF_PIN_BY_NAME,
175};
176
177enum libbpf_tristate {
178	TRI_NO = 0,
179	TRI_YES = 1,
180	TRI_MODULE = 2,
181};
182
183#define __kconfig __attribute__((section(".kconfig")))
184#define __ksym __attribute__((section(".ksyms")))
185#define __kptr_untrusted __attribute__((btf_type_tag("kptr_untrusted")))
186#define __kptr __attribute__((btf_type_tag("kptr")))
187#define __percpu_kptr __attribute__((btf_type_tag("percpu_kptr")))
188#define __uptr __attribute__((btf_type_tag("uptr")))
189
190#if defined (__clang__)
191#define bpf_ksym_exists(sym) ({						\
192	_Static_assert(!__builtin_constant_p(!!sym),			\
193		       #sym " should be marked as __weak");		\
194	!!sym;								\
195})
196#elif __GNUC__ > 8
197#define bpf_ksym_exists(sym) ({						\
198	_Static_assert(__builtin_has_attribute (*sym, __weak__),	\
199		       #sym " should be marked as __weak");		\
200	!!sym;								\
201})
202#else
203#define bpf_ksym_exists(sym) !!sym
204#endif
205
206#define __arg_ctx __attribute__((btf_decl_tag("arg:ctx")))
207#define __arg_nonnull __attribute((btf_decl_tag("arg:nonnull")))
208#define __arg_nullable __attribute((btf_decl_tag("arg:nullable")))
209#define __arg_trusted __attribute((btf_decl_tag("arg:trusted")))
210#define __arg_arena __attribute((btf_decl_tag("arg:arena")))
211
212#ifndef ___bpf_concat
213#define ___bpf_concat(a, b) a ## b
214#endif
215#ifndef ___bpf_apply
216#define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
217#endif
218#ifndef ___bpf_nth
219#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
220#endif
221#ifndef ___bpf_narg
222#define ___bpf_narg(...) \
223	___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
224#endif
225
226#define ___bpf_fill0(arr, p, x) do {} while (0)
227#define ___bpf_fill1(arr, p, x) arr[p] = x
228#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
229#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
230#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
231#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
232#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
233#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
234#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
235#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
236#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
237#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
238#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
239#define ___bpf_fill(arr, args...) \
240	___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
241
242/*
243 * BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
244 * in a structure.
245 */
246#define BPF_SEQ_PRINTF(seq, fmt, args...)			\
247({								\
248	static const char ___fmt[] = fmt;			\
249	unsigned long long ___param[___bpf_narg(args)];		\
250								\
251	_Pragma("GCC diagnostic push")				\
252	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
253	___bpf_fill(___param, args);				\
254	_Pragma("GCC diagnostic pop")				\
255								\
256	bpf_seq_printf(seq, ___fmt, sizeof(___fmt),		\
257		       ___param, sizeof(___param));		\
258})
259
260/*
261 * BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
262 * an array of u64.
263 */
264#define BPF_SNPRINTF(out, out_size, fmt, args...)		\
265({								\
266	static const char ___fmt[] = fmt;			\
267	unsigned long long ___param[___bpf_narg(args)];		\
268								\
269	_Pragma("GCC diagnostic push")				\
270	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
271	___bpf_fill(___param, args);				\
272	_Pragma("GCC diagnostic pop")				\
273								\
274	bpf_snprintf(out, out_size, ___fmt,			\
275		     ___param, sizeof(___param));		\
276})
277
278#ifdef BPF_NO_GLOBAL_DATA
279#define BPF_PRINTK_FMT_MOD
280#else
281#define BPF_PRINTK_FMT_MOD static const
282#endif
283
284#define __bpf_printk(fmt, ...)				\
285({							\
286	BPF_PRINTK_FMT_MOD char ____fmt[] = fmt;	\
287	bpf_trace_printk(____fmt, sizeof(____fmt),	\
288			 ##__VA_ARGS__);		\
289})
290
291/*
292 * __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments
293 * instead of an array of u64.
294 */
295#define __bpf_vprintk(fmt, args...)				\
296({								\
297	static const char ___fmt[] = fmt;			\
298	unsigned long long ___param[___bpf_narg(args)];		\
299								\
300	_Pragma("GCC diagnostic push")				\
301	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
302	___bpf_fill(___param, args);				\
303	_Pragma("GCC diagnostic pop")				\
304								\
305	bpf_trace_vprintk(___fmt, sizeof(___fmt),		\
306			  ___param, sizeof(___param));		\
307})
308
309/* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args
310 * Otherwise use __bpf_vprintk
311 */
312#define ___bpf_pick_printk(...) \
313	___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk,	\
314		   __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk,		\
315		   __bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\
316		   __bpf_printk /*1*/, __bpf_printk /*0*/)
317
318/* Helper macro to print out debug messages */
319#define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args)
320
321struct bpf_iter_num;
322
323extern int bpf_iter_num_new(struct bpf_iter_num *it, int start, int end) __weak __ksym;
324extern int *bpf_iter_num_next(struct bpf_iter_num *it) __weak __ksym;
325extern void bpf_iter_num_destroy(struct bpf_iter_num *it) __weak __ksym;
326
327#ifndef bpf_for_each
328/* bpf_for_each(iter_type, cur_elem, args...) provides generic construct for
329 * using BPF open-coded iterators without having to write mundane explicit
330 * low-level loop logic. Instead, it provides for()-like generic construct
331 * that can be used pretty naturally. E.g., for some hypothetical cgroup
332 * iterator, you'd write:
333 *
334 * struct cgroup *cg, *parent_cg = <...>;
335 *
336 * bpf_for_each(cgroup, cg, parent_cg, CG_ITER_CHILDREN) {
337 *     bpf_printk("Child cgroup id = %d", cg->cgroup_id);
338 *     if (cg->cgroup_id == 123)
339 *         break;
340 * }
341 *
342 * I.e., it looks almost like high-level for each loop in other languages,
343 * supports continue/break, and is verifiable by BPF verifier.
344 *
345 * For iterating integers, the difference between bpf_for_each(num, i, N, M)
346 * and bpf_for(i, N, M) is in that bpf_for() provides additional proof to
347 * verifier that i is in [N, M) range, and in bpf_for_each() case i is `int
348 * *`, not just `int`. So for integers bpf_for() is more convenient.
349 *
350 * Note: this macro relies on C99 feature of allowing to declare variables
351 * inside for() loop, bound to for() loop lifetime. It also utilizes GCC
352 * extension: __attribute__((cleanup(<func>))), supported by both GCC and
353 * Clang.
354 */
355#define bpf_for_each(type, cur, args...) for (							\
356	/* initialize and define destructor */							\
357	struct bpf_iter_##type ___it __attribute__((aligned(8), /* enforce, just in case */,	\
358						    cleanup(bpf_iter_##type##_destroy))),	\
359	/* ___p pointer is just to call bpf_iter_##type##_new() *once* to init ___it */		\
360			       *___p __attribute__((unused)) = (				\
361					bpf_iter_##type##_new(&___it, ##args),			\
362	/* this is a workaround for Clang bug: it currently doesn't emit BTF */			\
363	/* for bpf_iter_##type##_destroy() when used from cleanup() attribute */		\
364					(void)bpf_iter_##type##_destroy, (void *)0);		\
365	/* iteration and termination check */							\
366	(((cur) = bpf_iter_##type##_next(&___it)));						\
367)
368#endif /* bpf_for_each */
369
370#ifndef bpf_for
371/* bpf_for(i, start, end) implements a for()-like looping construct that sets
372 * provided integer variable *i* to values starting from *start* through,
373 * but not including, *end*. It also proves to BPF verifier that *i* belongs
374 * to range [start, end), so this can be used for accessing arrays without
375 * extra checks.
376 *
377 * Note: *start* and *end* are assumed to be expressions with no side effects
378 * and whose values do not change throughout bpf_for() loop execution. They do
379 * not have to be statically known or constant, though.
380 *
381 * Note: similarly to bpf_for_each(), it relies on C99 feature of declaring for()
382 * loop bound variables and cleanup attribute, supported by GCC and Clang.
383 */
384#define bpf_for(i, start, end) for (								\
385	/* initialize and define destructor */							\
386	struct bpf_iter_num ___it __attribute__((aligned(8), /* enforce, just in case */	\
387						 cleanup(bpf_iter_num_destroy))),		\
388	/* ___p pointer is necessary to call bpf_iter_num_new() *once* to init ___it */		\
389			    *___p __attribute__((unused)) = (					\
390				bpf_iter_num_new(&___it, (start), (end)),			\
391	/* this is a workaround for Clang bug: it currently doesn't emit BTF */			\
392	/* for bpf_iter_num_destroy() when used from cleanup() attribute */			\
393				(void)bpf_iter_num_destroy, (void *)0);				\
394	({											\
395		/* iteration step */								\
396		int *___t = bpf_iter_num_next(&___it);						\
397		/* termination and bounds check */						\
398		(___t && ((i) = *___t, (i) >= (start) && (i) < (end)));				\
399	});											\
400)
401#endif /* bpf_for */
402
403#ifndef bpf_repeat
404/* bpf_repeat(N) performs N iterations without exposing iteration number
405 *
406 * Note: similarly to bpf_for_each(), it relies on C99 feature of declaring for()
407 * loop bound variables and cleanup attribute, supported by GCC and Clang.
408 */
409#define bpf_repeat(N) for (									\
410	/* initialize and define destructor */							\
411	struct bpf_iter_num ___it __attribute__((aligned(8), /* enforce, just in case */	\
412						 cleanup(bpf_iter_num_destroy))),		\
413	/* ___p pointer is necessary to call bpf_iter_num_new() *once* to init ___it */		\
414			    *___p __attribute__((unused)) = (					\
415				bpf_iter_num_new(&___it, 0, (N)),				\
416	/* this is a workaround for Clang bug: it currently doesn't emit BTF */			\
417	/* for bpf_iter_num_destroy() when used from cleanup() attribute */			\
418				(void)bpf_iter_num_destroy, (void *)0);				\
419	bpf_iter_num_next(&___it);								\
420	/* nothing here  */									\
421)
422#endif /* bpf_repeat */
423
424#endif