bpf_helpers.h 16 KB

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