1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3 
4 #include <linux/bpf.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <sys/syscall.h>
8 
9 #include "fdset.h"
10 #include "list.h"
11 #include "macro.h"
12 
13 typedef struct BPFProgram BPFProgram;
14 
15 /* This encapsulates three different concepts: the loaded BPF program, the BPF code, and the attachment to a
16  * cgroup. Typically our BPF programs go through all three stages: we build the code, we load it, and finally
17  * we attach it, but it might happen that we operate with programs that aren't loaded or aren't attached, or
18  * where we don't have the code. */
19 struct BPFProgram {
20         /* The loaded BPF program, if loaded */
21         int kernel_fd;
22         uint32_t prog_type;
23         char *prog_name;
24 
25         /* The code of it BPF program, if known */
26         size_t n_instructions;
27         struct bpf_insn *instructions;
28 
29         /* The cgroup path the program is attached to, if it is attached. If non-NULL bpf_program_unref()
30          * will detach on destruction. */
31         char *attached_path;
32         int attached_type;
33         uint32_t attached_flags;
34 };
35 
36 int bpf_program_new(uint32_t prog_type, const char *prog_name, BPFProgram **ret);
37 int bpf_program_new_from_bpffs_path(const char *path, BPFProgram **ret);
38 BPFProgram *bpf_program_free(BPFProgram *p);
39 
40 int bpf_program_add_instructions(BPFProgram *p, const struct bpf_insn *insn, size_t count);
41 int bpf_program_load_kernel(BPFProgram *p, char *log_buf, size_t log_size);
42 int bpf_program_load_from_bpf_fs(BPFProgram *p, const char *path);
43 
44 int bpf_program_cgroup_attach(BPFProgram *p, int type, const char *path, uint32_t flags);
45 int bpf_program_cgroup_detach(BPFProgram *p);
46 
47 int bpf_program_pin(int prog_fd, const char *bpffs_path);
48 int bpf_program_get_id_by_fd(int prog_fd, uint32_t *ret_id);
49 
50 int bpf_program_serialize_attachment(FILE *f, FDSet *fds, const char *key, BPFProgram *p);
51 int bpf_program_serialize_attachment_set(FILE *f, FDSet *fds, const char *key, Set *set);
52 int bpf_program_deserialize_attachment(const char *v, FDSet *fds, BPFProgram **bpfp);
53 int bpf_program_deserialize_attachment_set(const char *v, FDSet *fds, Set **bpfsetp);
54 
55 extern const struct hash_ops bpf_program_hash_ops;
56 
57 int bpf_map_new(enum bpf_map_type type, size_t key_size, size_t value_size, size_t max_entries, uint32_t flags);
58 int bpf_map_update_element(int fd, const void *key, void *value);
59 int bpf_map_lookup_element(int fd, const void *key, void *value);
60 
61 int bpf_cgroup_attach_type_from_string(const char *str) _pure_;
62 const char *bpf_cgroup_attach_type_to_string(int attach_type) _const_;
63 
64 DEFINE_TRIVIAL_CLEANUP_FUNC(BPFProgram*, bpf_program_free);
65