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