1 /* eBPF example program:
5 * The eBPF program sets the sk_bound_dev_if index in new AF_INET{6}
6 * sockets opened by processes in the cgroup.
8 * - Attaches the new program to a cgroup using BPF_PROG_ATTACH
22 #include <linux/bpf.h>
26 char bpf_log_buf[BPF_LOG_BUF_SIZE];
28 static int prog_load(int idx)
30 struct bpf_insn prog[] = {
31 BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
32 BPF_MOV64_IMM(BPF_REG_3, idx),
33 BPF_MOV64_IMM(BPF_REG_2, offsetof(struct bpf_sock, bound_dev_if)),
34 BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, offsetof(struct bpf_sock, bound_dev_if)),
35 BPF_MOV64_IMM(BPF_REG_0, 1), /* r0 = verdict */
38 size_t insns_cnt = sizeof(prog) / sizeof(struct bpf_insn);
40 return bpf_load_program(BPF_PROG_TYPE_CGROUP_SOCK, prog, insns_cnt,
41 "GPL", 0, bpf_log_buf, BPF_LOG_BUF_SIZE);
44 static int usage(const char *argv0)
46 printf("Usage: %s cg-path device-index\n", argv0);
50 int main(int argc, char **argv)
52 int cg_fd, prog_fd, ret;
56 return usage(argv[0]);
58 idx = if_nametoindex(argv[2]);
60 printf("Invalid device name\n");
64 cg_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
66 printf("Failed to open cgroup path: '%s'\n", strerror(errno));
70 prog_fd = prog_load(idx);
71 printf("Output from kernel verifier:\n%s\n-------\n", bpf_log_buf);
74 printf("Failed to load prog: '%s'\n", strerror(errno));
78 ret = bpf_prog_attach(prog_fd, cg_fd, BPF_CGROUP_INET_SOCK_CREATE);
80 printf("Failed to attach prog to cgroup: '%s'\n",