1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 PLUMgrid
5 #include <linux/if_link.h>
18 #include <bpf/libbpf.h>
21 static __u32 xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
24 static void int_exit(int sig)
26 __u32 curr_prog_id = 0;
28 if (bpf_xdp_query_id(ifindex, xdp_flags, &curr_prog_id)) {
29 printf("bpf_xdp_query_id failed\n");
32 if (prog_id == curr_prog_id)
33 bpf_xdp_detach(ifindex, xdp_flags, NULL);
34 else if (!curr_prog_id)
35 printf("couldn't find a prog id on a given interface\n");
37 printf("program on interface changed, not removing\n");
41 /* simple per-protocol drop counter
43 static void poll_stats(int map_fd, int interval)
45 unsigned int nr_cpus = bpf_num_possible_cpus();
46 __u64 values[nr_cpus], prev[UINT8_MAX] = { 0 };
50 __u32 key = UINT32_MAX;
54 while (bpf_map_get_next_key(map_fd, &key, &key) == 0) {
57 assert(bpf_map_lookup_elem(map_fd, &key, values) == 0);
58 for (i = 0; i < nr_cpus; i++)
61 printf("proto %u: %10llu pkt/s\n",
62 key, (sum - prev[key]) / interval);
68 static void usage(const char *prog)
71 "usage: %s [OPTS] IFACE\n\n"
74 " -N enforce native mode\n"
75 " -F force loading prog\n",
79 int main(int argc, char **argv)
81 struct bpf_prog_info info = {};
82 __u32 info_len = sizeof(info);
83 const char *optstr = "FSN";
84 int prog_fd, map_fd, opt;
85 struct bpf_program *prog;
86 struct bpf_object *obj;
91 while ((opt = getopt(argc, argv, optstr)) != -1) {
94 xdp_flags |= XDP_FLAGS_SKB_MODE;
97 /* default, set below */
100 xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
103 usage(basename(argv[0]));
108 if (!(xdp_flags & XDP_FLAGS_SKB_MODE))
109 xdp_flags |= XDP_FLAGS_DRV_MODE;
111 if (optind == argc) {
112 usage(basename(argv[0]));
116 ifindex = if_nametoindex(argv[optind]);
118 perror("if_nametoindex");
122 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
123 obj = bpf_object__open_file(filename, NULL);
124 if (libbpf_get_error(obj))
127 prog = bpf_object__next_program(obj, NULL);
128 bpf_program__set_type(prog, BPF_PROG_TYPE_XDP);
130 err = bpf_object__load(obj);
134 prog_fd = bpf_program__fd(prog);
136 map = bpf_object__next_map(obj, NULL);
138 printf("finding a map in obj file failed\n");
141 map_fd = bpf_map__fd(map);
144 printf("bpf_prog_load_xattr: %s\n", strerror(errno));
148 signal(SIGINT, int_exit);
149 signal(SIGTERM, int_exit);
151 if (bpf_xdp_attach(ifindex, prog_fd, xdp_flags, NULL) < 0) {
152 printf("link set xdp fd failed\n");
156 err = bpf_prog_get_info_by_fd(prog_fd, &info, &info_len);
158 printf("can't get prog info - %s\n", strerror(errno));
163 poll_stats(map_fd, 1);