xref: /linux-tools/ebpf/kernel-samples-bpf/l3lb.c (revision 7889a9fe3f6cd23238c94fad4e1c698d5585c3fe)
1 #include <bpf/libbpf.h>
2 #include <linux/if_link.h>
3 #include <net/if.h>
4 #include <string.h>
5 #include <bpf/bpf.h>
6 #include "l3lb.h"
7 
8 
main(int argc,char ** argv)9 int main(int argc, char **argv) {
10     __u32 curr_prog_fd=0;
11     int prog_fd;
12     if (argc != 4) {
13         printf("Usage: %s [in_inf] [out_inf] [tx_addr]\n", argv[0]);
14         return 1;
15     }
16     int if1 = if_nametoindex(argv[1]);
17     if (!if1) { perror("Fail to get inf index"); return 1; }
18     if (bpf_get_link_xdp_id(if1, &curr_prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST)) { perror("bpf_get_link_xdp_id failed\n"); return 1; }
19     if (curr_prog_fd) {
20         printf("xdp prog id(%d) already linked to %s, removing it now..\n", curr_prog_fd, argv[1]);
21         bpf_set_link_xdp_fd(if1, -1, XDP_FLAGS_UPDATE_IF_NOEXIST);
22     }
23     int if2 = if_nametoindex(argv[2]);
24     if (!if2) { perror("Fail to get inf index"); return 1; }
25     if (bpf_get_link_xdp_id(if2, &curr_prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST)) { perror("bpf_get_link_xdp_id failed\n"); return 1; }
26     if (curr_prog_fd) {
27         printf("xdp prog id(%d) already linked to %s, removing it now..\n", curr_prog_fd, argv[2]);
28         bpf_set_link_xdp_fd(if2, -1, XDP_FLAGS_UPDATE_IF_NOEXIST);
29     }
30     unsigned int tx_addr = parse_ip(argv[3]);
31     if (tx_addr==0) { printf("invalid tx ip address %s\n", argv[3]); return 1; }
32     // load bpf object
33 	struct bpf_prog_load_attr prog_load_attr = {
34 		.prog_type	= BPF_PROG_TYPE_XDP,
35         .file = "./l3lb_kern.o",
36 	};
37 	struct bpf_object *obj;
38 	if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd)) {
39         perror("Fail to load bpf object");
40         return 1;
41     }
42 	int map_fd = bpf_object__find_map_fd_by_name(obj, "tx_addr");
43     if (map_fd<0) { perror("Fail to locate tx addr map"); return 1; }
44     int key = 0;
45 	int ret = bpf_map_update_elem(map_fd, &key, &tx_addr, 0);
46     if (ret) { perror("Fail to update tx addr"); return 1; }
47 
48     if (bpf_set_link_xdp_fd(if1, prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST) < 0) {
49         printf("fail to link if1\n"); return 1;
50     }
51     if (bpf_set_link_xdp_fd(if2, prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST) < 0) {
52         printf("fail to link if2\n"); return 1;
53     }
54     return 0;
55 }
56