1 // SPDX-License-Identifier: GPL-2.0
2 /* eBPF example program:
6 * The eBPF program loads a filter from file and attaches the
7 * program to a cgroup using BPF_PROG_ATTACH
21 #include <linux/bpf.h>
23 #include <bpf/libbpf.h>
27 static int usage(const char *argv0
)
29 printf("Usage: %s cg-path filter-path [filter-id]\n", argv0
);
33 int main(int argc
, char **argv
)
35 int cg_fd
, err
, ret
= EXIT_FAILURE
, filter_id
= 0, prog_cnt
= 0;
36 const char *link_pin_path
= "/sys/fs/bpf/test_cgrp2_sock2";
37 struct bpf_link
*link
= NULL
;
38 struct bpf_program
*progs
[2];
39 struct bpf_program
*prog
;
40 struct bpf_object
*obj
;
43 return usage(argv
[0]);
46 filter_id
= atoi(argv
[3]);
48 cg_fd
= open(argv
[1], O_DIRECTORY
| O_RDONLY
);
50 printf("Failed to open cgroup path: '%s'\n", strerror(errno
));
54 obj
= bpf_object__open_file(argv
[2], NULL
);
55 if (libbpf_get_error(obj
)) {
56 printf("ERROR: opening BPF object file failed\n");
60 bpf_object__for_each_program(prog
, obj
) {
61 progs
[prog_cnt
] = prog
;
65 if (filter_id
>= prog_cnt
) {
66 printf("Invalid program id; program not found in file\n");
70 /* load BPF program */
71 if (bpf_object__load(obj
)) {
72 printf("ERROR: loading BPF object file failed\n");
76 link
= bpf_program__attach_cgroup(progs
[filter_id
], cg_fd
);
77 if (libbpf_get_error(link
)) {
78 printf("ERROR: bpf_program__attach failed\n");
83 err
= bpf_link__pin(link
, link_pin_path
);
85 printf("ERROR: bpf_link__pin failed: %d\n", err
);
92 bpf_link__destroy(link
);
93 bpf_object__close(obj
);