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