Loading...
Note: File does not exist in v6.8.
1// SPDX-License-Identifier: GPL-2.0
2/* Copyright(c) 2017 - 2018 Intel Corporation. */
3
4#include <asm/barrier.h>
5#include <errno.h>
6#include <getopt.h>
7#include <libgen.h>
8#include <linux/bpf.h>
9#include <linux/compiler.h>
10#include <linux/if_link.h>
11#include <linux/if_xdp.h>
12#include <linux/if_ether.h>
13#include <linux/ip.h>
14#include <linux/limits.h>
15#include <linux/udp.h>
16#include <arpa/inet.h>
17#include <locale.h>
18#include <net/ethernet.h>
19#include <net/if.h>
20#include <poll.h>
21#include <pthread.h>
22#include <signal.h>
23#include <stdbool.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/capability.h>
28#include <sys/mman.h>
29#include <sys/resource.h>
30#include <sys/socket.h>
31#include <sys/types.h>
32#include <sys/un.h>
33#include <time.h>
34#include <unistd.h>
35
36#include <bpf/libbpf.h>
37#include <bpf/xsk.h>
38#include <bpf/bpf.h>
39#include "xdpsock.h"
40
41#ifndef SOL_XDP
42#define SOL_XDP 283
43#endif
44
45#ifndef AF_XDP
46#define AF_XDP 44
47#endif
48
49#ifndef PF_XDP
50#define PF_XDP AF_XDP
51#endif
52
53#define NUM_FRAMES (4 * 1024)
54#define MIN_PKT_SIZE 64
55
56#define DEBUG_HEXDUMP 0
57
58typedef __u64 u64;
59typedef __u32 u32;
60typedef __u16 u16;
61typedef __u8 u8;
62
63static unsigned long prev_time;
64
65enum benchmark_type {
66 BENCH_RXDROP = 0,
67 BENCH_TXONLY = 1,
68 BENCH_L2FWD = 2,
69};
70
71static enum benchmark_type opt_bench = BENCH_RXDROP;
72static u32 opt_xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
73static const char *opt_if = "";
74static int opt_ifindex;
75static int opt_queue;
76static unsigned long opt_duration;
77static unsigned long start_time;
78static bool benchmark_done;
79static u32 opt_batch_size = 64;
80static int opt_pkt_count;
81static u16 opt_pkt_size = MIN_PKT_SIZE;
82static u32 opt_pkt_fill_pattern = 0x12345678;
83static bool opt_extra_stats;
84static bool opt_quiet;
85static bool opt_app_stats;
86static const char *opt_irq_str = "";
87static u32 irq_no;
88static int irqs_at_init = -1;
89static int opt_poll;
90static int opt_interval = 1;
91static u32 opt_xdp_bind_flags = XDP_USE_NEED_WAKEUP;
92static u32 opt_umem_flags;
93static int opt_unaligned_chunks;
94static int opt_mmap_flags;
95static int opt_xsk_frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
96static int opt_timeout = 1000;
97static bool opt_need_wakeup = true;
98static u32 opt_num_xsks = 1;
99static u32 prog_id;
100static bool opt_busy_poll;
101static bool opt_reduced_cap;
102
103struct xsk_ring_stats {
104 unsigned long rx_npkts;
105 unsigned long tx_npkts;
106 unsigned long rx_dropped_npkts;
107 unsigned long rx_invalid_npkts;
108 unsigned long tx_invalid_npkts;
109 unsigned long rx_full_npkts;
110 unsigned long rx_fill_empty_npkts;
111 unsigned long tx_empty_npkts;
112 unsigned long prev_rx_npkts;
113 unsigned long prev_tx_npkts;
114 unsigned long prev_rx_dropped_npkts;
115 unsigned long prev_rx_invalid_npkts;
116 unsigned long prev_tx_invalid_npkts;
117 unsigned long prev_rx_full_npkts;
118 unsigned long prev_rx_fill_empty_npkts;
119 unsigned long prev_tx_empty_npkts;
120};
121
122struct xsk_driver_stats {
123 unsigned long intrs;
124 unsigned long prev_intrs;
125};
126
127struct xsk_app_stats {
128 unsigned long rx_empty_polls;
129 unsigned long fill_fail_polls;
130 unsigned long copy_tx_sendtos;
131 unsigned long tx_wakeup_sendtos;
132 unsigned long opt_polls;
133 unsigned long prev_rx_empty_polls;
134 unsigned long prev_fill_fail_polls;
135 unsigned long prev_copy_tx_sendtos;
136 unsigned long prev_tx_wakeup_sendtos;
137 unsigned long prev_opt_polls;
138};
139
140struct xsk_umem_info {
141 struct xsk_ring_prod fq;
142 struct xsk_ring_cons cq;
143 struct xsk_umem *umem;
144 void *buffer;
145};
146
147struct xsk_socket_info {
148 struct xsk_ring_cons rx;
149 struct xsk_ring_prod tx;
150 struct xsk_umem_info *umem;
151 struct xsk_socket *xsk;
152 struct xsk_ring_stats ring_stats;
153 struct xsk_app_stats app_stats;
154 struct xsk_driver_stats drv_stats;
155 u32 outstanding_tx;
156};
157
158static int num_socks;
159struct xsk_socket_info *xsks[MAX_SOCKS];
160int sock;
161
162static unsigned long get_nsecs(void)
163{
164 struct timespec ts;
165
166 clock_gettime(CLOCK_MONOTONIC, &ts);
167 return ts.tv_sec * 1000000000UL + ts.tv_nsec;
168}
169
170static void print_benchmark(bool running)
171{
172 const char *bench_str = "INVALID";
173
174 if (opt_bench == BENCH_RXDROP)
175 bench_str = "rxdrop";
176 else if (opt_bench == BENCH_TXONLY)
177 bench_str = "txonly";
178 else if (opt_bench == BENCH_L2FWD)
179 bench_str = "l2fwd";
180
181 printf("%s:%d %s ", opt_if, opt_queue, bench_str);
182 if (opt_xdp_flags & XDP_FLAGS_SKB_MODE)
183 printf("xdp-skb ");
184 else if (opt_xdp_flags & XDP_FLAGS_DRV_MODE)
185 printf("xdp-drv ");
186 else
187 printf(" ");
188
189 if (opt_poll)
190 printf("poll() ");
191
192 if (running) {
193 printf("running...");
194 fflush(stdout);
195 }
196}
197
198static int xsk_get_xdp_stats(int fd, struct xsk_socket_info *xsk)
199{
200 struct xdp_statistics stats;
201 socklen_t optlen;
202 int err;
203
204 optlen = sizeof(stats);
205 err = getsockopt(fd, SOL_XDP, XDP_STATISTICS, &stats, &optlen);
206 if (err)
207 return err;
208
209 if (optlen == sizeof(struct xdp_statistics)) {
210 xsk->ring_stats.rx_dropped_npkts = stats.rx_dropped;
211 xsk->ring_stats.rx_invalid_npkts = stats.rx_invalid_descs;
212 xsk->ring_stats.tx_invalid_npkts = stats.tx_invalid_descs;
213 xsk->ring_stats.rx_full_npkts = stats.rx_ring_full;
214 xsk->ring_stats.rx_fill_empty_npkts = stats.rx_fill_ring_empty_descs;
215 xsk->ring_stats.tx_empty_npkts = stats.tx_ring_empty_descs;
216 return 0;
217 }
218
219 return -EINVAL;
220}
221
222static void dump_app_stats(long dt)
223{
224 int i;
225
226 for (i = 0; i < num_socks && xsks[i]; i++) {
227 char *fmt = "%-18s %'-14.0f %'-14lu\n";
228 double rx_empty_polls_ps, fill_fail_polls_ps, copy_tx_sendtos_ps,
229 tx_wakeup_sendtos_ps, opt_polls_ps;
230
231 rx_empty_polls_ps = (xsks[i]->app_stats.rx_empty_polls -
232 xsks[i]->app_stats.prev_rx_empty_polls) * 1000000000. / dt;
233 fill_fail_polls_ps = (xsks[i]->app_stats.fill_fail_polls -
234 xsks[i]->app_stats.prev_fill_fail_polls) * 1000000000. / dt;
235 copy_tx_sendtos_ps = (xsks[i]->app_stats.copy_tx_sendtos -
236 xsks[i]->app_stats.prev_copy_tx_sendtos) * 1000000000. / dt;
237 tx_wakeup_sendtos_ps = (xsks[i]->app_stats.tx_wakeup_sendtos -
238 xsks[i]->app_stats.prev_tx_wakeup_sendtos)
239 * 1000000000. / dt;
240 opt_polls_ps = (xsks[i]->app_stats.opt_polls -
241 xsks[i]->app_stats.prev_opt_polls) * 1000000000. / dt;
242
243 printf("\n%-18s %-14s %-14s\n", "", "calls/s", "count");
244 printf(fmt, "rx empty polls", rx_empty_polls_ps, xsks[i]->app_stats.rx_empty_polls);
245 printf(fmt, "fill fail polls", fill_fail_polls_ps,
246 xsks[i]->app_stats.fill_fail_polls);
247 printf(fmt, "copy tx sendtos", copy_tx_sendtos_ps,
248 xsks[i]->app_stats.copy_tx_sendtos);
249 printf(fmt, "tx wakeup sendtos", tx_wakeup_sendtos_ps,
250 xsks[i]->app_stats.tx_wakeup_sendtos);
251 printf(fmt, "opt polls", opt_polls_ps, xsks[i]->app_stats.opt_polls);
252
253 xsks[i]->app_stats.prev_rx_empty_polls = xsks[i]->app_stats.rx_empty_polls;
254 xsks[i]->app_stats.prev_fill_fail_polls = xsks[i]->app_stats.fill_fail_polls;
255 xsks[i]->app_stats.prev_copy_tx_sendtos = xsks[i]->app_stats.copy_tx_sendtos;
256 xsks[i]->app_stats.prev_tx_wakeup_sendtos = xsks[i]->app_stats.tx_wakeup_sendtos;
257 xsks[i]->app_stats.prev_opt_polls = xsks[i]->app_stats.opt_polls;
258 }
259}
260
261static bool get_interrupt_number(void)
262{
263 FILE *f_int_proc;
264 char line[4096];
265 bool found = false;
266
267 f_int_proc = fopen("/proc/interrupts", "r");
268 if (f_int_proc == NULL) {
269 printf("Failed to open /proc/interrupts.\n");
270 return found;
271 }
272
273 while (!feof(f_int_proc) && !found) {
274 /* Make sure to read a full line at a time */
275 if (fgets(line, sizeof(line), f_int_proc) == NULL ||
276 line[strlen(line) - 1] != '\n') {
277 printf("Error reading from interrupts file\n");
278 break;
279 }
280
281 /* Extract interrupt number from line */
282 if (strstr(line, opt_irq_str) != NULL) {
283 irq_no = atoi(line);
284 found = true;
285 break;
286 }
287 }
288
289 fclose(f_int_proc);
290
291 return found;
292}
293
294static int get_irqs(void)
295{
296 char count_path[PATH_MAX];
297 int total_intrs = -1;
298 FILE *f_count_proc;
299 char line[4096];
300
301 snprintf(count_path, sizeof(count_path),
302 "/sys/kernel/irq/%i/per_cpu_count", irq_no);
303 f_count_proc = fopen(count_path, "r");
304 if (f_count_proc == NULL) {
305 printf("Failed to open %s\n", count_path);
306 return total_intrs;
307 }
308
309 if (fgets(line, sizeof(line), f_count_proc) == NULL ||
310 line[strlen(line) - 1] != '\n') {
311 printf("Error reading from %s\n", count_path);
312 } else {
313 static const char com[2] = ",";
314 char *token;
315
316 total_intrs = 0;
317 token = strtok(line, com);
318 while (token != NULL) {
319 /* sum up interrupts across all cores */
320 total_intrs += atoi(token);
321 token = strtok(NULL, com);
322 }
323 }
324
325 fclose(f_count_proc);
326
327 return total_intrs;
328}
329
330static void dump_driver_stats(long dt)
331{
332 int i;
333
334 for (i = 0; i < num_socks && xsks[i]; i++) {
335 char *fmt = "%-18s %'-14.0f %'-14lu\n";
336 double intrs_ps;
337 int n_ints = get_irqs();
338
339 if (n_ints < 0) {
340 printf("error getting intr info for intr %i\n", irq_no);
341 return;
342 }
343 xsks[i]->drv_stats.intrs = n_ints - irqs_at_init;
344
345 intrs_ps = (xsks[i]->drv_stats.intrs - xsks[i]->drv_stats.prev_intrs) *
346 1000000000. / dt;
347
348 printf("\n%-18s %-14s %-14s\n", "", "intrs/s", "count");
349 printf(fmt, "irqs", intrs_ps, xsks[i]->drv_stats.intrs);
350
351 xsks[i]->drv_stats.prev_intrs = xsks[i]->drv_stats.intrs;
352 }
353}
354
355static void dump_stats(void)
356{
357 unsigned long now = get_nsecs();
358 long dt = now - prev_time;
359 int i;
360
361 prev_time = now;
362
363 for (i = 0; i < num_socks && xsks[i]; i++) {
364 char *fmt = "%-18s %'-14.0f %'-14lu\n";
365 double rx_pps, tx_pps, dropped_pps, rx_invalid_pps, full_pps, fill_empty_pps,
366 tx_invalid_pps, tx_empty_pps;
367
368 rx_pps = (xsks[i]->ring_stats.rx_npkts - xsks[i]->ring_stats.prev_rx_npkts) *
369 1000000000. / dt;
370 tx_pps = (xsks[i]->ring_stats.tx_npkts - xsks[i]->ring_stats.prev_tx_npkts) *
371 1000000000. / dt;
372
373 printf("\n sock%d@", i);
374 print_benchmark(false);
375 printf("\n");
376
377 printf("%-18s %-14s %-14s %-14.2f\n", "", "pps", "pkts",
378 dt / 1000000000.);
379 printf(fmt, "rx", rx_pps, xsks[i]->ring_stats.rx_npkts);
380 printf(fmt, "tx", tx_pps, xsks[i]->ring_stats.tx_npkts);
381
382 xsks[i]->ring_stats.prev_rx_npkts = xsks[i]->ring_stats.rx_npkts;
383 xsks[i]->ring_stats.prev_tx_npkts = xsks[i]->ring_stats.tx_npkts;
384
385 if (opt_extra_stats) {
386 if (!xsk_get_xdp_stats(xsk_socket__fd(xsks[i]->xsk), xsks[i])) {
387 dropped_pps = (xsks[i]->ring_stats.rx_dropped_npkts -
388 xsks[i]->ring_stats.prev_rx_dropped_npkts) *
389 1000000000. / dt;
390 rx_invalid_pps = (xsks[i]->ring_stats.rx_invalid_npkts -
391 xsks[i]->ring_stats.prev_rx_invalid_npkts) *
392 1000000000. / dt;
393 tx_invalid_pps = (xsks[i]->ring_stats.tx_invalid_npkts -
394 xsks[i]->ring_stats.prev_tx_invalid_npkts) *
395 1000000000. / dt;
396 full_pps = (xsks[i]->ring_stats.rx_full_npkts -
397 xsks[i]->ring_stats.prev_rx_full_npkts) *
398 1000000000. / dt;
399 fill_empty_pps = (xsks[i]->ring_stats.rx_fill_empty_npkts -
400 xsks[i]->ring_stats.prev_rx_fill_empty_npkts) *
401 1000000000. / dt;
402 tx_empty_pps = (xsks[i]->ring_stats.tx_empty_npkts -
403 xsks[i]->ring_stats.prev_tx_empty_npkts) *
404 1000000000. / dt;
405
406 printf(fmt, "rx dropped", dropped_pps,
407 xsks[i]->ring_stats.rx_dropped_npkts);
408 printf(fmt, "rx invalid", rx_invalid_pps,
409 xsks[i]->ring_stats.rx_invalid_npkts);
410 printf(fmt, "tx invalid", tx_invalid_pps,
411 xsks[i]->ring_stats.tx_invalid_npkts);
412 printf(fmt, "rx queue full", full_pps,
413 xsks[i]->ring_stats.rx_full_npkts);
414 printf(fmt, "fill ring empty", fill_empty_pps,
415 xsks[i]->ring_stats.rx_fill_empty_npkts);
416 printf(fmt, "tx ring empty", tx_empty_pps,
417 xsks[i]->ring_stats.tx_empty_npkts);
418
419 xsks[i]->ring_stats.prev_rx_dropped_npkts =
420 xsks[i]->ring_stats.rx_dropped_npkts;
421 xsks[i]->ring_stats.prev_rx_invalid_npkts =
422 xsks[i]->ring_stats.rx_invalid_npkts;
423 xsks[i]->ring_stats.prev_tx_invalid_npkts =
424 xsks[i]->ring_stats.tx_invalid_npkts;
425 xsks[i]->ring_stats.prev_rx_full_npkts =
426 xsks[i]->ring_stats.rx_full_npkts;
427 xsks[i]->ring_stats.prev_rx_fill_empty_npkts =
428 xsks[i]->ring_stats.rx_fill_empty_npkts;
429 xsks[i]->ring_stats.prev_tx_empty_npkts =
430 xsks[i]->ring_stats.tx_empty_npkts;
431 } else {
432 printf("%-15s\n", "Error retrieving extra stats");
433 }
434 }
435 }
436
437 if (opt_app_stats)
438 dump_app_stats(dt);
439 if (irq_no)
440 dump_driver_stats(dt);
441}
442
443static bool is_benchmark_done(void)
444{
445 if (opt_duration > 0) {
446 unsigned long dt = (get_nsecs() - start_time);
447
448 if (dt >= opt_duration)
449 benchmark_done = true;
450 }
451 return benchmark_done;
452}
453
454static void *poller(void *arg)
455{
456 (void)arg;
457 while (!is_benchmark_done()) {
458 sleep(opt_interval);
459 dump_stats();
460 }
461
462 return NULL;
463}
464
465static void remove_xdp_program(void)
466{
467 u32 curr_prog_id = 0;
468
469 if (bpf_get_link_xdp_id(opt_ifindex, &curr_prog_id, opt_xdp_flags)) {
470 printf("bpf_get_link_xdp_id failed\n");
471 exit(EXIT_FAILURE);
472 }
473
474 if (prog_id == curr_prog_id)
475 bpf_set_link_xdp_fd(opt_ifindex, -1, opt_xdp_flags);
476 else if (!curr_prog_id)
477 printf("couldn't find a prog id on a given interface\n");
478 else
479 printf("program on interface changed, not removing\n");
480}
481
482static void int_exit(int sig)
483{
484 benchmark_done = true;
485}
486
487static void __exit_with_error(int error, const char *file, const char *func,
488 int line)
489{
490 fprintf(stderr, "%s:%s:%i: errno: %d/\"%s\"\n", file, func,
491 line, error, strerror(error));
492
493 if (opt_num_xsks > 1)
494 remove_xdp_program();
495 exit(EXIT_FAILURE);
496}
497
498#define exit_with_error(error) __exit_with_error(error, __FILE__, __func__, __LINE__)
499
500static void xdpsock_cleanup(void)
501{
502 struct xsk_umem *umem = xsks[0]->umem->umem;
503 int i, cmd = CLOSE_CONN;
504
505 dump_stats();
506 for (i = 0; i < num_socks; i++)
507 xsk_socket__delete(xsks[i]->xsk);
508 (void)xsk_umem__delete(umem);
509
510 if (opt_reduced_cap) {
511 if (write(sock, &cmd, sizeof(int)) < 0)
512 exit_with_error(errno);
513 }
514
515 if (opt_num_xsks > 1)
516 remove_xdp_program();
517}
518
519static void swap_mac_addresses(void *data)
520{
521 struct ether_header *eth = (struct ether_header *)data;
522 struct ether_addr *src_addr = (struct ether_addr *)ð->ether_shost;
523 struct ether_addr *dst_addr = (struct ether_addr *)ð->ether_dhost;
524 struct ether_addr tmp;
525
526 tmp = *src_addr;
527 *src_addr = *dst_addr;
528 *dst_addr = tmp;
529}
530
531static void hex_dump(void *pkt, size_t length, u64 addr)
532{
533 const unsigned char *address = (unsigned char *)pkt;
534 const unsigned char *line = address;
535 size_t line_size = 32;
536 unsigned char c;
537 char buf[32];
538 int i = 0;
539
540 if (!DEBUG_HEXDUMP)
541 return;
542
543 sprintf(buf, "addr=%llu", addr);
544 printf("length = %zu\n", length);
545 printf("%s | ", buf);
546 while (length-- > 0) {
547 printf("%02X ", *address++);
548 if (!(++i % line_size) || (length == 0 && i % line_size)) {
549 if (length == 0) {
550 while (i++ % line_size)
551 printf("__ ");
552 }
553 printf(" | "); /* right close */
554 while (line < address) {
555 c = *line++;
556 printf("%c", (c < 33 || c == 255) ? 0x2E : c);
557 }
558 printf("\n");
559 if (length > 0)
560 printf("%s | ", buf);
561 }
562 }
563 printf("\n");
564}
565
566static void *memset32_htonl(void *dest, u32 val, u32 size)
567{
568 u32 *ptr = (u32 *)dest;
569 int i;
570
571 val = htonl(val);
572
573 for (i = 0; i < (size & (~0x3)); i += 4)
574 ptr[i >> 2] = val;
575
576 for (; i < size; i++)
577 ((char *)dest)[i] = ((char *)&val)[i & 3];
578
579 return dest;
580}
581
582/*
583 * This function code has been taken from
584 * Linux kernel lib/checksum.c
585 */
586static inline unsigned short from32to16(unsigned int x)
587{
588 /* add up 16-bit and 16-bit for 16+c bit */
589 x = (x & 0xffff) + (x >> 16);
590 /* add up carry.. */
591 x = (x & 0xffff) + (x >> 16);
592 return x;
593}
594
595/*
596 * This function code has been taken from
597 * Linux kernel lib/checksum.c
598 */
599static unsigned int do_csum(const unsigned char *buff, int len)
600{
601 unsigned int result = 0;
602 int odd;
603
604 if (len <= 0)
605 goto out;
606 odd = 1 & (unsigned long)buff;
607 if (odd) {
608#ifdef __LITTLE_ENDIAN
609 result += (*buff << 8);
610#else
611 result = *buff;
612#endif
613 len--;
614 buff++;
615 }
616 if (len >= 2) {
617 if (2 & (unsigned long)buff) {
618 result += *(unsigned short *)buff;
619 len -= 2;
620 buff += 2;
621 }
622 if (len >= 4) {
623 const unsigned char *end = buff +
624 ((unsigned int)len & ~3);
625 unsigned int carry = 0;
626
627 do {
628 unsigned int w = *(unsigned int *)buff;
629
630 buff += 4;
631 result += carry;
632 result += w;
633 carry = (w > result);
634 } while (buff < end);
635 result += carry;
636 result = (result & 0xffff) + (result >> 16);
637 }
638 if (len & 2) {
639 result += *(unsigned short *)buff;
640 buff += 2;
641 }
642 }
643 if (len & 1)
644#ifdef __LITTLE_ENDIAN
645 result += *buff;
646#else
647 result += (*buff << 8);
648#endif
649 result = from32to16(result);
650 if (odd)
651 result = ((result >> 8) & 0xff) | ((result & 0xff) << 8);
652out:
653 return result;
654}
655
656__sum16 ip_fast_csum(const void *iph, unsigned int ihl);
657
658/*
659 * This is a version of ip_compute_csum() optimized for IP headers,
660 * which always checksum on 4 octet boundaries.
661 * This function code has been taken from
662 * Linux kernel lib/checksum.c
663 */
664__sum16 ip_fast_csum(const void *iph, unsigned int ihl)
665{
666 return (__force __sum16)~do_csum(iph, ihl * 4);
667}
668
669/*
670 * Fold a partial checksum
671 * This function code has been taken from
672 * Linux kernel include/asm-generic/checksum.h
673 */
674static inline __sum16 csum_fold(__wsum csum)
675{
676 u32 sum = (__force u32)csum;
677
678 sum = (sum & 0xffff) + (sum >> 16);
679 sum = (sum & 0xffff) + (sum >> 16);
680 return (__force __sum16)~sum;
681}
682
683/*
684 * This function code has been taken from
685 * Linux kernel lib/checksum.c
686 */
687static inline u32 from64to32(u64 x)
688{
689 /* add up 32-bit and 32-bit for 32+c bit */
690 x = (x & 0xffffffff) + (x >> 32);
691 /* add up carry.. */
692 x = (x & 0xffffffff) + (x >> 32);
693 return (u32)x;
694}
695
696__wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
697 __u32 len, __u8 proto, __wsum sum);
698
699/*
700 * This function code has been taken from
701 * Linux kernel lib/checksum.c
702 */
703__wsum csum_tcpudp_nofold(__be32 saddr, __be32 daddr,
704 __u32 len, __u8 proto, __wsum sum)
705{
706 unsigned long long s = (__force u32)sum;
707
708 s += (__force u32)saddr;
709 s += (__force u32)daddr;
710#ifdef __BIG_ENDIAN__
711 s += proto + len;
712#else
713 s += (proto + len) << 8;
714#endif
715 return (__force __wsum)from64to32(s);
716}
717
718/*
719 * This function has been taken from
720 * Linux kernel include/asm-generic/checksum.h
721 */
722static inline __sum16
723csum_tcpudp_magic(__be32 saddr, __be32 daddr, __u32 len,
724 __u8 proto, __wsum sum)
725{
726 return csum_fold(csum_tcpudp_nofold(saddr, daddr, len, proto, sum));
727}
728
729static inline u16 udp_csum(u32 saddr, u32 daddr, u32 len,
730 u8 proto, u16 *udp_pkt)
731{
732 u32 csum = 0;
733 u32 cnt = 0;
734
735 /* udp hdr and data */
736 for (; cnt < len; cnt += 2)
737 csum += udp_pkt[cnt >> 1];
738
739 return csum_tcpudp_magic(saddr, daddr, len, proto, csum);
740}
741
742#define ETH_FCS_SIZE 4
743
744#define PKT_HDR_SIZE (sizeof(struct ethhdr) + sizeof(struct iphdr) + \
745 sizeof(struct udphdr))
746
747#define PKT_SIZE (opt_pkt_size - ETH_FCS_SIZE)
748#define IP_PKT_SIZE (PKT_SIZE - sizeof(struct ethhdr))
749#define UDP_PKT_SIZE (IP_PKT_SIZE - sizeof(struct iphdr))
750#define UDP_PKT_DATA_SIZE (UDP_PKT_SIZE - sizeof(struct udphdr))
751
752static u8 pkt_data[XSK_UMEM__DEFAULT_FRAME_SIZE];
753
754static void gen_eth_hdr_data(void)
755{
756 struct udphdr *udp_hdr = (struct udphdr *)(pkt_data +
757 sizeof(struct ethhdr) +
758 sizeof(struct iphdr));
759 struct iphdr *ip_hdr = (struct iphdr *)(pkt_data +
760 sizeof(struct ethhdr));
761 struct ethhdr *eth_hdr = (struct ethhdr *)pkt_data;
762
763 /* ethernet header */
764 memcpy(eth_hdr->h_dest, "\x3c\xfd\xfe\x9e\x7f\x71", ETH_ALEN);
765 memcpy(eth_hdr->h_source, "\xec\xb1\xd7\x98\x3a\xc0", ETH_ALEN);
766 eth_hdr->h_proto = htons(ETH_P_IP);
767
768 /* IP header */
769 ip_hdr->version = IPVERSION;
770 ip_hdr->ihl = 0x5; /* 20 byte header */
771 ip_hdr->tos = 0x0;
772 ip_hdr->tot_len = htons(IP_PKT_SIZE);
773 ip_hdr->id = 0;
774 ip_hdr->frag_off = 0;
775 ip_hdr->ttl = IPDEFTTL;
776 ip_hdr->protocol = IPPROTO_UDP;
777 ip_hdr->saddr = htonl(0x0a0a0a10);
778 ip_hdr->daddr = htonl(0x0a0a0a20);
779
780 /* IP header checksum */
781 ip_hdr->check = 0;
782 ip_hdr->check = ip_fast_csum((const void *)ip_hdr, ip_hdr->ihl);
783
784 /* UDP header */
785 udp_hdr->source = htons(0x1000);
786 udp_hdr->dest = htons(0x1000);
787 udp_hdr->len = htons(UDP_PKT_SIZE);
788
789 /* UDP data */
790 memset32_htonl(pkt_data + PKT_HDR_SIZE, opt_pkt_fill_pattern,
791 UDP_PKT_DATA_SIZE);
792
793 /* UDP header checksum */
794 udp_hdr->check = 0;
795 udp_hdr->check = udp_csum(ip_hdr->saddr, ip_hdr->daddr, UDP_PKT_SIZE,
796 IPPROTO_UDP, (u16 *)udp_hdr);
797}
798
799static void gen_eth_frame(struct xsk_umem_info *umem, u64 addr)
800{
801 memcpy(xsk_umem__get_data(umem->buffer, addr), pkt_data,
802 PKT_SIZE);
803}
804
805static struct xsk_umem_info *xsk_configure_umem(void *buffer, u64 size)
806{
807 struct xsk_umem_info *umem;
808 struct xsk_umem_config cfg = {
809 /* We recommend that you set the fill ring size >= HW RX ring size +
810 * AF_XDP RX ring size. Make sure you fill up the fill ring
811 * with buffers at regular intervals, and you will with this setting
812 * avoid allocation failures in the driver. These are usually quite
813 * expensive since drivers have not been written to assume that
814 * allocation failures are common. For regular sockets, kernel
815 * allocated memory is used that only runs out in OOM situations
816 * that should be rare.
817 */
818 .fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS * 2,
819 .comp_size = XSK_RING_CONS__DEFAULT_NUM_DESCS,
820 .frame_size = opt_xsk_frame_size,
821 .frame_headroom = XSK_UMEM__DEFAULT_FRAME_HEADROOM,
822 .flags = opt_umem_flags
823 };
824 int ret;
825
826 umem = calloc(1, sizeof(*umem));
827 if (!umem)
828 exit_with_error(errno);
829
830 ret = xsk_umem__create(&umem->umem, buffer, size, &umem->fq, &umem->cq,
831 &cfg);
832 if (ret)
833 exit_with_error(-ret);
834
835 umem->buffer = buffer;
836 return umem;
837}
838
839static void xsk_populate_fill_ring(struct xsk_umem_info *umem)
840{
841 int ret, i;
842 u32 idx;
843
844 ret = xsk_ring_prod__reserve(&umem->fq,
845 XSK_RING_PROD__DEFAULT_NUM_DESCS * 2, &idx);
846 if (ret != XSK_RING_PROD__DEFAULT_NUM_DESCS * 2)
847 exit_with_error(-ret);
848 for (i = 0; i < XSK_RING_PROD__DEFAULT_NUM_DESCS * 2; i++)
849 *xsk_ring_prod__fill_addr(&umem->fq, idx++) =
850 i * opt_xsk_frame_size;
851 xsk_ring_prod__submit(&umem->fq, XSK_RING_PROD__DEFAULT_NUM_DESCS * 2);
852}
853
854static struct xsk_socket_info *xsk_configure_socket(struct xsk_umem_info *umem,
855 bool rx, bool tx)
856{
857 struct xsk_socket_config cfg;
858 struct xsk_socket_info *xsk;
859 struct xsk_ring_cons *rxr;
860 struct xsk_ring_prod *txr;
861 int ret;
862
863 xsk = calloc(1, sizeof(*xsk));
864 if (!xsk)
865 exit_with_error(errno);
866
867 xsk->umem = umem;
868 cfg.rx_size = XSK_RING_CONS__DEFAULT_NUM_DESCS;
869 cfg.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
870 if (opt_num_xsks > 1 || opt_reduced_cap)
871 cfg.libbpf_flags = XSK_LIBBPF_FLAGS__INHIBIT_PROG_LOAD;
872 else
873 cfg.libbpf_flags = 0;
874 cfg.xdp_flags = opt_xdp_flags;
875 cfg.bind_flags = opt_xdp_bind_flags;
876
877 rxr = rx ? &xsk->rx : NULL;
878 txr = tx ? &xsk->tx : NULL;
879 ret = xsk_socket__create(&xsk->xsk, opt_if, opt_queue, umem->umem,
880 rxr, txr, &cfg);
881 if (ret)
882 exit_with_error(-ret);
883
884 ret = bpf_get_link_xdp_id(opt_ifindex, &prog_id, opt_xdp_flags);
885 if (ret)
886 exit_with_error(-ret);
887
888 xsk->app_stats.rx_empty_polls = 0;
889 xsk->app_stats.fill_fail_polls = 0;
890 xsk->app_stats.copy_tx_sendtos = 0;
891 xsk->app_stats.tx_wakeup_sendtos = 0;
892 xsk->app_stats.opt_polls = 0;
893 xsk->app_stats.prev_rx_empty_polls = 0;
894 xsk->app_stats.prev_fill_fail_polls = 0;
895 xsk->app_stats.prev_copy_tx_sendtos = 0;
896 xsk->app_stats.prev_tx_wakeup_sendtos = 0;
897 xsk->app_stats.prev_opt_polls = 0;
898
899 return xsk;
900}
901
902static struct option long_options[] = {
903 {"rxdrop", no_argument, 0, 'r'},
904 {"txonly", no_argument, 0, 't'},
905 {"l2fwd", no_argument, 0, 'l'},
906 {"interface", required_argument, 0, 'i'},
907 {"queue", required_argument, 0, 'q'},
908 {"poll", no_argument, 0, 'p'},
909 {"xdp-skb", no_argument, 0, 'S'},
910 {"xdp-native", no_argument, 0, 'N'},
911 {"interval", required_argument, 0, 'n'},
912 {"zero-copy", no_argument, 0, 'z'},
913 {"copy", no_argument, 0, 'c'},
914 {"frame-size", required_argument, 0, 'f'},
915 {"no-need-wakeup", no_argument, 0, 'm'},
916 {"unaligned", no_argument, 0, 'u'},
917 {"shared-umem", no_argument, 0, 'M'},
918 {"force", no_argument, 0, 'F'},
919 {"duration", required_argument, 0, 'd'},
920 {"batch-size", required_argument, 0, 'b'},
921 {"tx-pkt-count", required_argument, 0, 'C'},
922 {"tx-pkt-size", required_argument, 0, 's'},
923 {"tx-pkt-pattern", required_argument, 0, 'P'},
924 {"extra-stats", no_argument, 0, 'x'},
925 {"quiet", no_argument, 0, 'Q'},
926 {"app-stats", no_argument, 0, 'a'},
927 {"irq-string", no_argument, 0, 'I'},
928 {"busy-poll", no_argument, 0, 'B'},
929 {"reduce-cap", no_argument, 0, 'R'},
930 {0, 0, 0, 0}
931};
932
933static void usage(const char *prog)
934{
935 const char *str =
936 " Usage: %s [OPTIONS]\n"
937 " Options:\n"
938 " -r, --rxdrop Discard all incoming packets (default)\n"
939 " -t, --txonly Only send packets\n"
940 " -l, --l2fwd MAC swap L2 forwarding\n"
941 " -i, --interface=n Run on interface n\n"
942 " -q, --queue=n Use queue n (default 0)\n"
943 " -p, --poll Use poll syscall\n"
944 " -S, --xdp-skb=n Use XDP skb-mod\n"
945 " -N, --xdp-native=n Enforce XDP native mode\n"
946 " -n, --interval=n Specify statistics update interval (default 1 sec).\n"
947 " -z, --zero-copy Force zero-copy mode.\n"
948 " -c, --copy Force copy mode.\n"
949 " -m, --no-need-wakeup Turn off use of driver need wakeup flag.\n"
950 " -f, --frame-size=n Set the frame size (must be a power of two in aligned mode, default is %d).\n"
951 " -u, --unaligned Enable unaligned chunk placement\n"
952 " -M, --shared-umem Enable XDP_SHARED_UMEM (cannot be used with -R)\n"
953 " -F, --force Force loading the XDP prog\n"
954 " -d, --duration=n Duration in secs to run command.\n"
955 " Default: forever.\n"
956 " -b, --batch-size=n Batch size for sending or receiving\n"
957 " packets. Default: %d\n"
958 " -C, --tx-pkt-count=n Number of packets to send.\n"
959 " Default: Continuous packets.\n"
960 " -s, --tx-pkt-size=n Transmit packet size.\n"
961 " (Default: %d bytes)\n"
962 " Min size: %d, Max size %d.\n"
963 " -P, --tx-pkt-pattern=nPacket fill pattern. Default: 0x%x\n"
964 " -x, --extra-stats Display extra statistics.\n"
965 " -Q, --quiet Do not display any stats.\n"
966 " -a, --app-stats Display application (syscall) statistics.\n"
967 " -I, --irq-string Display driver interrupt statistics for interface associated with irq-string.\n"
968 " -B, --busy-poll Busy poll.\n"
969 " -R, --reduce-cap Use reduced capabilities (cannot be used with -M)\n"
970 "\n";
971 fprintf(stderr, str, prog, XSK_UMEM__DEFAULT_FRAME_SIZE,
972 opt_batch_size, MIN_PKT_SIZE, MIN_PKT_SIZE,
973 XSK_UMEM__DEFAULT_FRAME_SIZE, opt_pkt_fill_pattern);
974
975 exit(EXIT_FAILURE);
976}
977
978static void parse_command_line(int argc, char **argv)
979{
980 int option_index, c;
981
982 opterr = 0;
983
984 for (;;) {
985 c = getopt_long(argc, argv, "Frtli:q:pSNn:czf:muMd:b:C:s:P:xQaI:BR",
986 long_options, &option_index);
987 if (c == -1)
988 break;
989
990 switch (c) {
991 case 'r':
992 opt_bench = BENCH_RXDROP;
993 break;
994 case 't':
995 opt_bench = BENCH_TXONLY;
996 break;
997 case 'l':
998 opt_bench = BENCH_L2FWD;
999 break;
1000 case 'i':
1001 opt_if = optarg;
1002 break;
1003 case 'q':
1004 opt_queue = atoi(optarg);
1005 break;
1006 case 'p':
1007 opt_poll = 1;
1008 break;
1009 case 'S':
1010 opt_xdp_flags |= XDP_FLAGS_SKB_MODE;
1011 opt_xdp_bind_flags |= XDP_COPY;
1012 break;
1013 case 'N':
1014 /* default, set below */
1015 break;
1016 case 'n':
1017 opt_interval = atoi(optarg);
1018 break;
1019 case 'z':
1020 opt_xdp_bind_flags |= XDP_ZEROCOPY;
1021 break;
1022 case 'c':
1023 opt_xdp_bind_flags |= XDP_COPY;
1024 break;
1025 case 'u':
1026 opt_umem_flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
1027 opt_unaligned_chunks = 1;
1028 opt_mmap_flags = MAP_HUGETLB;
1029 break;
1030 case 'F':
1031 opt_xdp_flags &= ~XDP_FLAGS_UPDATE_IF_NOEXIST;
1032 break;
1033 case 'f':
1034 opt_xsk_frame_size = atoi(optarg);
1035 break;
1036 case 'm':
1037 opt_need_wakeup = false;
1038 opt_xdp_bind_flags &= ~XDP_USE_NEED_WAKEUP;
1039 break;
1040 case 'M':
1041 opt_num_xsks = MAX_SOCKS;
1042 break;
1043 case 'd':
1044 opt_duration = atoi(optarg);
1045 opt_duration *= 1000000000;
1046 break;
1047 case 'b':
1048 opt_batch_size = atoi(optarg);
1049 break;
1050 case 'C':
1051 opt_pkt_count = atoi(optarg);
1052 break;
1053 case 's':
1054 opt_pkt_size = atoi(optarg);
1055 if (opt_pkt_size > (XSK_UMEM__DEFAULT_FRAME_SIZE) ||
1056 opt_pkt_size < MIN_PKT_SIZE) {
1057 fprintf(stderr,
1058 "ERROR: Invalid frame size %d\n",
1059 opt_pkt_size);
1060 usage(basename(argv[0]));
1061 }
1062 break;
1063 case 'P':
1064 opt_pkt_fill_pattern = strtol(optarg, NULL, 16);
1065 break;
1066 case 'x':
1067 opt_extra_stats = 1;
1068 break;
1069 case 'Q':
1070 opt_quiet = 1;
1071 break;
1072 case 'a':
1073 opt_app_stats = 1;
1074 break;
1075 case 'I':
1076 opt_irq_str = optarg;
1077 if (get_interrupt_number())
1078 irqs_at_init = get_irqs();
1079 if (irqs_at_init < 0) {
1080 fprintf(stderr, "ERROR: Failed to get irqs for %s\n", opt_irq_str);
1081 usage(basename(argv[0]));
1082 }
1083 break;
1084 case 'B':
1085 opt_busy_poll = 1;
1086 break;
1087 case 'R':
1088 opt_reduced_cap = true;
1089 break;
1090 default:
1091 usage(basename(argv[0]));
1092 }
1093 }
1094
1095 if (!(opt_xdp_flags & XDP_FLAGS_SKB_MODE))
1096 opt_xdp_flags |= XDP_FLAGS_DRV_MODE;
1097
1098 opt_ifindex = if_nametoindex(opt_if);
1099 if (!opt_ifindex) {
1100 fprintf(stderr, "ERROR: interface \"%s\" does not exist\n",
1101 opt_if);
1102 usage(basename(argv[0]));
1103 }
1104
1105 if ((opt_xsk_frame_size & (opt_xsk_frame_size - 1)) &&
1106 !opt_unaligned_chunks) {
1107 fprintf(stderr, "--frame-size=%d is not a power of two\n",
1108 opt_xsk_frame_size);
1109 usage(basename(argv[0]));
1110 }
1111
1112 if (opt_reduced_cap && opt_num_xsks > 1) {
1113 fprintf(stderr, "ERROR: -M and -R cannot be used together\n");
1114 usage(basename(argv[0]));
1115 }
1116}
1117
1118static void kick_tx(struct xsk_socket_info *xsk)
1119{
1120 int ret;
1121
1122 ret = sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
1123 if (ret >= 0 || errno == ENOBUFS || errno == EAGAIN ||
1124 errno == EBUSY || errno == ENETDOWN)
1125 return;
1126 exit_with_error(errno);
1127}
1128
1129static inline void complete_tx_l2fwd(struct xsk_socket_info *xsk)
1130{
1131 struct xsk_umem_info *umem = xsk->umem;
1132 u32 idx_cq = 0, idx_fq = 0;
1133 unsigned int rcvd;
1134 size_t ndescs;
1135
1136 if (!xsk->outstanding_tx)
1137 return;
1138
1139 /* In copy mode, Tx is driven by a syscall so we need to use e.g. sendto() to
1140 * really send the packets. In zero-copy mode we do not have to do this, since Tx
1141 * is driven by the NAPI loop. So as an optimization, we do not have to call
1142 * sendto() all the time in zero-copy mode for l2fwd.
1143 */
1144 if (opt_xdp_bind_flags & XDP_COPY) {
1145 xsk->app_stats.copy_tx_sendtos++;
1146 kick_tx(xsk);
1147 }
1148
1149 ndescs = (xsk->outstanding_tx > opt_batch_size) ? opt_batch_size :
1150 xsk->outstanding_tx;
1151
1152 /* re-add completed Tx buffers */
1153 rcvd = xsk_ring_cons__peek(&umem->cq, ndescs, &idx_cq);
1154 if (rcvd > 0) {
1155 unsigned int i;
1156 int ret;
1157
1158 ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
1159 while (ret != rcvd) {
1160 if (ret < 0)
1161 exit_with_error(-ret);
1162 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&umem->fq)) {
1163 xsk->app_stats.fill_fail_polls++;
1164 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL,
1165 NULL);
1166 }
1167 ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
1168 }
1169
1170 for (i = 0; i < rcvd; i++)
1171 *xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) =
1172 *xsk_ring_cons__comp_addr(&umem->cq, idx_cq++);
1173
1174 xsk_ring_prod__submit(&xsk->umem->fq, rcvd);
1175 xsk_ring_cons__release(&xsk->umem->cq, rcvd);
1176 xsk->outstanding_tx -= rcvd;
1177 }
1178}
1179
1180static inline void complete_tx_only(struct xsk_socket_info *xsk,
1181 int batch_size)
1182{
1183 unsigned int rcvd;
1184 u32 idx;
1185
1186 if (!xsk->outstanding_tx)
1187 return;
1188
1189 if (!opt_need_wakeup || xsk_ring_prod__needs_wakeup(&xsk->tx)) {
1190 xsk->app_stats.tx_wakeup_sendtos++;
1191 kick_tx(xsk);
1192 }
1193
1194 rcvd = xsk_ring_cons__peek(&xsk->umem->cq, batch_size, &idx);
1195 if (rcvd > 0) {
1196 xsk_ring_cons__release(&xsk->umem->cq, rcvd);
1197 xsk->outstanding_tx -= rcvd;
1198 }
1199}
1200
1201static void rx_drop(struct xsk_socket_info *xsk)
1202{
1203 unsigned int rcvd, i;
1204 u32 idx_rx = 0, idx_fq = 0;
1205 int ret;
1206
1207 rcvd = xsk_ring_cons__peek(&xsk->rx, opt_batch_size, &idx_rx);
1208 if (!rcvd) {
1209 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->umem->fq)) {
1210 xsk->app_stats.rx_empty_polls++;
1211 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1212 }
1213 return;
1214 }
1215
1216 ret = xsk_ring_prod__reserve(&xsk->umem->fq, rcvd, &idx_fq);
1217 while (ret != rcvd) {
1218 if (ret < 0)
1219 exit_with_error(-ret);
1220 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->umem->fq)) {
1221 xsk->app_stats.fill_fail_polls++;
1222 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1223 }
1224 ret = xsk_ring_prod__reserve(&xsk->umem->fq, rcvd, &idx_fq);
1225 }
1226
1227 for (i = 0; i < rcvd; i++) {
1228 u64 addr = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx)->addr;
1229 u32 len = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++)->len;
1230 u64 orig = xsk_umem__extract_addr(addr);
1231
1232 addr = xsk_umem__add_offset_to_addr(addr);
1233 char *pkt = xsk_umem__get_data(xsk->umem->buffer, addr);
1234
1235 hex_dump(pkt, len, addr);
1236 *xsk_ring_prod__fill_addr(&xsk->umem->fq, idx_fq++) = orig;
1237 }
1238
1239 xsk_ring_prod__submit(&xsk->umem->fq, rcvd);
1240 xsk_ring_cons__release(&xsk->rx, rcvd);
1241 xsk->ring_stats.rx_npkts += rcvd;
1242}
1243
1244static void rx_drop_all(void)
1245{
1246 struct pollfd fds[MAX_SOCKS] = {};
1247 int i, ret;
1248
1249 for (i = 0; i < num_socks; i++) {
1250 fds[i].fd = xsk_socket__fd(xsks[i]->xsk);
1251 fds[i].events = POLLIN;
1252 }
1253
1254 for (;;) {
1255 if (opt_poll) {
1256 for (i = 0; i < num_socks; i++)
1257 xsks[i]->app_stats.opt_polls++;
1258 ret = poll(fds, num_socks, opt_timeout);
1259 if (ret <= 0)
1260 continue;
1261 }
1262
1263 for (i = 0; i < num_socks; i++)
1264 rx_drop(xsks[i]);
1265
1266 if (benchmark_done)
1267 break;
1268 }
1269}
1270
1271static void tx_only(struct xsk_socket_info *xsk, u32 *frame_nb, int batch_size)
1272{
1273 u32 idx;
1274 unsigned int i;
1275
1276 while (xsk_ring_prod__reserve(&xsk->tx, batch_size, &idx) <
1277 batch_size) {
1278 complete_tx_only(xsk, batch_size);
1279 if (benchmark_done)
1280 return;
1281 }
1282
1283 for (i = 0; i < batch_size; i++) {
1284 struct xdp_desc *tx_desc = xsk_ring_prod__tx_desc(&xsk->tx,
1285 idx + i);
1286 tx_desc->addr = (*frame_nb + i) * opt_xsk_frame_size;
1287 tx_desc->len = PKT_SIZE;
1288 }
1289
1290 xsk_ring_prod__submit(&xsk->tx, batch_size);
1291 xsk->ring_stats.tx_npkts += batch_size;
1292 xsk->outstanding_tx += batch_size;
1293 *frame_nb += batch_size;
1294 *frame_nb %= NUM_FRAMES;
1295 complete_tx_only(xsk, batch_size);
1296}
1297
1298static inline int get_batch_size(int pkt_cnt)
1299{
1300 if (!opt_pkt_count)
1301 return opt_batch_size;
1302
1303 if (pkt_cnt + opt_batch_size <= opt_pkt_count)
1304 return opt_batch_size;
1305
1306 return opt_pkt_count - pkt_cnt;
1307}
1308
1309static void complete_tx_only_all(void)
1310{
1311 bool pending;
1312 int i;
1313
1314 do {
1315 pending = false;
1316 for (i = 0; i < num_socks; i++) {
1317 if (xsks[i]->outstanding_tx) {
1318 complete_tx_only(xsks[i], opt_batch_size);
1319 pending = !!xsks[i]->outstanding_tx;
1320 }
1321 }
1322 } while (pending);
1323}
1324
1325static void tx_only_all(void)
1326{
1327 struct pollfd fds[MAX_SOCKS] = {};
1328 u32 frame_nb[MAX_SOCKS] = {};
1329 int pkt_cnt = 0;
1330 int i, ret;
1331
1332 for (i = 0; i < num_socks; i++) {
1333 fds[0].fd = xsk_socket__fd(xsks[i]->xsk);
1334 fds[0].events = POLLOUT;
1335 }
1336
1337 while ((opt_pkt_count && pkt_cnt < opt_pkt_count) || !opt_pkt_count) {
1338 int batch_size = get_batch_size(pkt_cnt);
1339
1340 if (opt_poll) {
1341 for (i = 0; i < num_socks; i++)
1342 xsks[i]->app_stats.opt_polls++;
1343 ret = poll(fds, num_socks, opt_timeout);
1344 if (ret <= 0)
1345 continue;
1346
1347 if (!(fds[0].revents & POLLOUT))
1348 continue;
1349 }
1350
1351 for (i = 0; i < num_socks; i++)
1352 tx_only(xsks[i], &frame_nb[i], batch_size);
1353
1354 pkt_cnt += batch_size;
1355
1356 if (benchmark_done)
1357 break;
1358 }
1359
1360 if (opt_pkt_count)
1361 complete_tx_only_all();
1362}
1363
1364static void l2fwd(struct xsk_socket_info *xsk)
1365{
1366 unsigned int rcvd, i;
1367 u32 idx_rx = 0, idx_tx = 0;
1368 int ret;
1369
1370 complete_tx_l2fwd(xsk);
1371
1372 rcvd = xsk_ring_cons__peek(&xsk->rx, opt_batch_size, &idx_rx);
1373 if (!rcvd) {
1374 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->umem->fq)) {
1375 xsk->app_stats.rx_empty_polls++;
1376 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1377 }
1378 return;
1379 }
1380 xsk->ring_stats.rx_npkts += rcvd;
1381
1382 ret = xsk_ring_prod__reserve(&xsk->tx, rcvd, &idx_tx);
1383 while (ret != rcvd) {
1384 if (ret < 0)
1385 exit_with_error(-ret);
1386 complete_tx_l2fwd(xsk);
1387 if (opt_busy_poll || xsk_ring_prod__needs_wakeup(&xsk->tx)) {
1388 xsk->app_stats.tx_wakeup_sendtos++;
1389 kick_tx(xsk);
1390 }
1391 ret = xsk_ring_prod__reserve(&xsk->tx, rcvd, &idx_tx);
1392 }
1393
1394 for (i = 0; i < rcvd; i++) {
1395 u64 addr = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx)->addr;
1396 u32 len = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++)->len;
1397 u64 orig = addr;
1398
1399 addr = xsk_umem__add_offset_to_addr(addr);
1400 char *pkt = xsk_umem__get_data(xsk->umem->buffer, addr);
1401
1402 swap_mac_addresses(pkt);
1403
1404 hex_dump(pkt, len, addr);
1405 xsk_ring_prod__tx_desc(&xsk->tx, idx_tx)->addr = orig;
1406 xsk_ring_prod__tx_desc(&xsk->tx, idx_tx++)->len = len;
1407 }
1408
1409 xsk_ring_prod__submit(&xsk->tx, rcvd);
1410 xsk_ring_cons__release(&xsk->rx, rcvd);
1411
1412 xsk->ring_stats.tx_npkts += rcvd;
1413 xsk->outstanding_tx += rcvd;
1414}
1415
1416static void l2fwd_all(void)
1417{
1418 struct pollfd fds[MAX_SOCKS] = {};
1419 int i, ret;
1420
1421 for (;;) {
1422 if (opt_poll) {
1423 for (i = 0; i < num_socks; i++) {
1424 fds[i].fd = xsk_socket__fd(xsks[i]->xsk);
1425 fds[i].events = POLLOUT | POLLIN;
1426 xsks[i]->app_stats.opt_polls++;
1427 }
1428 ret = poll(fds, num_socks, opt_timeout);
1429 if (ret <= 0)
1430 continue;
1431 }
1432
1433 for (i = 0; i < num_socks; i++)
1434 l2fwd(xsks[i]);
1435
1436 if (benchmark_done)
1437 break;
1438 }
1439}
1440
1441static void load_xdp_program(char **argv, struct bpf_object **obj)
1442{
1443 struct bpf_prog_load_attr prog_load_attr = {
1444 .prog_type = BPF_PROG_TYPE_XDP,
1445 };
1446 char xdp_filename[256];
1447 int prog_fd;
1448
1449 snprintf(xdp_filename, sizeof(xdp_filename), "%s_kern.o", argv[0]);
1450 prog_load_attr.file = xdp_filename;
1451
1452 if (bpf_prog_load_xattr(&prog_load_attr, obj, &prog_fd))
1453 exit(EXIT_FAILURE);
1454 if (prog_fd < 0) {
1455 fprintf(stderr, "ERROR: no program found: %s\n",
1456 strerror(prog_fd));
1457 exit(EXIT_FAILURE);
1458 }
1459
1460 if (bpf_set_link_xdp_fd(opt_ifindex, prog_fd, opt_xdp_flags) < 0) {
1461 fprintf(stderr, "ERROR: link set xdp fd failed\n");
1462 exit(EXIT_FAILURE);
1463 }
1464}
1465
1466static void enter_xsks_into_map(struct bpf_object *obj)
1467{
1468 struct bpf_map *map;
1469 int i, xsks_map;
1470
1471 map = bpf_object__find_map_by_name(obj, "xsks_map");
1472 xsks_map = bpf_map__fd(map);
1473 if (xsks_map < 0) {
1474 fprintf(stderr, "ERROR: no xsks map found: %s\n",
1475 strerror(xsks_map));
1476 exit(EXIT_FAILURE);
1477 }
1478
1479 for (i = 0; i < num_socks; i++) {
1480 int fd = xsk_socket__fd(xsks[i]->xsk);
1481 int key, ret;
1482
1483 key = i;
1484 ret = bpf_map_update_elem(xsks_map, &key, &fd, 0);
1485 if (ret) {
1486 fprintf(stderr, "ERROR: bpf_map_update_elem %d\n", i);
1487 exit(EXIT_FAILURE);
1488 }
1489 }
1490}
1491
1492static void apply_setsockopt(struct xsk_socket_info *xsk)
1493{
1494 int sock_opt;
1495
1496 if (!opt_busy_poll)
1497 return;
1498
1499 sock_opt = 1;
1500 if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_PREFER_BUSY_POLL,
1501 (void *)&sock_opt, sizeof(sock_opt)) < 0)
1502 exit_with_error(errno);
1503
1504 sock_opt = 20;
1505 if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL,
1506 (void *)&sock_opt, sizeof(sock_opt)) < 0)
1507 exit_with_error(errno);
1508
1509 sock_opt = opt_batch_size;
1510 if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL_BUDGET,
1511 (void *)&sock_opt, sizeof(sock_opt)) < 0)
1512 exit_with_error(errno);
1513}
1514
1515static int recv_xsks_map_fd_from_ctrl_node(int sock, int *_fd)
1516{
1517 char cms[CMSG_SPACE(sizeof(int))];
1518 struct cmsghdr *cmsg;
1519 struct msghdr msg;
1520 struct iovec iov;
1521 int value;
1522 int len;
1523
1524 iov.iov_base = &value;
1525 iov.iov_len = sizeof(int);
1526
1527 msg.msg_name = 0;
1528 msg.msg_namelen = 0;
1529 msg.msg_iov = &iov;
1530 msg.msg_iovlen = 1;
1531 msg.msg_flags = 0;
1532 msg.msg_control = (caddr_t)cms;
1533 msg.msg_controllen = sizeof(cms);
1534
1535 len = recvmsg(sock, &msg, 0);
1536
1537 if (len < 0) {
1538 fprintf(stderr, "Recvmsg failed length incorrect.\n");
1539 return -EINVAL;
1540 }
1541
1542 if (len == 0) {
1543 fprintf(stderr, "Recvmsg failed no data\n");
1544 return -EINVAL;
1545 }
1546
1547 cmsg = CMSG_FIRSTHDR(&msg);
1548 *_fd = *(int *)CMSG_DATA(cmsg);
1549
1550 return 0;
1551}
1552
1553static int
1554recv_xsks_map_fd(int *xsks_map_fd)
1555{
1556 struct sockaddr_un server;
1557 int err;
1558
1559 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1560 if (sock < 0) {
1561 fprintf(stderr, "Error opening socket stream: %s", strerror(errno));
1562 return errno;
1563 }
1564
1565 server.sun_family = AF_UNIX;
1566 strcpy(server.sun_path, SOCKET_NAME);
1567
1568 if (connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
1569 close(sock);
1570 fprintf(stderr, "Error connecting stream socket: %s", strerror(errno));
1571 return errno;
1572 }
1573
1574 err = recv_xsks_map_fd_from_ctrl_node(sock, xsks_map_fd);
1575 if (err) {
1576 fprintf(stderr, "Error %d receiving fd\n", err);
1577 return err;
1578 }
1579 return 0;
1580}
1581
1582int main(int argc, char **argv)
1583{
1584 struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
1585 struct __user_cap_data_struct data[2] = { { 0 } };
1586 struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
1587 bool rx = false, tx = false;
1588 struct xsk_umem_info *umem;
1589 struct bpf_object *obj;
1590 int xsks_map_fd = 0;
1591 pthread_t pt;
1592 int i, ret;
1593 void *bufs;
1594
1595 parse_command_line(argc, argv);
1596
1597 if (opt_reduced_cap) {
1598 if (capget(&hdr, data) < 0)
1599 fprintf(stderr, "Error getting capabilities\n");
1600
1601 data->effective &= CAP_TO_MASK(CAP_NET_RAW);
1602 data->permitted &= CAP_TO_MASK(CAP_NET_RAW);
1603
1604 if (capset(&hdr, data) < 0)
1605 fprintf(stderr, "Setting capabilities failed\n");
1606
1607 if (capget(&hdr, data) < 0) {
1608 fprintf(stderr, "Error getting capabilities\n");
1609 } else {
1610 fprintf(stderr, "Capabilities EFF %x Caps INH %x Caps Per %x\n",
1611 data[0].effective, data[0].inheritable, data[0].permitted);
1612 fprintf(stderr, "Capabilities EFF %x Caps INH %x Caps Per %x\n",
1613 data[1].effective, data[1].inheritable, data[1].permitted);
1614 }
1615 } else {
1616 if (setrlimit(RLIMIT_MEMLOCK, &r)) {
1617 fprintf(stderr, "ERROR: setrlimit(RLIMIT_MEMLOCK) \"%s\"\n",
1618 strerror(errno));
1619 exit(EXIT_FAILURE);
1620 }
1621
1622 if (opt_num_xsks > 1)
1623 load_xdp_program(argv, &obj);
1624 }
1625
1626 /* Reserve memory for the umem. Use hugepages if unaligned chunk mode */
1627 bufs = mmap(NULL, NUM_FRAMES * opt_xsk_frame_size,
1628 PROT_READ | PROT_WRITE,
1629 MAP_PRIVATE | MAP_ANONYMOUS | opt_mmap_flags, -1, 0);
1630 if (bufs == MAP_FAILED) {
1631 printf("ERROR: mmap failed\n");
1632 exit(EXIT_FAILURE);
1633 }
1634
1635 /* Create sockets... */
1636 umem = xsk_configure_umem(bufs, NUM_FRAMES * opt_xsk_frame_size);
1637 if (opt_bench == BENCH_RXDROP || opt_bench == BENCH_L2FWD) {
1638 rx = true;
1639 xsk_populate_fill_ring(umem);
1640 }
1641 if (opt_bench == BENCH_L2FWD || opt_bench == BENCH_TXONLY)
1642 tx = true;
1643 for (i = 0; i < opt_num_xsks; i++)
1644 xsks[num_socks++] = xsk_configure_socket(umem, rx, tx);
1645
1646 for (i = 0; i < opt_num_xsks; i++)
1647 apply_setsockopt(xsks[i]);
1648
1649 if (opt_bench == BENCH_TXONLY) {
1650 gen_eth_hdr_data();
1651
1652 for (i = 0; i < NUM_FRAMES; i++)
1653 gen_eth_frame(umem, i * opt_xsk_frame_size);
1654 }
1655
1656 if (opt_num_xsks > 1 && opt_bench != BENCH_TXONLY)
1657 enter_xsks_into_map(obj);
1658
1659 if (opt_reduced_cap) {
1660 ret = recv_xsks_map_fd(&xsks_map_fd);
1661 if (ret) {
1662 fprintf(stderr, "Error %d receiving xsks_map_fd\n", ret);
1663 exit_with_error(ret);
1664 }
1665 if (xsks[0]->xsk) {
1666 ret = xsk_socket__update_xskmap(xsks[0]->xsk, xsks_map_fd);
1667 if (ret) {
1668 fprintf(stderr, "Update of BPF map failed(%d)\n", ret);
1669 exit_with_error(ret);
1670 }
1671 }
1672 }
1673
1674 signal(SIGINT, int_exit);
1675 signal(SIGTERM, int_exit);
1676 signal(SIGABRT, int_exit);
1677
1678 setlocale(LC_ALL, "");
1679
1680 if (!opt_quiet) {
1681 ret = pthread_create(&pt, NULL, poller, NULL);
1682 if (ret)
1683 exit_with_error(ret);
1684 }
1685
1686 prev_time = get_nsecs();
1687 start_time = prev_time;
1688
1689 if (opt_bench == BENCH_RXDROP)
1690 rx_drop_all();
1691 else if (opt_bench == BENCH_TXONLY)
1692 tx_only_all();
1693 else
1694 l2fwd_all();
1695
1696 benchmark_done = true;
1697
1698 if (!opt_quiet)
1699 pthread_join(pt, NULL);
1700
1701 xdpsock_cleanup();
1702
1703 munmap(bufs, NUM_FRAMES * opt_xsk_frame_size);
1704
1705 return 0;
1706}