1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2016 PLUMgrid
5 #include <linux/if_link.h>
14 #include <sys/resource.h>
19 #include <bpf/libbpf.h>
22 static __u32 xdp_flags
= XDP_FLAGS_UPDATE_IF_NOEXIST
;
25 static void int_exit(int sig
)
27 __u32 curr_prog_id
= 0;
29 if (bpf_get_link_xdp_id(ifindex
, &curr_prog_id
, xdp_flags
)) {
30 printf("bpf_get_link_xdp_id failed\n");
33 if (prog_id
== curr_prog_id
)
34 bpf_set_link_xdp_fd(ifindex
, -1, xdp_flags
);
35 else if (!curr_prog_id
)
36 printf("couldn't find a prog id on a given interface\n");
38 printf("program on interface changed, not removing\n");
42 /* simple per-protocol drop counter
44 static void poll_stats(int map_fd
, int interval
)
46 unsigned int nr_cpus
= bpf_num_possible_cpus();
47 __u64 values
[nr_cpus
], prev
[UINT8_MAX
] = { 0 };
51 __u32 key
= UINT32_MAX
;
55 while (bpf_map_get_next_key(map_fd
, &key
, &key
) != -1) {
58 assert(bpf_map_lookup_elem(map_fd
, &key
, values
) == 0);
59 for (i
= 0; i
< nr_cpus
; i
++)
62 printf("proto %u: %10llu pkt/s\n",
63 key
, (sum
- prev
[key
]) / interval
);
69 static void usage(const char *prog
)
72 "usage: %s [OPTS] IFACE\n\n"
75 " -N enforce native mode\n"
76 " -F force loading prog\n",
80 int main(int argc
, char **argv
)
82 struct bpf_prog_load_attr prog_load_attr
= {
83 .prog_type
= BPF_PROG_TYPE_XDP
,
85 struct bpf_prog_info info
= {};
86 __u32 info_len
= sizeof(info
);
87 const char *optstr
= "FSN";
88 int prog_fd
, map_fd
, opt
;
89 struct bpf_object
*obj
;
94 while ((opt
= getopt(argc
, argv
, optstr
)) != -1) {
97 xdp_flags
|= XDP_FLAGS_SKB_MODE
;
100 /* default, set below */
103 xdp_flags
&= ~XDP_FLAGS_UPDATE_IF_NOEXIST
;
106 usage(basename(argv
[0]));
111 if (!(xdp_flags
& XDP_FLAGS_SKB_MODE
))
112 xdp_flags
|= XDP_FLAGS_DRV_MODE
;
114 if (optind
== argc
) {
115 usage(basename(argv
[0]));
119 ifindex
= if_nametoindex(argv
[optind
]);
121 perror("if_nametoindex");
125 snprintf(filename
, sizeof(filename
), "%s_kern.o", argv
[0]);
126 prog_load_attr
.file
= filename
;
128 if (bpf_prog_load_xattr(&prog_load_attr
, &obj
, &prog_fd
))
131 map
= bpf_map__next(NULL
, obj
);
133 printf("finding a map in obj file failed\n");
136 map_fd
= bpf_map__fd(map
);
139 printf("bpf_prog_load_xattr: %s\n", strerror(errno
));
143 signal(SIGINT
, int_exit
);
144 signal(SIGTERM
, int_exit
);
146 if (bpf_set_link_xdp_fd(ifindex
, prog_fd
, xdp_flags
) < 0) {
147 printf("link set xdp fd failed\n");
151 err
= bpf_obj_get_info_by_fd(prog_fd
, &info
, &info_len
);
153 printf("can't get prog info - %s\n", strerror(errno
));
158 poll_stats(map_fd
, 2);