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