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>
23 #include <sys/resource.h>
29 static int ifindex_in
;
30 static int ifindex_out
;
31 static bool ifindex_out_xdp_dummy_attached
= true;
33 static __u32 xdp_flags
;
35 static void int_exit(int sig
)
37 bpf_set_link_xdp_fd(ifindex_in
, -1, xdp_flags
);
38 if (ifindex_out_xdp_dummy_attached
)
39 bpf_set_link_xdp_fd(ifindex_out
, -1, xdp_flags
);
43 static void poll_stats(int interval
, int ifindex
)
45 unsigned int nr_cpus
= bpf_num_possible_cpus();
46 __u64 values
[nr_cpus
], prev
[nr_cpus
];
48 memset(prev
, 0, sizeof(prev
));
56 assert(bpf_map_lookup_elem(map_fd
[1], &key
, values
) == 0);
57 for (i
= 0; i
< nr_cpus
; i
++)
58 sum
+= (values
[i
] - prev
[i
]);
60 printf("ifindex %i: %10llu pkt/s\n",
61 ifindex
, sum
/ interval
);
62 memcpy(prev
, values
, sizeof(values
));
66 static void usage(const char *prog
)
69 "usage: %s [OPTS] IFINDEX_IN IFINDEX_OUT\n\n"
72 " -N enforce native mode\n",
77 int main(int argc
, char **argv
)
79 struct rlimit r
= {RLIM_INFINITY
, RLIM_INFINITY
};
80 const char *optstr
= "SN";
82 int ret
, opt
, key
= 0;
84 while ((opt
= getopt(argc
, argv
, optstr
)) != -1) {
87 xdp_flags
|= XDP_FLAGS_SKB_MODE
;
90 xdp_flags
|= XDP_FLAGS_DRV_MODE
;
93 usage(basename(argv
[0]));
99 printf("usage: %s IFINDEX_IN IFINDEX_OUT\n", argv
[0]);
103 if (setrlimit(RLIMIT_MEMLOCK
, &r
)) {
104 perror("setrlimit(RLIMIT_MEMLOCK)");
108 ifindex_in
= strtoul(argv
[optind
], NULL
, 0);
109 ifindex_out
= strtoul(argv
[optind
+ 1], NULL
, 0);
110 printf("input: %d output: %d\n", ifindex_in
, ifindex_out
);
112 snprintf(filename
, sizeof(filename
), "%s_kern.o", argv
[0]);
114 if (load_bpf_file(filename
)) {
115 printf("%s", bpf_log_buf
);
120 printf("load_bpf_file: %s\n", strerror(errno
));
124 if (bpf_set_link_xdp_fd(ifindex_in
, prog_fd
[0], xdp_flags
) < 0) {
125 printf("ERROR: link set xdp fd failed on %d\n", ifindex_in
);
129 /* Loading dummy XDP prog on out-device */
130 if (bpf_set_link_xdp_fd(ifindex_out
, prog_fd
[1],
131 (xdp_flags
| XDP_FLAGS_UPDATE_IF_NOEXIST
)) < 0) {
132 printf("WARN: link set xdp fd failed on %d\n", ifindex_out
);
133 ifindex_out_xdp_dummy_attached
= false;
136 signal(SIGINT
, int_exit
);
137 signal(SIGTERM
, int_exit
);
139 /* bpf redirect port */
140 ret
= bpf_map_update_elem(map_fd
[0], &key
, &ifindex_out
, 0);
142 perror("bpf_update_elem");
146 poll_stats(2, ifindex_out
);