]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tools/tools/netmap/pkt-gen.c
libarchive: merge from vendor branch
[FreeBSD/FreeBSD.git] / tools / tools / netmap / pkt-gen.c
1 /*
2  * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo. All rights reserved.
3  * Copyright (C) 2013-2015 Universita` di Pisa. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *   1. Redistributions of source code must retain the above copyright
9  *      notice, this list of conditions and the following disclaimer.
10  *   2. Redistributions in binary form must reproduce the above copyright
11  *      notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 /*
28  * $FreeBSD$
29  * $Id: pkt-gen.c 12346 2013-06-12 17:36:25Z luigi $
30  *
31  * Example program to show how to build a multithreaded packet
32  * source/sink using the netmap device.
33  *
34  * In this example we create a programmable number of threads
35  * to take care of all the queues of the interface used to
36  * send or receive traffic.
37  *
38  */
39
40 #define _GNU_SOURCE     /* for CPU_SET() */
41 #include <arpa/inet.h>  /* ntohs */
42 #include <assert.h>
43 #include <ctype.h>      // isprint()
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <ifaddrs.h>    /* getifaddrs */
47 #include <libnetmap.h>
48 #include <math.h>
49 #include <net/ethernet.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <netinet/ip6.h>
53 #include <netinet/udp.h>
54 #ifndef NO_PCAP
55 #include <pcap/pcap.h>
56 #endif
57 #include <pthread.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <sys/ioctl.h>
63 #include <sys/poll.h>
64 #include <sys/stat.h>
65 #if !defined(_WIN32) && !defined(linux)
66 #include <sys/sysctl.h> /* sysctl */
67 #endif
68 #include <sys/types.h>
69 #include <unistd.h>     // sysconf()
70 #ifdef linux
71 #define IPV6_VERSION    0x60
72 #define IPV6_DEFHLIM    64
73 #endif
74
75 #include "ctrs.h"
76
77 static void usage(int);
78
79 #ifdef _WIN32
80 #define cpuset_t        DWORD_PTR   //uint64_t
81 static inline void CPU_ZERO(cpuset_t *p)
82 {
83         *p = 0;
84 }
85
86 static inline void CPU_SET(uint32_t i, cpuset_t *p)
87 {
88         *p |= 1<< (i & 0x3f);
89 }
90
91 #define pthread_setaffinity_np(a, b, c) !SetThreadAffinityMask(a, *c)    //((void)a, 0)
92 #define TAP_CLONEDEV    "/dev/tap"
93 #define AF_LINK 18      //defined in winsocks.h
94 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
95 #include <net/if_dl.h>
96
97 /*
98  * Convert an ASCII representation of an ethernet address to
99  * binary form.
100  */
101 struct ether_addr *
102 ether_aton(const char *a)
103 {
104         int i;
105         static struct ether_addr o;
106         unsigned int o0, o1, o2, o3, o4, o5;
107
108         i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o0, &o1, &o2, &o3, &o4, &o5);
109
110         if (i != 6)
111                 return (NULL);
112
113         o.octet[0]=o0;
114         o.octet[1]=o1;
115         o.octet[2]=o2;
116         o.octet[3]=o3;
117         o.octet[4]=o4;
118         o.octet[5]=o5;
119
120         return ((struct ether_addr *)&o);
121 }
122
123 /*
124  * Convert a binary representation of an ethernet address to
125  * an ASCII string.
126  */
127 char *
128 ether_ntoa(const struct ether_addr *n)
129 {
130         int i;
131         static char a[18];
132
133         i = sprintf(a, "%02x:%02x:%02x:%02x:%02x:%02x",
134             n->octet[0], n->octet[1], n->octet[2],
135             n->octet[3], n->octet[4], n->octet[5]);
136         return (i < 17 ? NULL : (char *)&a);
137 }
138 #endif /* _WIN32 */
139
140 #ifdef linux
141
142 #define cpuset_t        cpu_set_t
143
144 #define ifr_flagshigh  ifr_flags        /* only the low 16 bits here */
145 #define IFF_PPROMISC   IFF_PROMISC      /* IFF_PPROMISC does not exist */
146 #include <linux/ethtool.h>
147 #include <linux/sockios.h>
148
149 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
150 #include <netinet/ether.h>      /* ether_aton */
151 #include <linux/if_packet.h>    /* sockaddr_ll */
152 #endif  /* linux */
153
154 #ifdef __FreeBSD__
155 #include <sys/endian.h> /* le64toh */
156 #include <machine/param.h>
157
158 #include <pthread_np.h> /* pthread w/ affinity */
159 #include <sys/cpuset.h> /* cpu_set */
160 #include <net/if_dl.h>  /* LLADDR */
161 #endif  /* __FreeBSD__ */
162
163 #ifdef __APPLE__
164
165 #define cpuset_t        uint64_t        // XXX
166 static inline void CPU_ZERO(cpuset_t *p)
167 {
168         *p = 0;
169 }
170
171 static inline void CPU_SET(uint32_t i, cpuset_t *p)
172 {
173         *p |= 1<< (i & 0x3f);
174 }
175
176 #define pthread_setaffinity_np(a, b, c) ((void)a, 0)
177
178 #define ifr_flagshigh  ifr_flags        // XXX
179 #define IFF_PPROMISC   IFF_PROMISC
180 #include <net/if_dl.h>  /* LLADDR */
181 #define clock_gettime(a,b)      \
182         do {struct timespec t0 = {0,0}; *(b) = t0; } while (0)
183 #endif  /* __APPLE__ */
184
185 static const char *default_payload = "netmap pkt-gen DIRECT payload\n"
186         "http://info.iet.unipi.it/~luigi/netmap/ ";
187
188 static const char *indirect_payload = "netmap pkt-gen indirect payload\n"
189         "http://info.iet.unipi.it/~luigi/netmap/ ";
190
191 static int verbose = 0;
192 static int normalize = 1;
193
194 #define VIRT_HDR_1      10      /* length of a base vnet-hdr */
195 #define VIRT_HDR_2      12      /* length of the extenede vnet-hdr */
196 #define VIRT_HDR_MAX    VIRT_HDR_2
197 struct virt_header {
198         uint8_t fields[VIRT_HDR_MAX];
199 };
200
201 #define MAX_BODYSIZE    65536
202
203 struct pkt {
204         struct virt_header vh;
205         struct ether_header eh;
206         union {
207                 struct {
208                         struct ip ip;
209                         struct udphdr udp;
210                         uint8_t body[MAX_BODYSIZE];     /* hardwired */
211                 } ipv4;
212                 struct {
213                         struct ip6_hdr ip;
214                         struct udphdr udp;
215                         uint8_t body[MAX_BODYSIZE];     /* hardwired */
216                 } ipv6;
217         };
218 } __attribute__((__packed__));
219
220 #define PKT(p, f, af)   \
221     ((af) == AF_INET ? (p)->ipv4.f: (p)->ipv6.f)
222
223 struct ip_range {
224         const char *name;
225         union {
226                 struct {
227                         uint32_t start, end; /* same as struct in_addr */
228                 } ipv4;
229                 struct {
230                         struct in6_addr start, end;
231                         uint8_t sgroup, egroup;
232                 } ipv6;
233         };
234         uint16_t port0, port1;
235 };
236
237 struct mac_range {
238         const char *name;
239         struct ether_addr start, end;
240 };
241
242 /* ifname can be netmap:foo-xxxx */
243 #define MAX_IFNAMELEN   512     /* our buffer for ifname */
244 //#define MAX_PKTSIZE   1536
245 #define MAX_PKTSIZE     MAX_BODYSIZE    /* XXX: + IP_HDR + ETH_HDR */
246
247 /* compact timestamp to fit into 60 byte packet. (enough to obtain RTT) */
248 struct tstamp {
249         uint32_t sec;
250         uint32_t nsec;
251 };
252
253 /*
254  * global arguments for all threads
255  */
256
257 struct glob_arg {
258         int af;         /* address family AF_INET/AF_INET6 */
259         struct ip_range src_ip;
260         struct ip_range dst_ip;
261         struct mac_range dst_mac;
262         struct mac_range src_mac;
263         int pkt_size;
264         int pkt_min_size;
265         int burst;
266         int forever;
267         uint64_t npackets;      /* total packets to send */
268         int frags;              /* fragments per packet */
269         u_int frag_size;        /* size of each fragment */
270         int nthreads;
271         int cpus;       /* cpus used for running */
272         int system_cpus;        /* cpus on the system */
273
274         int options;    /* testing */
275 #define OPT_PREFETCH    1
276 #define OPT_ACCESS      2
277 #define OPT_COPY        4
278 #define OPT_MEMCPY      8
279 #define OPT_TS          16      /* add a timestamp */
280 #define OPT_INDIRECT    32      /* use indirect buffers, tx only */
281 #define OPT_DUMP        64      /* dump rx/tx traffic */
282 #define OPT_RUBBISH     256     /* send whatever the buffers contain */
283 #define OPT_RANDOM_SRC  512
284 #define OPT_RANDOM_DST  1024
285 #define OPT_PPS_STATS   2048
286         int dev_type;
287 #ifndef NO_PCAP
288         pcap_t *p;
289 #endif
290
291         int tx_rate;
292         struct timespec tx_period;
293
294         int affinity;
295         int main_fd;
296         struct nmport_d *nmd;
297         uint32_t orig_mode;
298         int report_interval;            /* milliseconds between prints */
299         void *(*td_body)(void *);
300         int td_type;
301         void *mmap_addr;
302         char ifname[MAX_IFNAMELEN];
303         const char *nmr_config;
304         int dummy_send;
305         int virt_header;        /* send also the virt_header */
306         char *packet_file;      /* -P option */
307 #define STATS_WIN       15
308         int win_idx;
309         int64_t win[STATS_WIN];
310         int wait_link;
311         int framing;            /* #bits of framing (for bw output) */
312 };
313 enum dev_type { DEV_NONE, DEV_NETMAP, DEV_PCAP, DEV_TAP };
314
315 enum {
316         TD_TYPE_SENDER = 1,
317         TD_TYPE_RECEIVER,
318         TD_TYPE_OTHER,
319 };
320
321 /*
322  * Arguments for a new thread. The same structure is used by
323  * the source and the sink
324  */
325 struct targ {
326         struct glob_arg *g;
327         int used;
328         int completed;
329         int cancel;
330         int fd;
331         struct nmport_d *nmd;
332         /* these ought to be volatile, but they are
333          * only sampled and errors should not accumulate
334          */
335         struct my_ctrs ctr;
336
337         struct timespec tic, toc;
338         int me;
339         pthread_t thread;
340         int affinity;
341
342         struct pkt pkt;
343         void *frame;
344         uint16_t seed[3];
345         u_int frags;
346         u_int frag_size;
347 };
348
349 static __inline uint16_t
350 cksum_add(uint16_t sum, uint16_t a)
351 {
352         uint16_t res;
353
354         res = sum + a;
355         return (res + (res < a));
356 }
357
358 static void
359 extract_ipv4_addr(char *name, uint32_t *addr, uint16_t *port)
360 {
361         struct in_addr a;
362         char *pp;
363
364         pp = strchr(name, ':');
365         if (pp != NULL) {       /* do we have ports ? */
366                 *pp++ = '\0';
367                 *port = (uint16_t)strtol(pp, NULL, 0);
368         }
369
370         inet_pton(AF_INET, name, &a);
371         *addr = ntohl(a.s_addr);
372 }
373
374 static void
375 extract_ipv6_addr(char *name, struct in6_addr *addr, uint16_t *port,
376     uint8_t *group)
377 {
378         char *pp;
379
380         /*
381          * We accept IPv6 address in the following form:
382          *  group@[2001:DB8::1001]:port (w/ brackets and port)
383          *  group@[2001:DB8::1]         (w/ brackets and w/o port)
384          *  group@2001:DB8::1234        (w/o brackets and w/o port)
385          */
386         pp = strchr(name, '@');
387         if (pp != NULL) {
388                 *pp++ = '\0';
389                 *group = (uint8_t)strtol(name, NULL, 0);
390                 if (*group > 7)
391                         *group = 7;
392                 name = pp;
393         }
394         if (name[0] == '[')
395                 name++;
396         pp = strchr(name, ']');
397         if (pp != NULL)
398                 *pp++ = '\0';
399         if (pp != NULL && *pp != ':')
400                 pp = NULL;
401         if (pp != NULL) {       /* do we have ports ? */
402                 *pp++ = '\0';
403                 *port = (uint16_t)strtol(pp, NULL, 0);
404         }
405         inet_pton(AF_INET6, name, addr);
406 }
407 /*
408  * extract the extremes from a range of ipv4 addresses.
409  * addr_lo[-addr_hi][:port_lo[-port_hi]]
410  */
411 static int
412 extract_ip_range(struct ip_range *r, int af)
413 {
414         char *name, *ap, start[INET6_ADDRSTRLEN];
415         char end[INET6_ADDRSTRLEN];
416         struct in_addr a;
417         uint32_t tmp;
418
419         if (verbose)
420                 D("extract IP range from %s", r->name);
421
422         name = strdup(r->name);
423         if (name == NULL) {
424                 D("strdup failed");
425                 usage(-1);
426         }
427         /* the first - splits start/end of range */
428         ap = strchr(name, '-');
429         if (ap != NULL)
430                 *ap++ = '\0';
431         r->port0 = 1234;        /* default port */
432         if (af == AF_INET6) {
433                 r->ipv6.sgroup = 7; /* default group */
434                 extract_ipv6_addr(name, &r->ipv6.start, &r->port0,
435                     &r->ipv6.sgroup);
436         } else
437                 extract_ipv4_addr(name, &r->ipv4.start, &r->port0);
438
439         r->port1 = r->port0;
440         if (af == AF_INET6) {
441                 if (ap != NULL) {
442                         r->ipv6.egroup = r->ipv6.sgroup;
443                         extract_ipv6_addr(ap, &r->ipv6.end, &r->port1,
444                             &r->ipv6.egroup);
445                 } else {
446                         r->ipv6.end = r->ipv6.start;
447                         r->ipv6.egroup = r->ipv6.sgroup;
448                 }
449         } else {
450                 if (ap != NULL) {
451                         extract_ipv4_addr(ap, &r->ipv4.end, &r->port1);
452                         if (r->ipv4.start > r->ipv4.end) {
453                                 tmp = r->ipv4.end;
454                                 r->ipv4.end = r->ipv4.start;
455                                 r->ipv4.start = tmp;
456                         }
457                 } else
458                         r->ipv4.end = r->ipv4.start;
459         }
460
461         if (r->port0 > r->port1) {
462                 tmp = r->port0;
463                 r->port0 = r->port1;
464                 r->port1 = tmp;
465         }
466         if (af == AF_INET) {
467                 a.s_addr = htonl(r->ipv4.start);
468                 inet_ntop(af, &a, start, sizeof(start));
469                 a.s_addr = htonl(r->ipv4.end);
470                 inet_ntop(af, &a, end, sizeof(end));
471         } else {
472                 inet_ntop(af, &r->ipv6.start, start, sizeof(start));
473                 inet_ntop(af, &r->ipv6.end, end, sizeof(end));
474         }
475         if (af == AF_INET)
476                 D("range is %s:%d to %s:%d", start, r->port0, end, r->port1);
477         else
478                 D("range is %d@[%s]:%d to %d@[%s]:%d", r->ipv6.sgroup,
479                     start, r->port0, r->ipv6.egroup, end, r->port1);
480
481         free(name);
482         if (r->port0 != r->port1 ||
483             (af == AF_INET && r->ipv4.start != r->ipv4.end) ||
484             (af == AF_INET6 &&
485                 !IN6_ARE_ADDR_EQUAL(&r->ipv6.start, &r->ipv6.end)))
486                 return (OPT_COPY);
487         return (0);
488 }
489
490 static int
491 extract_mac_range(struct mac_range *r)
492 {
493         struct ether_addr *e;
494         if (verbose)
495             D("extract MAC range from %s", r->name);
496
497         e = ether_aton(r->name);
498         if (e == NULL) {
499                 D("invalid MAC address '%s'", r->name);
500                 return 1;
501         }
502         bcopy(e, &r->start, 6);
503         bcopy(e, &r->end, 6);
504 #if 0
505         bcopy(targ->src_mac, eh->ether_shost, 6);
506         p = index(targ->g->src_mac, '-');
507         if (p)
508                 targ->src_mac_range = atoi(p+1);
509
510         bcopy(ether_aton(targ->g->dst_mac), targ->dst_mac, 6);
511         bcopy(targ->dst_mac, eh->ether_dhost, 6);
512         p = index(targ->g->dst_mac, '-');
513         if (p)
514                 targ->dst_mac_range = atoi(p+1);
515 #endif
516         if (verbose)
517                 D("%s starts at %s", r->name, ether_ntoa(&r->start));
518         return 0;
519 }
520
521 static int
522 get_if_mtu(const struct glob_arg *g)
523 {
524         struct ifreq ifreq;
525         int s, ret;
526         const char *ifname = g->nmd->hdr.nr_name;
527         size_t len;
528
529         if (!strncmp(g->ifname, "netmap:", 7) && !strchr(ifname, '{')
530                         && !strchr(ifname, '}')) {
531
532                 len = strlen(ifname);
533
534                 if (len > IFNAMSIZ) {
535                         D("'%s' too long, cannot ask for MTU", ifname);
536                         return -1;
537                 }
538
539                 s = socket(AF_INET, SOCK_DGRAM, 0);
540                 if (s < 0) {
541                         D("socket() failed: %s", strerror(errno));
542                         return s;
543                 }
544
545                 memset(&ifreq, 0, sizeof(ifreq));
546                 memcpy(ifreq.ifr_name, ifname, len);
547
548                 ret = ioctl(s, SIOCGIFMTU, &ifreq);
549                 if (ret) {
550                         D("ioctl(SIOCGIFMTU) failed: %s", strerror(errno));
551                 }
552
553                 close(s);
554
555                 return ifreq.ifr_mtu;
556         }
557
558         /* This is a pipe or a VALE port, where the MTU is very large,
559          * so we use some practical limit. */
560         return 65536;
561 }
562
563 static struct targ *targs;
564 static int global_nthreads;
565
566 /* control-C handler */
567 static void
568 sigint_h(int sig)
569 {
570         int i;
571
572         (void)sig;      /* UNUSED */
573         D("received control-C on thread %p", (void *)pthread_self());
574         for (i = 0; i < global_nthreads; i++) {
575                 targs[i].cancel = 1;
576         }
577 }
578
579 /* sysctl wrapper to return the number of active CPUs */
580 static int
581 system_ncpus(void)
582 {
583         int ncpus;
584 #if defined (__FreeBSD__)
585         int mib[2] = { CTL_HW, HW_NCPU };
586         size_t len = sizeof(mib);
587         sysctl(mib, 2, &ncpus, &len, NULL, 0);
588 #elif defined(linux)
589         ncpus = sysconf(_SC_NPROCESSORS_ONLN);
590 #elif defined(_WIN32)
591         {
592                 SYSTEM_INFO sysinfo;
593                 GetSystemInfo(&sysinfo);
594                 ncpus = sysinfo.dwNumberOfProcessors;
595         }
596 #else /* others */
597         ncpus = 1;
598 #endif /* others */
599         return (ncpus);
600 }
601
602 #ifdef __linux__
603 #define sockaddr_dl    sockaddr_ll
604 #define sdl_family     sll_family
605 #define AF_LINK        AF_PACKET
606 #define LLADDR(s)      s->sll_addr;
607 #include <linux/if_tun.h>
608 #define TAP_CLONEDEV    "/dev/net/tun"
609 #endif /* __linux__ */
610
611 #ifdef __FreeBSD__
612 #include <net/if_tun.h>
613 #define TAP_CLONEDEV    "/dev/tap"
614 #endif /* __FreeBSD */
615
616 #ifdef __APPLE__
617 // #warning TAP not supported on apple ?
618 #include <net/if_utun.h>
619 #define TAP_CLONEDEV    "/dev/tap"
620 #endif /* __APPLE__ */
621
622
623 /*
624  * parse the vale configuration in conf and put it in nmr.
625  * Return the flag set if necessary.
626  * The configuration may consist of 1 to 4 numbers separated
627  * by commas: #tx-slots,#rx-slots,#tx-rings,#rx-rings.
628  * Missing numbers or zeroes stand for default values.
629  * As an additional convenience, if exactly one number
630  * is specified, then this is assigned to both #tx-slots and #rx-slots.
631  * If there is no 4th number, then the 3rd is assigned to both #tx-rings
632  * and #rx-rings.
633  */
634 static int
635 parse_nmr_config(const char* conf, struct nmreq_register *nmr)
636 {
637         char *w, *tok;
638         int i, v;
639
640         if (conf == NULL || ! *conf)
641                 return 0;
642         nmr->nr_tx_rings = nmr->nr_rx_rings = 0;
643         nmr->nr_tx_slots = nmr->nr_rx_slots = 0;
644         w = strdup(conf);
645         for (i = 0, tok = strtok(w, ","); tok; i++, tok = strtok(NULL, ",")) {
646                 v = atoi(tok);
647                 switch (i) {
648                 case 0:
649                         nmr->nr_tx_slots = nmr->nr_rx_slots = v;
650                         break;
651                 case 1:
652                         nmr->nr_rx_slots = v;
653                         break;
654                 case 2:
655                         nmr->nr_tx_rings = nmr->nr_rx_rings = v;
656                         break;
657                 case 3:
658                         nmr->nr_rx_rings = v;
659                         break;
660                 default:
661                         D("ignored config: %s", tok);
662                         break;
663                 }
664         }
665         D("txr %d txd %d rxr %d rxd %d",
666                         nmr->nr_tx_rings, nmr->nr_tx_slots,
667                         nmr->nr_rx_rings, nmr->nr_rx_slots);
668         free(w);
669         return 0;
670 }
671
672
673 /*
674  * locate the src mac address for our interface, put it
675  * into the user-supplied buffer. return 0 if ok, -1 on error.
676  */
677 static int
678 source_hwaddr(const char *ifname, char *buf)
679 {
680         struct ifaddrs *ifaphead, *ifap;
681
682         if (getifaddrs(&ifaphead) != 0) {
683                 D("getifaddrs %s failed", ifname);
684                 return (-1);
685         }
686
687         for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
688                 struct sockaddr_dl *sdl =
689                         (struct sockaddr_dl *)ifap->ifa_addr;
690                 uint8_t *mac;
691
692                 if (!sdl || sdl->sdl_family != AF_LINK)
693                         continue;
694                 if (strncmp(ifap->ifa_name, ifname, IFNAMSIZ) != 0)
695                         continue;
696                 mac = (uint8_t *)LLADDR(sdl);
697                 sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
698                         mac[0], mac[1], mac[2],
699                         mac[3], mac[4], mac[5]);
700                 if (verbose)
701                         D("source hwaddr %s", buf);
702                 break;
703         }
704         freeifaddrs(ifaphead);
705         return ifap ? 0 : 1;
706 }
707
708
709 /* set the thread affinity. */
710 static int
711 setaffinity(pthread_t me, int i)
712 {
713         cpuset_t cpumask;
714
715         if (i == -1)
716                 return 0;
717
718         /* Set thread affinity affinity.*/
719         CPU_ZERO(&cpumask);
720         CPU_SET(i, &cpumask);
721
722         if (pthread_setaffinity_np(me, sizeof(cpuset_t), &cpumask) != 0) {
723                 D("Unable to set affinity: %s", strerror(errno));
724                 return 1;
725         }
726         return 0;
727 }
728
729
730 /* Compute the checksum of the given ip header. */
731 static uint32_t
732 checksum(const void *data, uint16_t len, uint32_t sum)
733 {
734         const uint8_t *addr = data;
735         uint32_t i;
736
737         /* Checksum all the pairs of bytes first... */
738         for (i = 0; i < (len & ~1U); i += 2) {
739                 sum += (uint16_t)ntohs(*((const uint16_t *)(addr + i)));
740                 if (sum > 0xFFFF)
741                         sum -= 0xFFFF;
742         }
743         /*
744          * If there's a single byte left over, checksum it, too.
745          * Network byte order is big-endian, so the remaining byte is
746          * the high byte.
747          */
748         if (i < len) {
749                 sum += addr[i] << 8;
750                 if (sum > 0xFFFF)
751                         sum -= 0xFFFF;
752         }
753         return sum;
754 }
755
756 static uint16_t
757 wrapsum(uint32_t sum)
758 {
759         sum = ~sum & 0xFFFF;
760         return (htons(sum));
761 }
762
763 /* Check the payload of the packet for errors (use it for debug).
764  * Look for consecutive ascii representations of the size of the packet.
765  */
766 static void
767 dump_payload(const char *_p, int len, struct netmap_ring *ring, int cur)
768 {
769         char buf[128];
770         int i, j, i0;
771         const unsigned char *p = (const unsigned char *)_p;
772
773         /* get the length in ASCII of the length of the packet. */
774
775         printf("ring %p cur %5d [buf %6d flags 0x%04x len %5d]\n",
776                 ring, cur, ring->slot[cur].buf_idx,
777                 ring->slot[cur].flags, len);
778         /* hexdump routine */
779         for (i = 0; i < len; ) {
780                 memset(buf, ' ', sizeof(buf));
781                 sprintf(buf, "%5d: ", i);
782                 i0 = i;
783                 for (j=0; j < 16 && i < len; i++, j++)
784                         sprintf(buf+7+j*3, "%02x ", (uint8_t)(p[i]));
785                 i = i0;
786                 for (j=0; j < 16 && i < len; i++, j++)
787                         sprintf(buf+7+j + 48, "%c",
788                                 isprint(p[i]) ? p[i] : '.');
789                 printf("%s\n", buf);
790         }
791 }
792
793 /*
794  * Fill a packet with some payload.
795  * We create a UDP packet so the payload starts at
796  *      14+20+8 = 42 bytes.
797  */
798 #ifdef __linux__
799 #define uh_sport source
800 #define uh_dport dest
801 #define uh_ulen len
802 #define uh_sum check
803 #endif /* linux */
804
805 static uint16_t
806 new_ip_sum(uint16_t ip_sum, uint32_t oaddr, uint32_t naddr)
807 {
808         ip_sum = cksum_add(ip_sum, ~oaddr >> 16);
809         ip_sum = cksum_add(ip_sum, ~oaddr & 0xffff);
810         ip_sum = cksum_add(ip_sum, naddr >> 16);
811         ip_sum = cksum_add(ip_sum, naddr & 0xffff);
812         return ip_sum;
813 }
814
815 static uint16_t
816 new_udp_sum(uint16_t udp_sum, uint16_t oport, uint16_t nport)
817 {
818         udp_sum = cksum_add(udp_sum, ~oport);
819         udp_sum = cksum_add(udp_sum, nport);
820         return udp_sum;
821 }
822
823
824 static void
825 update_ip(struct pkt *pkt, struct targ *t)
826 {
827         struct glob_arg *g = t->g;
828         struct ip ip;
829         struct udphdr udp;
830         uint32_t oaddr, naddr;
831         uint16_t oport, nport;
832         uint16_t ip_sum = 0, udp_sum = 0;
833
834         memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
835         memcpy(&udp, &pkt->ipv4.udp, sizeof(udp));
836         do {
837                 ip_sum = udp_sum = 0;
838                 naddr = oaddr = ntohl(ip.ip_src.s_addr);
839                 nport = oport = ntohs(udp.uh_sport);
840                 if (g->options & OPT_RANDOM_SRC) {
841                         ip.ip_src.s_addr = nrand48(t->seed);
842                         udp.uh_sport = nrand48(t->seed);
843                         naddr = ntohl(ip.ip_src.s_addr);
844                         nport = ntohs(udp.uh_sport);
845                         ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
846                         udp_sum = new_udp_sum(udp_sum, oport, nport);
847                 } else {
848                         if (oport < g->src_ip.port1) {
849                                 nport = oport + 1;
850                                 udp.uh_sport = htons(nport);
851                                 udp_sum = new_udp_sum(udp_sum, oport, nport);
852                                 break;
853                         }
854                         nport = g->src_ip.port0;
855                         udp.uh_sport = htons(nport);
856                         if (oaddr < g->src_ip.ipv4.end) {
857                                 naddr = oaddr + 1;
858                                 ip.ip_src.s_addr = htonl(naddr);
859                                 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
860                                 break;
861                         }
862                         naddr = g->src_ip.ipv4.start;
863                         ip.ip_src.s_addr = htonl(naddr);
864                         ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
865                 }
866
867                 naddr = oaddr = ntohl(ip.ip_dst.s_addr);
868                 nport = oport = ntohs(udp.uh_dport);
869                 if (g->options & OPT_RANDOM_DST) {
870                         ip.ip_dst.s_addr = nrand48(t->seed);
871                         udp.uh_dport = nrand48(t->seed);
872                         naddr = ntohl(ip.ip_dst.s_addr);
873                         nport = ntohs(udp.uh_dport);
874                         ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
875                         udp_sum = new_udp_sum(udp_sum, oport, nport);
876                 } else {
877                         if (oport < g->dst_ip.port1) {
878                                 nport = oport + 1;
879                                 udp.uh_dport = htons(nport);
880                                 udp_sum = new_udp_sum(udp_sum, oport, nport);
881                                 break;
882                         }
883                         nport = g->dst_ip.port0;
884                         udp.uh_dport = htons(nport);
885                         if (oaddr < g->dst_ip.ipv4.end) {
886                                 naddr = oaddr + 1;
887                                 ip.ip_dst.s_addr = htonl(naddr);
888                                 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
889                                 break;
890                         }
891                         naddr = g->dst_ip.ipv4.start;
892                         ip.ip_dst.s_addr = htonl(naddr);
893                         ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
894                 }
895         } while (0);
896         /* update checksums */
897         if (udp_sum != 0)
898                 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(udp_sum));
899         if (ip_sum != 0) {
900                 ip.ip_sum = ~cksum_add(~ip.ip_sum, htons(ip_sum));
901                 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(ip_sum));
902         }
903         memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
904         memcpy(&pkt->ipv4.udp, &udp, sizeof(udp));
905 }
906
907 #ifndef s6_addr16
908 #define s6_addr16       __u6_addr.__u6_addr16
909 #endif
910 static void
911 update_ip6(struct pkt *pkt, struct targ *t)
912 {
913         struct glob_arg *g = t->g;
914         struct ip6_hdr ip6;
915         struct udphdr udp;
916         uint16_t udp_sum;
917         uint16_t oaddr, naddr;
918         uint16_t oport, nport;
919         uint8_t group;
920
921         memcpy(&ip6, &pkt->ipv6.ip, sizeof(ip6));
922         memcpy(&udp, &pkt->ipv6.udp, sizeof(udp));
923         do {
924                 udp_sum = 0;
925                 group = g->src_ip.ipv6.sgroup;
926                 naddr = oaddr = ntohs(ip6.ip6_src.s6_addr16[group]);
927                 nport = oport = ntohs(udp.uh_sport);
928                 if (g->options & OPT_RANDOM_SRC) {
929                         ip6.ip6_src.s6_addr16[group] = nrand48(t->seed);
930                         udp.uh_sport = nrand48(t->seed);
931                         naddr = ntohs(ip6.ip6_src.s6_addr16[group]);
932                         nport = ntohs(udp.uh_sport);
933                         break;
934                 }
935                 if (oport < g->src_ip.port1) {
936                         nport = oport + 1;
937                         udp.uh_sport = htons(nport);
938                         break;
939                 }
940                 nport = g->src_ip.port0;
941                 udp.uh_sport = htons(nport);
942                 if (oaddr < ntohs(g->src_ip.ipv6.end.s6_addr16[group])) {
943                         naddr = oaddr + 1;
944                         ip6.ip6_src.s6_addr16[group] = htons(naddr);
945                         break;
946                 }
947                 naddr = ntohs(g->src_ip.ipv6.start.s6_addr16[group]);
948                 ip6.ip6_src.s6_addr16[group] = htons(naddr);
949
950                 /* update checksums if needed */
951                 if (oaddr != naddr)
952                         udp_sum = cksum_add(~oaddr, naddr);
953                 if (oport != nport)
954                         udp_sum = cksum_add(udp_sum,
955                             cksum_add(~oport, nport));
956
957                 group = g->dst_ip.ipv6.egroup;
958                 naddr = oaddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
959                 nport = oport = ntohs(udp.uh_dport);
960                 if (g->options & OPT_RANDOM_DST) {
961                         ip6.ip6_dst.s6_addr16[group] = nrand48(t->seed);
962                         udp.uh_dport = nrand48(t->seed);
963                         naddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
964                         nport = ntohs(udp.uh_dport);
965                         break;
966                 }
967                 if (oport < g->dst_ip.port1) {
968                         nport = oport + 1;
969                         udp.uh_dport = htons(nport);
970                         break;
971                 }
972                 nport = g->dst_ip.port0;
973                 udp.uh_dport = htons(nport);
974                 if (oaddr < ntohs(g->dst_ip.ipv6.end.s6_addr16[group])) {
975                         naddr = oaddr + 1;
976                         ip6.ip6_dst.s6_addr16[group] = htons(naddr);
977                         break;
978                 }
979                 naddr = ntohs(g->dst_ip.ipv6.start.s6_addr16[group]);
980                 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
981         } while (0);
982         /* update checksums */
983         if (oaddr != naddr)
984                 udp_sum = cksum_add(udp_sum,
985                     cksum_add(~oaddr, naddr));
986         if (oport != nport)
987                 udp_sum = cksum_add(udp_sum,
988                     cksum_add(~oport, nport));
989         if (udp_sum != 0)
990                 udp.uh_sum = ~cksum_add(~udp.uh_sum, udp_sum);
991         memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
992         memcpy(&pkt->ipv6.udp, &udp, sizeof(udp));
993 }
994
995 static void
996 update_addresses(struct pkt *pkt, struct targ *t)
997 {
998
999         if (t->g->af == AF_INET)
1000                 update_ip(pkt, t);
1001         else
1002                 update_ip6(pkt, t);
1003 }
1004 /*
1005  * initialize one packet and prepare for the next one.
1006  * The copy could be done better instead of repeating it each time.
1007  */
1008 static void
1009 initialize_packet(struct targ *targ)
1010 {
1011         struct pkt *pkt = &targ->pkt;
1012         struct ether_header *eh;
1013         struct ip6_hdr ip6;
1014         struct ip ip;
1015         struct udphdr udp;
1016         void *udp_ptr;
1017         uint16_t paylen;
1018         uint32_t csum = 0;
1019         const char *payload = targ->g->options & OPT_INDIRECT ?
1020                 indirect_payload : default_payload;
1021         int i, l0 = strlen(payload);
1022
1023 #ifndef NO_PCAP
1024         char errbuf[PCAP_ERRBUF_SIZE];
1025         pcap_t *file;
1026         struct pcap_pkthdr *header;
1027         const unsigned char *packet;
1028
1029         /* Read a packet from a PCAP file if asked. */
1030         if (targ->g->packet_file != NULL) {
1031                 if ((file = pcap_open_offline(targ->g->packet_file,
1032                             errbuf)) == NULL)
1033                         D("failed to open pcap file %s",
1034                             targ->g->packet_file);
1035                 if (pcap_next_ex(file, &header, &packet) < 0)
1036                         D("failed to read packet from %s",
1037                             targ->g->packet_file);
1038                 if ((targ->frame = malloc(header->caplen)) == NULL)
1039                         D("out of memory");
1040                 bcopy(packet, (unsigned char *)targ->frame, header->caplen);
1041                 targ->g->pkt_size = header->caplen;
1042                 pcap_close(file);
1043                 return;
1044         }
1045 #endif
1046
1047         paylen = targ->g->pkt_size - sizeof(*eh) -
1048             (targ->g->af == AF_INET ? sizeof(ip): sizeof(ip6));
1049
1050         /* create a nice NUL-terminated string */
1051         for (i = 0; i < paylen; i += l0) {
1052                 if (l0 > paylen - i)
1053                         l0 = paylen - i; // last round
1054                 bcopy(payload, PKT(pkt, body, targ->g->af) + i, l0);
1055         }
1056         PKT(pkt, body, targ->g->af)[i - 1] = '\0';
1057
1058         /* prepare the headers */
1059         eh = &pkt->eh;
1060         bcopy(&targ->g->src_mac.start, eh->ether_shost, 6);
1061         bcopy(&targ->g->dst_mac.start, eh->ether_dhost, 6);
1062
1063         if (targ->g->af == AF_INET) {
1064                 eh->ether_type = htons(ETHERTYPE_IP);
1065                 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
1066                 udp_ptr = &pkt->ipv4.udp;
1067                 ip.ip_v = IPVERSION;
1068                 ip.ip_hl = sizeof(ip) >> 2;
1069                 ip.ip_id = 0;
1070                 ip.ip_tos = IPTOS_LOWDELAY;
1071                 ip.ip_len = htons(targ->g->pkt_size - sizeof(*eh));
1072                 ip.ip_id = 0;
1073                 ip.ip_off = htons(IP_DF); /* Don't fragment */
1074                 ip.ip_ttl = IPDEFTTL;
1075                 ip.ip_p = IPPROTO_UDP;
1076                 ip.ip_dst.s_addr = htonl(targ->g->dst_ip.ipv4.start);
1077                 ip.ip_src.s_addr = htonl(targ->g->src_ip.ipv4.start);
1078                 ip.ip_sum = wrapsum(checksum(&ip, sizeof(ip), 0));
1079                 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1080         } else {
1081                 eh->ether_type = htons(ETHERTYPE_IPV6);
1082                 memcpy(&ip6, &pkt->ipv4.ip, sizeof(ip6));
1083                 udp_ptr = &pkt->ipv6.udp;
1084                 ip6.ip6_flow = 0;
1085                 ip6.ip6_plen = htons(paylen);
1086                 ip6.ip6_vfc = IPV6_VERSION;
1087                 ip6.ip6_nxt = IPPROTO_UDP;
1088                 ip6.ip6_hlim = IPV6_DEFHLIM;
1089                 ip6.ip6_src = targ->g->src_ip.ipv6.start;
1090                 ip6.ip6_dst = targ->g->dst_ip.ipv6.start;
1091         }
1092         memcpy(&udp, udp_ptr, sizeof(udp));
1093
1094         udp.uh_sport = htons(targ->g->src_ip.port0);
1095         udp.uh_dport = htons(targ->g->dst_ip.port0);
1096         udp.uh_ulen = htons(paylen);
1097         if (targ->g->af == AF_INET) {
1098                 /* Magic: taken from sbin/dhclient/packet.c */
1099                 udp.uh_sum = wrapsum(
1100                     checksum(&udp, sizeof(udp), /* udp header */
1101                     checksum(pkt->ipv4.body,    /* udp payload */
1102                     paylen - sizeof(udp),
1103                     checksum(&pkt->ipv4.ip.ip_src, /* pseudo header */
1104                         2 * sizeof(pkt->ipv4.ip.ip_src),
1105                         IPPROTO_UDP + (u_int32_t)ntohs(udp.uh_ulen)))));
1106                 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1107         } else {
1108                 /* Save part of pseudo header checksum into csum */
1109                 csum = IPPROTO_UDP << 24;
1110                 csum = checksum(&csum, sizeof(csum), paylen);
1111                 udp.uh_sum = wrapsum(
1112                     checksum(udp_ptr, sizeof(udp),      /* udp header */
1113                     checksum(pkt->ipv6.body,    /* udp payload */
1114                     paylen - sizeof(udp),
1115                     checksum(&pkt->ipv6.ip.ip6_src, /* pseudo header */
1116                         2 * sizeof(pkt->ipv6.ip.ip6_src), csum))));
1117                 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
1118         }
1119         memcpy(udp_ptr, &udp, sizeof(udp));
1120
1121         bzero(&pkt->vh, sizeof(pkt->vh));
1122         // dump_payload((void *)pkt, targ->g->pkt_size, NULL, 0);
1123 }
1124
1125 static void
1126 get_vnet_hdr_len(struct glob_arg *g)
1127 {
1128         struct nmreq_header hdr;
1129         struct nmreq_port_hdr ph;
1130         int err;
1131
1132         hdr = g->nmd->hdr; /* copy name and version */
1133         hdr.nr_reqtype = NETMAP_REQ_PORT_HDR_GET;
1134         hdr.nr_options = 0;
1135         memset(&ph, 0, sizeof(ph));
1136         hdr.nr_body = (uintptr_t)&ph;
1137         err = ioctl(g->main_fd, NIOCCTRL, &hdr);
1138         if (err) {
1139                 D("Unable to get virtio-net header length");
1140                 return;
1141         }
1142
1143         g->virt_header = ph.nr_hdr_len;
1144         if (g->virt_header) {
1145                 D("Port requires virtio-net header, length = %d",
1146                   g->virt_header);
1147         }
1148 }
1149
1150 static void
1151 set_vnet_hdr_len(struct glob_arg *g)
1152 {
1153         int err, l = g->virt_header;
1154         struct nmreq_header hdr;
1155         struct nmreq_port_hdr ph;
1156
1157         if (l == 0)
1158                 return;
1159
1160         hdr = g->nmd->hdr; /* copy name and version */
1161         hdr.nr_reqtype = NETMAP_REQ_PORT_HDR_SET;
1162         hdr.nr_options = 0;
1163         memset(&ph, 0, sizeof(ph));
1164         hdr.nr_body = (uintptr_t)&ph;
1165         err = ioctl(g->main_fd, NIOCCTRL, &hdr);
1166         if (err) {
1167                 D("Unable to set virtio-net header length %d", l);
1168         }
1169 }
1170
1171 /*
1172  * create and enqueue a batch of packets on a ring.
1173  * On the last one set NS_REPORT to tell the driver to generate
1174  * an interrupt when done.
1175  */
1176 static int
1177 send_packets(struct netmap_ring *ring, struct pkt *pkt, void *frame,
1178                 int size, struct targ *t, u_int count, int options)
1179 {
1180         u_int n, sent, head = ring->head;
1181         u_int frags = t->frags;
1182         u_int frag_size = t->frag_size;
1183         struct netmap_slot *slot = &ring->slot[head];
1184
1185         n = nm_ring_space(ring);
1186 #if 0
1187         if (options & (OPT_COPY | OPT_PREFETCH) ) {
1188                 for (sent = 0; sent < count; sent++) {
1189                         struct netmap_slot *slot = &ring->slot[head];
1190                         char *p = NETMAP_BUF(ring, slot->buf_idx);
1191
1192                         __builtin_prefetch(p);
1193                         head = nm_ring_next(ring, head);
1194                 }
1195                 head = ring->head;
1196         }
1197 #endif
1198         for (sent = 0; sent < count && n >= frags; sent++, n--) {
1199                 char *p;
1200                 int buf_changed;
1201                 u_int tosend = size;
1202
1203                 slot = &ring->slot[head];
1204                 p = NETMAP_BUF(ring, slot->buf_idx);
1205                 buf_changed = slot->flags & NS_BUF_CHANGED;
1206
1207                 slot->flags = 0;
1208                 if (options & OPT_RUBBISH) {
1209                         /* do nothing */
1210                 } else if (options & OPT_INDIRECT) {
1211                         slot->flags |= NS_INDIRECT;
1212                         slot->ptr = (uint64_t)((uintptr_t)frame);
1213                 } else if (frags > 1) {
1214                         u_int i;
1215                         const char *f = frame;
1216                         char *fp = p;
1217                         for (i = 0; i < frags - 1; i++) {
1218                                 memcpy(fp, f, frag_size);
1219                                 slot->len = frag_size;
1220                                 slot->flags = NS_MOREFRAG;
1221                                 if (options & OPT_DUMP)
1222                                         dump_payload(fp, frag_size, ring, head);
1223                                 tosend -= frag_size;
1224                                 f += frag_size;
1225                                 head = nm_ring_next(ring, head);
1226                                 slot = &ring->slot[head];
1227                                 fp = NETMAP_BUF(ring, slot->buf_idx);
1228                         }
1229                         n -= (frags - 1);
1230                         p = fp;
1231                         slot->flags = 0;
1232                         memcpy(p, f, tosend);
1233                         update_addresses(pkt, t);
1234                 } else if ((options & (OPT_COPY | OPT_MEMCPY)) || buf_changed) {
1235                         if (options & OPT_COPY)
1236                                 nm_pkt_copy(frame, p, size);
1237                         else
1238                                 memcpy(p, frame, size);
1239                         update_addresses(pkt, t);
1240                 } else if (options & OPT_PREFETCH) {
1241                         __builtin_prefetch(p);
1242                 }
1243                 slot->len = tosend;
1244                 if (options & OPT_DUMP)
1245                         dump_payload(p, tosend, ring, head);
1246                 head = nm_ring_next(ring, head);
1247         }
1248         if (sent) {
1249                 slot->flags |= NS_REPORT;
1250                 ring->head = ring->cur = head;
1251         }
1252         if (sent < count) {
1253                 /* tell netmap that we need more slots */
1254                 ring->cur = ring->tail;
1255         }
1256
1257         return (sent);
1258 }
1259
1260 /*
1261  * Index of the highest bit set
1262  */
1263 static uint32_t
1264 msb64(uint64_t x)
1265 {
1266         uint64_t m = 1ULL << 63;
1267         int i;
1268
1269         for (i = 63; i >= 0; i--, m >>=1)
1270                 if (m & x)
1271                         return i;
1272         return 0;
1273 }
1274
1275 /*
1276  * wait until ts, either busy or sleeping if more than 1ms.
1277  * Return wakeup time.
1278  */
1279 static struct timespec
1280 wait_time(struct timespec ts)
1281 {
1282         for (;;) {
1283                 struct timespec w, cur;
1284                 clock_gettime(CLOCK_REALTIME_PRECISE, &cur);
1285                 w = timespec_sub(ts, cur);
1286                 if (w.tv_sec < 0)
1287                         return cur;
1288                 else if (w.tv_sec > 0 || w.tv_nsec > 1000000)
1289                         poll(NULL, 0, 1);
1290         }
1291 }
1292
1293 /*
1294  * Send a packet, and wait for a response.
1295  * The payload (after UDP header, ofs 42) has a 4-byte sequence
1296  * followed by a struct timeval (or bintime?)
1297  */
1298
1299 static void *
1300 ping_body(void *data)
1301 {
1302         struct targ *targ = (struct targ *) data;
1303         struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1304         struct netmap_if *nifp = targ->nmd->nifp;
1305         int i, m, rx = 0;
1306         void *frame;
1307         int size;
1308         struct timespec ts, now, last_print;
1309         struct timespec nexttime = {0, 0}; /* silence compiler */
1310         uint64_t sent = 0, n = targ->g->npackets;
1311         uint64_t count = 0, t_cur, t_min = ~0, av = 0;
1312         uint64_t g_min = ~0, g_av = 0;
1313         uint64_t buckets[64];   /* bins for delays, ns */
1314         int rate_limit = targ->g->tx_rate, tosend = 0;
1315
1316         frame = (char*)&targ->pkt + sizeof(targ->pkt.vh) - targ->g->virt_header;
1317         size = targ->g->pkt_size + targ->g->virt_header;
1318
1319
1320         if (targ->g->nthreads > 1) {
1321                 D("can only ping with 1 thread");
1322                 return NULL;
1323         }
1324
1325         if (targ->g->af == AF_INET6) {
1326                 D("Warning: ping-pong with IPv6 not supported");
1327         }
1328
1329         bzero(&buckets, sizeof(buckets));
1330         clock_gettime(CLOCK_REALTIME_PRECISE, &last_print);
1331         now = last_print;
1332         if (rate_limit) {
1333                 targ->tic = timespec_add(now, (struct timespec){2,0});
1334                 targ->tic.tv_nsec = 0;
1335                 wait_time(targ->tic);
1336                 nexttime = targ->tic;
1337         }
1338         while (!targ->cancel && (n == 0 || sent < n)) {
1339                 struct netmap_ring *ring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1340                 struct netmap_slot *slot;
1341                 char *p;
1342                 int rv;
1343                 uint64_t limit, event = 0;
1344
1345                 if (rate_limit && tosend <= 0) {
1346                         tosend = targ->g->burst;
1347                         nexttime = timespec_add(nexttime, targ->g->tx_period);
1348                         wait_time(nexttime);
1349                 }
1350
1351                 limit = rate_limit ? tosend : targ->g->burst;
1352                 if (n > 0 && n - sent < limit)
1353                         limit = n - sent;
1354                 for (m = 0; (unsigned)m < limit; m++) {
1355                         slot = &ring->slot[ring->head];
1356                         slot->len = size;
1357                         p = NETMAP_BUF(ring, slot->buf_idx);
1358
1359                         if (nm_ring_empty(ring)) {
1360                                 D("-- ouch, cannot send");
1361                                 break;
1362                         } else {
1363                                 struct tstamp *tp;
1364                                 nm_pkt_copy(frame, p, size);
1365                                 clock_gettime(CLOCK_REALTIME_PRECISE, &ts);
1366                                 bcopy(&sent, p+42, sizeof(sent));
1367                                 tp = (struct tstamp *)(p+46);
1368                                 tp->sec = (uint32_t)ts.tv_sec;
1369                                 tp->nsec = (uint32_t)ts.tv_nsec;
1370                                 sent++;
1371                                 ring->head = ring->cur = nm_ring_next(ring, ring->head);
1372                         }
1373                 }
1374                 if (m > 0)
1375                         event++;
1376                 targ->ctr.pkts = sent;
1377                 targ->ctr.bytes = sent*size;
1378                 targ->ctr.events = event;
1379                 if (rate_limit)
1380                         tosend -= m;
1381 #ifdef BUSYWAIT
1382                 rv = ioctl(pfd.fd, NIOCTXSYNC, NULL);
1383                 if (rv < 0) {
1384                         D("TXSYNC error on queue %d: %s", targ->me,
1385                                 strerror(errno));
1386                 }
1387         again:
1388                 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1389 #else
1390                 /* should use a parameter to decide how often to send */
1391                 if ( (rv = poll(&pfd, 1, 3000)) <= 0) {
1392                         D("poll error on queue %d: %s", targ->me,
1393                                 (rv ? strerror(errno) : "timeout"));
1394                         continue;
1395                 }
1396 #endif /* BUSYWAIT */
1397                 /* see what we got back */
1398                 rx = 0;
1399                 for (i = targ->nmd->first_rx_ring;
1400                         i <= targ->nmd->last_rx_ring; i++) {
1401                         ring = NETMAP_RXRING(nifp, i);
1402                         while (!nm_ring_empty(ring)) {
1403                                 uint32_t seq;
1404                                 struct tstamp *tp;
1405                                 int pos;
1406
1407                                 slot = &ring->slot[ring->head];
1408                                 p = NETMAP_BUF(ring, slot->buf_idx);
1409
1410                                 clock_gettime(CLOCK_REALTIME_PRECISE, &now);
1411                                 bcopy(p+42, &seq, sizeof(seq));
1412                                 tp = (struct tstamp *)(p+46);
1413                                 ts.tv_sec = (time_t)tp->sec;
1414                                 ts.tv_nsec = (long)tp->nsec;
1415                                 ts.tv_sec = now.tv_sec - ts.tv_sec;
1416                                 ts.tv_nsec = now.tv_nsec - ts.tv_nsec;
1417                                 if (ts.tv_nsec < 0) {
1418                                         ts.tv_nsec += 1000000000;
1419                                         ts.tv_sec--;
1420                                 }
1421                                 if (0) D("seq %d/%llu delta %d.%09d", seq,
1422                                         (unsigned long long)sent,
1423                                         (int)ts.tv_sec, (int)ts.tv_nsec);
1424                                 t_cur = ts.tv_sec * 1000000000UL + ts.tv_nsec;
1425                                 if (t_cur < t_min)
1426                                         t_min = t_cur;
1427                                 count ++;
1428                                 av += t_cur;
1429                                 pos = msb64(t_cur);
1430                                 buckets[pos]++;
1431                                 /* now store it in a bucket */
1432                                 ring->head = ring->cur = nm_ring_next(ring, ring->head);
1433                                 rx++;
1434                         }
1435                 }
1436                 //D("tx %d rx %d", sent, rx);
1437                 //usleep(100000);
1438                 ts.tv_sec = now.tv_sec - last_print.tv_sec;
1439                 ts.tv_nsec = now.tv_nsec - last_print.tv_nsec;
1440                 if (ts.tv_nsec < 0) {
1441                         ts.tv_nsec += 1000000000;
1442                         ts.tv_sec--;
1443                 }
1444                 if (ts.tv_sec >= 1) {
1445                         D("count %d RTT: min %d av %d ns",
1446                                 (int)count, (int)t_min, (int)(av/count));
1447                         int k, j, kmin, off;
1448                         char buf[512];
1449
1450                         for (kmin = 0; kmin < 64; kmin ++)
1451                                 if (buckets[kmin])
1452                                         break;
1453                         for (k = 63; k >= kmin; k--)
1454                                 if (buckets[k])
1455                                         break;
1456                         buf[0] = '\0';
1457                         off = 0;
1458                         for (j = kmin; j <= k; j++) {
1459                                 off += sprintf(buf + off, " %5d", (int)buckets[j]);
1460                         }
1461                         D("k: %d .. %d\n\t%s", 1<<kmin, 1<<k, buf);
1462                         bzero(&buckets, sizeof(buckets));
1463                         count = 0;
1464                         g_av += av;
1465                         av = 0;
1466                         if (t_min < g_min)
1467                                 g_min = t_min;
1468                         t_min = ~0;
1469                         last_print = now;
1470                 }
1471 #ifdef BUSYWAIT
1472                 if (rx < m && ts.tv_sec <= 3 && !targ->cancel)
1473                         goto again;
1474 #endif /* BUSYWAIT */
1475         }
1476
1477         if (sent > 0) {
1478                 D("RTT over %llu packets: min %d av %d ns",
1479                         (long long unsigned)sent, (int)g_min,
1480                         (int)((double)g_av/sent));
1481         }
1482         targ->completed = 1;
1483
1484         /* reset the ``used`` flag. */
1485         targ->used = 0;
1486
1487         return NULL;
1488 }
1489
1490
1491 /*
1492  * reply to ping requests
1493  */
1494 static void *
1495 pong_body(void *data)
1496 {
1497         struct targ *targ = (struct targ *) data;
1498         struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1499         struct netmap_if *nifp = targ->nmd->nifp;
1500         struct netmap_ring *txring, *rxring;
1501         int i, rx = 0;
1502         uint64_t sent = 0, n = targ->g->npackets;
1503
1504         if (targ->g->nthreads > 1) {
1505                 D("can only reply ping with 1 thread");
1506                 return NULL;
1507         }
1508         if (n > 0)
1509                 D("understood ponger %llu but don't know how to do it",
1510                         (unsigned long long)n);
1511
1512         if (targ->g->af == AF_INET6) {
1513                 D("Warning: ping-pong with IPv6 not supported");
1514         }
1515
1516         while (!targ->cancel && (n == 0 || sent < n)) {
1517                 uint32_t txhead, txavail;
1518 //#define BUSYWAIT
1519 #ifdef BUSYWAIT
1520                 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1521 #else
1522                 int rv;
1523                 if ( (rv = poll(&pfd, 1, 1000)) <= 0) {
1524                         D("poll error on queue %d: %s", targ->me,
1525                                 rv ? strerror(errno) : "timeout");
1526                         continue;
1527                 }
1528 #endif
1529                 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1530                 txhead = txring->head;
1531                 txavail = nm_ring_space(txring);
1532                 /* see what we got back */
1533                 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1534                         rxring = NETMAP_RXRING(nifp, i);
1535                         while (!nm_ring_empty(rxring)) {
1536                                 uint16_t *spkt, *dpkt;
1537                                 uint32_t head = rxring->head;
1538                                 struct netmap_slot *slot = &rxring->slot[head];
1539                                 char *src, *dst;
1540                                 src = NETMAP_BUF(rxring, slot->buf_idx);
1541                                 //D("got pkt %p of size %d", src, slot->len);
1542                                 rxring->head = rxring->cur = nm_ring_next(rxring, head);
1543                                 rx++;
1544                                 if (txavail == 0)
1545                                         continue;
1546                                 dst = NETMAP_BUF(txring,
1547                                     txring->slot[txhead].buf_idx);
1548                                 /* copy... */
1549                                 dpkt = (uint16_t *)dst;
1550                                 spkt = (uint16_t *)src;
1551                                 nm_pkt_copy(src, dst, slot->len);
1552                                 /* swap source and destination MAC */
1553                                 dpkt[0] = spkt[3];
1554                                 dpkt[1] = spkt[4];
1555                                 dpkt[2] = spkt[5];
1556                                 dpkt[3] = spkt[0];
1557                                 dpkt[4] = spkt[1];
1558                                 dpkt[5] = spkt[2];
1559                                 /* swap source and destination IPv4 */
1560                                 if (spkt[6] == htons(ETHERTYPE_IP)) {
1561                                         dpkt[13] = spkt[15];
1562                                         dpkt[14] = spkt[16];
1563                                         dpkt[15] = spkt[13];
1564                                         dpkt[16] = spkt[14];
1565                                 }
1566                                 txring->slot[txhead].len = slot->len;
1567                                 //dump_payload(dst, slot->len, txring, txhead);
1568                                 txhead = nm_ring_next(txring, txhead);
1569                                 txavail--;
1570                                 sent++;
1571                         }
1572                 }
1573                 txring->head = txring->cur = txhead;
1574                 targ->ctr.pkts = sent;
1575 #ifdef BUSYWAIT
1576                 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1577 #endif
1578                 //D("tx %d rx %d", sent, rx);
1579         }
1580
1581         targ->completed = 1;
1582
1583         /* reset the ``used`` flag. */
1584         targ->used = 0;
1585
1586         return NULL;
1587 }
1588
1589
1590 static void *
1591 sender_body(void *data)
1592 {
1593         struct targ *targ = (struct targ *) data;
1594         struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1595         struct netmap_if *nifp;
1596         struct netmap_ring *txring = NULL;
1597         int i;
1598         uint64_t n = targ->g->npackets / targ->g->nthreads;
1599         uint64_t sent = 0;
1600         uint64_t event = 0;
1601         int options = targ->g->options | OPT_COPY;
1602         struct timespec nexttime = { 0, 0}; // XXX silence compiler
1603         int rate_limit = targ->g->tx_rate;
1604         struct pkt *pkt = &targ->pkt;
1605         void *frame;
1606         int size;
1607
1608         if (targ->frame == NULL) {
1609                 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1610                 size = targ->g->pkt_size + targ->g->virt_header;
1611         } else {
1612                 frame = targ->frame;
1613                 size = targ->g->pkt_size;
1614         }
1615
1616         D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1617         if (setaffinity(targ->thread, targ->affinity))
1618                 goto quit;
1619
1620         /* main loop.*/
1621         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1622         if (rate_limit) {
1623                 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1624                 targ->tic.tv_nsec = 0;
1625                 wait_time(targ->tic);
1626                 nexttime = targ->tic;
1627         }
1628         if (targ->g->dev_type == DEV_TAP) {
1629             D("writing to file desc %d", targ->g->main_fd);
1630
1631             for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1632                 if (write(targ->g->main_fd, frame, size) != -1)
1633                         sent++;
1634                 update_addresses(pkt, targ);
1635                 if (i > 10000) {
1636                         targ->ctr.pkts = sent;
1637                         targ->ctr.bytes = sent*size;
1638                         targ->ctr.events = sent;
1639                         i = 0;
1640                 }
1641             }
1642 #ifndef NO_PCAP
1643     } else if (targ->g->dev_type == DEV_PCAP) {
1644             pcap_t *p = targ->g->p;
1645
1646             for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1647                 if (pcap_inject(p, frame, size) != -1)
1648                         sent++;
1649                 update_addresses(pkt, targ);
1650                 if (i > 10000) {
1651                         targ->ctr.pkts = sent;
1652                         targ->ctr.bytes = sent*size;
1653                         targ->ctr.events = sent;
1654                         i = 0;
1655                 }
1656             }
1657 #endif /* NO_PCAP */
1658     } else {
1659         int tosend = 0;
1660         u_int bufsz, frag_size = targ->g->frag_size;
1661
1662         nifp = targ->nmd->nifp;
1663         txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1664         bufsz = txring->nr_buf_size;
1665         if (bufsz < frag_size)
1666                 frag_size = bufsz;
1667         targ->frag_size = targ->g->pkt_size / targ->frags;
1668         if (targ->frag_size > frag_size) {
1669                 targ->frags = targ->g->pkt_size / frag_size;
1670                 targ->frag_size = frag_size;
1671                 if (targ->g->pkt_size % frag_size != 0)
1672                         targ->frags++;
1673         }
1674         D("frags %u frag_size %u", targ->frags, targ->frag_size);
1675         while (!targ->cancel && (n == 0 || sent < n)) {
1676                 int rv;
1677
1678                 if (rate_limit && tosend <= 0) {
1679                         tosend = targ->g->burst;
1680                         nexttime = timespec_add(nexttime, targ->g->tx_period);
1681                         wait_time(nexttime);
1682                 }
1683
1684                 /*
1685                  * wait for available room in the send queue(s)
1686                  */
1687 #ifdef BUSYWAIT
1688                 (void)rv;
1689                 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1690                         D("ioctl error on queue %d: %s", targ->me,
1691                                         strerror(errno));
1692                         goto quit;
1693                 }
1694 #else /* !BUSYWAIT */
1695                 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
1696                         if (targ->cancel)
1697                                 break;
1698                         D("poll error on queue %d: %s", targ->me,
1699                                 rv ? strerror(errno) : "timeout");
1700                         // goto quit;
1701                 }
1702                 if (pfd.revents & POLLERR) {
1703                         D("poll error on %d ring %d-%d", pfd.fd,
1704                                 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
1705                         goto quit;
1706                 }
1707 #endif /* !BUSYWAIT */
1708                 /*
1709                  * scan our queues and send on those with room
1710                  */
1711                 if (options & OPT_COPY && sent > 100000 && !(targ->g->options & OPT_COPY) ) {
1712                         D("drop copy");
1713                         options &= ~OPT_COPY;
1714                 }
1715                 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1716                         int m;
1717                         uint64_t limit = rate_limit ?  tosend : targ->g->burst;
1718
1719                         if (n > 0 && n == sent)
1720                                 break;
1721
1722                         if (n > 0 && n - sent < limit)
1723                                 limit = n - sent;
1724                         txring = NETMAP_TXRING(nifp, i);
1725                         if (nm_ring_empty(txring))
1726                                 continue;
1727
1728                         if (targ->g->pkt_min_size > 0) {
1729                                 size = nrand48(targ->seed) %
1730                                         (targ->g->pkt_size - targ->g->pkt_min_size) +
1731                                         targ->g->pkt_min_size;
1732                         }
1733                         m = send_packets(txring, pkt, frame, size, targ,
1734                                          limit, options);
1735                         ND("limit %lu tail %d m %d",
1736                                 limit, txring->tail, m);
1737                         sent += m;
1738                         if (m > 0) //XXX-ste: can m be 0?
1739                                 event++;
1740                         targ->ctr.pkts = sent;
1741                         targ->ctr.bytes += m*size;
1742                         targ->ctr.events = event;
1743                         if (rate_limit) {
1744                                 tosend -= m;
1745                                 if (tosend <= 0)
1746                                         break;
1747                         }
1748                 }
1749         }
1750         /* flush any remaining packets */
1751         if (txring != NULL) {
1752                 D("flush tail %d head %d on thread %p",
1753                         txring->tail, txring->head,
1754                         (void *)pthread_self());
1755                 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1756         }
1757
1758         /* final part: wait all the TX queues to be empty. */
1759         for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1760                 txring = NETMAP_TXRING(nifp, i);
1761                 while (!targ->cancel && nm_tx_pending(txring)) {
1762                         RD(5, "pending tx tail %d head %d on ring %d",
1763                                 txring->tail, txring->head, i);
1764                         ioctl(pfd.fd, NIOCTXSYNC, NULL);
1765                         usleep(1); /* wait 1 tick */
1766                 }
1767         }
1768     } /* end DEV_NETMAP */
1769
1770         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1771         targ->completed = 1;
1772         targ->ctr.pkts = sent;
1773         targ->ctr.bytes = sent*size;
1774         targ->ctr.events = event;
1775 quit:
1776         /* reset the ``used`` flag. */
1777         targ->used = 0;
1778
1779         return (NULL);
1780 }
1781
1782
1783 #ifndef NO_PCAP
1784 static void
1785 receive_pcap(u_char *user, const struct pcap_pkthdr * h,
1786         const u_char * bytes)
1787 {
1788         struct my_ctrs *ctr = (struct my_ctrs *)user;
1789         (void)bytes;    /* UNUSED */
1790         ctr->bytes += h->len;
1791         ctr->pkts++;
1792 }
1793 #endif /* !NO_PCAP */
1794
1795
1796 static int
1797 receive_packets(struct netmap_ring *ring, u_int limit, int dump, uint64_t *bytes)
1798 {
1799         u_int head, rx, n;
1800         uint64_t b = 0;
1801         u_int complete = 0;
1802
1803         if (bytes == NULL)
1804                 bytes = &b;
1805
1806         head = ring->head;
1807         n = nm_ring_space(ring);
1808         if (n < limit)
1809                 limit = n;
1810         for (rx = 0; rx < limit; rx++) {
1811                 struct netmap_slot *slot = &ring->slot[head];
1812                 char *p = NETMAP_BUF(ring, slot->buf_idx);
1813
1814                 *bytes += slot->len;
1815                 if (dump)
1816                         dump_payload(p, slot->len, ring, head);
1817                 if (!(slot->flags & NS_MOREFRAG))
1818                         complete++;
1819
1820                 head = nm_ring_next(ring, head);
1821         }
1822         ring->head = ring->cur = head;
1823
1824         return (complete);
1825 }
1826
1827 static void *
1828 receiver_body(void *data)
1829 {
1830         struct targ *targ = (struct targ *) data;
1831         struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1832         struct netmap_if *nifp;
1833         struct netmap_ring *rxring;
1834         int i;
1835         struct my_ctrs cur;
1836         uint64_t n = targ->g->npackets / targ->g->nthreads;
1837
1838         memset(&cur, 0, sizeof(cur));
1839
1840         if (setaffinity(targ->thread, targ->affinity))
1841                 goto quit;
1842
1843         D("reading from %s fd %d main_fd %d",
1844                 targ->g->ifname, targ->fd, targ->g->main_fd);
1845         /* unbounded wait for the first packet. */
1846         for (;!targ->cancel;) {
1847                 i = poll(&pfd, 1, 1000);
1848                 if (i > 0 && !(pfd.revents & POLLERR))
1849                         break;
1850                 if (i < 0) {
1851                         D("poll() error: %s", strerror(errno));
1852                         goto quit;
1853                 }
1854                 if (pfd.revents & POLLERR) {
1855                         D("fd error");
1856                         goto quit;
1857                 }
1858                 RD(1, "waiting for initial packets, poll returns %d %d",
1859                         i, pfd.revents);
1860         }
1861         /* main loop, exit after 1s silence */
1862         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1863     if (targ->g->dev_type == DEV_TAP) {
1864         while (!targ->cancel && (n == 0 || targ->ctr.pkts < n)) {
1865                 char buf[MAX_BODYSIZE];
1866                 /* XXX should we poll ? */
1867                 i = read(targ->g->main_fd, buf, sizeof(buf));
1868                 if (i > 0) {
1869                         targ->ctr.pkts++;
1870                         targ->ctr.bytes += i;
1871                         targ->ctr.events++;
1872                 }
1873         }
1874 #ifndef NO_PCAP
1875     } else if (targ->g->dev_type == DEV_PCAP) {
1876         while (!targ->cancel && (n == 0 || targ->ctr.pkts < n)) {
1877                 /* XXX should we poll ? */
1878                 pcap_dispatch(targ->g->p, targ->g->burst, receive_pcap,
1879                         (u_char *)&targ->ctr);
1880                 targ->ctr.events++;
1881         }
1882 #endif /* !NO_PCAP */
1883     } else {
1884         int dump = targ->g->options & OPT_DUMP;
1885
1886         nifp = targ->nmd->nifp;
1887         while (!targ->cancel && (n == 0 || targ->ctr.pkts < n)) {
1888                 /* Once we started to receive packets, wait at most 1 seconds
1889                    before quitting. */
1890 #ifdef BUSYWAIT
1891                 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
1892                         D("ioctl error on queue %d: %s", targ->me,
1893                                         strerror(errno));
1894                         goto quit;
1895                 }
1896 #else /* !BUSYWAIT */
1897                 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
1898                         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1899                         targ->toc.tv_sec -= 1; /* Subtract timeout time. */
1900                         goto out;
1901                 }
1902
1903                 if (pfd.revents & POLLERR) {
1904                         D("poll err");
1905                         goto quit;
1906                 }
1907 #endif /* !BUSYWAIT */
1908                 uint64_t cur_space = 0;
1909                 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1910                         int m;
1911
1912                         rxring = NETMAP_RXRING(nifp, i);
1913                         /* compute free space in the ring */
1914                         m = rxring->head + rxring->num_slots - rxring->tail;
1915                         if (m >= (int) rxring->num_slots)
1916                                 m -= rxring->num_slots;
1917                         cur_space += m;
1918                         if (nm_ring_empty(rxring))
1919                                 continue;
1920
1921                         m = receive_packets(rxring, targ->g->burst, dump, &cur.bytes);
1922                         cur.pkts += m;
1923                         if (m > 0)
1924                                 cur.events++;
1925                 }
1926                 cur.min_space = targ->ctr.min_space;
1927                 if (cur_space < cur.min_space)
1928                         cur.min_space = cur_space;
1929                 targ->ctr = cur;
1930         }
1931     }
1932
1933         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1934
1935 #if !defined(BUSYWAIT)
1936 out:
1937 #endif
1938         targ->completed = 1;
1939         targ->ctr = cur;
1940
1941 quit:
1942         /* reset the ``used`` flag. */
1943         targ->used = 0;
1944
1945         return (NULL);
1946 }
1947
1948 static void *
1949 txseq_body(void *data)
1950 {
1951         struct targ *targ = (struct targ *) data;
1952         struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1953         struct netmap_ring *ring;
1954         int64_t sent = 0;
1955         uint64_t event = 0;
1956         int options = targ->g->options | OPT_COPY;
1957         struct timespec nexttime = {0, 0};
1958         int rate_limit = targ->g->tx_rate;
1959         struct pkt *pkt = &targ->pkt;
1960         int frags = targ->g->frags;
1961         uint32_t sequence = 0;
1962         int budget = 0;
1963         void *frame;
1964         int size;
1965
1966         if (targ->g->nthreads > 1) {
1967                 D("can only txseq ping with 1 thread");
1968                 return NULL;
1969         }
1970
1971         if (targ->g->npackets > 0) {
1972                 D("Ignoring -n argument");
1973         }
1974
1975         frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1976         size = targ->g->pkt_size + targ->g->virt_header;
1977
1978         D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1979         if (setaffinity(targ->thread, targ->affinity))
1980                 goto quit;
1981
1982         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1983         if (rate_limit) {
1984                 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1985                 targ->tic.tv_nsec = 0;
1986                 wait_time(targ->tic);
1987                 nexttime = targ->tic;
1988         }
1989
1990         /* Only use the first queue. */
1991         ring = NETMAP_TXRING(targ->nmd->nifp, targ->nmd->first_tx_ring);
1992
1993         while (!targ->cancel) {
1994                 int64_t limit;
1995                 unsigned int space;
1996                 unsigned int head;
1997                 int fcnt;
1998                 uint16_t sum = 0;
1999                 int rv;
2000
2001                 if (!rate_limit) {
2002                         budget = targ->g->burst;
2003
2004                 } else if (budget <= 0) {
2005                         budget = targ->g->burst;
2006                         nexttime = timespec_add(nexttime, targ->g->tx_period);
2007                         wait_time(nexttime);
2008                 }
2009
2010                 /* wait for available room in the send queue */
2011 #ifdef BUSYWAIT
2012                 (void)rv;
2013                 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
2014                         D("ioctl error on queue %d: %s", targ->me,
2015                                         strerror(errno));
2016                         goto quit;
2017                 }
2018 #else /* !BUSYWAIT */
2019                 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
2020                         if (targ->cancel)
2021                                 break;
2022                         D("poll error on queue %d: %s", targ->me,
2023                                 rv ? strerror(errno) : "timeout");
2024                         // goto quit;
2025                 }
2026                 if (pfd.revents & POLLERR) {
2027                         D("poll error on %d ring %d-%d", pfd.fd,
2028                                 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
2029                         goto quit;
2030                 }
2031 #endif /* !BUSYWAIT */
2032
2033                 /* If no room poll() again. */
2034                 space = nm_ring_space(ring);
2035                 if (!space) {
2036                         continue;
2037                 }
2038
2039                 limit = budget;
2040
2041                 if (space < limit) {
2042                         limit = space;
2043                 }
2044
2045                 /* Cut off ``limit`` to make sure is multiple of ``frags``. */
2046                 if (frags > 1) {
2047                         limit = (limit / frags) * frags;
2048                 }
2049
2050                 limit = sent + limit; /* Convert to absolute. */
2051
2052                 for (fcnt = frags, head = ring->head;
2053                                 sent < limit; sent++, sequence++) {
2054                         struct netmap_slot *slot = &ring->slot[head];
2055                         char *p = NETMAP_BUF(ring, slot->buf_idx);
2056                         uint16_t *w = (uint16_t *)PKT(pkt, body, targ->g->af), t;
2057
2058                         memcpy(&sum, targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, sizeof(sum));
2059
2060                         slot->flags = 0;
2061                         t = *w;
2062                         PKT(pkt, body, targ->g->af)[0] = sequence >> 24;
2063                         PKT(pkt, body, targ->g->af)[1] = (sequence >> 16) & 0xff;
2064                         sum = ~cksum_add(~sum, cksum_add(~t, *w));
2065                         t = *++w;
2066                         PKT(pkt, body, targ->g->af)[2] = (sequence >> 8) & 0xff;
2067                         PKT(pkt, body, targ->g->af)[3] = sequence & 0xff;
2068                         sum = ~cksum_add(~sum, cksum_add(~t, *w));
2069                         memcpy(targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, &sum, sizeof(sum));
2070                         nm_pkt_copy(frame, p, size);
2071                         if (fcnt == frags) {
2072                                 update_addresses(pkt, targ);
2073                         }
2074
2075                         if (options & OPT_DUMP) {
2076                                 dump_payload(p, size, ring, head);
2077                         }
2078
2079                         slot->len = size;
2080
2081                         if (--fcnt > 0) {
2082                                 slot->flags |= NS_MOREFRAG;
2083                         } else {
2084                                 fcnt = frags;
2085                         }
2086
2087                         if (sent == limit - 1) {
2088                                 /* Make sure we don't push an incomplete
2089                                  * packet. */
2090                                 assert(!(slot->flags & NS_MOREFRAG));
2091                                 slot->flags |= NS_REPORT;
2092                         }
2093
2094                         head = nm_ring_next(ring, head);
2095                         if (rate_limit) {
2096                                 budget--;
2097                         }
2098                 }
2099
2100                 ring->cur = ring->head = head;
2101
2102                 event ++;
2103                 targ->ctr.pkts = sent;
2104                 targ->ctr.bytes = sent * size;
2105                 targ->ctr.events = event;
2106         }
2107
2108         /* flush any remaining packets */
2109         D("flush tail %d head %d on thread %p",
2110                 ring->tail, ring->head,
2111                 (void *)pthread_self());
2112         ioctl(pfd.fd, NIOCTXSYNC, NULL);
2113
2114         /* final part: wait the TX queues to become empty. */
2115         while (!targ->cancel && nm_tx_pending(ring)) {
2116                 RD(5, "pending tx tail %d head %d on ring %d",
2117                                 ring->tail, ring->head, targ->nmd->first_tx_ring);
2118                 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2119                 usleep(1); /* wait 1 tick */
2120         }
2121
2122         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2123         targ->completed = 1;
2124         targ->ctr.pkts = sent;
2125         targ->ctr.bytes = sent * size;
2126         targ->ctr.events = event;
2127 quit:
2128         /* reset the ``used`` flag. */
2129         targ->used = 0;
2130
2131         return (NULL);
2132 }
2133
2134
2135 static char *
2136 multi_slot_to_string(struct netmap_ring *ring, unsigned int head,
2137                      unsigned int nfrags, char *strbuf, size_t strbuflen)
2138 {
2139         unsigned int f;
2140         char *ret = strbuf;
2141
2142         for (f = 0; f < nfrags; f++) {
2143                 struct netmap_slot *slot = &ring->slot[head];
2144                 int m = snprintf(strbuf, strbuflen, "|%u,%x|", slot->len,
2145                                  slot->flags);
2146                 if (m >= (int)strbuflen) {
2147                         break;
2148                 }
2149                 strbuf += m;
2150                 strbuflen -= m;
2151
2152                 head = nm_ring_next(ring, head);
2153         }
2154
2155         return ret;
2156 }
2157
2158 static void *
2159 rxseq_body(void *data)
2160 {
2161         struct targ *targ = (struct targ *) data;
2162         struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
2163         int dump = targ->g->options & OPT_DUMP;
2164         struct netmap_ring *ring;
2165         unsigned int frags_exp = 1;
2166         struct my_ctrs cur;
2167         unsigned int frags = 0;
2168         int first_packet = 1;
2169         int first_slot = 1;
2170         int i, j, af, nrings;
2171         uint32_t seq, *seq_exp = NULL;
2172
2173         memset(&cur, 0, sizeof(cur));
2174
2175         if (setaffinity(targ->thread, targ->affinity))
2176                 goto quit;
2177
2178         nrings = targ->nmd->last_rx_ring - targ->nmd->first_rx_ring + 1;
2179         seq_exp = calloc(nrings, sizeof(uint32_t));
2180         if (seq_exp == NULL) {
2181                 D("failed to allocate seq array");
2182                 goto quit;
2183         }
2184
2185         D("reading from %s fd %d main_fd %d",
2186                 targ->g->ifname, targ->fd, targ->g->main_fd);
2187         /* unbounded wait for the first packet. */
2188         for (;!targ->cancel;) {
2189                 i = poll(&pfd, 1, 1000);
2190                 if (i > 0 && !(pfd.revents & POLLERR))
2191                         break;
2192                 RD(1, "waiting for initial packets, poll returns %d %d",
2193                         i, pfd.revents);
2194         }
2195
2196         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
2197
2198
2199         while (!targ->cancel) {
2200                 unsigned int head;
2201                 int limit;
2202
2203 #ifdef BUSYWAIT
2204                 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
2205                         D("ioctl error on queue %d: %s", targ->me,
2206                                         strerror(errno));
2207                         goto quit;
2208                 }
2209 #else /* !BUSYWAIT */
2210                 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
2211                         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2212                         targ->toc.tv_sec -= 1; /* Subtract timeout time. */
2213                         goto out;
2214                 }
2215
2216                 if (pfd.revents & POLLERR) {
2217                         D("poll err");
2218                         goto quit;
2219                 }
2220 #endif /* !BUSYWAIT */
2221
2222                 for (j = targ->nmd->first_rx_ring; j <= targ->nmd->last_rx_ring; j++) {
2223                         ring = NETMAP_RXRING(targ->nmd->nifp, j);
2224                         if (nm_ring_empty(ring))
2225                                 continue;
2226
2227                         limit = nm_ring_space(ring);
2228                         if (limit > targ->g->burst)
2229                                 limit = targ->g->burst;
2230
2231 #if 0
2232                         /* Enable this if
2233                          *     1) we remove the early-return optimization from
2234                          *        the netmap poll implementation, or
2235                          *     2) pipes get NS_MOREFRAG support.
2236                          * With the current netmap implementation, an experiment like
2237                          *    pkt-gen -i vale:1{1 -f txseq -F 9
2238                          *    pkt-gen -i vale:1}1 -f rxseq
2239                          * would get stuck as soon as we find nm_ring_space(ring) < 9,
2240                          * since here limit is rounded to 0 and
2241                          * pipe rxsync is not called anymore by the poll() of this loop.
2242                          */
2243                         if (frags_exp > 1) {
2244                                 int o = limit;
2245                                 /* Cut off to the closest smaller multiple. */
2246                                 limit = (limit / frags_exp) * frags_exp;
2247                                 RD(2, "LIMIT %d --> %d", o, limit);
2248                         }
2249 #endif
2250
2251                         for (head = ring->head, i = 0; i < limit; i++) {
2252                                 struct netmap_slot *slot = &ring->slot[head];
2253                                 char *p = NETMAP_BUF(ring, slot->buf_idx);
2254                                 int len = slot->len;
2255                                 struct pkt *pkt;
2256
2257                                 if (dump) {
2258                                         dump_payload(p, slot->len, ring, head);
2259                                 }
2260
2261                                 frags++;
2262                                 if (!(slot->flags & NS_MOREFRAG)) {
2263                                         if (first_packet) {
2264                                                 first_packet = 0;
2265                                         } else if (frags != frags_exp) {
2266                                                 char prbuf[512];
2267                                                 RD(1, "Received packets with %u frags, "
2268                                                                 "expected %u, '%s'", frags, frags_exp,
2269                                                                 multi_slot_to_string(ring, head-frags+1,
2270                                                                 frags,
2271                                                                         prbuf, sizeof(prbuf)));
2272                                         }
2273                                         first_packet = 0;
2274                                         frags_exp = frags;
2275                                         frags = 0;
2276                                 }
2277
2278                                 p -= sizeof(pkt->vh) - targ->g->virt_header;
2279                                 len += sizeof(pkt->vh) - targ->g->virt_header;
2280                                 pkt = (struct pkt *)p;
2281                                 if (ntohs(pkt->eh.ether_type) == ETHERTYPE_IP)
2282                                         af = AF_INET;
2283                                 else
2284                                         af = AF_INET6;
2285
2286                                 if ((char *)pkt + len < ((char *)PKT(pkt, body, af)) +
2287                                                 sizeof(seq)) {
2288                                         RD(1, "%s: packet too small (len=%u)", __func__,
2289                                                         slot->len);
2290                                 } else {
2291                                         seq = (PKT(pkt, body, af)[0] << 24) |
2292                                                 (PKT(pkt, body, af)[1] << 16) |
2293                                                 (PKT(pkt, body, af)[2] << 8) |
2294                                                 PKT(pkt, body, af)[3];
2295                                         if (first_slot) {
2296                                                 /* Grab the first one, whatever it
2297                                                    is. */
2298                                                 seq_exp[j] = seq;
2299                                                 first_slot = 0;
2300                                         } else if (seq != seq_exp[j]) {
2301                                                 uint32_t delta = seq - seq_exp[j];
2302
2303                                                 if (delta < (0xFFFFFFFF >> 1)) {
2304                                                         RD(2, "Sequence GAP: exp %u found %u",
2305                                                                         seq_exp[j], seq);
2306                                                 } else {
2307                                                         RD(2, "Sequence OUT OF ORDER: "
2308                                                                         "exp %u found %u", seq_exp[j], seq);
2309                                                 }
2310                                                 seq_exp[j] = seq;
2311                                         }
2312                                         seq_exp[j]++;
2313                                 }
2314
2315                                 cur.bytes += slot->len;
2316                                 head = nm_ring_next(ring, head);
2317                                 cur.pkts++;
2318                         }
2319
2320                         ring->cur = ring->head = head;
2321
2322                         cur.events++;
2323                         targ->ctr = cur;
2324                 }
2325         }
2326         clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2327
2328 #ifndef BUSYWAIT
2329 out:
2330 #endif /* !BUSYWAIT */
2331         targ->completed = 1;
2332         targ->ctr = cur;
2333
2334 quit:
2335         if (seq_exp != NULL)
2336                 free(seq_exp);
2337         /* reset the ``used`` flag. */
2338         targ->used = 0;
2339
2340         return (NULL);
2341 }
2342
2343
2344 static void
2345 tx_output(struct glob_arg *g, struct my_ctrs *cur, double delta, const char *msg)
2346 {
2347         double bw, raw_bw, pps, abs;
2348         char b1[40], b2[80], b3[80];
2349         int size;
2350
2351         if (cur->pkts == 0) {
2352                 printf("%s nothing.\n", msg);
2353                 return;
2354         }
2355
2356         size = (int)(cur->bytes / cur->pkts);
2357
2358         printf("%s %llu packets %llu bytes %llu events %d bytes each in %.2f seconds.\n",
2359                 msg,
2360                 (unsigned long long)cur->pkts,
2361                 (unsigned long long)cur->bytes,
2362                 (unsigned long long)cur->events, size, delta);
2363         if (delta == 0)
2364                 delta = 1e-6;
2365         if (size < 60)          /* correct for min packet size */
2366                 size = 60;
2367         pps = cur->pkts / delta;
2368         bw = (8.0 * cur->bytes) / delta;
2369         raw_bw = (8.0 * cur->bytes + cur->pkts * g->framing) / delta;
2370         abs = cur->pkts / (double)(cur->events);
2371
2372         printf("Speed: %spps Bandwidth: %sbps (raw %sbps). Average batch: %.2f pkts\n",
2373                 norm(b1, pps, normalize), norm(b2, bw, normalize), norm(b3, raw_bw, normalize), abs);
2374 }
2375
2376 static void
2377 usage(int errcode)
2378 {
2379 /* This usage is generated from the pkt-gen man page:
2380  *   $ man pkt-gen > x
2381  * and pasted here adding the string terminators and endlines with simple
2382  * regular expressions. */
2383         const char *cmd = "pkt-gen";
2384         fprintf(stderr,
2385                 "Usage:\n"
2386                 "%s arguments\n"
2387 "     -h      Show program usage and exit.\n"
2388 "\n"
2389 "     -i interface\n"
2390 "             Name of the network interface that pkt-gen operates on.  It can be a system network interface\n"
2391 "             (e.g., em0), the name of a vale(4) port (e.g., valeSSS:PPP), the name of a netmap pipe or\n"
2392 "             monitor, or any valid netmap port name accepted by the nm_open library function, as docu-\n"
2393 "             mented in netmap(4) (NIOCREGIF section).\n"
2394 "\n"
2395 "     -f function\n"
2396 "             The function to be executed by pkt-gen.  Specify tx for transmission, rx for reception, ping\n"
2397 "             for client-side ping-pong operation, and pong for server-side ping-pong operation.\n"
2398 "\n"
2399 "     -n count\n"
2400 "             Number of iterations of the pkt-gen function (with 0 meaning infinite).  In case of tx or rx,\n"
2401 "             count is the number of packets to receive or transmit.  In case of ping or pong, count is the\n"
2402 "             number of ping-pong transactions.\n"
2403 "\n"
2404 "     -l pkt_size\n"
2405 "             Packet size in bytes excluding CRC.  If passed a second time, use random sizes larger or\n"
2406 "             equal than the second one and lower than the first one.\n"
2407 "\n"
2408 "     -b burst_size\n"
2409 "             Transmit or receive up to burst_size packets at a time.\n"
2410 "\n"
2411 "     -4      Use IPv4 addresses.\n"
2412 "\n"
2413 "     -6      Use IPv6 addresses.\n"
2414 "\n"
2415 "     -d dst_ip[:port[-dst_ip:port]]\n"
2416 "             Destination IPv4/IPv6 address and port, single or range.\n"
2417 "\n"
2418 "     -s src_ip[:port[-src_ip:port]]\n"
2419 "             Source IPv4/IPv6 address and port, single or range.\n"
2420 "\n"
2421 "     -D dst_mac\n"
2422 "             Destination MAC address in colon notation (e.g., aa:bb:cc:dd:ee:00).\n"
2423 "\n"
2424 "     -S src_mac\n"
2425 "             Source MAC address in colon notation.\n"
2426 "\n"
2427 "     -a cpu_id\n"
2428 "             Pin the first thread of pkt-gen to a particular CPU using pthread_setaffinity_np(3).  If more\n"
2429 "             threads are used, they are pinned to the subsequent CPUs, one per thread.\n"
2430 "\n"
2431 "     -c cpus\n"
2432 "             Maximum number of CPUs to use (0 means to use all the available ones).\n"
2433 "\n"
2434 "     -p threads\n"
2435 "             Number of threads to use.  By default, only a single thread is used to handle all the netmap\n"
2436 "             rings.  If threads is larger than one, each thread handles a single TX ring (in tx mode), a\n"
2437 "             single RX ring (in rx mode), or a TX/RX ring pair.  The number of threads must be less than or\n"
2438 "             equal to the number of TX (or RX) rings available in the device specified by interface.\n"
2439 "\n"
2440 "     -T report_ms\n"
2441 "             Number of milliseconds between reports.\n"
2442 "\n"
2443 "     -w wait_for_link_time\n"
2444 "             Number of seconds to wait before starting the pkt-gen function, useful to make sure that the\n"
2445 "             network link is up.  A network device driver may take some time to enter netmap mode, or to\n"
2446 "             create a new transmit/receive ring pair when netmap(4) requests one.\n"
2447 "\n"
2448 "     -R rate\n"
2449 "             Packet transmission rate.  Not setting the packet transmission rate tells pkt-gen to transmit\n"
2450 "             packets as quickly as possible.  On servers from 2010 onward netmap(4) is able to com-\n"
2451 "             pletely use all of the bandwidth of a 10 or 40Gbps link, so this option should be used unless\n"
2452 "             your intention is to saturate the link.\n"
2453 "\n"
2454 "     -X      Dump payload of each packet transmitted or received.\n"
2455 "\n"
2456 "     -H len  Add empty virtio-net-header with size 'len'.  Valid sizes are 0, 10 and 12.  This option is\n"
2457 "             only used with Virtual Machine technologies that use virtio as a network interface.\n"
2458 "\n"
2459 "     -P file\n"
2460 "             Load the packet to be transmitted from a pcap file rather than constructing it within\n"
2461 "             pkt-gen.\n"
2462 "\n"
2463 "     -z      Use random IPv4/IPv6 src address/port.\n"
2464 "\n"
2465 "     -Z      Use random IPv4/IPv6 dst address/port.\n"
2466 "\n"
2467 "     -N      Do not normalize units (i.e., use bps, pps instead of Mbps, Kpps, etc.).\n"
2468 "\n"
2469 "     -F num_frags\n"
2470 "             Send multi-slot packets, each one with num_frags fragments.  A multi-slot packet is repre-\n"
2471 "             sented by two or more consecutive netmap slots with the NS_MOREFRAG flag set (except for the\n"
2472 "             last slot).  This is useful to transmit or receive packets larger than the netmap buffer\n"
2473 "             size.\n"
2474 "\n"
2475 "     -M frag_size\n"
2476 "             In multi-slot mode, frag_size specifies the size of each fragment, if smaller than the packet\n"
2477 "             length divided by num_frags.\n"
2478 "\n"
2479 "     -I      Use indirect buffers.  It is only valid for transmitting on VALE ports, and it is implemented\n"
2480 "             by setting the NS_INDIRECT flag in the netmap slots.\n"
2481 "\n"
2482 "     -W      Exit immediately if all the RX rings are empty the first time they are examined.\n"
2483 "\n"
2484 "     -v      Increase the verbosity level.\n"
2485 "\n"
2486 "     -r      In tx mode, do not initialize packets, but send whatever the content of the uninitialized\n"
2487 "             netmap buffers is (rubbish mode).\n"
2488 "\n"
2489 "     -A      Compute mean and standard deviation (over a sliding window) for the transmit or receive rate.\n"
2490 "\n"
2491 "     -B      Take Ethernet framing and CRC into account when computing the average bps.  This adds 4 bytes\n"
2492 "             of CRC and 20 bytes of framing to each packet.\n"
2493 "\n"
2494 "     -C tx_slots[,rx_slots[,tx_rings[,rx_rings]]]\n"
2495 "             Configuration in terms of number of rings and slots to be used when opening the netmap port.\n"
2496 "             Such configuration has an effect on software ports created on the fly, such as VALE ports and\n"
2497 "             netmap pipes.  The configuration may consist of 1 to 4 numbers separated by commas: tx_slots,\n"
2498 "             rx_slots, tx_rings, rx_rings.  Missing numbers or zeroes stand for default values.  As an\n"
2499 "             additional convenience, if exactly one number is specified, then this is assigned to both\n"
2500 "             tx_slots and rx_slots.  If there is no fourth number, then the third one is assigned to both\n"
2501 "             tx_rings and rx_rings.\n"
2502 "\n"
2503 "     -o options                data generation options (parsed using atoi)\n"
2504 "                               OPT_PREFETCH    1\n"
2505 "                               OPT_ACCESS      2\n"
2506 "                               OPT_COPY        4\n"
2507 "                               OPT_MEMCPY      8\n"
2508 "                               OPT_TS          16 (add a timestamp)\n"
2509 "                               OPT_INDIRECT    32 (use indirect buffers)\n"
2510 "                               OPT_DUMP        64 (dump rx/tx traffic)\n"
2511 "                               OPT_RUBBISH     256\n"
2512 "                                       (send whatever the buffers contain)\n"
2513 "                               OPT_RANDOM_SRC  512\n"
2514 "                               OPT_RANDOM_DST  1024\n"
2515 "                               OPT_PPS_STATS   2048\n"
2516                      "",
2517                 cmd);
2518         exit(errcode);
2519 }
2520
2521 static int
2522 start_threads(struct glob_arg *g) {
2523         int i;
2524
2525         targs = calloc(g->nthreads, sizeof(*targs));
2526         struct targ *t;
2527         /*
2528          * Now create the desired number of threads, each one
2529          * using a single descriptor.
2530          */
2531         for (i = 0; i < g->nthreads; i++) {
2532                 uint64_t seed = (uint64_t)time(0) | ((uint64_t)time(0) << 32);
2533                 t = &targs[i];
2534
2535                 bzero(t, sizeof(*t));
2536                 t->fd = -1; /* default, with pcap */
2537                 t->g = g;
2538                 memcpy(t->seed, &seed, sizeof(t->seed));
2539
2540                 if (g->dev_type == DEV_NETMAP) {
2541                         int m = -1;
2542
2543                         /*
2544                          * if the user wants both HW and SW rings, we need to
2545                          * know when to switch from NR_REG_ONE_NIC to NR_REG_ONE_SW
2546                          */
2547                         if (g->orig_mode == NR_REG_NIC_SW) {
2548                                 m = (g->td_type == TD_TYPE_RECEIVER ?
2549                                                 g->nmd->reg.nr_rx_rings :
2550                                                 g->nmd->reg.nr_tx_rings);
2551                         }
2552
2553                         if (i > 0) {
2554                                 int j;
2555                                 /* the first thread uses the fd opened by the main
2556                                  * thread, the other threads re-open /dev/netmap
2557                                  */
2558                                 t->nmd = nmport_clone(g->nmd);
2559                                 if (t->nmd == NULL)
2560                                         return -1;
2561
2562                                 j = i;
2563                                 if (m > 0 && j >= m) {
2564                                         /* switch to the software rings */
2565                                         t->nmd->reg.nr_mode = NR_REG_ONE_SW;
2566                                         j -= m;
2567                                 }
2568                                 t->nmd->reg.nr_ringid = j & NETMAP_RING_MASK;
2569                                 /* Only touch one of the rings (rx is already ok) */
2570                                 if (g->td_type == TD_TYPE_RECEIVER)
2571                                         t->nmd->reg.nr_flags |= NETMAP_NO_TX_POLL;
2572
2573                                 /* register interface. Override ifname and ringid etc. */
2574                                 if (nmport_open_desc(t->nmd) < 0) {
2575                                         nmport_undo_prepare(t->nmd);
2576                                         t->nmd = NULL;
2577                                         return -1;
2578                                 }
2579                         } else {
2580                                 t->nmd = g->nmd;
2581                         }
2582                         t->fd = t->nmd->fd;
2583                         t->frags = g->frags;
2584                 } else {
2585                         targs[i].fd = g->main_fd;
2586                 }
2587                 t->used = 1;
2588                 t->me = i;
2589                 if (g->affinity >= 0) {
2590                         t->affinity = (g->affinity + i) % g->cpus;
2591                 } else {
2592                         t->affinity = -1;
2593                 }
2594                 /* default, init packets */
2595                 initialize_packet(t);
2596         }
2597         /* Wait for PHY reset. */
2598         D("Wait %d secs for phy reset", g->wait_link);
2599         sleep(g->wait_link);
2600         D("Ready...");
2601
2602         for (i = 0; i < g->nthreads; i++) {
2603                 t = &targs[i];
2604                 if (pthread_create(&t->thread, NULL, g->td_body, t) == -1) {
2605                         D("Unable to create thread %d: %s", i, strerror(errno));
2606                         t->used = 0;
2607                 }
2608         }
2609         return 0;
2610 }
2611
2612 static void
2613 main_thread(struct glob_arg *g)
2614 {
2615         int i;
2616
2617         struct my_ctrs prev, cur;
2618         double delta_t;
2619         struct timeval tic, toc;
2620
2621         prev.pkts = prev.bytes = prev.events = 0;
2622         gettimeofday(&prev.t, NULL);
2623         for (;;) {
2624                 char b1[40], b2[40], b3[40], b4[100];
2625                 uint64_t pps, usec;
2626                 struct my_ctrs x;
2627                 double abs;
2628                 int done = 0;
2629
2630                 usec = wait_for_next_report(&prev.t, &cur.t,
2631                                 g->report_interval);
2632
2633                 cur.pkts = cur.bytes = cur.events = 0;
2634                 cur.min_space = 0;
2635                 if (usec < 10000) /* too short to be meaningful */
2636                         continue;
2637                 /* accumulate counts for all threads */
2638                 for (i = 0; i < g->nthreads; i++) {
2639                         cur.pkts += targs[i].ctr.pkts;
2640                         cur.bytes += targs[i].ctr.bytes;
2641                         cur.events += targs[i].ctr.events;
2642                         cur.min_space += targs[i].ctr.min_space;
2643                         targs[i].ctr.min_space = 99999;
2644                         if (targs[i].used == 0)
2645                                 done++;
2646                 }
2647                 x.pkts = cur.pkts - prev.pkts;
2648                 x.bytes = cur.bytes - prev.bytes;
2649                 x.events = cur.events - prev.events;
2650                 pps = (x.pkts*1000000 + usec/2) / usec;
2651                 abs = (x.events > 0) ? (x.pkts / (double) x.events) : 0;
2652
2653                 if (!(g->options & OPT_PPS_STATS)) {
2654                         strcpy(b4, "");
2655                 } else {
2656                         /* Compute some pps stats using a sliding window. */
2657                         double ppsavg = 0.0, ppsdev = 0.0;
2658                         int nsamples = 0;
2659
2660                         g->win[g->win_idx] = pps;
2661                         g->win_idx = (g->win_idx + 1) % STATS_WIN;
2662
2663                         for (i = 0; i < STATS_WIN; i++) {
2664                                 ppsavg += g->win[i];
2665                                 if (g->win[i]) {
2666                                         nsamples ++;
2667                                 }
2668                         }
2669                         ppsavg /= nsamples;
2670
2671                         for (i = 0; i < STATS_WIN; i++) {
2672                                 if (g->win[i] == 0) {
2673                                         continue;
2674                                 }
2675                                 ppsdev += (g->win[i] - ppsavg) * (g->win[i] - ppsavg);
2676                         }
2677                         ppsdev /= nsamples;
2678                         ppsdev = sqrt(ppsdev);
2679
2680                         snprintf(b4, sizeof(b4), "[avg/std %s/%s pps]",
2681                                  norm(b1, ppsavg, normalize), norm(b2, ppsdev, normalize));
2682                 }
2683
2684                 D("%spps %s(%spkts %sbps in %llu usec) %.2f avg_batch %d min_space",
2685                         norm(b1, pps, normalize), b4,
2686                         norm(b2, (double)x.pkts, normalize),
2687                         norm(b3, 1000000*((double)x.bytes*8+(double)x.pkts*g->framing)/usec, normalize),
2688                         (unsigned long long)usec,
2689                         abs, (int)cur.min_space);
2690                 prev = cur;
2691
2692                 if (done == g->nthreads)
2693                         break;
2694         }
2695
2696         timerclear(&tic);
2697         timerclear(&toc);
2698         cur.pkts = cur.bytes = cur.events = 0;
2699         /* final round */
2700         for (i = 0; i < g->nthreads; i++) {
2701                 struct timespec t_tic, t_toc;
2702                 /*
2703                  * Join active threads, unregister interfaces and close
2704                  * file descriptors.
2705                  */
2706                 if (targs[i].used)
2707                         pthread_join(targs[i].thread, NULL); /* blocking */
2708                 if (g->dev_type == DEV_NETMAP) {
2709                         nmport_close(targs[i].nmd);
2710                         targs[i].nmd = NULL;
2711                 } else {
2712                         close(targs[i].fd);
2713                 }
2714
2715                 if (targs[i].completed == 0)
2716                         D("ouch, thread %d exited with error", i);
2717
2718                 /*
2719                  * Collect threads output and extract information about
2720                  * how long it took to send all the packets.
2721                  */
2722                 cur.pkts += targs[i].ctr.pkts;
2723                 cur.bytes += targs[i].ctr.bytes;
2724                 cur.events += targs[i].ctr.events;
2725                 /* collect the largest start (tic) and end (toc) times,
2726                  * XXX maybe we should do the earliest tic, or do a weighted
2727                  * average ?
2728                  */
2729                 t_tic = timeval2spec(&tic);
2730                 t_toc = timeval2spec(&toc);
2731                 if (!timerisset(&tic) || timespec_ge(&targs[i].tic, &t_tic))
2732                         tic = timespec2val(&targs[i].tic);
2733                 if (!timerisset(&toc) || timespec_ge(&targs[i].toc, &t_toc))
2734                         toc = timespec2val(&targs[i].toc);
2735         }
2736
2737         /* print output. */
2738         timersub(&toc, &tic, &toc);
2739         delta_t = toc.tv_sec + 1e-6* toc.tv_usec;
2740         if (g->td_type == TD_TYPE_SENDER)
2741                 tx_output(g, &cur, delta_t, "Sent");
2742         else if (g->td_type == TD_TYPE_RECEIVER)
2743                 tx_output(g, &cur, delta_t, "Received");
2744 }
2745
2746 struct td_desc {
2747         int ty;
2748         const char *key;
2749         void *f;
2750         int default_burst;
2751 };
2752
2753 static struct td_desc func[] = {
2754         { TD_TYPE_RECEIVER,     "rx",           receiver_body,  512},   /* default */
2755         { TD_TYPE_SENDER,       "tx",           sender_body,    512 },
2756         { TD_TYPE_OTHER,        "ping",         ping_body,      1 },
2757         { TD_TYPE_OTHER,        "pong",         pong_body,      1 },
2758         { TD_TYPE_SENDER,       "txseq",        txseq_body,     512 },
2759         { TD_TYPE_RECEIVER,     "rxseq",        rxseq_body,     512 },
2760         { 0,                    NULL,           NULL,           0 }
2761 };
2762
2763 static int
2764 tap_alloc(char *dev)
2765 {
2766         struct ifreq ifr;
2767         int fd, err;
2768         const char *clonedev = TAP_CLONEDEV;
2769
2770         (void)err;
2771         (void)dev;
2772         /* Arguments taken by the function:
2773          *
2774          * char *dev: the name of an interface (or '\0'). MUST have enough
2775          *   space to hold the interface name if '\0' is passed
2776          * int flags: interface flags (eg, IFF_TUN etc.)
2777          */
2778
2779 #ifdef __FreeBSD__
2780         if (dev[3]) { /* tapSomething */
2781                 static char buf[128];
2782                 snprintf(buf, sizeof(buf), "/dev/%s", dev);
2783                 clonedev = buf;
2784         }
2785 #endif
2786         /* open the device */
2787         if( (fd = open(clonedev, O_RDWR)) < 0 ) {
2788                 return fd;
2789         }
2790         D("%s open successful", clonedev);
2791
2792         /* preparation of the struct ifr, of type "struct ifreq" */
2793         memset(&ifr, 0, sizeof(ifr));
2794
2795 #ifdef linux
2796         ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2797
2798         if (*dev) {
2799                 /* if a device name was specified, put it in the structure; otherwise,
2800                 * the kernel will try to allocate the "next" device of the
2801                 * specified type */
2802                 size_t len = strlen(dev);
2803                 if (len > IFNAMSIZ) {
2804                         D("%s too long", dev);
2805                         return -1;
2806                 }
2807                 memcpy(ifr.ifr_name, dev, len);
2808         }
2809
2810         /* try to create the device */
2811         if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
2812                 D("failed to do a TUNSETIFF: %s", strerror(errno));
2813                 close(fd);
2814                 return err;
2815         }
2816
2817         /* if the operation was successful, write back the name of the
2818         * interface to the variable "dev", so the caller can know
2819         * it. Note that the caller MUST reserve space in *dev (see calling
2820         * code below) */
2821         strcpy(dev, ifr.ifr_name);
2822         D("new name is %s", dev);
2823 #endif /* linux */
2824
2825         /* this is the special file descriptor that the caller will use to talk
2826          * with the virtual interface */
2827         return fd;
2828 }
2829
2830 int
2831 main(int arc, char **argv)
2832 {
2833         int i;
2834         struct sigaction sa;
2835         sigset_t ss;
2836
2837         struct glob_arg g;
2838
2839         int ch;
2840         int devqueues = 1;      /* how many device queues */
2841         int wait_link_arg = 0;
2842
2843         int pkt_size_done = 0;
2844
2845         struct td_desc *fn = func;
2846
2847         bzero(&g, sizeof(g));
2848
2849         g.main_fd = -1;
2850         g.td_body = fn->f;
2851         g.td_type = fn->ty;
2852         g.report_interval = 1000;       /* report interval */
2853         g.affinity = -1;
2854         /* ip addresses can also be a range x.x.x.x-x.x.x.y */
2855         g.af = AF_INET;         /* default */
2856         g.src_ip.name = "10.0.0.1";
2857         g.dst_ip.name = "10.1.0.1";
2858         g.dst_mac.name = "ff:ff:ff:ff:ff:ff";
2859         g.src_mac.name = NULL;
2860         g.pkt_size = 60;
2861         g.pkt_min_size = 0;
2862         g.nthreads = 1;
2863         g.cpus = 1;             /* default */
2864         g.forever = 1;
2865         g.tx_rate = 0;
2866         g.frags = 1;
2867         g.frag_size = (u_int)-1;        /* use the netmap buffer size by default */
2868         g.nmr_config = "";
2869         g.virt_header = 0;
2870         g.wait_link = 2;        /* wait 2 seconds for physical ports */
2871
2872         while ((ch = getopt(arc, argv, "46a:f:F:Nn:i:Il:d:s:D:S:b:c:o:p:"
2873             "T:w:WvR:XC:H:rP:zZAhBM:")) != -1) {
2874
2875                 switch(ch) {
2876                 default:
2877                         D("bad option %c %s", ch, optarg);
2878                         usage(-1);
2879                         break;
2880
2881                 case 'h':
2882                         usage(0);
2883                         break;
2884
2885                 case '4':
2886                         g.af = AF_INET;
2887                         break;
2888
2889                 case '6':
2890                         g.af = AF_INET6;
2891                         break;
2892
2893                 case 'N':
2894                         normalize = 0;
2895                         break;
2896
2897                 case 'n':
2898                         g.npackets = strtoull(optarg, NULL, 10);
2899                         break;
2900
2901                 case 'F':
2902                         i = atoi(optarg);
2903                         if (i < 1 || i > 63) {
2904                                 D("invalid frags %d [1..63], ignore", i);
2905                                 break;
2906                         }
2907                         g.frags = i;
2908                         break;
2909
2910                 case 'M':
2911                         g.frag_size = atoi(optarg);
2912                         break;
2913
2914                 case 'f':
2915                         for (fn = func; fn->key; fn++) {
2916                                 if (!strcmp(fn->key, optarg))
2917                                         break;
2918                         }
2919                         if (fn->key) {
2920                                 g.td_body = fn->f;
2921                                 g.td_type = fn->ty;
2922                         } else {
2923                                 D("unrecognised function %s", optarg);
2924                         }
2925                         break;
2926
2927                 case 'o':       /* data generation options */
2928                         g.options |= atoi(optarg);
2929                         break;
2930
2931                 case 'a':       /* force affinity */
2932                         g.affinity = atoi(optarg);
2933                         break;
2934
2935                 case 'i':       /* interface */
2936                         /* a prefix of tap: netmap: or pcap: forces the mode.
2937                          * otherwise we guess
2938                          */
2939                         D("interface is %s", optarg);
2940                         if (strlen(optarg) > MAX_IFNAMELEN - 8) {
2941                                 D("ifname too long %s", optarg);
2942                                 break;
2943                         }
2944                         strcpy(g.ifname, optarg);
2945                         if (!strcmp(optarg, "null")) {
2946                                 g.dev_type = DEV_NETMAP;
2947                                 g.dummy_send = 1;
2948                         } else if (!strncmp(optarg, "tap:", 4)) {
2949                                 g.dev_type = DEV_TAP;
2950                                 strcpy(g.ifname, optarg + 4);
2951                         } else if (!strncmp(optarg, "pcap:", 5)) {
2952                                 g.dev_type = DEV_PCAP;
2953                                 strcpy(g.ifname, optarg + 5);
2954                         } else if (!strncmp(optarg, "netmap:", 7) ||
2955                                    !strncmp(optarg, "vale", 4)) {
2956                                 g.dev_type = DEV_NETMAP;
2957                         } else if (!strncmp(optarg, "tap", 3)) {
2958                                 g.dev_type = DEV_TAP;
2959                         } else { /* prepend netmap: */
2960                                 g.dev_type = DEV_NETMAP;
2961                                 sprintf(g.ifname, "netmap:%s", optarg);
2962                         }
2963                         break;
2964
2965                 case 'I':
2966                         g.options |= OPT_INDIRECT;      /* use indirect buffers */
2967                         break;
2968
2969                 case 'l':       /* pkt_size */
2970                         if (pkt_size_done) {
2971                                 g.pkt_min_size = atoi(optarg);
2972                         } else {
2973                                 g.pkt_size = atoi(optarg);
2974                                 pkt_size_done = 1;
2975                         }
2976                         break;
2977
2978                 case 'd':
2979                         g.dst_ip.name = optarg;
2980                         break;
2981
2982                 case 's':
2983                         g.src_ip.name = optarg;
2984                         break;
2985
2986                 case 'T':       /* report interval */
2987                         g.report_interval = atoi(optarg);
2988                         break;
2989
2990                 case 'w':
2991                         g.wait_link = atoi(optarg);
2992                         wait_link_arg = 1;
2993                         break;
2994
2995                 case 'W':
2996                         g.forever = 0; /* exit RX with no traffic */
2997                         break;
2998
2999                 case 'b':       /* burst */
3000                         g.burst = atoi(optarg);
3001                         break;
3002                 case 'c':
3003                         g.cpus = atoi(optarg);
3004                         break;
3005                 case 'p':
3006                         g.nthreads = atoi(optarg);
3007                         break;
3008
3009                 case 'D': /* destination mac */
3010                         g.dst_mac.name = optarg;
3011                         break;
3012
3013                 case 'S': /* source mac */
3014                         g.src_mac.name = optarg;
3015                         break;
3016                 case 'v':
3017                         verbose++;
3018                         break;
3019                 case 'R':
3020                         g.tx_rate = atoi(optarg);
3021                         break;
3022                 case 'X':
3023                         g.options |= OPT_DUMP;
3024                         break;
3025                 case 'C':
3026                         D("WARNING: the 'C' option is deprecated, use the '+conf:' libnetmap option instead");
3027                         g.nmr_config = strdup(optarg);
3028                         break;
3029                 case 'H':
3030                         g.virt_header = atoi(optarg);
3031                         break;
3032                 case 'P':
3033                         g.packet_file = strdup(optarg);
3034                         break;
3035                 case 'r':
3036                         g.options |= OPT_RUBBISH;
3037                         break;
3038                 case 'z':
3039                         g.options |= OPT_RANDOM_SRC;
3040                         break;
3041                 case 'Z':
3042                         g.options |= OPT_RANDOM_DST;
3043                         break;
3044                 case 'A':
3045                         g.options |= OPT_PPS_STATS;
3046                         break;
3047                 case 'B':
3048                         /* raw packets have4 bytes crc + 20 bytes framing */
3049                         // XXX maybe add an option to pass the IFG
3050                         g.framing = 24 * 8;
3051                         break;
3052                 }
3053         }
3054
3055         if (strlen(g.ifname) <=0 ) {
3056                 D("missing ifname");
3057                 usage(-1);
3058         }
3059
3060         if (g.burst == 0) {
3061                 g.burst = fn->default_burst;
3062                 D("using default burst size: %d", g.burst);
3063         }
3064
3065         g.system_cpus = i = system_ncpus();
3066         if (g.cpus < 0 || g.cpus > i) {
3067                 D("%d cpus is too high, have only %d cpus", g.cpus, i);
3068                 usage(-1);
3069         }
3070         D("running on %d cpus (have %d)", g.cpus, i);
3071         if (g.cpus == 0)
3072                 g.cpus = i;
3073
3074         if (!wait_link_arg && !strncmp(g.ifname, "vale", 4)) {
3075                 g.wait_link = 0;
3076         }
3077
3078         if (g.pkt_size < 16 || g.pkt_size > MAX_PKTSIZE) {
3079                 D("bad pktsize %d [16..%d]\n", g.pkt_size, MAX_PKTSIZE);
3080                 usage(-1);
3081         }
3082
3083         if (g.pkt_min_size > 0 && (g.pkt_min_size < 16 || g.pkt_min_size > g.pkt_size)) {
3084                 D("bad pktminsize %d [16..%d]\n", g.pkt_min_size, g.pkt_size);
3085                 usage(-1);
3086         }
3087
3088         if (g.src_mac.name == NULL) {
3089                 static char mybuf[20] = "00:00:00:00:00:00";
3090                 /* retrieve source mac address. */
3091                 if (source_hwaddr(g.ifname, mybuf) == -1) {
3092                         D("Unable to retrieve source mac");
3093                         // continue, fail later
3094                 }
3095                 g.src_mac.name = mybuf;
3096         }
3097         /* extract address ranges */
3098         if (extract_mac_range(&g.src_mac) || extract_mac_range(&g.dst_mac))
3099                 usage(-1);
3100         g.options |= extract_ip_range(&g.src_ip, g.af);
3101         g.options |= extract_ip_range(&g.dst_ip, g.af);
3102
3103         if (g.virt_header != 0 && g.virt_header != VIRT_HDR_1
3104                         && g.virt_header != VIRT_HDR_2) {
3105                 D("bad virtio-net-header length");
3106                 usage(-1);
3107         }
3108
3109     if (g.dev_type == DEV_TAP) {
3110         D("want to use tap %s", g.ifname);
3111         g.main_fd = tap_alloc(g.ifname);
3112         if (g.main_fd < 0) {
3113                 D("cannot open tap %s", g.ifname);
3114                 usage(-1);
3115         }
3116 #ifndef NO_PCAP
3117     } else if (g.dev_type == DEV_PCAP) {
3118         char pcap_errbuf[PCAP_ERRBUF_SIZE];
3119
3120         pcap_errbuf[0] = '\0'; // init the buffer
3121         g.p = pcap_open_live(g.ifname, 256 /* XXX */, 1, 100, pcap_errbuf);
3122         if (g.p == NULL) {
3123                 D("cannot open pcap on %s", g.ifname);
3124                 usage(-1);
3125         }
3126         g.main_fd = pcap_fileno(g.p);
3127         D("using pcap on %s fileno %d", g.ifname, g.main_fd);
3128 #endif /* !NO_PCAP */
3129     } else if (g.dummy_send) { /* but DEV_NETMAP */
3130         D("using a dummy send routine");
3131     } else {
3132         g.nmd = nmport_prepare(g.ifname);
3133         if (g.nmd == NULL)
3134                 goto out;
3135
3136         parse_nmr_config(g.nmr_config, &g.nmd->reg);
3137
3138         g.nmd->reg.nr_flags |= NR_ACCEPT_VNET_HDR;
3139
3140         /*
3141          * Open the netmap device using nm_open().
3142          *
3143          * protocol stack and may cause a reset of the card,
3144          * which in turn may take some time for the PHY to
3145          * reconfigure. We do the open here to have time to reset.
3146          */
3147         g.orig_mode = g.nmd->reg.nr_mode;
3148         if (g.nthreads > 1) {
3149                 switch (g.orig_mode) {
3150                 case NR_REG_ALL_NIC:
3151                 case NR_REG_NIC_SW:
3152                         g.nmd->reg.nr_mode = NR_REG_ONE_NIC;
3153                         break;
3154                 case NR_REG_SW:
3155                         g.nmd->reg.nr_mode = NR_REG_ONE_SW;
3156                         break;
3157                 default:
3158                         break;
3159                 }
3160                 g.nmd->reg.nr_ringid = 0;
3161         }
3162         if (nmport_open_desc(g.nmd) < 0)
3163                 goto out;
3164         g.main_fd = g.nmd->fd;
3165         ND("mapped %luKB at %p", (unsigned long)(g.nmd->req.nr_memsize>>10),
3166                                 g.nmd->mem);
3167
3168         if (g.virt_header) {
3169                 /* Set the virtio-net header length, since the user asked
3170                  * for it explicitly. */
3171                 set_vnet_hdr_len(&g);
3172         } else {
3173                 /* Check whether the netmap port we opened requires us to send
3174                  * and receive frames with virtio-net header. */
3175                 get_vnet_hdr_len(&g);
3176         }
3177
3178         /* get num of queues in tx or rx */
3179         if (g.td_type == TD_TYPE_SENDER)
3180                 devqueues = g.nmd->reg.nr_tx_rings + g.nmd->reg.nr_host_tx_rings;
3181         else
3182                 devqueues = g.nmd->reg.nr_rx_rings + g.nmd->reg.nr_host_rx_rings;
3183
3184         /* validate provided nthreads. */
3185         if (g.nthreads < 1 || g.nthreads > devqueues) {
3186                 D("bad nthreads %d, have %d queues", g.nthreads, devqueues);
3187                 // continue, fail later
3188         }
3189
3190         if (g.td_type == TD_TYPE_SENDER) {
3191                 int mtu = get_if_mtu(&g);
3192
3193                 if (mtu > 0 && g.pkt_size > mtu) {
3194                         D("pkt_size (%d) must be <= mtu (%d)",
3195                                 g.pkt_size, mtu);
3196                         return -1;
3197                 }
3198         }
3199
3200         if (verbose) {
3201                 struct netmap_if *nifp = g.nmd->nifp;
3202                 struct nmreq_register *req = &g.nmd->reg;
3203
3204                 D("nifp at offset %"PRIu64" ntxqs %d nrxqs %d memid %d",
3205                     req->nr_offset, req->nr_tx_rings, req->nr_rx_rings,
3206                     req->nr_mem_id);
3207                 for (i = 0; i < req->nr_tx_rings + req->nr_host_tx_rings; i++) {
3208                         struct netmap_ring *ring = NETMAP_TXRING(nifp, i);
3209                         D("   TX%d at offset %p slots %d", i,
3210                             (void *)((char *)ring - (char *)nifp), ring->num_slots);
3211                 }
3212                 for (i = 0; i < req->nr_rx_rings + req->nr_host_rx_rings; i++) {
3213                         struct netmap_ring *ring = NETMAP_RXRING(nifp, i);
3214                         D("   RX%d at offset %p slots %d", i,
3215                             (void *)((char *)ring - (char *)nifp), ring->num_slots);
3216                 }
3217         }
3218
3219         /* Print some debug information. */
3220         fprintf(stdout,
3221                 "%s %s: %d queues, %d threads and %d cpus.\n",
3222                 (g.td_type == TD_TYPE_SENDER) ? "Sending on" :
3223                         ((g.td_type == TD_TYPE_RECEIVER) ? "Receiving from" :
3224                         "Working on"),
3225                 g.ifname,
3226                 devqueues,
3227                 g.nthreads,
3228                 g.cpus);
3229         if (g.td_type == TD_TYPE_SENDER) {
3230                 fprintf(stdout, "%s -> %s (%s -> %s)\n",
3231                         g.src_ip.name, g.dst_ip.name,
3232                         g.src_mac.name, g.dst_mac.name);
3233         }
3234
3235 out:
3236         /* Exit if something went wrong. */
3237         if (g.main_fd < 0) {
3238                 D("aborting");
3239                 usage(-1);
3240         }
3241     }
3242
3243
3244         if (g.options) {
3245                 D("--- SPECIAL OPTIONS:%s%s%s%s%s%s\n",
3246                         g.options & OPT_PREFETCH ? " prefetch" : "",
3247                         g.options & OPT_ACCESS ? " access" : "",
3248                         g.options & OPT_MEMCPY ? " memcpy" : "",
3249                         g.options & OPT_INDIRECT ? " indirect" : "",
3250                         g.options & OPT_COPY ? " copy" : "",
3251                         g.options & OPT_RUBBISH ? " rubbish " : "");
3252         }
3253
3254         g.tx_period.tv_sec = g.tx_period.tv_nsec = 0;
3255         if (g.tx_rate > 0) {
3256                 /* try to have at least something every second,
3257                  * reducing the burst size to some 0.01s worth of data
3258                  * (but no less than one full set of fragments)
3259                  */
3260                 uint64_t x;
3261                 int lim = (g.tx_rate)/300;
3262                 if (g.burst > lim)
3263                         g.burst = lim;
3264                 if (g.burst == 0)
3265                         g.burst = 1;
3266                 x = ((uint64_t)1000000000 * (uint64_t)g.burst) / (uint64_t) g.tx_rate;
3267                 g.tx_period.tv_nsec = x;
3268                 g.tx_period.tv_sec = g.tx_period.tv_nsec / 1000000000;
3269                 g.tx_period.tv_nsec = g.tx_period.tv_nsec % 1000000000;
3270         }
3271         if (g.td_type == TD_TYPE_SENDER)
3272             D("Sending %d packets every  %ld.%09ld s",
3273                         g.burst, g.tx_period.tv_sec, g.tx_period.tv_nsec);
3274         /* Install ^C handler. */
3275         global_nthreads = g.nthreads;
3276         sigemptyset(&ss);
3277         sigaddset(&ss, SIGINT);
3278         /* block SIGINT now, so that all created threads will inherit the mask */
3279         if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0) {
3280                 D("failed to block SIGINT: %s", strerror(errno));
3281         }
3282         if (start_threads(&g) < 0)
3283                 return 1;
3284         /* Install the handler and re-enable SIGINT for the main thread */
3285         memset(&sa, 0, sizeof(sa));
3286         sa.sa_handler = sigint_h;
3287         if (sigaction(SIGINT, &sa, NULL) < 0) {
3288                 D("failed to install ^C handler: %s", strerror(errno));
3289         }
3290
3291         if (pthread_sigmask(SIG_UNBLOCK, &ss, NULL) < 0) {
3292                 D("failed to re-enable SIGINT: %s", strerror(errno));
3293         }
3294         main_thread(&g);
3295         free(targs);
3296         return 0;
3297 }
3298
3299 /* end of file */