1 /* Copyright (c) 2016 John Fastabend <john.r.fastabend@intel.com>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
7 * This program is distributed in the hope that it will be useful, but
8 * WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * General Public License for more details.
12 #include <linux/bpf.h>
13 #include <linux/if_link.h>
28 static int ifindex_in;
29 static int ifindex_out;
30 static bool ifindex_out_xdp_dummy_attached = true;
32 static __u32 xdp_flags;
34 static void int_exit(int sig)
36 set_link_xdp_fd(ifindex_in, -1, xdp_flags);
37 if (ifindex_out_xdp_dummy_attached)
38 set_link_xdp_fd(ifindex_out, -1, xdp_flags);
42 static void poll_stats(int interval, int ifindex)
44 unsigned int nr_cpus = bpf_num_possible_cpus();
45 __u64 values[nr_cpus], prev[nr_cpus];
47 memset(prev, 0, sizeof(prev));
55 assert(bpf_map_lookup_elem(map_fd[1], &key, values) == 0);
56 for (i = 0; i < nr_cpus; i++)
57 sum += (values[i] - prev[i]);
59 printf("ifindex %i: %10llu pkt/s\n",
60 ifindex, sum / interval);
61 memcpy(prev, values, sizeof(values));
65 static void usage(const char *prog)
68 "usage: %s [OPTS] IFINDEX_IN IFINDEX_OUT\n\n"
71 " -N enforce native mode\n",
76 int main(int argc, char **argv)
78 const char *optstr = "SN";
80 int ret, opt, key = 0;
82 while ((opt = getopt(argc, argv, optstr)) != -1) {
85 xdp_flags |= XDP_FLAGS_SKB_MODE;
88 xdp_flags |= XDP_FLAGS_DRV_MODE;
91 usage(basename(argv[0]));
97 printf("usage: %s IFINDEX_IN IFINDEX_OUT\n", argv[0]);
101 ifindex_in = strtoul(argv[optind], NULL, 0);
102 ifindex_out = strtoul(argv[optind + 1], NULL, 0);
103 printf("input: %d output: %d\n", ifindex_in, ifindex_out);
105 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
107 if (load_bpf_file(filename)) {
108 printf("%s", bpf_log_buf);
113 printf("load_bpf_file: %s\n", strerror(errno));
117 if (set_link_xdp_fd(ifindex_in, prog_fd[0], xdp_flags) < 0) {
118 printf("ERROR: link set xdp fd failed on %d\n", ifindex_in);
122 /* Loading dummy XDP prog on out-device */
123 if (set_link_xdp_fd(ifindex_out, prog_fd[1],
124 (xdp_flags | XDP_FLAGS_UPDATE_IF_NOEXIST)) < 0) {
125 printf("WARN: link set xdp fd failed on %d\n", ifindex_out);
126 ifindex_out_xdp_dummy_attached = false;
129 signal(SIGINT, int_exit);
130 signal(SIGTERM, int_exit);
132 /* bpf redirect port */
133 ret = bpf_map_update_elem(map_fd[0], &key, &ifindex_out, 0);
135 perror("bpf_update_elem");
139 poll_stats(2, ifindex_out);