xref: /linux/tools/lib/bpf/libbpf.h (revision aec2f682d47c54ef434b2d440992626d80b1ebdc)
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  */
10 #ifndef __LIBBPF_LIBBPF_H
11 #define __LIBBPF_LIBBPF_H
12 
13 #include <stdarg.h>
14 #include <stdio.h>
15 #include <stdint.h>
16 #include <stdbool.h>
17 #include <sys/types.h>  // for size_t
18 #include <linux/bpf.h>
19 
20 #include "libbpf_common.h"
21 #include "libbpf_legacy.h"
22 
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26 
27 /**
28  * @brief **libbpf_major_version()** provides the major version of libbpf.
29  * @return An integer, the major version number
30  */
31 LIBBPF_API __u32 libbpf_major_version(void);
32 
33 /**
34  * @brief **libbpf_minor_version()** provides the minor version of libbpf.
35  * @return An integer, the minor version number
36  */
37 LIBBPF_API __u32 libbpf_minor_version(void);
38 
39 /**
40  * @brief **libbpf_version_string()** provides the version of libbpf in a
41  * human-readable form, e.g., "v1.7".
42  * @return Pointer to a static string containing the version
43  *
44  * The format is *not* a part of a stable API and may change in the future.
45  */
46 LIBBPF_API const char *libbpf_version_string(void);
47 
48 enum libbpf_errno {
49 	__LIBBPF_ERRNO__START = 4000,
50 
51 	/* Something wrong in libelf */
52 	LIBBPF_ERRNO__LIBELF = __LIBBPF_ERRNO__START,
53 	LIBBPF_ERRNO__FORMAT,	/* BPF object format invalid */
54 	LIBBPF_ERRNO__KVERSION,	/* Incorrect or no 'version' section */
55 	LIBBPF_ERRNO__ENDIAN,	/* Endian mismatch */
56 	LIBBPF_ERRNO__INTERNAL,	/* Internal error in libbpf */
57 	LIBBPF_ERRNO__RELOC,	/* Relocation failed */
58 	LIBBPF_ERRNO__LOAD,	/* Load program failure for unknown reason */
59 	LIBBPF_ERRNO__VERIFY,	/* Kernel verifier blocks program loading */
60 	LIBBPF_ERRNO__PROG2BIG,	/* Program too big */
61 	LIBBPF_ERRNO__KVER,	/* Incorrect kernel version */
62 	LIBBPF_ERRNO__PROGTYPE,	/* Kernel doesn't support this program type */
63 	LIBBPF_ERRNO__WRNGPID,	/* Wrong pid in netlink message */
64 	LIBBPF_ERRNO__INVSEQ,	/* Invalid netlink sequence */
65 	LIBBPF_ERRNO__NLPARSE,	/* netlink parsing error */
66 	__LIBBPF_ERRNO__END,
67 };
68 
69 /**
70  * @brief **libbpf_strerror()** converts the provided error code into a
71  * human-readable string.
72  * @param err The error code to convert
73  * @param buf Pointer to a buffer where the error message will be stored
74  * @param size The number of bytes in the buffer
75  * @return 0, on success; negative error code, otherwise
76  */
77 LIBBPF_API int libbpf_strerror(int err, char *buf, size_t size);
78 
79 /**
80  * @brief **libbpf_bpf_attach_type_str()** converts the provided attach type
81  * value into a textual representation.
82  * @param t The attach type.
83  * @return Pointer to a static string identifying the attach type. NULL is
84  * returned for unknown **bpf_attach_type** values.
85  */
86 LIBBPF_API const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t);
87 
88 /**
89  * @brief **libbpf_bpf_link_type_str()** converts the provided link type value
90  * into a textual representation.
91  * @param t The link type.
92  * @return Pointer to a static string identifying the link type. NULL is
93  * returned for unknown **bpf_link_type** values.
94  */
95 LIBBPF_API const char *libbpf_bpf_link_type_str(enum bpf_link_type t);
96 
97 /**
98  * @brief **libbpf_bpf_map_type_str()** converts the provided map type value
99  * into a textual representation.
100  * @param t The map type.
101  * @return Pointer to a static string identifying the map type. NULL is
102  * returned for unknown **bpf_map_type** values.
103  */
104 LIBBPF_API const char *libbpf_bpf_map_type_str(enum bpf_map_type t);
105 
106 /**
107  * @brief **libbpf_bpf_prog_type_str()** converts the provided program type
108  * value into a textual representation.
109  * @param t The program type.
110  * @return Pointer to a static string identifying the program type. NULL is
111  * returned for unknown **bpf_prog_type** values.
112  */
113 LIBBPF_API const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t);
114 
115 enum libbpf_print_level {
116         LIBBPF_WARN,
117         LIBBPF_INFO,
118         LIBBPF_DEBUG,
119 };
120 
121 typedef int (*libbpf_print_fn_t)(enum libbpf_print_level level,
122 				 const char *, va_list ap);
123 
124 /**
125  * @brief **libbpf_set_print()** sets user-provided log callback function to
126  * be used for libbpf warnings and informational messages. If the user callback
127  * is not set, messages are logged to stderr by default. The verbosity of these
128  * messages can be controlled by setting the environment variable
129  * LIBBPF_LOG_LEVEL to either warn, info, or debug.
130  * @param fn The log print function. If NULL, libbpf won't print anything.
131  * @return Pointer to old print function.
132  *
133  * This function is thread-safe.
134  */
135 LIBBPF_API libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn);
136 
137 /* Hide internal to user */
138 struct bpf_object;
139 
140 struct bpf_object_open_opts {
141 	/* size of this struct, for forward/backward compatibility */
142 	size_t sz;
143 	/* object name override, if provided:
144 	 * - for object open from file, this will override setting object
145 	 *   name from file path's base name;
146 	 * - for object open from memory buffer, this will specify an object
147 	 *   name and will override default "<addr>-<buf-size>" name;
148 	 */
149 	const char *object_name;
150 	/* parse map definitions non-strictly, allowing extra attributes/data */
151 	bool relaxed_maps;
152 	/* maps that set the 'pinning' attribute in their definition will have
153 	 * their pin_path attribute set to a file in this directory, and be
154 	 * auto-pinned to that path on load; defaults to "/sys/fs/bpf".
155 	 */
156 	const char *pin_root_path;
157 
158 	__u32 :32; /* stub out now removed attach_prog_fd */
159 
160 	/* Additional kernel config content that augments and overrides
161 	 * system Kconfig for CONFIG_xxx externs.
162 	 */
163 	const char *kconfig;
164 	/* Path to the custom BTF to be used for BPF CO-RE relocations.
165 	 * This custom BTF completely replaces the use of vmlinux BTF
166 	 * for the purpose of CO-RE relocations.
167 	 * NOTE: any other BPF feature (e.g., fentry/fexit programs,
168 	 * struct_ops, etc) will need actual kernel BTF at /sys/kernel/btf/vmlinux.
169 	 */
170 	const char *btf_custom_path;
171 	/* Pointer to a buffer for storing kernel logs for applicable BPF
172 	 * commands. Valid kernel_log_size has to be specified as well and are
173 	 * passed-through to bpf() syscall. Keep in mind that kernel might
174 	 * fail operation with -ENOSPC error if provided buffer is too small
175 	 * to contain entire log output.
176 	 * See the comment below for kernel_log_level for interaction between
177 	 * log_buf and log_level settings.
178 	 *
179 	 * If specified, this log buffer will be passed for:
180 	 *   - each BPF progral load (BPF_PROG_LOAD) attempt, unless overridden
181 	 *     with bpf_program__set_log() on per-program level, to get
182 	 *     BPF verifier log output.
183 	 *   - during BPF object's BTF load into kernel (BPF_BTF_LOAD) to get
184 	 *     BTF sanity checking log.
185 	 *
186 	 * Each BPF command (BPF_BTF_LOAD or BPF_PROG_LOAD) will overwrite
187 	 * previous contents, so if you need more fine-grained control, set
188 	 * per-program buffer with bpf_program__set_log_buf() to preserve each
189 	 * individual program's verification log. Keep using kernel_log_buf
190 	 * for BTF verification log, if necessary.
191 	 */
192 	char *kernel_log_buf;
193 	size_t kernel_log_size;
194 	/*
195 	 * Log level can be set independently from log buffer. Log_level=0
196 	 * means that libbpf will attempt loading BTF or program without any
197 	 * logging requested, but will retry with either its own or custom log
198 	 * buffer, if provided, and log_level=1 on any error.
199 	 * And vice versa, setting log_level>0 will request BTF or prog
200 	 * loading with verbose log from the first attempt (and as such also
201 	 * for successfully loaded BTF or program), and the actual log buffer
202 	 * could be either libbpf's own auto-allocated log buffer, if
203 	 * kernel_log_buffer is NULL, or user-provided custom kernel_log_buf.
204 	 * If user didn't provide custom log buffer, libbpf will emit captured
205 	 * logs through its print callback.
206 	 */
207 	__u32 kernel_log_level;
208 	/* Path to BPF FS mount point to derive BPF token from.
209 	 *
210 	 * Created BPF token will be used for all bpf() syscall operations
211 	 * that accept BPF token (e.g., map creation, BTF and program loads,
212 	 * etc) automatically within instantiated BPF object.
213 	 *
214 	 * If bpf_token_path is not specified, libbpf will consult
215 	 * LIBBPF_BPF_TOKEN_PATH environment variable. If set, it will be
216 	 * taken as a value of bpf_token_path option and will force libbpf to
217 	 * either create BPF token from provided custom BPF FS path, or will
218 	 * disable implicit BPF token creation, if envvar value is an empty
219 	 * string. bpf_token_path overrides LIBBPF_BPF_TOKEN_PATH, if both are
220 	 * set at the same time.
221 	 *
222 	 * Setting bpf_token_path option to empty string disables libbpf's
223 	 * automatic attempt to create BPF token from default BPF FS mount
224 	 * point (/sys/fs/bpf), in case this default behavior is undesirable.
225 	 */
226 	const char *bpf_token_path;
227 
228 	size_t :0;
229 };
230 #define bpf_object_open_opts__last_field bpf_token_path
231 
232 /**
233  * @brief **bpf_object__open()** creates a bpf_object by opening
234  * the BPF ELF object file pointed to by the passed path and loading it
235  * into memory.
236  * @param path BPF object file path.
237  * @return pointer to the new bpf_object; or NULL is returned on error,
238  * error code is stored in errno
239  */
240 LIBBPF_API struct bpf_object *bpf_object__open(const char *path);
241 
242 /**
243  * @brief **bpf_object__open_file()** creates a bpf_object by opening
244  * the BPF ELF object file pointed to by the passed path and loading it
245  * into memory.
246  * @param path BPF object file path
247  * @param opts options for how to load the bpf object, this parameter is
248  * optional and can be set to NULL
249  * @return pointer to the new bpf_object; or NULL is returned on error,
250  * error code is stored in errno
251  */
252 LIBBPF_API struct bpf_object *
253 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts);
254 
255 /**
256  * @brief **bpf_object__open_mem()** creates a bpf_object by reading
257  * the BPF objects raw bytes from a memory buffer containing a valid
258  * BPF ELF object file.
259  * @param obj_buf pointer to the buffer containing ELF file bytes
260  * @param obj_buf_sz number of bytes in the buffer
261  * @param opts options for how to load the bpf object
262  * @return pointer to the new bpf_object; or NULL is returned on error,
263  * error code is stored in errno
264  */
265 LIBBPF_API struct bpf_object *
266 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
267 		     const struct bpf_object_open_opts *opts);
268 
269 /**
270  * @brief **bpf_object__prepare()** prepares BPF object for loading:
271  * performs ELF processing, relocations, prepares final state of BPF program
272  * instructions (accessible with bpf_program__insns()), creates and
273  * (potentially) pins maps. Leaves BPF object in the state ready for program
274  * loading.
275  * @param obj Pointer to a valid BPF object instance returned by
276  * **bpf_object__open*()** API
277  * @return 0, on success; negative error code, otherwise, error code is
278  * stored in errno
279  */
280 LIBBPF_API int bpf_object__prepare(struct bpf_object *obj);
281 
282 /**
283  * @brief **bpf_object__load()** loads BPF object into kernel.
284  * @param obj Pointer to a valid BPF object instance returned by
285  * **bpf_object__open*()** APIs
286  * @return 0, on success; negative error code, otherwise, error code is
287  * stored in errno
288  */
289 LIBBPF_API int bpf_object__load(struct bpf_object *obj);
290 
291 /**
292  * @brief **bpf_object__close()** closes a BPF object and releases all
293  * resources.
294  * @param obj Pointer to a valid BPF object
295  */
296 LIBBPF_API void bpf_object__close(struct bpf_object *obj);
297 
298 /**
299  * @brief **bpf_object__pin_maps()** pins each map contained within
300  * the BPF object at the passed directory.
301  * @param obj Pointer to a valid BPF object
302  * @param path A directory where maps should be pinned.
303  * @return 0, on success; negative error code, otherwise
304  *
305  * If `path` is NULL `bpf_map__pin` (which is being used on each map)
306  * will use the pin_path attribute of each map. In this case, maps that
307  * don't have a pin_path set will be ignored.
308  */
309 LIBBPF_API int bpf_object__pin_maps(struct bpf_object *obj, const char *path);
310 
311 /**
312  * @brief **bpf_object__unpin_maps()** unpins each map contained within
313  * the BPF object found in the passed directory.
314  * @param obj Pointer to a valid BPF object
315  * @param path A directory where pinned maps should be searched for.
316  * @return 0, on success; negative error code, otherwise
317  *
318  * If `path` is NULL `bpf_map__unpin` (which is being used on each map)
319  * will use the pin_path attribute of each map. In this case, maps that
320  * don't have a pin_path set will be ignored.
321  */
322 LIBBPF_API int bpf_object__unpin_maps(struct bpf_object *obj,
323 				      const char *path);
324 LIBBPF_API int bpf_object__pin_programs(struct bpf_object *obj,
325 					const char *path);
326 LIBBPF_API int bpf_object__unpin_programs(struct bpf_object *obj,
327 					  const char *path);
328 LIBBPF_API int bpf_object__pin(struct bpf_object *object, const char *path);
329 LIBBPF_API int bpf_object__unpin(struct bpf_object *object, const char *path);
330 
331 LIBBPF_API const char *bpf_object__name(const struct bpf_object *obj);
332 LIBBPF_API unsigned int bpf_object__kversion(const struct bpf_object *obj);
333 LIBBPF_API int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version);
334 
335 /**
336  * @brief **bpf_object__token_fd** is an accessor for BPF token FD associated
337  * with BPF object.
338  * @param obj Pointer to a valid BPF object
339  * @return BPF token FD or -1, if it wasn't set
340  */
341 LIBBPF_API int bpf_object__token_fd(const struct bpf_object *obj);
342 
343 struct btf;
344 LIBBPF_API struct btf *bpf_object__btf(const struct bpf_object *obj);
345 LIBBPF_API int bpf_object__btf_fd(const struct bpf_object *obj);
346 
347 LIBBPF_API struct bpf_program *
348 bpf_object__find_program_by_name(const struct bpf_object *obj,
349 				 const char *name);
350 
351 LIBBPF_API int
352 libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
353 			 enum bpf_attach_type *expected_attach_type);
354 LIBBPF_API int libbpf_attach_type_by_name(const char *name,
355 					  enum bpf_attach_type *attach_type);
356 LIBBPF_API int libbpf_find_vmlinux_btf_id(const char *name,
357 					  enum bpf_attach_type attach_type);
358 
359 /* Accessors of bpf_program */
360 struct bpf_program;
361 
362 LIBBPF_API struct bpf_program *
363 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prog);
364 
365 #define bpf_object__for_each_program(pos, obj)			\
366 	for ((pos) = bpf_object__next_program((obj), NULL);	\
367 	     (pos) != NULL;					\
368 	     (pos) = bpf_object__next_program((obj), (pos)))
369 
370 LIBBPF_API struct bpf_program *
371 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *prog);
372 
373 LIBBPF_API void bpf_program__set_ifindex(struct bpf_program *prog,
374 					 __u32 ifindex);
375 
376 LIBBPF_API const char *bpf_program__name(const struct bpf_program *prog);
377 LIBBPF_API const char *bpf_program__section_name(const struct bpf_program *prog);
378 LIBBPF_API bool bpf_program__autoload(const struct bpf_program *prog);
379 LIBBPF_API int bpf_program__set_autoload(struct bpf_program *prog, bool autoload);
380 LIBBPF_API bool bpf_program__autoattach(const struct bpf_program *prog);
381 LIBBPF_API void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach);
382 
383 struct bpf_insn;
384 
385 /**
386  * @brief **bpf_program__insns()** gives read-only access to BPF program's
387  * underlying BPF instructions.
388  * @param prog BPF program for which to return instructions
389  * @return a pointer to an array of BPF instructions that belong to the
390  * specified BPF program
391  *
392  * Returned pointer is always valid and not NULL. Number of `struct bpf_insn`
393  * pointed to can be fetched using **bpf_program__insn_cnt()** API.
394  *
395  * Keep in mind, libbpf can modify and append/delete BPF program's
396  * instructions as it processes BPF object file and prepares everything for
397  * uploading into the kernel. So depending on the point in BPF object
398  * lifetime, **bpf_program__insns()** can return different sets of
399  * instructions. As an example, during BPF object load phase BPF program
400  * instructions will be CO-RE-relocated, BPF subprograms instructions will be
401  * appended, ldimm64 instructions will have FDs embedded, etc. So instructions
402  * returned before **bpf_object__load()** and after it might be quite
403  * different.
404  */
405 LIBBPF_API const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog);
406 
407 /**
408  * @brief **bpf_program__set_insns()** can set BPF program's underlying
409  * BPF instructions.
410  *
411  * WARNING: This is a very advanced libbpf API and users need to know
412  * what they are doing. This should be used from prog_prepare_load_fn
413  * callback only.
414  *
415  * @param prog BPF program for which to return instructions
416  * @param new_insns a pointer to an array of BPF instructions
417  * @param new_insn_cnt number of `struct bpf_insn`'s that form
418  * specified BPF program
419  * @return 0, on success; negative error code, otherwise
420  */
421 LIBBPF_API int bpf_program__set_insns(struct bpf_program *prog,
422 				      struct bpf_insn *new_insns, size_t new_insn_cnt);
423 
424 /**
425  * @brief **bpf_program__insn_cnt()** returns number of `struct bpf_insn`'s
426  * that form specified BPF program.
427  * @param prog BPF program for which to return number of BPF instructions
428  *
429  * See **bpf_program__insns()** documentation for notes on how libbpf can
430  * change instructions and their count during different phases of
431  * **bpf_object** lifetime.
432  */
433 LIBBPF_API size_t bpf_program__insn_cnt(const struct bpf_program *prog);
434 
435 LIBBPF_API int bpf_program__fd(const struct bpf_program *prog);
436 
437 /**
438  * @brief **bpf_program__pin()** pins the BPF program to a file
439  * in the BPF FS specified by a path. This increments the programs
440  * reference count, allowing it to stay loaded after the process
441  * which loaded it has exited.
442  *
443  * @param prog BPF program to pin, must already be loaded
444  * @param path file path in a BPF file system
445  * @return 0, on success; negative error code, otherwise
446  */
447 LIBBPF_API int bpf_program__pin(struct bpf_program *prog, const char *path);
448 
449 /**
450  * @brief **bpf_program__unpin()** unpins the BPF program from a file
451  * in the BPFFS specified by a path. This decrements program's in-kernel
452  * reference count.
453  *
454  * The file pinning the BPF program can also be unlinked by a different
455  * process in which case this function will return an error.
456  *
457  * @param prog BPF program to unpin
458  * @param path file path to the pin in a BPF file system
459  * @return 0, on success; negative error code, otherwise
460  */
461 LIBBPF_API int bpf_program__unpin(struct bpf_program *prog, const char *path);
462 LIBBPF_API void bpf_program__unload(struct bpf_program *prog);
463 
464 struct bpf_link;
465 
466 LIBBPF_API struct bpf_link *bpf_link__open(const char *path);
467 LIBBPF_API int bpf_link__fd(const struct bpf_link *link);
468 LIBBPF_API const char *bpf_link__pin_path(const struct bpf_link *link);
469 /**
470  * @brief **bpf_link__pin()** pins the BPF link to a file
471  * in the BPF FS specified by a path. This increments the links
472  * reference count, allowing it to stay loaded after the process
473  * which loaded it has exited.
474  *
475  * @param link BPF link to pin, must already be loaded
476  * @param path file path in a BPF file system
477  * @return 0, on success; negative error code, otherwise
478  */
479 
480 LIBBPF_API int bpf_link__pin(struct bpf_link *link, const char *path);
481 
482 /**
483  * @brief **bpf_link__unpin()** unpins the BPF link from a file
484  * in the BPFFS. This decrements link's in-kernel reference count.
485  *
486  * The file pinning the BPF link can also be unlinked by a different
487  * process in which case this function will return an error.
488  *
489  * @param link BPF link to unpin
490  * @return 0, on success; negative error code, otherwise
491  */
492 LIBBPF_API int bpf_link__unpin(struct bpf_link *link);
493 LIBBPF_API int bpf_link__update_program(struct bpf_link *link,
494 					struct bpf_program *prog);
495 LIBBPF_API void bpf_link__disconnect(struct bpf_link *link);
496 LIBBPF_API int bpf_link__detach(struct bpf_link *link);
497 LIBBPF_API int bpf_link__destroy(struct bpf_link *link);
498 
499 /**
500  * @brief **bpf_program__attach()** is a generic function for attaching
501  * a BPF program based on auto-detection of program type, attach type,
502  * and extra parameters, where applicable.
503  *
504  * @param prog BPF program to attach
505  * @return Reference to the newly created BPF link; or NULL is returned on error,
506  * error code is stored in errno
507  *
508  * This is supported for:
509  *   - kprobe/kretprobe (depends on SEC() definition)
510  *   - uprobe/uretprobe (depends on SEC() definition)
511  *   - tracepoint
512  *   - raw tracepoint
513  *   - tracing programs (typed raw TP/fentry/fexit/fmod_ret)
514  */
515 LIBBPF_API struct bpf_link *
516 bpf_program__attach(const struct bpf_program *prog);
517 
518 struct bpf_perf_event_opts {
519 	/* size of this struct, for forward/backward compatibility */
520 	size_t sz;
521 	/* custom user-provided value fetchable through bpf_get_attach_cookie() */
522 	__u64 bpf_cookie;
523 	/* don't use BPF link when attach BPF program */
524 	bool force_ioctl_attach;
525 	/* don't automatically enable the event */
526 	bool dont_enable;
527 	size_t :0;
528 };
529 #define bpf_perf_event_opts__last_field dont_enable
530 
531 LIBBPF_API struct bpf_link *
532 bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd);
533 
534 LIBBPF_API struct bpf_link *
535 bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
536 				    const struct bpf_perf_event_opts *opts);
537 
538 /**
539  * enum probe_attach_mode - the mode to attach kprobe/uprobe
540  *
541  * force libbpf to attach kprobe/uprobe in specific mode, -ENOTSUP will
542  * be returned if it is not supported by the kernel.
543  */
544 enum probe_attach_mode {
545 	/* attach probe in latest supported mode by kernel */
546 	PROBE_ATTACH_MODE_DEFAULT = 0,
547 	/* attach probe in legacy mode, using debugfs/tracefs */
548 	PROBE_ATTACH_MODE_LEGACY,
549 	/* create perf event with perf_event_open() syscall */
550 	PROBE_ATTACH_MODE_PERF,
551 	/* attach probe with BPF link */
552 	PROBE_ATTACH_MODE_LINK,
553 };
554 
555 struct bpf_kprobe_opts {
556 	/* size of this struct, for forward/backward compatibility */
557 	size_t sz;
558 	/* custom user-provided value fetchable through bpf_get_attach_cookie() */
559 	__u64 bpf_cookie;
560 	/* function offset, or raw address if func_name == NULL */
561 	size_t offset;
562 	/* kprobe is return probe */
563 	bool retprobe;
564 	/* kprobe attach mode */
565 	enum probe_attach_mode attach_mode;
566 	size_t :0;
567 };
568 
569 #define bpf_kprobe_opts__last_field attach_mode
570 
571 /**
572  * @brief **bpf_program__attach_kprobe()** attaches a BPF program to a
573  * kernel function entry or return.
574  *
575  * @param prog BPF program to attach
576  * @param retprobe Attach to function return
577  * @param func_name Name of the kernel function to attach to
578  * @return Reference to the newly created BPF link; or NULL is returned on
579  * error, error code is stored in errno
580  */
581 LIBBPF_API struct bpf_link *
582 bpf_program__attach_kprobe(const struct bpf_program *prog, bool retprobe,
583 			   const char *func_name);
584 
585 /**
586  * @brief **bpf_program__attach_kprobe_opts()** is just like
587  * bpf_program__attach_kprobe() except with an options struct
588  * for various configurations.
589  *
590  * @param prog BPF program to attach
591  * @param func_name Name of the kernel function to attach to. If NULL,
592  * opts->offset is treated as a raw kernel address. Raw-address attach
593  * is supported with PROBE_ATTACH_MODE_PERF and PROBE_ATTACH_MODE_LINK.
594  * @param opts Options for altering program attachment
595  * @return Reference to the newly created BPF link; or NULL is returned on
596  * error, error code is stored in errno
597  */
598 LIBBPF_API struct bpf_link *
599 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
600                                 const char *func_name,
601                                 const struct bpf_kprobe_opts *opts);
602 
603 struct bpf_kprobe_multi_opts {
604 	/* size of this struct, for forward/backward compatibility */
605 	size_t sz;
606 	/* array of function symbols to attach */
607 	const char **syms;
608 	/* array of function addresses to attach */
609 	const unsigned long *addrs;
610 	/* array of user-provided values fetchable through bpf_get_attach_cookie */
611 	const __u64 *cookies;
612 	/* number of elements in syms/addrs/cookies arrays */
613 	size_t cnt;
614 	/* create return kprobes */
615 	bool retprobe;
616 	/* create session kprobes */
617 	bool session;
618 	/* enforce unique match */
619 	bool unique_match;
620 	size_t :0;
621 };
622 
623 #define bpf_kprobe_multi_opts__last_field unique_match
624 
625 LIBBPF_API struct bpf_link *
626 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
627 				      const char *pattern,
628 				      const struct bpf_kprobe_multi_opts *opts);
629 
630 struct bpf_uprobe_multi_opts {
631 	/* size of this struct, for forward/backward compatibility */
632 	size_t sz;
633 	/* array of function symbols to attach to */
634 	const char **syms;
635 	/* array of function addresses to attach to */
636 	const unsigned long *offsets;
637 	/* optional, array of associated ref counter offsets */
638 	const unsigned long *ref_ctr_offsets;
639 	/* optional, array of associated BPF cookies */
640 	const __u64 *cookies;
641 	/* number of elements in syms/addrs/cookies arrays */
642 	size_t cnt;
643 	/* create return uprobes */
644 	bool retprobe;
645 	/* create session kprobes */
646 	bool session;
647 	size_t :0;
648 };
649 
650 #define bpf_uprobe_multi_opts__last_field session
651 
652 /**
653  * @brief **bpf_program__attach_uprobe_multi()** attaches a BPF program
654  * to multiple uprobes with uprobe_multi link.
655  *
656  * User can specify 2 mutually exclusive set of inputs:
657  *
658  *   1) use only path/func_pattern/pid arguments
659  *
660  *   2) use path/pid with allowed combinations of
661  *      syms/offsets/ref_ctr_offsets/cookies/cnt
662  *
663  *      - syms and offsets are mutually exclusive
664  *      - ref_ctr_offsets and cookies are optional
665  *
666  *
667  * @param prog BPF program to attach
668  * @param pid Process ID to attach the uprobe to, 0 for self (own process),
669  * -1 for all processes
670  * @param binary_path Path to binary
671  * @param func_pattern Regular expression to specify functions to attach
672  * BPF program to
673  * @param opts Additional options (see **struct bpf_uprobe_multi_opts**)
674  * @return 0, on success; negative error code, otherwise
675  */
676 LIBBPF_API struct bpf_link *
677 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
678 				 pid_t pid,
679 				 const char *binary_path,
680 				 const char *func_pattern,
681 				 const struct bpf_uprobe_multi_opts *opts);
682 
683 struct bpf_ksyscall_opts {
684 	/* size of this struct, for forward/backward compatibility */
685 	size_t sz;
686 	/* custom user-provided value fetchable through bpf_get_attach_cookie() */
687 	__u64 bpf_cookie;
688 	/* attach as return probe? */
689 	bool retprobe;
690 	size_t :0;
691 };
692 #define bpf_ksyscall_opts__last_field retprobe
693 
694 /**
695  * @brief **bpf_program__attach_ksyscall()** attaches a BPF program
696  * to kernel syscall handler of a specified syscall. Optionally it's possible
697  * to request to install retprobe that will be triggered at syscall exit. It's
698  * also possible to associate BPF cookie (though options).
699  *
700  * Libbpf automatically will determine correct full kernel function name,
701  * which depending on system architecture and kernel version/configuration
702  * could be of the form __<arch>_sys_<syscall> or __se_sys_<syscall>, and will
703  * attach specified program using kprobe/kretprobe mechanism.
704  *
705  * **bpf_program__attach_ksyscall()** is an API counterpart of declarative
706  * **SEC("ksyscall/<syscall>")** annotation of BPF programs.
707  *
708  * At the moment **SEC("ksyscall")** and **bpf_program__attach_ksyscall()** do
709  * not handle all the calling convention quirks for mmap(), clone() and compat
710  * syscalls. It also only attaches to "native" syscall interfaces. If host
711  * system supports compat syscalls or defines 32-bit syscalls in 64-bit
712  * kernel, such syscall interfaces won't be attached to by libbpf.
713  *
714  * These limitations may or may not change in the future. Therefore it is
715  * recommended to use SEC("kprobe") for these syscalls or if working with
716  * compat and 32-bit interfaces is required.
717  *
718  * @param prog BPF program to attach
719  * @param syscall_name Symbolic name of the syscall (e.g., "bpf")
720  * @param opts Additional options (see **struct bpf_ksyscall_opts**)
721  * @return Reference to the newly created BPF link; or NULL is returned on
722  * error, error code is stored in errno
723  */
724 LIBBPF_API struct bpf_link *
725 bpf_program__attach_ksyscall(const struct bpf_program *prog,
726 			     const char *syscall_name,
727 			     const struct bpf_ksyscall_opts *opts);
728 
729 struct bpf_uprobe_opts {
730 	/* size of this struct, for forward/backward compatibility */
731 	size_t sz;
732 	/* offset of kernel reference counted USDT semaphore, added in
733 	 * a6ca88b241d5 ("trace_uprobe: support reference counter in fd-based uprobe")
734 	 */
735 	size_t ref_ctr_offset;
736 	/* custom user-provided value fetchable through bpf_get_attach_cookie() */
737 	__u64 bpf_cookie;
738 	/* uprobe is return probe, invoked at function return time */
739 	bool retprobe;
740 	/* Function name to attach to.  Could be an unqualified ("abc") or library-qualified
741 	 * "abc@LIBXYZ" name.  To specify function entry, func_name should be set while
742 	 * func_offset argument to bpf_prog__attach_uprobe_opts() should be 0.  To trace an
743 	 * offset within a function, specify func_name and use func_offset argument to specify
744 	 * offset within the function.  Shared library functions must specify the shared library
745 	 * binary_path.
746 	 */
747 	const char *func_name;
748 	/* uprobe attach mode */
749 	enum probe_attach_mode attach_mode;
750 	size_t :0;
751 };
752 #define bpf_uprobe_opts__last_field attach_mode
753 
754 /**
755  * @brief **bpf_program__attach_uprobe()** attaches a BPF program
756  * to the userspace function which is found by binary path and
757  * offset. You can optionally specify a particular process to attach
758  * to. You can also optionally attach the program to the function
759  * exit instead of entry.
760  *
761  * @param prog BPF program to attach
762  * @param retprobe Attach to function exit
763  * @param pid Process ID to attach the uprobe to, 0 for self (own process),
764  * -1 for all processes
765  * @param binary_path Path to binary that contains the function symbol
766  * @param func_offset Offset within the binary of the function symbol
767  * @return Reference to the newly created BPF link; or NULL is returned on error,
768  * error code is stored in errno
769  */
770 LIBBPF_API struct bpf_link *
771 bpf_program__attach_uprobe(const struct bpf_program *prog, bool retprobe,
772 			   pid_t pid, const char *binary_path,
773 			   size_t func_offset);
774 
775 /**
776  * @brief **bpf_program__attach_uprobe_opts()** is just like
777  * bpf_program__attach_uprobe() except with a options struct
778  * for various configurations.
779  *
780  * @param prog BPF program to attach
781  * @param pid Process ID to attach the uprobe to, 0 for self (own process),
782  * -1 for all processes
783  * @param binary_path Path to binary that contains the function symbol
784  * @param func_offset Offset within the binary of the function symbol
785  * @param opts Options for altering program attachment
786  * @return Reference to the newly created BPF link; or NULL is returned on error,
787  * error code is stored in errno
788  */
789 LIBBPF_API struct bpf_link *
790 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
791 				const char *binary_path, size_t func_offset,
792 				const struct bpf_uprobe_opts *opts);
793 
794 struct bpf_usdt_opts {
795 	/* size of this struct, for forward/backward compatibility */
796 	size_t sz;
797 	/* custom user-provided value accessible through usdt_cookie() */
798 	__u64 usdt_cookie;
799 	size_t :0;
800 };
801 #define bpf_usdt_opts__last_field usdt_cookie
802 
803 /**
804  * @brief **bpf_program__attach_usdt()** is just like
805  * bpf_program__attach_uprobe_opts() except it covers USDT (User-space
806  * Statically Defined Tracepoint) attachment, instead of attaching to
807  * user-space function entry or exit.
808  *
809  * @param prog BPF program to attach
810  * @param pid Process ID to attach the uprobe to, 0 for self (own process),
811  * -1 for all processes
812  * @param binary_path Path to binary that contains provided USDT probe
813  * @param usdt_provider USDT provider name
814  * @param usdt_name USDT probe name
815  * @param opts Options for altering program attachment
816  * @return Reference to the newly created BPF link; or NULL is returned on error,
817  * error code is stored in errno
818  */
819 LIBBPF_API struct bpf_link *
820 bpf_program__attach_usdt(const struct bpf_program *prog,
821 			 pid_t pid, const char *binary_path,
822 			 const char *usdt_provider, const char *usdt_name,
823 			 const struct bpf_usdt_opts *opts);
824 
825 struct bpf_tracepoint_opts {
826 	/* size of this struct, for forward/backward compatibility */
827 	size_t sz;
828 	/* custom user-provided value fetchable through bpf_get_attach_cookie() */
829 	__u64 bpf_cookie;
830 };
831 #define bpf_tracepoint_opts__last_field bpf_cookie
832 
833 LIBBPF_API struct bpf_link *
834 bpf_program__attach_tracepoint(const struct bpf_program *prog,
835 			       const char *tp_category,
836 			       const char *tp_name);
837 LIBBPF_API struct bpf_link *
838 bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
839 				    const char *tp_category,
840 				    const char *tp_name,
841 				    const struct bpf_tracepoint_opts *opts);
842 
843 struct bpf_raw_tracepoint_opts {
844 	size_t sz; /* size of this struct for forward/backward compatibility */
845 	__u64 cookie;
846 	size_t :0;
847 };
848 #define bpf_raw_tracepoint_opts__last_field cookie
849 
850 LIBBPF_API struct bpf_link *
851 bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
852 				   const char *tp_name);
853 LIBBPF_API struct bpf_link *
854 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
855 					const char *tp_name,
856 					struct bpf_raw_tracepoint_opts *opts);
857 
858 struct bpf_trace_opts {
859 	/* size of this struct, for forward/backward compatibility */
860 	size_t sz;
861 	/* custom user-provided value fetchable through bpf_get_attach_cookie() */
862 	__u64 cookie;
863 };
864 #define bpf_trace_opts__last_field cookie
865 
866 LIBBPF_API struct bpf_link *
867 bpf_program__attach_trace(const struct bpf_program *prog);
868 LIBBPF_API struct bpf_link *
869 bpf_program__attach_trace_opts(const struct bpf_program *prog, const struct bpf_trace_opts *opts);
870 
871 LIBBPF_API struct bpf_link *
872 bpf_program__attach_lsm(const struct bpf_program *prog);
873 LIBBPF_API struct bpf_link *
874 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd);
875 LIBBPF_API struct bpf_link *
876 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd);
877 LIBBPF_API struct bpf_link *
878 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd);
879 LIBBPF_API struct bpf_link *
880 bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex);
881 LIBBPF_API struct bpf_link *
882 bpf_program__attach_freplace(const struct bpf_program *prog,
883 			     int target_fd, const char *attach_func_name);
884 
885 struct bpf_netfilter_opts {
886 	/* size of this struct, for forward/backward compatibility */
887 	size_t sz;
888 
889 	__u32 pf;
890 	__u32 hooknum;
891 	__s32 priority;
892 	__u32 flags;
893 };
894 #define bpf_netfilter_opts__last_field flags
895 
896 LIBBPF_API struct bpf_link *
897 bpf_program__attach_netfilter(const struct bpf_program *prog,
898 			      const struct bpf_netfilter_opts *opts);
899 
900 struct bpf_tcx_opts {
901 	/* size of this struct, for forward/backward compatibility */
902 	size_t sz;
903 	__u32 flags;
904 	__u32 relative_fd;
905 	__u32 relative_id;
906 	__u64 expected_revision;
907 	size_t :0;
908 };
909 #define bpf_tcx_opts__last_field expected_revision
910 
911 LIBBPF_API struct bpf_link *
912 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
913 			const struct bpf_tcx_opts *opts);
914 
915 struct bpf_netkit_opts {
916 	/* size of this struct, for forward/backward compatibility */
917 	size_t sz;
918 	__u32 flags;
919 	__u32 relative_fd;
920 	__u32 relative_id;
921 	__u64 expected_revision;
922 	size_t :0;
923 };
924 #define bpf_netkit_opts__last_field expected_revision
925 
926 LIBBPF_API struct bpf_link *
927 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
928 			   const struct bpf_netkit_opts *opts);
929 
930 struct bpf_cgroup_opts {
931 	/* size of this struct, for forward/backward compatibility */
932 	size_t sz;
933 	__u32 flags;
934 	__u32 relative_fd;
935 	__u32 relative_id;
936 	__u64 expected_revision;
937 	size_t :0;
938 };
939 #define bpf_cgroup_opts__last_field expected_revision
940 
941 LIBBPF_API struct bpf_link *
942 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
943 				const struct bpf_cgroup_opts *opts);
944 
945 struct bpf_map;
946 
947 LIBBPF_API struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map);
948 LIBBPF_API int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map);
949 
950 struct bpf_iter_attach_opts {
951 	size_t sz; /* size of this struct for forward/backward compatibility */
952 	union bpf_iter_link_info *link_info;
953 	__u32 link_info_len;
954 };
955 #define bpf_iter_attach_opts__last_field link_info_len
956 
957 LIBBPF_API struct bpf_link *
958 bpf_program__attach_iter(const struct bpf_program *prog,
959 			 const struct bpf_iter_attach_opts *opts);
960 
961 LIBBPF_API enum bpf_prog_type bpf_program__type(const struct bpf_program *prog);
962 
963 /**
964  * @brief **bpf_program__set_type()** sets the program
965  * type of the passed BPF program.
966  * @param prog BPF program to set the program type for
967  * @param type program type to set the BPF map to have
968  * @return error code; or 0 if no error. An error occurs
969  * if the object is already loaded.
970  *
971  * This must be called before the BPF object is loaded,
972  * otherwise it has no effect and an error is returned.
973  */
974 LIBBPF_API int bpf_program__set_type(struct bpf_program *prog,
975 				     enum bpf_prog_type type);
976 
977 LIBBPF_API enum bpf_attach_type
978 bpf_program__expected_attach_type(const struct bpf_program *prog);
979 
980 /**
981  * @brief **bpf_program__set_expected_attach_type()** sets the
982  * attach type of the passed BPF program. This is used for
983  * auto-detection of attachment when programs are loaded.
984  * @param prog BPF program to set the attach type for
985  * @param type attach type to set the BPF map to have
986  * @return error code; or 0 if no error. An error occurs
987  * if the object is already loaded.
988  *
989  * This must be called before the BPF object is loaded,
990  * otherwise it has no effect and an error is returned.
991  */
992 LIBBPF_API int
993 bpf_program__set_expected_attach_type(struct bpf_program *prog,
994 				      enum bpf_attach_type type);
995 
996 LIBBPF_API __u32 bpf_program__flags(const struct bpf_program *prog);
997 LIBBPF_API int bpf_program__set_flags(struct bpf_program *prog, __u32 flags);
998 
999 /* Per-program log level and log buffer getters/setters.
1000  * See bpf_object_open_opts comments regarding log_level and log_buf
1001  * interactions.
1002  */
1003 LIBBPF_API __u32 bpf_program__log_level(const struct bpf_program *prog);
1004 LIBBPF_API int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level);
1005 LIBBPF_API const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size);
1006 LIBBPF_API int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size);
1007 
1008 LIBBPF_API struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog);
1009 LIBBPF_API __u32 bpf_program__func_info_cnt(const struct bpf_program *prog);
1010 
1011 LIBBPF_API struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog);
1012 LIBBPF_API __u32 bpf_program__line_info_cnt(const struct bpf_program *prog);
1013 
1014 /**
1015  * @brief **bpf_program__set_attach_target()** sets BTF-based attach target
1016  * for supported BPF program types:
1017  *   - BTF-aware raw tracepoints (tp_btf);
1018  *   - fentry/fexit/fmod_ret;
1019  *   - lsm;
1020  *   - freplace.
1021  * @param prog BPF program to configure; must be not yet loaded.
1022  * @param attach_prog_fd FD of target BPF program (for freplace/extension).
1023  * If >0 and func name omitted, defers BTF ID resolution.
1024  * @param attach_func_name Target function name. Used either with
1025  * attach_prog_fd to find destination BTF type ID in that BPF program, or
1026  * alone (no attach_prog_fd) to resolve kernel (vmlinux/module) BTF ID.
1027  * Must be provided if attach_prog_fd is 0.
1028  * @return error code; or 0 if no error occurred.
1029  */
1030 LIBBPF_API int
1031 bpf_program__set_attach_target(struct bpf_program *prog, int attach_prog_fd,
1032 			       const char *attach_func_name);
1033 
1034 struct bpf_prog_assoc_struct_ops_opts; /* defined in bpf.h */
1035 
1036 /**
1037  * @brief **bpf_program__assoc_struct_ops()** associates a BPF program with a
1038  * struct_ops map.
1039  *
1040  * @param prog BPF program
1041  * @param map struct_ops map to be associated with the BPF program
1042  * @param opts optional options, can be NULL
1043  *
1044  * @return 0, on success; negative error code, otherwise
1045  */
1046 LIBBPF_API int
1047 bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
1048 			      struct bpf_prog_assoc_struct_ops_opts *opts);
1049 
1050 /**
1051  * @brief **bpf_object__find_map_by_name()** returns BPF map of
1052  * the given name, if it exists within the passed BPF object
1053  * @param obj BPF object
1054  * @param name name of the BPF map
1055  * @return BPF map instance, if such map exists within the BPF object;
1056  * or NULL otherwise.
1057  */
1058 LIBBPF_API struct bpf_map *
1059 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name);
1060 
1061 LIBBPF_API int
1062 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name);
1063 
1064 LIBBPF_API struct bpf_map *
1065 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *map);
1066 
1067 #define bpf_object__for_each_map(pos, obj)		\
1068 	for ((pos) = bpf_object__next_map((obj), NULL);	\
1069 	     (pos) != NULL;				\
1070 	     (pos) = bpf_object__next_map((obj), (pos)))
1071 #define bpf_map__for_each bpf_object__for_each_map
1072 
1073 LIBBPF_API struct bpf_map *
1074 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *map);
1075 
1076 /**
1077  * @brief **bpf_map__set_autocreate()** sets whether libbpf has to auto-create
1078  * BPF map during BPF object load phase.
1079  * @param map the BPF map instance
1080  * @param autocreate whether to create BPF map during BPF object load
1081  * @return 0 on success; -EBUSY if BPF object was already loaded
1082  *
1083  * **bpf_map__set_autocreate()** allows to opt-out from libbpf auto-creating
1084  * BPF map. By default, libbpf will attempt to create every single BPF map
1085  * defined in BPF object file using BPF_MAP_CREATE command of bpf() syscall
1086  * and fill in map FD in BPF instructions.
1087  *
1088  * This API allows to opt-out of this process for specific map instance. This
1089  * can be useful if host kernel doesn't support such BPF map type or used
1090  * combination of flags and user application wants to avoid creating such
1091  * a map in the first place. User is still responsible to make sure that their
1092  * BPF-side code that expects to use such missing BPF map is recognized by BPF
1093  * verifier as dead code, otherwise BPF verifier will reject such BPF program.
1094  */
1095 LIBBPF_API int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate);
1096 LIBBPF_API bool bpf_map__autocreate(const struct bpf_map *map);
1097 
1098 /**
1099  * @brief **bpf_map__set_autoattach()** sets whether libbpf has to auto-attach
1100  * map during BPF skeleton attach phase.
1101  * @param map the BPF map instance
1102  * @param autoattach whether to attach map during BPF skeleton attach phase
1103  * @return 0 on success; negative error code, otherwise
1104  */
1105 LIBBPF_API int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach);
1106 
1107 /**
1108  * @brief **bpf_map__autoattach()** returns whether BPF map is configured to
1109  * auto-attach during BPF skeleton attach phase.
1110  * @param map the BPF map instance
1111  * @return true if map is set to auto-attach during skeleton attach phase; false, otherwise
1112  */
1113 LIBBPF_API bool bpf_map__autoattach(const struct bpf_map *map);
1114 
1115 /**
1116  * @brief **bpf_map__fd()** gets the file descriptor of the passed
1117  * BPF map
1118  * @param map the BPF map instance
1119  * @return the file descriptor; or -EINVAL in case of an error
1120  */
1121 LIBBPF_API int bpf_map__fd(const struct bpf_map *map);
1122 LIBBPF_API int bpf_map__reuse_fd(struct bpf_map *map, int fd);
1123 /* get map name */
1124 LIBBPF_API const char *bpf_map__name(const struct bpf_map *map);
1125 /* get/set map type */
1126 LIBBPF_API enum bpf_map_type bpf_map__type(const struct bpf_map *map);
1127 LIBBPF_API int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type);
1128 /* get/set map size (max_entries) */
1129 LIBBPF_API __u32 bpf_map__max_entries(const struct bpf_map *map);
1130 LIBBPF_API int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries);
1131 /* get/set map flags */
1132 LIBBPF_API __u32 bpf_map__map_flags(const struct bpf_map *map);
1133 LIBBPF_API int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags);
1134 /* get/set map NUMA node */
1135 LIBBPF_API __u32 bpf_map__numa_node(const struct bpf_map *map);
1136 LIBBPF_API int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node);
1137 /* get/set map key size */
1138 LIBBPF_API __u32 bpf_map__key_size(const struct bpf_map *map);
1139 LIBBPF_API int bpf_map__set_key_size(struct bpf_map *map, __u32 size);
1140 /* get map value size */
1141 LIBBPF_API __u32 bpf_map__value_size(const struct bpf_map *map);
1142 /**
1143  * @brief **bpf_map__set_value_size()** sets map value size.
1144  * @param map the BPF map instance
1145  * @param size the new value size
1146  * @return 0, on success; negative error, otherwise
1147  *
1148  * There is a special case for maps with associated memory-mapped regions, like
1149  * the global data section maps (bss, data, rodata). When this function is used
1150  * on such a map, the mapped region is resized. Afterward, an attempt is made to
1151  * adjust the corresponding BTF info. This attempt is best-effort and can only
1152  * succeed if the last variable of the data section map is an array. The array
1153  * BTF type is replaced by a new BTF array type with a different length.
1154  * Any previously existing pointers returned from bpf_map__initial_value() or
1155  * corresponding data section skeleton pointer must be reinitialized.
1156  */
1157 LIBBPF_API int bpf_map__set_value_size(struct bpf_map *map, __u32 size);
1158 /* get map key/value BTF type IDs */
1159 LIBBPF_API __u32 bpf_map__btf_key_type_id(const struct bpf_map *map);
1160 LIBBPF_API __u32 bpf_map__btf_value_type_id(const struct bpf_map *map);
1161 /* get/set map if_index */
1162 LIBBPF_API __u32 bpf_map__ifindex(const struct bpf_map *map);
1163 LIBBPF_API int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex);
1164 /* get/set map map_extra flags */
1165 LIBBPF_API __u64 bpf_map__map_extra(const struct bpf_map *map);
1166 LIBBPF_API int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra);
1167 
1168 LIBBPF_API int bpf_map__set_initial_value(struct bpf_map *map,
1169 					  const void *data, size_t size);
1170 LIBBPF_API void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize);
1171 
1172 /**
1173  * @brief **bpf_map__is_internal()** tells the caller whether or not the
1174  * passed map is a special map created by libbpf automatically for things like
1175  * global variables, __ksym externs, Kconfig values, etc
1176  * @param map the bpf_map
1177  * @return true, if the map is an internal map; false, otherwise
1178  */
1179 LIBBPF_API bool bpf_map__is_internal(const struct bpf_map *map);
1180 
1181 /**
1182  * @brief **bpf_map__set_pin_path()** sets the path attribute that tells where the
1183  * BPF map should be pinned. This does not actually create the 'pin'.
1184  * @param map The bpf_map
1185  * @param path The path
1186  * @return 0, on success; negative error, otherwise
1187  */
1188 LIBBPF_API int bpf_map__set_pin_path(struct bpf_map *map, const char *path);
1189 
1190 /**
1191  * @brief **bpf_map__pin_path()** gets the path attribute that tells where the
1192  * BPF map should be pinned.
1193  * @param map The bpf_map
1194  * @return The path string; which can be NULL
1195  */
1196 LIBBPF_API const char *bpf_map__pin_path(const struct bpf_map *map);
1197 
1198 /**
1199  * @brief **bpf_map__is_pinned()** tells the caller whether or not the
1200  * passed map has been pinned via a 'pin' file.
1201  * @param map The bpf_map
1202  * @return true, if the map is pinned; false, otherwise
1203  */
1204 LIBBPF_API bool bpf_map__is_pinned(const struct bpf_map *map);
1205 
1206 /**
1207  * @brief **bpf_map__pin()** creates a file that serves as a 'pin'
1208  * for the BPF map. This increments the reference count on the
1209  * BPF map which will keep the BPF map loaded even after the
1210  * userspace process which loaded it has exited.
1211  * @param map The bpf_map to pin
1212  * @param path A file path for the 'pin'
1213  * @return 0, on success; negative error, otherwise
1214  *
1215  * If `path` is NULL the maps `pin_path` attribute will be used. If this is
1216  * also NULL, an error will be returned and the map will not be pinned.
1217  */
1218 LIBBPF_API int bpf_map__pin(struct bpf_map *map, const char *path);
1219 
1220 /**
1221  * @brief **bpf_map__unpin()** removes the file that serves as a
1222  * 'pin' for the BPF map.
1223  * @param map The bpf_map to unpin
1224  * @param path A file path for the 'pin'
1225  * @return 0, on success; negative error, otherwise
1226  *
1227  * The `path` parameter can be NULL, in which case the `pin_path`
1228  * map attribute is unpinned. If both the `path` parameter and
1229  * `pin_path` map attribute are set, they must be equal.
1230  */
1231 LIBBPF_API int bpf_map__unpin(struct bpf_map *map, const char *path);
1232 
1233 LIBBPF_API int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd);
1234 LIBBPF_API struct bpf_map *bpf_map__inner_map(struct bpf_map *map);
1235 
1236 /**
1237  * @brief **bpf_map__lookup_elem()** allows to lookup BPF map value
1238  * corresponding to provided key.
1239  * @param map BPF map to lookup element in
1240  * @param key pointer to memory containing bytes of the key used for lookup
1241  * @param key_sz size in bytes of key data, needs to match BPF map definition's **key_size**
1242  * @param value pointer to memory in which looked up value will be stored
1243  * @param value_sz size in byte of value data memory; it has to match BPF map
1244  * definition's **value_size**. For per-CPU BPF maps, value size can be
1245  * `value_size` if either **BPF_F_CPU** or **BPF_F_ALL_CPUS** is specified
1246  * in **flags**, otherwise a product of BPF map value size and number of
1247  * possible CPUs in the system (could be fetched with
1248  * **libbpf_num_possible_cpus()**). Note also that for per-CPU values value
1249  * size has to be aligned up to closest 8 bytes, so expected size is:
1250  * `round_up(value_size, 8) * libbpf_num_possible_cpus()`.
1251  * @param flags extra flags passed to kernel for this operation
1252  * @return 0, on success; negative error, otherwise
1253  *
1254  * **bpf_map__lookup_elem()** is high-level equivalent of
1255  * **bpf_map_lookup_elem()** API with added check for key and value size.
1256  */
1257 LIBBPF_API int bpf_map__lookup_elem(const struct bpf_map *map,
1258 				    const void *key, size_t key_sz,
1259 				    void *value, size_t value_sz, __u64 flags);
1260 
1261 /**
1262  * @brief **bpf_map__update_elem()** allows to insert or update value in BPF
1263  * map that corresponds to provided key.
1264  * @param map BPF map to insert to or update element in
1265  * @param key pointer to memory containing bytes of the key
1266  * @param key_sz size in bytes of key data, needs to match BPF map definition's **key_size**
1267  * @param value pointer to memory containing bytes of the value
1268  * @param value_sz refer to **bpf_map__lookup_elem**'s description.'
1269  * @param flags extra flags passed to kernel for this operation
1270  * @return 0, on success; negative error, otherwise
1271  *
1272  * **bpf_map__update_elem()** is high-level equivalent of
1273  * **bpf_map_update_elem()** API with added check for key and value size.
1274  */
1275 LIBBPF_API int bpf_map__update_elem(const struct bpf_map *map,
1276 				    const void *key, size_t key_sz,
1277 				    const void *value, size_t value_sz, __u64 flags);
1278 
1279 /**
1280  * @brief **bpf_map__delete_elem()** allows to delete element in BPF map that
1281  * corresponds to provided key.
1282  * @param map BPF map to delete element from
1283  * @param key pointer to memory containing bytes of the key
1284  * @param key_sz size in bytes of key data, needs to match BPF map definition's **key_size**
1285  * @param flags extra flags passed to kernel for this operation
1286  * @return 0, on success; negative error, otherwise
1287  *
1288  * **bpf_map__delete_elem()** is high-level equivalent of
1289  * **bpf_map_delete_elem()** API with added check for key size.
1290  */
1291 LIBBPF_API int bpf_map__delete_elem(const struct bpf_map *map,
1292 				    const void *key, size_t key_sz, __u64 flags);
1293 
1294 /**
1295  * @brief **bpf_map__lookup_and_delete_elem()** allows to lookup BPF map value
1296  * corresponding to provided key and atomically delete it afterwards.
1297  * @param map BPF map to lookup element in
1298  * @param key pointer to memory containing bytes of the key used for lookup
1299  * @param key_sz size in bytes of key data, needs to match BPF map definition's **key_size**
1300  * @param value pointer to memory in which looked up value will be stored
1301  * @param value_sz size in byte of value data memory; it has to match BPF map
1302  * definition's **value_size**. For per-CPU BPF maps value size has to be
1303  * a product of BPF map value size and number of possible CPUs in the system
1304  * (could be fetched with **libbpf_num_possible_cpus()**). Note also that for
1305  * per-CPU values value size has to be aligned up to closest 8 bytes for
1306  * alignment reasons, so expected size is: `round_up(value_size, 8)
1307  * * libbpf_num_possible_cpus()`.
1308  * @param flags extra flags passed to kernel for this operation
1309  * @return 0, on success; negative error, otherwise
1310  *
1311  * **bpf_map__lookup_and_delete_elem()** is high-level equivalent of
1312  * **bpf_map_lookup_and_delete_elem()** API with added check for key and value size.
1313  */
1314 LIBBPF_API int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
1315 					       const void *key, size_t key_sz,
1316 					       void *value, size_t value_sz, __u64 flags);
1317 
1318 /**
1319  * @brief **bpf_map__get_next_key()** allows to iterate BPF map keys by
1320  * fetching next key that follows current key.
1321  * @param map BPF map to fetch next key from
1322  * @param cur_key pointer to memory containing bytes of current key or NULL to
1323  * fetch the first key
1324  * @param next_key pointer to memory to write next key into
1325  * @param key_sz size in bytes of key data, needs to match BPF map definition's **key_size**
1326  * @return 0, on success; -ENOENT if **cur_key** is the last key in BPF map;
1327  * negative error, otherwise
1328  *
1329  * **bpf_map__get_next_key()** is high-level equivalent of
1330  * **bpf_map_get_next_key()** API with added check for key size.
1331  */
1332 LIBBPF_API int bpf_map__get_next_key(const struct bpf_map *map,
1333 				     const void *cur_key, void *next_key, size_t key_sz);
1334 /**
1335  * @brief **bpf_map__set_exclusive_program()** sets a map to be exclusive to the
1336  * specified program. This must be called *before* the map is created.
1337  *
1338  * @param map BPF map to make exclusive.
1339  * @param prog BPF program to be the exclusive user of the map. Must belong
1340  * to the same bpf_object as the map.
1341  * @return 0 on success; a negative error code otherwise.
1342  *
1343  * This function must be called after the BPF object is opened but before
1344  * it is loaded. Once the object is loaded, only the specified program
1345  * will be able to access the map's contents.
1346  */
1347 LIBBPF_API int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog);
1348 
1349 /**
1350  * @brief **bpf_map__exclusive_program()** returns the exclusive program
1351  * that is registered with the map (if any).
1352  * @param map BPF map to which the exclusive program is registered.
1353  * @return the registered exclusive program.
1354  */
1355 LIBBPF_API struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map);
1356 
1357 struct bpf_xdp_set_link_opts {
1358 	size_t sz;
1359 	int old_fd;
1360 	size_t :0;
1361 };
1362 #define bpf_xdp_set_link_opts__last_field old_fd
1363 
1364 struct bpf_xdp_attach_opts {
1365 	size_t sz;
1366 	int old_prog_fd;
1367 	size_t :0;
1368 };
1369 #define bpf_xdp_attach_opts__last_field old_prog_fd
1370 
1371 struct bpf_xdp_query_opts {
1372 	size_t sz;
1373 	__u32 prog_id;		/* output */
1374 	__u32 drv_prog_id;	/* output */
1375 	__u32 hw_prog_id;	/* output */
1376 	__u32 skb_prog_id;	/* output */
1377 	__u8 attach_mode;	/* output */
1378 	__u64 feature_flags;	/* output */
1379 	__u32 xdp_zc_max_segs;	/* output */
1380 	size_t :0;
1381 };
1382 #define bpf_xdp_query_opts__last_field xdp_zc_max_segs
1383 
1384 LIBBPF_API int bpf_xdp_attach(int ifindex, int prog_fd, __u32 flags,
1385 			      const struct bpf_xdp_attach_opts *opts);
1386 LIBBPF_API int bpf_xdp_detach(int ifindex, __u32 flags,
1387 			      const struct bpf_xdp_attach_opts *opts);
1388 LIBBPF_API int bpf_xdp_query(int ifindex, int flags, struct bpf_xdp_query_opts *opts);
1389 LIBBPF_API int bpf_xdp_query_id(int ifindex, int flags, __u32 *prog_id);
1390 
1391 /* TC related API */
1392 enum bpf_tc_attach_point {
1393 	BPF_TC_INGRESS = 1 << 0,
1394 	BPF_TC_EGRESS  = 1 << 1,
1395 	BPF_TC_CUSTOM  = 1 << 2,
1396 	BPF_TC_QDISC   = 1 << 3,
1397 };
1398 
1399 #define BPF_TC_PARENT(a, b) 	\
1400 	((((a) << 16) & 0xFFFF0000U) | ((b) & 0x0000FFFFU))
1401 
1402 enum bpf_tc_flags {
1403 	BPF_TC_F_REPLACE = 1 << 0,
1404 };
1405 
1406 struct bpf_tc_hook {
1407 	size_t sz;
1408 	int ifindex;
1409 	enum bpf_tc_attach_point attach_point;
1410 	__u32 parent;
1411 	__u32 handle;
1412 	const char *qdisc;
1413 	size_t :0;
1414 };
1415 #define bpf_tc_hook__last_field qdisc
1416 
1417 struct bpf_tc_opts {
1418 	size_t sz;
1419 	int prog_fd;
1420 	__u32 flags;
1421 	__u32 prog_id;
1422 	__u32 handle;
1423 	__u32 priority;
1424 	size_t :0;
1425 };
1426 #define bpf_tc_opts__last_field priority
1427 
1428 LIBBPF_API int bpf_tc_hook_create(struct bpf_tc_hook *hook);
1429 LIBBPF_API int bpf_tc_hook_destroy(struct bpf_tc_hook *hook);
1430 LIBBPF_API int bpf_tc_attach(const struct bpf_tc_hook *hook,
1431 			     struct bpf_tc_opts *opts);
1432 LIBBPF_API int bpf_tc_detach(const struct bpf_tc_hook *hook,
1433 			     const struct bpf_tc_opts *opts);
1434 LIBBPF_API int bpf_tc_query(const struct bpf_tc_hook *hook,
1435 			    struct bpf_tc_opts *opts);
1436 
1437 /* Ring buffer APIs */
1438 struct ring_buffer;
1439 struct ring;
1440 struct user_ring_buffer;
1441 
1442 typedef int (*ring_buffer_sample_fn)(void *ctx, void *data, size_t size);
1443 
1444 struct ring_buffer_opts {
1445 	size_t sz; /* size of this struct, for forward/backward compatibility */
1446 };
1447 
1448 #define ring_buffer_opts__last_field sz
1449 
1450 LIBBPF_API struct ring_buffer *
1451 ring_buffer__new(int map_fd, ring_buffer_sample_fn sample_cb, void *ctx,
1452 		 const struct ring_buffer_opts *opts);
1453 LIBBPF_API void ring_buffer__free(struct ring_buffer *rb);
1454 LIBBPF_API int ring_buffer__add(struct ring_buffer *rb, int map_fd,
1455 				ring_buffer_sample_fn sample_cb, void *ctx);
1456 LIBBPF_API int ring_buffer__poll(struct ring_buffer *rb, int timeout_ms);
1457 LIBBPF_API int ring_buffer__consume(struct ring_buffer *rb);
1458 LIBBPF_API int ring_buffer__consume_n(struct ring_buffer *rb, size_t n);
1459 LIBBPF_API int ring_buffer__epoll_fd(const struct ring_buffer *rb);
1460 
1461 /**
1462  * @brief **ring_buffer__ring()** returns the ringbuffer object inside a given
1463  * ringbuffer manager representing a single BPF_MAP_TYPE_RINGBUF map instance.
1464  *
1465  * @param rb A ringbuffer manager object.
1466  * @param idx An index into the ringbuffers contained within the ringbuffer
1467  * manager object. The index is 0-based and corresponds to the order in which
1468  * ring_buffer__add was called.
1469  * @return A ringbuffer object on success; NULL and errno set if the index is
1470  * invalid.
1471  */
1472 LIBBPF_API struct ring *ring_buffer__ring(struct ring_buffer *rb,
1473 					  unsigned int idx);
1474 
1475 /**
1476  * @brief **ring__consumer_pos()** returns the current consumer position in the
1477  * given ringbuffer.
1478  *
1479  * @param r A ringbuffer object.
1480  * @return The current consumer position.
1481  */
1482 LIBBPF_API unsigned long ring__consumer_pos(const struct ring *r);
1483 
1484 /**
1485  * @brief **ring__producer_pos()** returns the current producer position in the
1486  * given ringbuffer.
1487  *
1488  * @param r A ringbuffer object.
1489  * @return The current producer position.
1490  */
1491 LIBBPF_API unsigned long ring__producer_pos(const struct ring *r);
1492 
1493 /**
1494  * @brief **ring__avail_data_size()** returns the number of bytes in the
1495  * ringbuffer not yet consumed. This has no locking associated with it, so it
1496  * can be inaccurate if operations are ongoing while this is called. However, it
1497  * should still show the correct trend over the long-term.
1498  *
1499  * @param r A ringbuffer object.
1500  * @return The number of bytes not yet consumed.
1501  */
1502 LIBBPF_API size_t ring__avail_data_size(const struct ring *r);
1503 
1504 /**
1505  * @brief **ring__size()** returns the total size of the ringbuffer's map data
1506  * area (excluding special producer/consumer pages). Effectively this gives the
1507  * amount of usable bytes of data inside the ringbuffer.
1508  *
1509  * @param r A ringbuffer object.
1510  * @return The total size of the ringbuffer map data area.
1511  */
1512 LIBBPF_API size_t ring__size(const struct ring *r);
1513 
1514 /**
1515  * @brief **ring__map_fd()** returns the file descriptor underlying the given
1516  * ringbuffer.
1517  *
1518  * @param r A ringbuffer object.
1519  * @return The underlying ringbuffer file descriptor
1520  */
1521 LIBBPF_API int ring__map_fd(const struct ring *r);
1522 
1523 /**
1524  * @brief **ring__consume()** consumes available ringbuffer data without event
1525  * polling.
1526  *
1527  * @param r A ringbuffer object.
1528  * @return The number of records consumed (or INT_MAX, whichever is less), or
1529  * a negative number if any of the callbacks return an error.
1530  */
1531 LIBBPF_API int ring__consume(struct ring *r);
1532 
1533 /**
1534  * @brief **ring__consume_n()** consumes up to a requested amount of items from
1535  * a ringbuffer without event polling.
1536  *
1537  * @param r A ringbuffer object.
1538  * @param n Maximum amount of items to consume.
1539  * @return The number of items consumed, or a negative number if any of the
1540  * callbacks return an error.
1541  */
1542 LIBBPF_API int ring__consume_n(struct ring *r, size_t n);
1543 
1544 struct user_ring_buffer_opts {
1545 	size_t sz; /* size of this struct, for forward/backward compatibility */
1546 };
1547 
1548 #define user_ring_buffer_opts__last_field sz
1549 
1550 /**
1551  * @brief **user_ring_buffer__new()** creates a new instance of a user ring
1552  * buffer.
1553  *
1554  * @param map_fd A file descriptor to a BPF_MAP_TYPE_USER_RINGBUF map.
1555  * @param opts Options for how the ring buffer should be created.
1556  * @return A user ring buffer on success; NULL and errno being set on a
1557  * failure.
1558  */
1559 LIBBPF_API struct user_ring_buffer *
1560 user_ring_buffer__new(int map_fd, const struct user_ring_buffer_opts *opts);
1561 
1562 /**
1563  * @brief **user_ring_buffer__reserve()** reserves a pointer to a sample in the
1564  * user ring buffer.
1565  * @param rb A pointer to a user ring buffer.
1566  * @param size The size of the sample, in bytes.
1567  * @return A pointer to an 8-byte aligned reserved region of the user ring
1568  * buffer; NULL, and errno being set if a sample could not be reserved.
1569  *
1570  * This function is *not* thread safe, and callers must synchronize accessing
1571  * this function if there are multiple producers.  If a size is requested that
1572  * is larger than the size of the entire ring buffer, errno will be set to
1573  * E2BIG and NULL is returned. If the ring buffer could accommodate the size,
1574  * but currently does not have enough space, errno is set to ENOSPC and NULL is
1575  * returned.
1576  *
1577  * After initializing the sample, callers must invoke
1578  * **user_ring_buffer__submit()** to post the sample to the kernel. Otherwise,
1579  * the sample must be freed with **user_ring_buffer__discard()**.
1580  */
1581 LIBBPF_API void *user_ring_buffer__reserve(struct user_ring_buffer *rb, __u32 size);
1582 
1583 /**
1584  * @brief **user_ring_buffer__reserve_blocking()** reserves a record in the
1585  * ring buffer, possibly blocking for up to @timeout_ms until a sample becomes
1586  * available.
1587  * @param rb The user ring buffer.
1588  * @param size The size of the sample, in bytes.
1589  * @param timeout_ms The amount of time, in milliseconds, for which the caller
1590  * should block when waiting for a sample. -1 causes the caller to block
1591  * indefinitely.
1592  * @return A pointer to an 8-byte aligned reserved region of the user ring
1593  * buffer; NULL, and errno being set if a sample could not be reserved.
1594  *
1595  * This function is *not* thread safe, and callers must synchronize
1596  * accessing this function if there are multiple producers
1597  *
1598  * If **timeout_ms** is -1, the function will block indefinitely until a sample
1599  * becomes available. Otherwise, **timeout_ms** must be non-negative, or errno
1600  * is set to EINVAL, and NULL is returned. If **timeout_ms** is 0, no blocking
1601  * will occur and the function will return immediately after attempting to
1602  * reserve a sample.
1603  *
1604  * If **size** is larger than the size of the entire ring buffer, errno is set
1605  * to E2BIG and NULL is returned. If the ring buffer could accommodate
1606  * **size**, but currently does not have enough space, the caller will block
1607  * until at most **timeout_ms** has elapsed. If insufficient space is available
1608  * at that time, errno is set to ENOSPC, and NULL is returned.
1609  *
1610  * The kernel guarantees that it will wake up this thread to check if
1611  * sufficient space is available in the ring buffer at least once per
1612  * invocation of the **bpf_ringbuf_drain()** helper function, provided that at
1613  * least one sample is consumed, and the BPF program did not invoke the
1614  * function with BPF_RB_NO_WAKEUP. A wakeup may occur sooner than that, but the
1615  * kernel does not guarantee this. If the helper function is invoked with
1616  * BPF_RB_FORCE_WAKEUP, a wakeup event will be sent even if no sample is
1617  * consumed.
1618  *
1619  * When a sample of size **size** is found within **timeout_ms**, a pointer to
1620  * the sample is returned. After initializing the sample, callers must invoke
1621  * **user_ring_buffer__submit()** to post the sample to the ring buffer.
1622  * Otherwise, the sample must be freed with **user_ring_buffer__discard()**.
1623  */
1624 LIBBPF_API void *user_ring_buffer__reserve_blocking(struct user_ring_buffer *rb,
1625 						    __u32 size,
1626 						    int timeout_ms);
1627 
1628 /**
1629  * @brief **user_ring_buffer__submit()** submits a previously reserved sample
1630  * into the ring buffer.
1631  * @param rb The user ring buffer.
1632  * @param sample A reserved sample.
1633  *
1634  * It is not necessary to synchronize amongst multiple producers when invoking
1635  * this function.
1636  */
1637 LIBBPF_API void user_ring_buffer__submit(struct user_ring_buffer *rb, void *sample);
1638 
1639 /**
1640  * @brief **user_ring_buffer__discard()** discards a previously reserved sample.
1641  * @param rb The user ring buffer.
1642  * @param sample A reserved sample.
1643  *
1644  * It is not necessary to synchronize amongst multiple producers when invoking
1645  * this function.
1646  */
1647 LIBBPF_API void user_ring_buffer__discard(struct user_ring_buffer *rb, void *sample);
1648 
1649 /**
1650  * @brief **user_ring_buffer__free()** frees a ring buffer that was previously
1651  * created with **user_ring_buffer__new()**.
1652  * @param rb The user ring buffer being freed.
1653  */
1654 LIBBPF_API void user_ring_buffer__free(struct user_ring_buffer *rb);
1655 
1656 /* Perf buffer APIs */
1657 struct perf_buffer;
1658 
1659 typedef void (*perf_buffer_sample_fn)(void *ctx, int cpu,
1660 				      void *data, __u32 size);
1661 typedef void (*perf_buffer_lost_fn)(void *ctx, int cpu, __u64 cnt);
1662 
1663 /* common use perf buffer options */
1664 struct perf_buffer_opts {
1665 	size_t sz;
1666 	__u32 sample_period;
1667 	size_t :0;
1668 };
1669 #define perf_buffer_opts__last_field sample_period
1670 
1671 /**
1672  * @brief **perf_buffer__new()** creates BPF perfbuf manager for a specified
1673  * BPF_PERF_EVENT_ARRAY map
1674  * @param map_fd FD of BPF_PERF_EVENT_ARRAY BPF map that will be used by BPF
1675  * code to send data over to user-space
1676  * @param page_cnt number of memory pages allocated for each per-CPU buffer
1677  * @param sample_cb function called on each received data record
1678  * @param lost_cb function called when record loss has occurred
1679  * @param ctx user-provided extra context passed into *sample_cb* and *lost_cb*
1680  * @param opts optional parameters for the perf buffer, can be null
1681  * @return a new instance of struct perf_buffer on success, NULL on error with
1682  * *errno* containing an error code
1683  */
1684 LIBBPF_API struct perf_buffer *
1685 perf_buffer__new(int map_fd, size_t page_cnt,
1686 		 perf_buffer_sample_fn sample_cb, perf_buffer_lost_fn lost_cb, void *ctx,
1687 		 const struct perf_buffer_opts *opts);
1688 
1689 enum bpf_perf_event_ret {
1690 	LIBBPF_PERF_EVENT_DONE	= 0,
1691 	LIBBPF_PERF_EVENT_ERROR	= -1,
1692 	LIBBPF_PERF_EVENT_CONT	= -2,
1693 };
1694 
1695 struct perf_event_header;
1696 
1697 typedef enum bpf_perf_event_ret
1698 (*perf_buffer_event_fn)(void *ctx, int cpu, struct perf_event_header *event);
1699 
1700 /* raw perf buffer options, giving most power and control */
1701 struct perf_buffer_raw_opts {
1702 	size_t sz;
1703 	long :0;
1704 	long :0;
1705 	/* if cpu_cnt == 0, open all on all possible CPUs (up to the number of
1706 	 * max_entries of given PERF_EVENT_ARRAY map)
1707 	 */
1708 	int cpu_cnt;
1709 	/* if cpu_cnt > 0, cpus is an array of CPUs to open ring buffers on */
1710 	int *cpus;
1711 	/* if cpu_cnt > 0, map_keys specify map keys to set per-CPU FDs for */
1712 	int *map_keys;
1713 };
1714 #define perf_buffer_raw_opts__last_field map_keys
1715 
1716 struct perf_event_attr;
1717 
1718 LIBBPF_API struct perf_buffer *
1719 perf_buffer__new_raw(int map_fd, size_t page_cnt, struct perf_event_attr *attr,
1720 		     perf_buffer_event_fn event_cb, void *ctx,
1721 		     const struct perf_buffer_raw_opts *opts);
1722 
1723 LIBBPF_API void perf_buffer__free(struct perf_buffer *pb);
1724 LIBBPF_API int perf_buffer__epoll_fd(const struct perf_buffer *pb);
1725 LIBBPF_API int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms);
1726 LIBBPF_API int perf_buffer__consume(struct perf_buffer *pb);
1727 LIBBPF_API int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx);
1728 LIBBPF_API size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb);
1729 LIBBPF_API int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx);
1730 /**
1731  * @brief **perf_buffer__buffer()** returns the per-cpu raw mmap()'ed underlying
1732  * memory region of the ring buffer.
1733  * This ring buffer can be used to implement a custom events consumer.
1734  * The ring buffer starts with the *struct perf_event_mmap_page*, which
1735  * holds the ring buffer management fields, when accessing the header
1736  * structure it's important to be SMP aware.
1737  * You can refer to *perf_event_read_simple* for a simple example.
1738  * @param pb the perf buffer structure
1739  * @param buf_idx the buffer index to retrieve
1740  * @param buf (out) gets the base pointer of the mmap()'ed memory
1741  * @param buf_size (out) gets the size of the mmap()'ed region
1742  * @return 0 on success, negative error code for failure
1743  */
1744 LIBBPF_API int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf,
1745 				   size_t *buf_size);
1746 
1747 struct bpf_prog_linfo;
1748 struct bpf_prog_info;
1749 
1750 LIBBPF_API void bpf_prog_linfo__free(struct bpf_prog_linfo *prog_linfo);
1751 LIBBPF_API struct bpf_prog_linfo *
1752 bpf_prog_linfo__new(const struct bpf_prog_info *info);
1753 LIBBPF_API const struct bpf_line_info *
1754 bpf_prog_linfo__lfind_addr_func(const struct bpf_prog_linfo *prog_linfo,
1755 				__u64 addr, __u32 func_idx, __u32 nr_skip);
1756 LIBBPF_API const struct bpf_line_info *
1757 bpf_prog_linfo__lfind(const struct bpf_prog_linfo *prog_linfo,
1758 		      __u32 insn_off, __u32 nr_skip);
1759 
1760 /*
1761  * Probe for supported system features
1762  *
1763  * Note that running many of these probes in a short amount of time can cause
1764  * the kernel to reach the maximal size of lockable memory allowed for the
1765  * user, causing subsequent probes to fail. In this case, the caller may want
1766  * to adjust that limit with setrlimit().
1767  */
1768 
1769 /**
1770  * @brief **libbpf_probe_bpf_prog_type()** detects if host kernel supports
1771  * BPF programs of a given type.
1772  * @param prog_type BPF program type to detect kernel support for
1773  * @param opts reserved for future extensibility, should be NULL
1774  * @return 1, if given program type is supported; 0, if given program type is
1775  * not supported; negative error code if feature detection failed or can't be
1776  * performed
1777  *
1778  * Make sure the process has required set of CAP_* permissions (or runs as
1779  * root) when performing feature checking.
1780  */
1781 LIBBPF_API int libbpf_probe_bpf_prog_type(enum bpf_prog_type prog_type, const void *opts);
1782 /**
1783  * @brief **libbpf_probe_bpf_map_type()** detects if host kernel supports
1784  * BPF maps of a given type.
1785  * @param map_type BPF map type to detect kernel support for
1786  * @param opts reserved for future extensibility, should be NULL
1787  * @return 1, if given map type is supported; 0, if given map type is
1788  * not supported; negative error code if feature detection failed or can't be
1789  * performed
1790  *
1791  * Make sure the process has required set of CAP_* permissions (or runs as
1792  * root) when performing feature checking.
1793  */
1794 LIBBPF_API int libbpf_probe_bpf_map_type(enum bpf_map_type map_type, const void *opts);
1795 /**
1796  * @brief **libbpf_probe_bpf_helper()** detects if host kernel supports the
1797  * use of a given BPF helper from specified BPF program type.
1798  * @param prog_type BPF program type used to check the support of BPF helper
1799  * @param helper_id BPF helper ID (enum bpf_func_id) to check support for
1800  * @param opts reserved for future extensibility, should be NULL
1801  * @return 1, if given combination of program type and helper is supported; 0,
1802  * if the combination is not supported; negative error code if feature
1803  * detection for provided input arguments failed or can't be performed
1804  *
1805  * Make sure the process has required set of CAP_* permissions (or runs as
1806  * root) when performing feature checking.
1807  */
1808 LIBBPF_API int libbpf_probe_bpf_helper(enum bpf_prog_type prog_type,
1809 				       enum bpf_func_id helper_id, const void *opts);
1810 
1811 /**
1812  * @brief **libbpf_num_possible_cpus()** is a helper function to get the
1813  * number of possible CPUs that the host kernel supports and expects.
1814  * @return number of possible CPUs; or error code on failure
1815  *
1816  * Example usage:
1817  *
1818  *     int ncpus = libbpf_num_possible_cpus();
1819  *     if (ncpus < 0) {
1820  *          // error handling
1821  *     }
1822  *     long values[ncpus];
1823  *     bpf_map_lookup_elem(per_cpu_map_fd, key, values);
1824  */
1825 LIBBPF_API int libbpf_num_possible_cpus(void);
1826 
1827 struct bpf_map_skeleton {
1828 	const char *name;
1829 	struct bpf_map **map;
1830 	void **mmaped;
1831 	struct bpf_link **link;
1832 };
1833 
1834 struct bpf_prog_skeleton {
1835 	const char *name;
1836 	struct bpf_program **prog;
1837 	struct bpf_link **link;
1838 };
1839 
1840 struct bpf_object_skeleton {
1841 	size_t sz; /* size of this struct, for forward/backward compatibility */
1842 
1843 	const char *name;
1844 	const void *data;
1845 	size_t data_sz;
1846 
1847 	struct bpf_object **obj;
1848 
1849 	int map_cnt;
1850 	int map_skel_sz; /* sizeof(struct bpf_map_skeleton) */
1851 	struct bpf_map_skeleton *maps;
1852 
1853 	int prog_cnt;
1854 	int prog_skel_sz; /* sizeof(struct bpf_prog_skeleton) */
1855 	struct bpf_prog_skeleton *progs;
1856 };
1857 
1858 LIBBPF_API int
1859 bpf_object__open_skeleton(struct bpf_object_skeleton *s,
1860 			  const struct bpf_object_open_opts *opts);
1861 LIBBPF_API int bpf_object__load_skeleton(struct bpf_object_skeleton *s);
1862 LIBBPF_API int bpf_object__attach_skeleton(struct bpf_object_skeleton *s);
1863 LIBBPF_API void bpf_object__detach_skeleton(struct bpf_object_skeleton *s);
1864 LIBBPF_API void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s);
1865 
1866 struct bpf_var_skeleton {
1867 	const char *name;
1868 	struct bpf_map **map;
1869 	void **addr;
1870 };
1871 
1872 struct bpf_object_subskeleton {
1873 	size_t sz; /* size of this struct, for forward/backward compatibility */
1874 
1875 	const struct bpf_object *obj;
1876 
1877 	int map_cnt;
1878 	int map_skel_sz; /* sizeof(struct bpf_map_skeleton) */
1879 	struct bpf_map_skeleton *maps;
1880 
1881 	int prog_cnt;
1882 	int prog_skel_sz; /* sizeof(struct bpf_prog_skeleton) */
1883 	struct bpf_prog_skeleton *progs;
1884 
1885 	int var_cnt;
1886 	int var_skel_sz; /* sizeof(struct bpf_var_skeleton) */
1887 	struct bpf_var_skeleton *vars;
1888 };
1889 
1890 LIBBPF_API int
1891 bpf_object__open_subskeleton(struct bpf_object_subskeleton *s);
1892 LIBBPF_API void
1893 bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s);
1894 
1895 struct gen_loader_opts {
1896 	size_t sz; /* size of this struct, for forward/backward compatibility */
1897 	const char *data;
1898 	const char *insns;
1899 	__u32 data_sz;
1900 	__u32 insns_sz;
1901 	bool gen_hash;
1902 };
1903 
1904 #define gen_loader_opts__last_field gen_hash
1905 LIBBPF_API int bpf_object__gen_loader(struct bpf_object *obj,
1906 				      struct gen_loader_opts *opts);
1907 
1908 enum libbpf_tristate {
1909 	TRI_NO = 0,
1910 	TRI_YES = 1,
1911 	TRI_MODULE = 2,
1912 };
1913 
1914 struct bpf_linker_opts {
1915 	/* size of this struct, for forward/backward compatibility */
1916 	size_t sz;
1917 };
1918 #define bpf_linker_opts__last_field sz
1919 
1920 struct bpf_linker_file_opts {
1921 	/* size of this struct, for forward/backward compatibility */
1922 	size_t sz;
1923 };
1924 #define bpf_linker_file_opts__last_field sz
1925 
1926 struct bpf_linker;
1927 
1928 LIBBPF_API struct bpf_linker *bpf_linker__new(const char *filename, struct bpf_linker_opts *opts);
1929 LIBBPF_API struct bpf_linker *bpf_linker__new_fd(int fd, struct bpf_linker_opts *opts);
1930 LIBBPF_API int bpf_linker__add_file(struct bpf_linker *linker,
1931 				    const char *filename,
1932 				    const struct bpf_linker_file_opts *opts);
1933 LIBBPF_API int bpf_linker__add_fd(struct bpf_linker *linker, int fd,
1934 				  const struct bpf_linker_file_opts *opts);
1935 LIBBPF_API int bpf_linker__add_buf(struct bpf_linker *linker, void *buf, size_t buf_sz,
1936 				   const struct bpf_linker_file_opts *opts);
1937 LIBBPF_API int bpf_linker__finalize(struct bpf_linker *linker);
1938 LIBBPF_API void bpf_linker__free(struct bpf_linker *linker);
1939 
1940 /*
1941  * Custom handling of BPF program's SEC() definitions
1942  */
1943 
1944 struct bpf_prog_load_opts; /* defined in bpf.h */
1945 
1946 /* Called during bpf_object__open() for each recognized BPF program. Callback
1947  * can use various bpf_program__set_*() setters to adjust whatever properties
1948  * are necessary.
1949  */
1950 typedef int (*libbpf_prog_setup_fn_t)(struct bpf_program *prog, long cookie);
1951 
1952 /* Called right before libbpf performs bpf_prog_load() to load BPF program
1953  * into the kernel. Callback can adjust opts as necessary.
1954  */
1955 typedef int (*libbpf_prog_prepare_load_fn_t)(struct bpf_program *prog,
1956 					     struct bpf_prog_load_opts *opts, long cookie);
1957 
1958 /* Called during skeleton attach or through bpf_program__attach(). If
1959  * auto-attach is not supported, callback should return 0 and set link to
1960  * NULL (it's not considered an error during skeleton attach, but it will be
1961  * an error for bpf_program__attach() calls). On error, error should be
1962  * returned directly and link set to NULL. On success, return 0 and set link
1963  * to a valid struct bpf_link.
1964  */
1965 typedef int (*libbpf_prog_attach_fn_t)(const struct bpf_program *prog, long cookie,
1966 				       struct bpf_link **link);
1967 
1968 struct libbpf_prog_handler_opts {
1969 	/* size of this struct, for forward/backward compatibility */
1970 	size_t sz;
1971 	/* User-provided value that is passed to prog_setup_fn,
1972 	 * prog_prepare_load_fn, and prog_attach_fn callbacks. Allows user to
1973 	 * register one set of callbacks for multiple SEC() definitions and
1974 	 * still be able to distinguish them, if necessary. For example,
1975 	 * libbpf itself is using this to pass necessary flags (e.g.,
1976 	 * sleepable flag) to a common internal SEC() handler.
1977 	 */
1978 	long cookie;
1979 	/* BPF program initialization callback (see libbpf_prog_setup_fn_t).
1980 	 * Callback is optional, pass NULL if it's not necessary.
1981 	 */
1982 	libbpf_prog_setup_fn_t prog_setup_fn;
1983 	/* BPF program loading callback (see libbpf_prog_prepare_load_fn_t).
1984 	 * Callback is optional, pass NULL if it's not necessary.
1985 	 */
1986 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
1987 	/* BPF program attach callback (see libbpf_prog_attach_fn_t).
1988 	 * Callback is optional, pass NULL if it's not necessary.
1989 	 */
1990 	libbpf_prog_attach_fn_t prog_attach_fn;
1991 };
1992 #define libbpf_prog_handler_opts__last_field prog_attach_fn
1993 
1994 /**
1995  * @brief **libbpf_register_prog_handler()** registers a custom BPF program
1996  * SEC() handler.
1997  * @param sec section prefix for which custom handler is registered
1998  * @param prog_type BPF program type associated with specified section
1999  * @param exp_attach_type Expected BPF attach type associated with specified section
2000  * @param opts optional cookie, callbacks, and other extra options
2001  * @return Non-negative handler ID is returned on success. This handler ID has
2002  * to be passed to *libbpf_unregister_prog_handler()* to unregister such
2003  * custom handler. Negative error code is returned on error.
2004  *
2005  * *sec* defines which SEC() definitions are handled by this custom handler
2006  * registration. *sec* can have few different forms:
2007  *   - if *sec* is just a plain string (e.g., "abc"), it will match only
2008  *   SEC("abc"). If BPF program specifies SEC("abc/whatever") it will result
2009  *   in an error;
2010  *   - if *sec* is of the form "abc/", proper SEC() form is
2011  *   SEC("abc/something"), where acceptable "something" should be checked by
2012  *   *prog_init_fn* callback, if there are additional restrictions;
2013  *   - if *sec* is of the form "abc+", it will successfully match both
2014  *   SEC("abc") and SEC("abc/whatever") forms;
2015  *   - if *sec* is NULL, custom handler is registered for any BPF program that
2016  *   doesn't match any of the registered (custom or libbpf's own) SEC()
2017  *   handlers. There could be only one such generic custom handler registered
2018  *   at any given time.
2019  *
2020  * All custom handlers (except the one with *sec* == NULL) are processed
2021  * before libbpf's own SEC() handlers. It is allowed to "override" libbpf's
2022  * SEC() handlers by registering custom ones for the same section prefix
2023  * (i.e., it's possible to have custom SEC("perf_event/LLC-load-misses")
2024  * handler).
2025  *
2026  * Note, like much of global libbpf APIs (e.g., libbpf_set_print(),
2027  * libbpf_set_strict_mode(), etc)) these APIs are not thread-safe. User needs
2028  * to ensure synchronization if there is a risk of running this API from
2029  * multiple threads simultaneously.
2030  */
2031 LIBBPF_API int libbpf_register_prog_handler(const char *sec,
2032 					    enum bpf_prog_type prog_type,
2033 					    enum bpf_attach_type exp_attach_type,
2034 					    const struct libbpf_prog_handler_opts *opts);
2035 /**
2036  * @brief *libbpf_unregister_prog_handler()* unregisters previously registered
2037  * custom BPF program SEC() handler.
2038  * @param handler_id handler ID returned by *libbpf_register_prog_handler()*
2039  * after successful registration
2040  * @return 0 on success, negative error code if handler isn't found
2041  *
2042  * Note, like much of global libbpf APIs (e.g., libbpf_set_print(),
2043  * libbpf_set_strict_mode(), etc)) these APIs are not thread-safe. User needs
2044  * to ensure synchronization if there is a risk of running this API from
2045  * multiple threads simultaneously.
2046  */
2047 LIBBPF_API int libbpf_unregister_prog_handler(int handler_id);
2048 
2049 /**
2050  * @brief **bpf_program__clone()** loads a single BPF program from a prepared
2051  * BPF object into the kernel, returning its file descriptor.
2052  *
2053  * The BPF object must have been previously prepared with
2054  * **bpf_object__prepare()**. If @opts is provided, any non-zero field
2055  * overrides the defaults derived from the program/object internals.
2056  * If @opts is NULL, all fields are populated automatically.
2057  *
2058  * The returned FD is owned by the caller and must be closed with close().
2059  *
2060  * @param prog BPF program from a prepared object
2061  * @param opts Optional load options; non-zero fields override defaults
2062  * @return program FD (>= 0) on success; negative error code on failure
2063  */
2064 LIBBPF_API int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts);
2065 
2066 #ifdef __cplusplus
2067 } /* extern "C" */
2068 #endif
2069 
2070 #endif /* __LIBBPF_LIBBPF_H */
2071