1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2017 - 2018 Intel Corporation. */
4 #include <asm/barrier.h>
9 #include <linux/compiler.h>
10 #include <linux/if_link.h>
11 #include <linux/if_xdp.h>
12 #include <linux/if_ether.h>
14 #include <linux/limits.h>
15 #include <linux/udp.h>
16 #include <arpa/inet.h>
18 #include <net/ethernet.h>
28 #include <sys/resource.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
34 #include <bpf/libbpf.h>
51 #define NUM_FRAMES (4 * 1024)
52 #define MIN_PKT_SIZE 64
54 #define DEBUG_HEXDUMP 0
61 static unsigned long prev_time;
69 static enum benchmark_type opt_bench = BENCH_RXDROP;
70 static u32 opt_xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
71 static const char *opt_if = "";
72 static int opt_ifindex;
74 static unsigned long opt_duration;
75 static unsigned long start_time;
76 static bool benchmark_done;
77 static u32 opt_batch_size = 64;
78 static int opt_pkt_count;
79 static u16 opt_pkt_size = MIN_PKT_SIZE;
80 static u32 opt_pkt_fill_pattern = 0x12345678;
81 static bool opt_extra_stats;
82 static bool opt_quiet;
83 static bool opt_app_stats;
84 static const char *opt_irq_str = "";
86 static int irqs_at_init = -1;
88 static int opt_interval = 1;
89 static u32 opt_xdp_bind_flags = XDP_USE_NEED_WAKEUP;
90 static u32 opt_umem_flags;
91 static int opt_unaligned_chunks;
92 static int opt_mmap_flags;
93 static int opt_xsk_frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
94 static int opt_timeout = 1000;
95 static bool opt_need_wakeup = true;
96 static u32 opt_num_xsks = 1;
98 static bool opt_busy_poll;
100 struct xsk_ring_stats {
101 unsigned long rx_npkts;
102 unsigned long tx_npkts;
103 unsigned long rx_dropped_npkts;
104 unsigned long rx_invalid_npkts;
105 unsigned long tx_invalid_npkts;
106 unsigned long rx_full_npkts;
107 unsigned long rx_fill_empty_npkts;
108 unsigned long tx_empty_npkts;
109 unsigned long prev_rx_npkts;
110 unsigned long prev_tx_npkts;
111 unsigned long prev_rx_dropped_npkts;
112 unsigned long prev_rx_invalid_npkts;
113 unsigned long prev_tx_invalid_npkts;
114 unsigned long prev_rx_full_npkts;
115 unsigned long prev_rx_fill_empty_npkts;
116 unsigned long prev_tx_empty_npkts;
119 struct xsk_driver_stats {
121 unsigned long prev_intrs;
124 struct xsk_app_stats {
125 unsigned long rx_empty_polls;
126 unsigned long fill_fail_polls;
127 unsigned long copy_tx_sendtos;
128 unsigned long tx_wakeup_sendtos;
129 unsigned long opt_polls;
130 unsigned long prev_rx_empty_polls;
131 unsigned long prev_fill_fail_polls;
132 unsigned long prev_copy_tx_sendtos;
133 unsigned long prev_tx_wakeup_sendtos;
134 unsigned long prev_opt_polls;
137 struct xsk_umem_info {
138 struct xsk_ring_prod fq;
139 struct xsk_ring_cons cq;
140 struct xsk_umem *umem;
144 struct xsk_socket_info {
145 struct xsk_ring_cons rx;
146 struct xsk_ring_prod tx;
147 struct xsk_umem_info *umem;
148 struct xsk_socket *xsk;
149 struct xsk_ring_stats ring_stats;
150 struct xsk_app_stats app_stats;
151 struct xsk_driver_stats drv_stats;
155 static int num_socks;
156 struct xsk_socket_info *xsks[MAX_SOCKS];
158 static unsigned long get_nsecs(void)
162 clock_gettime(CLOCK_MONOTONIC, &ts);
163 return ts.tv_sec * 1000000000UL + ts.tv_nsec;
166 static void print_benchmark(bool running)
168 const char *bench_str = "INVALID";
170 if (opt_bench == BENCH_RXDROP)
171 bench_str = "rxdrop";
172 else if (opt_bench == BENCH_TXONLY)
173 bench_str = "txonly";
174 else if (opt_bench == BENCH_L2FWD)
177 printf("%s:%d %s ", opt_if, opt_queue, bench_str);
178 if (opt_xdp_flags & XDP_FLAGS_SKB_MODE)
180 else if (opt_xdp_flags & XDP_FLAGS_DRV_MODE)
189 printf("running...");
194 static int xsk_get_xdp_stats(int fd, struct xsk_socket_info *xsk)
196 struct xdp_statistics stats;
200 optlen = sizeof(stats);
201 err = getsockopt(fd, SOL_XDP, XDP_STATISTICS, &stats, &optlen);
205 if (optlen == sizeof(struct xdp_statistics)) {
206 xsk->ring_stats.rx_dropped_npkts = stats.rx_dropped;
207 xsk->ring_stats.rx_invalid_npkts = stats.rx_invalid_descs;
208 xsk->ring_stats.tx_invalid_npkts = stats.tx_invalid_descs;
209 xsk->ring_stats.rx_full_npkts = stats.rx_ring_full;
210 xsk->ring_stats.rx_fill_empty_npkts = stats.rx_fill_ring_empty_descs;
211 xsk->ring_stats.tx_empty_npkts = stats.tx_ring_empty_descs;
218 static void dump_app_stats(long dt)
222 for (i = 0; i < num_socks && xsks[i]; i++) {
223 char *fmt = "%-18s %'-14.0f %'-14lu\n";
224 double rx_empty_polls_ps, fill_fail_polls_ps, copy_tx_sendtos_ps,
225 tx_wakeup_sendtos_ps, opt_polls_ps;
227 rx_empty_polls_ps = (xsks[i]->app_stats.rx_empty_polls -
228 xsks[i]->app_stats.prev_rx_empty_polls) * 1000000000. / dt;
229 fill_fail_polls_ps = (xsks[i]->app_stats.fill_fail_polls -
230 xsks[i]->app_stats.prev_fill_fail_polls) * 1000000000. / dt;
231 copy_tx_sendtos_ps = (xsks[i]->app_stats.copy_tx_sendtos -
232 xsks[i]->app_stats.prev_copy_tx_sendtos) * 1000000000. / dt;
233 tx_wakeup_sendtos_ps = (xsks[i]->app_stats.tx_wakeup_sendtos -
234 xsks[i]->app_stats.prev_tx_wakeup_sendtos)
236 opt_polls_ps = (xsks[i]->app_stats.opt_polls -
237 xsks[i]->app_stats.prev_opt_polls) * 1000000000. / dt;
239 printf("\n%-18s %-14s %-14s\n", "", "calls/s", "count");
240 printf(fmt, "rx empty polls", rx_empty_polls_ps, xsks[i]->app_stats.rx_empty_polls);
241 printf(fmt, "fill fail polls", fill_fail_polls_ps,
242 xsks[i]->app_stats.fill_fail_polls);
243 printf(fmt, "copy tx sendtos", copy_tx_sendtos_ps,
244 xsks[i]->app_stats.copy_tx_sendtos);
245 printf(fmt, "tx wakeup sendtos", tx_wakeup_sendtos_ps,
246 xsks[i]->app_stats.tx_wakeup_sendtos);
247 printf(fmt, "opt polls", opt_polls_ps, xsks[i]->app_stats.opt_polls);
249 xsks[i]->app_stats.prev_rx_empty_polls = xsks[i]->app_stats.rx_empty_polls;
250 xsks[i]->app_stats.prev_fill_fail_polls = xsks[i]->app_stats.fill_fail_polls;
251 xsks[i]->app_stats.prev_copy_tx_sendtos = xsks[i]->app_stats.copy_tx_sendtos;
252 xsks[i]->app_stats.prev_tx_wakeup_sendtos = xsks[i]->app_stats.tx_wakeup_sendtos;
253 xsks[i]->app_stats.prev_opt_polls = xsks[i]->app_stats.opt_polls;
257 static bool get_interrupt_number(void)
263 f_int_proc = fopen("/proc/interrupts", "r");
264 if (f_int_proc == NULL) {
265 printf("Failed to open /proc/interrupts.\n");
269 while (!feof(f_int_proc) && !found) {
270 /* Make sure to read a full line at a time */
271 if (fgets(line, sizeof(line), f_int_proc) == NULL ||
272 line[strlen(line) - 1] != '\n') {
273 printf("Error reading from interrupts file\n");
277 /* Extract interrupt number from line */
278 if (strstr(line, opt_irq_str) != NULL) {
290 static int get_irqs(void)
292 char count_path[PATH_MAX];
293 int total_intrs = -1;
297 snprintf(count_path, sizeof(count_path),
298 "/sys/kernel/irq/%i/per_cpu_count", irq_no);
299 f_count_proc = fopen(count_path, "r");
300 if (f_count_proc == NULL) {
301 printf("Failed to open %s\n", count_path);
305 if (fgets(line, sizeof(line), f_count_proc) == NULL ||
306 line[strlen(line) - 1] != '\n') {
307 printf("Error reading from %s\n", count_path);
309 static const char com[2] = ",";
313 token = strtok(line, com);
314 while (token != NULL) {
315 /* sum up interrupts across all cores */
316 total_intrs += atoi(token);
317 token = strtok(NULL, com);
321 fclose(f_count_proc);
326 static void dump_driver_stats(long dt)
330 for (i = 0; i < num_socks && xsks[i]; i++) {
331 char *fmt = "%-18s %'-14.0f %'-14lu\n";
333 int n_ints = get_irqs();
336 printf("error getting intr info for intr %i\n", irq_no);
339 xsks[i]->drv_stats.intrs = n_ints - irqs_at_init;
341 intrs_ps = (xsks[i]->drv_stats.intrs - xsks[i]->drv_stats.prev_intrs) *
344 printf("\n%-18s %-14s %-14s\n", "", "intrs/s", "count");
345 printf(fmt, "irqs", intrs_ps, xsks[i]->drv_stats.intrs);
347 xsks[i]->drv_stats.prev_intrs = xsks[i]->drv_stats.intrs;
351 static void dump_stats(void)
353 unsigned long now = get_nsecs();
354 long dt = now - prev_time;
359 for (i = 0; i < num_socks && xsks[i]; i++) {
360 char *fmt = "%-18s %'-14.0f %'-14lu\n";
361 double rx_pps, tx_pps, dropped_pps, rx_invalid_pps, full_pps, fill_empty_pps,
362 tx_invalid_pps, tx_empty_pps;
364 rx_pps = (xsks[i]->ring_stats.rx_npkts - xsks[i]->ring_stats.prev_rx_npkts) *
366 tx_pps = (xsks[i]->ring_stats.tx_npkts - xsks[i]->ring_stats.prev_tx_npkts) *
369 printf("\n sock%d@", i);
370 print_benchmark(false);
373 printf("%-18s %-14s %-14s %-14.2f\n", "", "pps", "pkts",
375 printf(fmt, "rx", rx_pps, xsks[i]->ring_stats.rx_npkts);
376 printf(fmt, "tx", tx_pps, xsks[i]->ring_stats.tx_npkts);
378 xsks[i]->ring_stats.prev_rx_npkts = xsks[i]->ring_stats.rx_npkts;
379 xsks[i]->ring_stats.prev_tx_npkts = xsks[i]->ring_stats.tx_npkts;
381 if (opt_extra_stats) {
382 if (!xsk_get_xdp_stats(xsk_socket__fd(xsks[i]->xsk), xsks[i])) {
383 dropped_pps = (xsks[i]->ring_stats.rx_dropped_npkts -
384 xsks[i]->ring_stats.prev_rx_dropped_npkts) *
386 rx_invalid_pps = (xsks[i]->ring_stats.rx_invalid_npkts -
387 xsks[i]->ring_stats.prev_rx_invalid_npkts) *
389 tx_invalid_pps = (xsks[i]->ring_stats.tx_invalid_npkts -
390 xsks[i]->ring_stats.prev_tx_invalid_npkts) *
392 full_pps = (xsks[i]->ring_stats.rx_full_npkts -
393 xsks[i]->ring_stats.prev_rx_full_npkts) *
395 fill_empty_pps = (xsks[i]->ring_stats.rx_fill_empty_npkts -
396 xsks[i]->ring_stats.prev_rx_fill_empty_npkts) *
398 tx_empty_pps = (xsks[i]->ring_stats.tx_empty_npkts -
399 xsks[i]->ring_stats.prev_tx_empty_npkts) *
402 printf(fmt, "rx dropped", dropped_pps,
403 xsks[i]->ring_stats.rx_dropped_npkts);
404 printf(fmt, "rx invalid", rx_invalid_pps,
405 xsks[i]->ring_stats.rx_invalid_npkts);
406 printf(fmt, "tx invalid", tx_invalid_pps,
407 xsks[i]->ring_stats.tx_invalid_npkts);
408 printf(fmt, "rx queue full", full_pps,
409 xsks[i]->ring_stats.rx_full_npkts);
410 printf(fmt, "fill ring empty", fill_empty_pps,
411 xsks[i]->ring_stats.rx_fill_empty_npkts);
412 printf(fmt, "tx ring empty", tx_empty_pps,
413 xsks[i]->ring_stats.tx_empty_npkts);
415 xsks[i]->ring_stats.prev_rx_dropped_npkts =
416 xsks[i]->ring_stats.rx_dropped_npkts;
417 xsks[i]->ring_stats.prev_rx_invalid_npkts =
418 xsks[i]->ring_stats.rx_invalid_npkts;
419 xsks[i]->ring_stats.prev_tx_invalid_npkts =
420 xsks[i]->ring_stats.tx_invalid_npkts;
421 xsks[i]->ring_stats.prev_rx_full_npkts =
422 xsks[i]->ring_stats.rx_full_npkts;
423 xsks[i]->ring_stats.prev_rx_fill_empty_npkts =
424 xsks[i]->ring_stats.rx_fill_empty_npkts;
425 xsks[i]->ring_stats.prev_tx_empty_npkts =
426 xsks[i]->ring_stats.tx_empty_npkts;
428 printf("%-15s\n", "Error retrieving extra stats");
436 dump_driver_stats(dt);
439 static bool is_benchmark_done(void)
441 if (opt_duration > 0) {
442 unsigned long dt = (get_nsecs() - start_time);
444 if (dt >= opt_duration)
445 benchmark_done = true;
447 return benchmark_done;
450 static void *poller(void *arg)
453 while (!is_benchmark_done()) {
461 static void remove_xdp_program(void)
463 u32 curr_prog_id = 0;
465 if (bpf_get_link_xdp_id(opt_ifindex, &curr_prog_id, opt_xdp_flags)) {
466 printf("bpf_get_link_xdp_id failed\n");
469 if (prog_id == curr_prog_id)
470 bpf_set_link_xdp_fd(opt_ifindex, -1, opt_xdp_flags);
471 else if (!curr_prog_id)
472 printf("couldn't find a prog id on a given interface\n");
474 printf("program on interface changed, not removing\n");
477 static void int_exit(int sig)
479 benchmark_done = true;
482 static void xdpsock_cleanup(void)
484 struct xsk_umem *umem = xsks[0]->umem->umem;
488 for (i = 0; i < num_socks; i++)
489 xsk_socket__delete(xsks[i]->xsk);
490 (void)xsk_umem__delete(umem);
491 remove_xdp_program();
494 static void __exit_with_error(int error, const char *file, const char *func,
497 fprintf(stderr, "%s:%s:%i: errno: %d/\"%s\"\n", file, func,
498 line, error, strerror(error));
500 remove_xdp_program();
504 #define exit_with_error(error) __exit_with_error(error, __FILE__, __func__, \
506 static void swap_mac_addresses(void *data)
508 struct ether_header *eth = (struct ether_header *)data;
509 struct ether_addr *src_addr = (struct ether_addr *)ð->ether_shost;
510 struct ether_addr *dst_addr = (struct ether_addr *)ð->ether_dhost;
511 struct ether_addr tmp;
514 *src_addr = *dst_addr;
518 static void hex_dump(void *pkt, size_t length, u64 addr)
520 const unsigned char *address = (unsigned char *)pkt;
521 const unsigned char *line = address;
522 size_t line_size = 32;
530 sprintf(buf, "addr=%llu", addr);
531 printf("length = %zu\n", length);
532 printf("%s | ", buf);
533 while (length-- > 0) {
534 printf("%02X ", *address++);
535 if (!(++i % line_size) || (length == 0 && i % line_size)) {
537 while (i++ % line_size)
540 printf(" | "); /* right close */
541 while (line < address) {
543 printf("%c", (c < 33 || c == 255) ? 0x2E : c);
547 printf("%s | ", buf);
553 static void *memset32_htonl(void *dest, u32 val, u32 size)
555 u32 *ptr = (u32 *)dest;
560 for (i = 0; i < (size & (~0x3)); i += 4)
563 for (; i < size; i++)
564 ((char *)dest)[i] = ((char *)&val)[i & 3];
570 * This function code has been taken from
571 * Linux kernel lib/checksum.c
573 static inline unsigned short from32to16(unsigned int x)
575 /* add up 16-bit and 16-bit for 16+c bit */
576 x = (x & 0xffff) + (x >> 16);
578 x = (x & 0xffff) + (x >> 16);
583 * This function code has been taken from
584 * Linux kernel lib/checksum.c
586 static unsigned int do_csum(const unsigned char *buff, int len)
588 unsigned int result = 0;
593 odd = 1 & (unsigned long)buff;
595 #ifdef __LITTLE_ENDIAN
596 result += (*buff << 8);
604 if (2 & (unsigned long)buff) {
605 result += *(unsigned short *)buff;
610 const unsigned char *end = buff +
611 ((unsigned int)len & ~3);
612 unsigned int carry = 0;
615 unsigned int w = *(unsigned int *)buff;
620 carry = (w > result);
621 } while (buff < end);
623 result = (result & 0xffff) + (result >> 16);
626 result += *(unsigned short *)buff;
631 #ifdef __LITTLE_ENDIAN
634 result += (*buff << 8);
636 result = from32to16(result);
638 result = ((result >> 8) & 0xff) | ((result & 0xff) << 8);
643 __sum16 ip_fast_csum(const void *iph, unsigned int ihl);
646 * This is a version of ip_compute_csum() optimized for IP headers,
647 * which always checksum on 4 octet boundaries.
648 * This function code has been taken from
649 * Linux kernel lib/checksum.c
651 __sum16 ip_fast_csum(const void *iph, unsigned int ihl)
653 return (__force __sum16)~do_csum(iph, ihl * 4);
657 * Fold a partial checksum
658 * This function code has been taken from
659 * Linux kernel include/asm-generic/checksum.h
661 static inline __sum16 csum_fold(__wsum csum)
663 u32 sum = (__force u32)csum;
665 sum = (sum & 0xffff) + (sum >> 16);
666 sum = (sum & 0xffff) + (sum >> 16);
667 return (__force __sum16)~sum;
671 * This function code has been taken from
672 * Linux kernel lib/checksum.c
674 static inline u32 from64to32(u64 x)
676 /* add up 32-bit and 32-bit for 32+c bit */
677 x = (x & 0xffffffff) + (x >> 32);
679 x = (x & 0xffffffff) + (x >> 32);
683 __wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
684 __u32 len, __u8 proto, __wsum sum);
687 * This function code has been taken from
688 * Linux kernel lib/checksum.c
690 __wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
691 __u32 len, __u8 proto, __wsum sum)
693 unsigned long long s = (__force u32)sum;
695 s += (__force u32)saddr;
696 s += (__force u32)daddr;
697 #ifdef __BIG_ENDIAN__
700 s += (proto + len) << 8;
702 return (__force __wsum)from64to32(s);
706 * This function has been taken from
707 * Linux kernel include/asm-generic/checksum.h
709 static inline __sum16
710 csum_tcpudp_magic(__be32 saddr, __be32 daddr, __u32 len,
711 __u8 proto, __wsum sum)
713 return csum_fold(csum_tcpudp_nofold(saddr, daddr, len, proto, sum));
716 static inline u16 udp_csum(u32 saddr, u32 daddr, u32 len,
717 u8 proto, u16 *udp_pkt)
722 /* udp hdr and data */
723 for (; cnt < len; cnt += 2)
724 csum += udp_pkt[cnt >> 1];
726 return csum_tcpudp_magic(saddr, daddr, len, proto, csum);
729 #define ETH_FCS_SIZE 4
731 #define PKT_HDR_SIZE (sizeof(struct ethhdr) + sizeof(struct iphdr) + \
732 sizeof(struct udphdr))
734 #define PKT_SIZE (opt_pkt_size - ETH_FCS_SIZE)
735 #define IP_PKT_SIZE (PKT_SIZE - sizeof(struct ethhdr))
736 #define UDP_PKT_SIZE (IP_PKT_SIZE - sizeof(struct iphdr))
737 #define UDP_PKT_DATA_SIZE (UDP_PKT_SIZE - sizeof(struct udphdr))
739 static u8 pkt_data[XSK_UMEM__DEFAULT_FRAME_SIZE];
741 static void gen_eth_hdr_data(void)
743 struct udphdr *udp_hdr = (struct udphdr *)(pkt_data +
744 sizeof(struct ethhdr) +
745 sizeof(struct iphdr));
746 struct iphdr *ip_hdr = (struct iphdr *)(pkt_data +
747 sizeof(struct ethhdr));
748 struct ethhdr *eth_hdr = (struct ethhdr *)pkt_data;
750 /* ethernet header */
751 memcpy(eth_hdr->h_dest, "\x3c\xfd\xfe\x9e\x7f\x71", ETH_ALEN);
752 memcpy(eth_hdr->h_source, "\xec\xb1\xd7\x98\x3a\xc0", ETH_ALEN);
753 eth_hdr->h_proto = htons(ETH_P_IP);
756 ip_hdr->version = IPVERSION;
757 ip_hdr->ihl = 0x5; /* 20 byte header */
759 ip_hdr->tot_len = htons(IP_PKT_SIZE);
761 ip_hdr->frag_off = 0;
762 ip_hdr->ttl = IPDEFTTL;
763 ip_hdr->protocol = IPPROTO_UDP;
764 ip_hdr->saddr = htonl(0x0a0a0a10);
765 ip_hdr->daddr = htonl(0x0a0a0a20);
767 /* IP header checksum */
769 ip_hdr->check = ip_fast_csum((const void *)ip_hdr, ip_hdr->ihl);
772 udp_hdr->source = htons(0x1000);
773 udp_hdr->dest = htons(0x1000);
774 udp_hdr->len = htons(UDP_PKT_SIZE);
777 memset32_htonl(pkt_data + PKT_HDR_SIZE, opt_pkt_fill_pattern,
780 /* UDP header checksum */
782 udp_hdr->check = udp_csum(ip_hdr->saddr, ip_hdr->daddr, UDP_PKT_SIZE,
783 IPPROTO_UDP, (u16 *)udp_hdr);
786 static void gen_eth_frame(struct xsk_umem_info *umem, u64 addr)
788 memcpy(xsk_umem__get_data(umem->buffer, addr), pkt_data,
792 static struct xsk_umem_info *xsk_configure_umem(void *buffer, u64 size)
794 struct xsk_umem_info *umem;
795 struct xsk_umem_config cfg = {
796 /* We recommend that you set the fill ring size >= HW RX ring size +
797 * AF_XDP RX ring size. Make sure you fill up the fill ring
798 * with buffers at regular intervals, and you will with this setting
799 * avoid allocation failures in the driver. These are usually quite
800 * expensive since drivers have not been written to assume that
801 * allocation failures are common. For regular sockets, kernel
802 * allocated memory is used that only runs out in OOM situations
803 * that should be rare.
805 .fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS * 2,
806 .comp_size = XSK_RING_CONS__DEFAULT_NUM_DESCS,
807 .frame_size = opt_xsk_frame_size,
808 .frame_headroom = XSK_UMEM__DEFAULT_FRAME_HEADROOM,
809 .flags = opt_umem_flags
813 umem = calloc(1, sizeof(*umem));
815 exit_with_error(errno);
817 ret = xsk_umem__create(&umem->umem, buffer, size, &umem->fq, &umem->cq,
820 exit_with_error(-ret);
822 umem->buffer = buffer;
826 static void xsk_populate_fill_ring(struct xsk_umem_info *umem)
831 ret = xsk_ring_prod__reserve(&umem->fq,
832 XSK_RING_PROD__DEFAULT_NUM_DESCS * 2, &idx);
833 if (ret != XSK_RING_PROD__DEFAULT_NUM_DESCS * 2)
834 exit_with_error(-ret);
835 for (i = 0; i < XSK_RING_PROD__DEFAULT_NUM_DESCS * 2; i++)
836 *xsk_ring_prod__fill_addr(&umem->fq, idx++) =
837 i * opt_xsk_frame_size;
838 xsk_ring_prod__submit(&umem->fq, XSK_RING_PROD__DEFAULT_NUM_DESCS * 2);
841 static struct xsk_socket_info *xsk_configure_socket(struct xsk_umem_info *umem,
844 struct xsk_socket_config cfg;
845 struct xsk_socket_info *xsk;
846 struct xsk_ring_cons *rxr;
847 struct xsk_ring_prod *txr;
850 xsk = calloc(1, sizeof(*xsk));
852 exit_with_error(errno);
855 cfg.rx_size = XSK_RING_CONS__DEFAULT_NUM_DESCS;
856 cfg.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
857 if (opt_num_xsks > 1)
858 cfg.libbpf_flags = XSK_LIBBPF_FLAGS__INHIBIT_PROG_LOAD;
860 cfg.libbpf_flags = 0;
861 cfg.xdp_flags = opt_xdp_flags;
862 cfg.bind_flags = opt_xdp_bind_flags;
864 rxr = rx ? &xsk->rx : NULL;
865 txr = tx ? &xsk->tx : NULL;
866 ret = xsk_socket__create(&xsk->xsk, opt_if, opt_queue, umem->umem,
869 exit_with_error(-ret);
871 ret = bpf_get_link_xdp_id(opt_ifindex, &prog_id, opt_xdp_flags);
873 exit_with_error(-ret);
875 xsk->app_stats.rx_empty_polls = 0;
876 xsk->app_stats.fill_fail_polls = 0;
877 xsk->app_stats.copy_tx_sendtos = 0;
878 xsk->app_stats.tx_wakeup_sendtos = 0;
879 xsk->app_stats.opt_polls = 0;
880 xsk->app_stats.prev_rx_empty_polls = 0;
881 xsk->app_stats.prev_fill_fail_polls = 0;
882 xsk->app_stats.prev_copy_tx_sendtos = 0;
883 xsk->app_stats.prev_tx_wakeup_sendtos = 0;
884 xsk->app_stats.prev_opt_polls = 0;
889 static struct option long_options[] = {
890 {"rxdrop", no_argument, 0, 'r'},
891 {"txonly", no_argument, 0, 't'},
892 {"l2fwd", no_argument, 0, 'l'},
893 {"interface", required_argument, 0, 'i'},
894 {"queue", required_argument, 0, 'q'},
895 {"poll", no_argument, 0, 'p'},
896 {"xdp-skb", no_argument, 0, 'S'},
897 {"xdp-native", no_argument, 0, 'N'},
898 {"interval", required_argument, 0, 'n'},
899 {"zero-copy", no_argument, 0, 'z'},
900 {"copy", no_argument, 0, 'c'},
901 {"frame-size", required_argument, 0, 'f'},
902 {"no-need-wakeup", no_argument, 0, 'm'},
903 {"unaligned", no_argument, 0, 'u'},
904 {"shared-umem", no_argument, 0, 'M'},
905 {"force", no_argument, 0, 'F'},
906 {"duration", required_argument, 0, 'd'},
907 {"batch-size", required_argument, 0, 'b'},
908 {"tx-pkt-count", required_argument, 0, 'C'},
909 {"tx-pkt-size", required_argument, 0, 's'},
910 {"tx-pkt-pattern", required_argument, 0, 'P'},
911 {"extra-stats", no_argument, 0, 'x'},
912 {"quiet", no_argument, 0, 'Q'},
913 {"app-stats", no_argument, 0, 'a'},
914 {"irq-string", no_argument, 0, 'I'},
915 {"busy-poll", no_argument, 0, 'B'},
919 static void usage(const char *prog)
922 " Usage: %s [OPTIONS]\n"
924 " -r, --rxdrop Discard all incoming packets (default)\n"
925 " -t, --txonly Only send packets\n"
926 " -l, --l2fwd MAC swap L2 forwarding\n"
927 " -i, --interface=n Run on interface n\n"
928 " -q, --queue=n Use queue n (default 0)\n"
929 " -p, --poll Use poll syscall\n"
930 " -S, --xdp-skb=n Use XDP skb-mod\n"
931 " -N, --xdp-native=n Enforce XDP native mode\n"
932 " -n, --interval=n Specify statistics update interval (default 1 sec).\n"
933 " -z, --zero-copy Force zero-copy mode.\n"
934 " -c, --copy Force copy mode.\n"
935 " -m, --no-need-wakeup Turn off use of driver need wakeup flag.\n"
936 " -f, --frame-size=n Set the frame size (must be a power of two in aligned mode, default is %d).\n"
937 " -u, --unaligned Enable unaligned chunk placement\n"
938 " -M, --shared-umem Enable XDP_SHARED_UMEM\n"
939 " -F, --force Force loading the XDP prog\n"
940 " -d, --duration=n Duration in secs to run command.\n"
941 " Default: forever.\n"
942 " -b, --batch-size=n Batch size for sending or receiving\n"
943 " packets. Default: %d\n"
944 " -C, --tx-pkt-count=n Number of packets to send.\n"
945 " Default: Continuous packets.\n"
946 " -s, --tx-pkt-size=n Transmit packet size.\n"
947 " (Default: %d bytes)\n"
948 " Min size: %d, Max size %d.\n"
949 " -P, --tx-pkt-pattern=nPacket fill pattern. Default: 0x%x\n"
950 " -x, --extra-stats Display extra statistics.\n"
951 " -Q, --quiet Do not display any stats.\n"
952 " -a, --app-stats Display application (syscall) statistics.\n"
953 " -I, --irq-string Display driver interrupt statistics for interface associated with irq-string.\n"
954 " -B, --busy-poll Busy poll.\n"
956 fprintf(stderr, str, prog, XSK_UMEM__DEFAULT_FRAME_SIZE,
957 opt_batch_size, MIN_PKT_SIZE, MIN_PKT_SIZE,
958 XSK_UMEM__DEFAULT_FRAME_SIZE, opt_pkt_fill_pattern);
963 static void parse_command_line(int argc, char **argv)
970 c = getopt_long(argc, argv, "Frtli:q:pSNn:czf:muMd:b:C:s:P:xQaI:B",
971 long_options, &option_index);
977 opt_bench = BENCH_RXDROP;
980 opt_bench = BENCH_TXONLY;
983 opt_bench = BENCH_L2FWD;
989 opt_queue = atoi(optarg);
995 opt_xdp_flags |= XDP_FLAGS_SKB_MODE;
996 opt_xdp_bind_flags |= XDP_COPY;
999 /* default, set below */
1002 opt_interval = atoi(optarg);
1005 opt_xdp_bind_flags |= XDP_ZEROCOPY;
1008 opt_xdp_bind_flags |= XDP_COPY;
1011 opt_umem_flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
1012 opt_unaligned_chunks = 1;
1013 opt_mmap_flags = MAP_HUGETLB;
1016 opt_xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
1019 opt_xsk_frame_size = atoi(optarg);
1022 opt_need_wakeup = false;
1023 opt_xdp_bind_flags &= ~XDP_USE_NEED_WAKEUP;
1026 opt_num_xsks = MAX_SOCKS;
1029 opt_duration = atoi(optarg);
1030 opt_duration *= 1000000000;
1033 opt_batch_size = atoi(optarg);
1036 opt_pkt_count = atoi(optarg);
1039 opt_pkt_size = atoi(optarg);
1040 if (opt_pkt_size > (XSK_UMEM__DEFAULT_FRAME_SIZE) ||
1041 opt_pkt_size < MIN_PKT_SIZE) {
1043 "ERROR: Invalid frame size %d\n",
1045 usage(basename(argv[0]));
1049 opt_pkt_fill_pattern = strtol(optarg, NULL, 16);
1052 opt_extra_stats = 1;
1061 opt_irq_str = optarg;
1062 if (get_interrupt_number())
1063 irqs_at_init = get_irqs();
1064 if (irqs_at_init < 0) {
1065 fprintf(stderr, "ERROR: Failed to get irqs for %s\n", opt_irq_str);
1066 usage(basename(argv[0]));
1073 usage(basename(argv[0]));
1077 if (!(opt_xdp_flags & XDP_FLAGS_SKB_MODE))
1078 opt_xdp_flags |= XDP_FLAGS_DRV_MODE;
1080 opt_ifindex = if_nametoindex(opt_if);
1082 fprintf(stderr, "ERROR: interface \"%s\" does not exist\n",
1084 usage(basename(argv[0]));
1087 if ((opt_xsk_frame_size & (opt_xsk_frame_size - 1)) &&
1088 !opt_unaligned_chunks) {
1089 fprintf(stderr, "--frame-size=%d is not a power of two\n",
1090 opt_xsk_frame_size);
1091 usage(basename(argv[0]));
1095 static void kick_tx(struct xsk_socket_info *xsk)
1099 ret = sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
1100 if (ret >= 0 || errno == ENOBUFS || errno == EAGAIN ||
1101 errno == EBUSY || errno == ENETDOWN)
1103 exit_with_error(errno);
1106 static inline void complete_tx_l2fwd(struct xsk_socket_info *xsk)
1108 struct xsk_umem_info *umem = xsk->umem;
1109 u32 idx_cq = 0, idx_fq = 0;
1113 if (!xsk->outstanding_tx)
1116 /* In copy mode, Tx is driven by a syscall so we need to use e.g. sendto() to
1117 * really send the packets. In zero-copy mode we do not have to do this, since Tx
1118 * is driven by the NAPI loop. So as an optimization, we do not have to call
1119 * sendto() all the time in zero-copy mode for l2fwd.
1121 if (opt_xdp_bind_flags & XDP_COPY) {
1122 xsk->app_stats.copy_tx_sendtos++;
1126 ndescs = (xsk->outstanding_tx > opt_batch_size) ? opt_batch_size :
1127 xsk->outstanding_tx;
1129 /* re-add completed Tx buffers */
1130 rcvd = xsk_ring_cons__peek(&umem->cq, ndescs, &idx_cq);
1135 ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
1136 while (ret != rcvd) {
1138 exit_with_error(-ret);
1139 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&umem->fq)) {
1140 xsk->app_stats.fill_fail_polls++;
1141 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL,
1144 ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
1147 for (i = 0; i < rcvd; i++)
1148 *xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) =
1149 *xsk_ring_cons__comp_addr(&umem->cq, idx_cq++);
1151 xsk_ring_prod__submit(&xsk->umem->fq, rcvd);
1152 xsk_ring_cons__release(&xsk->umem->cq, rcvd);
1153 xsk->outstanding_tx -= rcvd;
1157 static inline void complete_tx_only(struct xsk_socket_info *xsk,
1163 if (!xsk->outstanding_tx)
1166 if (!opt_need_wakeup || xsk_ring_prod__needs_wakeup(&xsk->tx)) {
1167 xsk->app_stats.tx_wakeup_sendtos++;
1171 rcvd = xsk_ring_cons__peek(&xsk->umem->cq, batch_size, &idx);
1173 xsk_ring_cons__release(&xsk->umem->cq, rcvd);
1174 xsk->outstanding_tx -= rcvd;
1178 static void rx_drop(struct xsk_socket_info *xsk)
1180 unsigned int rcvd, i;
1181 u32 idx_rx = 0, idx_fq = 0;
1184 rcvd = xsk_ring_cons__peek(&xsk->rx, opt_batch_size, &idx_rx);
1186 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->umem->fq)) {
1187 xsk->app_stats.rx_empty_polls++;
1188 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1193 ret = xsk_ring_prod__reserve(&xsk->umem->fq, rcvd, &idx_fq);
1194 while (ret != rcvd) {
1196 exit_with_error(-ret);
1197 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->umem->fq)) {
1198 xsk->app_stats.fill_fail_polls++;
1199 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1201 ret = xsk_ring_prod__reserve(&xsk->umem->fq, rcvd, &idx_fq);
1204 for (i = 0; i < rcvd; i++) {
1205 u64 addr = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx)->addr;
1206 u32 len = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++)->len;
1207 u64 orig = xsk_umem__extract_addr(addr);
1209 addr = xsk_umem__add_offset_to_addr(addr);
1210 char *pkt = xsk_umem__get_data(xsk->umem->buffer, addr);
1212 hex_dump(pkt, len, addr);
1213 *xsk_ring_prod__fill_addr(&xsk->umem->fq, idx_fq++) = orig;
1216 xsk_ring_prod__submit(&xsk->umem->fq, rcvd);
1217 xsk_ring_cons__release(&xsk->rx, rcvd);
1218 xsk->ring_stats.rx_npkts += rcvd;
1221 static void rx_drop_all(void)
1223 struct pollfd fds[MAX_SOCKS] = {};
1226 for (i = 0; i < num_socks; i++) {
1227 fds[i].fd = xsk_socket__fd(xsks[i]->xsk);
1228 fds[i].events = POLLIN;
1233 for (i = 0; i < num_socks; i++)
1234 xsks[i]->app_stats.opt_polls++;
1235 ret = poll(fds, num_socks, opt_timeout);
1240 for (i = 0; i < num_socks; i++)
1248 static void tx_only(struct xsk_socket_info *xsk, u32 *frame_nb, int batch_size)
1253 while (xsk_ring_prod__reserve(&xsk->tx, batch_size, &idx) <
1255 complete_tx_only(xsk, batch_size);
1258 for (i = 0; i < batch_size; i++) {
1259 struct xdp_desc *tx_desc = xsk_ring_prod__tx_desc(&xsk->tx,
1261 tx_desc->addr = (*frame_nb + i) << XSK_UMEM__DEFAULT_FRAME_SHIFT;
1262 tx_desc->len = PKT_SIZE;
1265 xsk_ring_prod__submit(&xsk->tx, batch_size);
1266 xsk->ring_stats.tx_npkts += batch_size;
1267 xsk->outstanding_tx += batch_size;
1268 *frame_nb += batch_size;
1269 *frame_nb %= NUM_FRAMES;
1270 complete_tx_only(xsk, batch_size);
1273 static inline int get_batch_size(int pkt_cnt)
1276 return opt_batch_size;
1278 if (pkt_cnt + opt_batch_size <= opt_pkt_count)
1279 return opt_batch_size;
1281 return opt_pkt_count - pkt_cnt;
1284 static void complete_tx_only_all(void)
1291 for (i = 0; i < num_socks; i++) {
1292 if (xsks[i]->outstanding_tx) {
1293 complete_tx_only(xsks[i], opt_batch_size);
1294 pending = !!xsks[i]->outstanding_tx;
1300 static void tx_only_all(void)
1302 struct pollfd fds[MAX_SOCKS] = {};
1303 u32 frame_nb[MAX_SOCKS] = {};
1307 for (i = 0; i < num_socks; i++) {
1308 fds[0].fd = xsk_socket__fd(xsks[i]->xsk);
1309 fds[0].events = POLLOUT;
1312 while ((opt_pkt_count && pkt_cnt < opt_pkt_count) || !opt_pkt_count) {
1313 int batch_size = get_batch_size(pkt_cnt);
1316 for (i = 0; i < num_socks; i++)
1317 xsks[i]->app_stats.opt_polls++;
1318 ret = poll(fds, num_socks, opt_timeout);
1322 if (!(fds[0].revents & POLLOUT))
1326 for (i = 0; i < num_socks; i++)
1327 tx_only(xsks[i], &frame_nb[i], batch_size);
1329 pkt_cnt += batch_size;
1336 complete_tx_only_all();
1339 static void l2fwd(struct xsk_socket_info *xsk)
1341 unsigned int rcvd, i;
1342 u32 idx_rx = 0, idx_tx = 0;
1345 complete_tx_l2fwd(xsk);
1347 rcvd = xsk_ring_cons__peek(&xsk->rx, opt_batch_size, &idx_rx);
1349 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->umem->fq)) {
1350 xsk->app_stats.rx_empty_polls++;
1351 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1355 xsk->ring_stats.rx_npkts += rcvd;
1357 ret = xsk_ring_prod__reserve(&xsk->tx, rcvd, &idx_tx);
1358 while (ret != rcvd) {
1360 exit_with_error(-ret);
1361 complete_tx_l2fwd(xsk);
1362 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->tx)) {
1363 xsk->app_stats.tx_wakeup_sendtos++;
1366 ret = xsk_ring_prod__reserve(&xsk->tx, rcvd, &idx_tx);
1369 for (i = 0; i < rcvd; i++) {
1370 u64 addr = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx)->addr;
1371 u32 len = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++)->len;
1374 addr = xsk_umem__add_offset_to_addr(addr);
1375 char *pkt = xsk_umem__get_data(xsk->umem->buffer, addr);
1377 swap_mac_addresses(pkt);
1379 hex_dump(pkt, len, addr);
1380 xsk_ring_prod__tx_desc(&xsk->tx, idx_tx)->addr = orig;
1381 xsk_ring_prod__tx_desc(&xsk->tx, idx_tx++)->len = len;
1384 xsk_ring_prod__submit(&xsk->tx, rcvd);
1385 xsk_ring_cons__release(&xsk->rx, rcvd);
1387 xsk->ring_stats.tx_npkts += rcvd;
1388 xsk->outstanding_tx += rcvd;
1391 static void l2fwd_all(void)
1393 struct pollfd fds[MAX_SOCKS] = {};
1398 for (i = 0; i < num_socks; i++) {
1399 fds[i].fd = xsk_socket__fd(xsks[i]->xsk);
1400 fds[i].events = POLLOUT | POLLIN;
1401 xsks[i]->app_stats.opt_polls++;
1403 ret = poll(fds, num_socks, opt_timeout);
1408 for (i = 0; i < num_socks; i++)
1416 static void load_xdp_program(char **argv, struct bpf_object **obj)
1418 struct bpf_prog_load_attr prog_load_attr = {
1419 .prog_type = BPF_PROG_TYPE_XDP,
1421 char xdp_filename[256];
1424 snprintf(xdp_filename, sizeof(xdp_filename), "%s_kern.o", argv[0]);
1425 prog_load_attr.file = xdp_filename;
1427 if (bpf_prog_load_xattr(&prog_load_attr, obj, &prog_fd))
1430 fprintf(stderr, "ERROR: no program found: %s\n",
1435 if (bpf_set_link_xdp_fd(opt_ifindex, prog_fd, opt_xdp_flags) < 0) {
1436 fprintf(stderr, "ERROR: link set xdp fd failed\n");
1441 static void enter_xsks_into_map(struct bpf_object *obj)
1443 struct bpf_map *map;
1446 map = bpf_object__find_map_by_name(obj, "xsks_map");
1447 xsks_map = bpf_map__fd(map);
1449 fprintf(stderr, "ERROR: no xsks map found: %s\n",
1450 strerror(xsks_map));
1454 for (i = 0; i < num_socks; i++) {
1455 int fd = xsk_socket__fd(xsks[i]->xsk);
1459 ret = bpf_map_update_elem(xsks_map, &key, &fd, 0);
1461 fprintf(stderr, "ERROR: bpf_map_update_elem %d\n", i);
1467 static void apply_setsockopt(struct xsk_socket_info *xsk)
1475 if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_PREFER_BUSY_POLL,
1476 (void *)&sock_opt, sizeof(sock_opt)) < 0)
1477 exit_with_error(errno);
1480 if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL,
1481 (void *)&sock_opt, sizeof(sock_opt)) < 0)
1482 exit_with_error(errno);
1484 sock_opt = opt_batch_size;
1485 if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL_BUDGET,
1486 (void *)&sock_opt, sizeof(sock_opt)) < 0)
1487 exit_with_error(errno);
1490 int main(int argc, char **argv)
1492 bool rx = false, tx = false;
1493 struct xsk_umem_info *umem;
1494 struct bpf_object *obj;
1499 parse_command_line(argc, argv);
1501 if (opt_num_xsks > 1)
1502 load_xdp_program(argv, &obj);
1504 /* Reserve memory for the umem. Use hugepages if unaligned chunk mode */
1505 bufs = mmap(NULL, NUM_FRAMES * opt_xsk_frame_size,
1506 PROT_READ | PROT_WRITE,
1507 MAP_PRIVATE | MAP_ANONYMOUS | opt_mmap_flags, -1, 0);
1508 if (bufs == MAP_FAILED) {
1509 printf("ERROR: mmap failed\n");
1513 /* Create sockets... */
1514 umem = xsk_configure_umem(bufs, NUM_FRAMES * opt_xsk_frame_size);
1515 if (opt_bench == BENCH_RXDROP || opt_bench == BENCH_L2FWD) {
1517 xsk_populate_fill_ring(umem);
1519 if (opt_bench == BENCH_L2FWD || opt_bench == BENCH_TXONLY)
1521 for (i = 0; i < opt_num_xsks; i++)
1522 xsks[num_socks++] = xsk_configure_socket(umem, rx, tx);
1524 for (i = 0; i < opt_num_xsks; i++)
1525 apply_setsockopt(xsks[i]);
1527 if (opt_bench == BENCH_TXONLY) {
1530 for (i = 0; i < NUM_FRAMES; i++)
1531 gen_eth_frame(umem, i * opt_xsk_frame_size);
1534 if (opt_num_xsks > 1 && opt_bench != BENCH_TXONLY)
1535 enter_xsks_into_map(obj);
1537 signal(SIGINT, int_exit);
1538 signal(SIGTERM, int_exit);
1539 signal(SIGABRT, int_exit);
1541 setlocale(LC_ALL, "");
1544 ret = pthread_create(&pt, NULL, poller, NULL);
1546 exit_with_error(ret);
1549 prev_time = get_nsecs();
1550 start_time = prev_time;
1552 if (opt_bench == BENCH_RXDROP)
1554 else if (opt_bench == BENCH_TXONLY)
1559 benchmark_done = true;
1562 pthread_join(pt, NULL);