2 * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo. All rights reserved.
3 * Copyright (C) 2013-2015 Universita` di Pisa. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
29 * $Id: pkt-gen.c 12346 2013-06-12 17:36:25Z luigi $
31 * Example program to show how to build a multithreaded packet
32 * source/sink using the netmap device.
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.
40 #define _GNU_SOURCE /* for CPU_SET() */
42 #define NETMAP_WITH_LIBS
43 #include <net/netmap_user.h>
45 #include <ctype.h> // isprint()
46 #include <unistd.h> // sysconf()
48 #include <arpa/inet.h> /* ntohs */
50 #include <sys/sysctl.h> /* sysctl */
52 #include <ifaddrs.h> /* getifaddrs */
53 #include <net/ethernet.h>
54 #include <netinet/in.h>
55 #include <netinet/ip.h>
56 #include <netinet/udp.h>
57 #include <netinet/ip6.h>
59 #define IPV6_VERSION 0x60
60 #define IPV6_DEFHLIM 64
68 #include <pcap/pcap.h>
73 static void usage(int);
76 #define cpuset_t DWORD_PTR //uint64_t
77 static inline void CPU_ZERO(cpuset_t *p)
82 static inline void CPU_SET(uint32_t i, cpuset_t *p)
87 #define pthread_setaffinity_np(a, b, c) !SetThreadAffinityMask(a, *c) //((void)a, 0)
88 #define TAP_CLONEDEV "/dev/tap"
89 #define AF_LINK 18 //defined in winsocks.h
90 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
91 #include <net/if_dl.h>
94 * Convert an ASCII representation of an ethernet address to
98 ether_aton(const char *a)
101 static struct ether_addr o;
102 unsigned int o0, o1, o2, o3, o4, o5;
104 i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o0, &o1, &o2, &o3, &o4, &o5);
116 return ((struct ether_addr *)&o);
120 * Convert a binary representation of an ethernet address to
124 ether_ntoa(const struct ether_addr *n)
129 i = sprintf(a, "%02x:%02x:%02x:%02x:%02x:%02x",
130 n->octet[0], n->octet[1], n->octet[2],
131 n->octet[3], n->octet[4], n->octet[5]);
132 return (i < 17 ? NULL : (char *)&a);
138 #define cpuset_t cpu_set_t
140 #define ifr_flagshigh ifr_flags /* only the low 16 bits here */
141 #define IFF_PPROMISC IFF_PROMISC /* IFF_PPROMISC does not exist */
142 #include <linux/ethtool.h>
143 #include <linux/sockios.h>
145 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
146 #include <netinet/ether.h> /* ether_aton */
147 #include <linux/if_packet.h> /* sockaddr_ll */
151 #include <sys/endian.h> /* le64toh */
152 #include <machine/param.h>
154 #include <pthread_np.h> /* pthread w/ affinity */
155 #include <sys/cpuset.h> /* cpu_set */
156 #include <net/if_dl.h> /* LLADDR */
157 #endif /* __FreeBSD__ */
161 #define cpuset_t uint64_t // XXX
162 static inline void CPU_ZERO(cpuset_t *p)
167 static inline void CPU_SET(uint32_t i, cpuset_t *p)
169 *p |= 1<< (i & 0x3f);
172 #define pthread_setaffinity_np(a, b, c) ((void)a, 0)
174 #define ifr_flagshigh ifr_flags // XXX
175 #define IFF_PPROMISC IFF_PROMISC
176 #include <net/if_dl.h> /* LLADDR */
177 #define clock_gettime(a,b) \
178 do {struct timespec t0 = {0,0}; *(b) = t0; } while (0)
179 #endif /* __APPLE__ */
181 static const char *default_payload = "netmap pkt-gen DIRECT payload\n"
182 "http://info.iet.unipi.it/~luigi/netmap/ ";
184 static const char *indirect_payload = "netmap pkt-gen indirect payload\n"
185 "http://info.iet.unipi.it/~luigi/netmap/ ";
187 static int verbose = 0;
188 static int normalize = 1;
190 #define VIRT_HDR_1 10 /* length of a base vnet-hdr */
191 #define VIRT_HDR_2 12 /* length of the extenede vnet-hdr */
192 #define VIRT_HDR_MAX VIRT_HDR_2
194 uint8_t fields[VIRT_HDR_MAX];
197 #define MAX_BODYSIZE 65536
200 struct virt_header vh;
201 struct ether_header eh;
206 uint8_t body[MAX_BODYSIZE]; /* hardwired */
211 uint8_t body[MAX_BODYSIZE]; /* hardwired */
214 } __attribute__((__packed__));
216 #define PKT(p, f, af) \
217 ((af) == AF_INET ? (p)->ipv4.f: (p)->ipv6.f)
223 uint32_t start, end; /* same as struct in_addr */
226 struct in6_addr start, end;
227 uint8_t sgroup, egroup;
230 uint16_t port0, port1;
235 struct ether_addr start, end;
238 /* ifname can be netmap:foo-xxxx */
239 #define MAX_IFNAMELEN 64 /* our buffer for ifname */
240 #define MAX_PKTSIZE MAX_BODYSIZE /* XXX: + IP_HDR + ETH_HDR */
242 /* compact timestamp to fit into 60 byte packet. (enough to obtain RTT) */
249 * global arguments for all threads
253 int af; /* address family AF_INET/AF_INET6 */
254 struct ip_range src_ip;
255 struct ip_range dst_ip;
256 struct mac_range dst_mac;
257 struct mac_range src_mac;
262 uint64_t npackets; /* total packets to send */
263 int frags; /* fragments per packet */
264 u_int frag_size; /* size of each fragment */
266 int cpus; /* cpus used for running */
267 int system_cpus; /* cpus on the system */
269 int options; /* testing */
270 #define OPT_PREFETCH 1
274 #define OPT_TS 16 /* add a timestamp */
275 #define OPT_INDIRECT 32 /* use indirect buffers, tx only */
276 #define OPT_DUMP 64 /* dump rx/tx traffic */
277 #define OPT_RUBBISH 256 /* send whatever the buffers contain */
278 #define OPT_RANDOM_SRC 512
279 #define OPT_RANDOM_DST 1024
280 #define OPT_PPS_STATS 2048
287 struct timespec tx_period;
292 int report_interval; /* milliseconds between prints */
293 void *(*td_body)(void *);
296 char ifname[MAX_IFNAMELEN];
297 const char *nmr_config;
299 int virt_header; /* send also the virt_header */
300 char *packet_file; /* -P option */
303 int64_t win[STATS_WIN];
305 int framing; /* #bits of framing (for bw output) */
307 enum dev_type { DEV_NONE, DEV_NETMAP, DEV_PCAP, DEV_TAP };
316 * Arguments for a new thread. The same structure is used by
317 * the source and the sink
326 /* these ought to be volatile, but they are
327 * only sampled and errors should not accumulate
331 struct timespec tic, toc;
343 static __inline uint16_t
344 cksum_add(uint16_t sum, uint16_t a)
349 return (res + (res < a));
353 extract_ipv4_addr(char *name, uint32_t *addr, uint16_t *port)
358 pp = strchr(name, ':');
359 if (pp != NULL) { /* do we have ports ? */
361 *port = (uint16_t)strtol(pp, NULL, 0);
364 inet_pton(AF_INET, name, &a);
365 *addr = ntohl(a.s_addr);
369 extract_ipv6_addr(char *name, struct in6_addr *addr, uint16_t *port,
375 * We accept IPv6 address in the following form:
376 * group@[2001:DB8::1001]:port (w/ brackets and port)
377 * group@[2001:DB8::1] (w/ brackets and w/o port)
378 * group@2001:DB8::1234 (w/o brackets and w/o port)
380 pp = strchr(name, '@');
383 *group = (uint8_t)strtol(name, NULL, 0);
390 pp = strchr(name, ']');
393 if (pp != NULL && *pp != ':')
395 if (pp != NULL) { /* do we have ports ? */
397 *port = (uint16_t)strtol(pp, NULL, 0);
399 inet_pton(AF_INET6, name, addr);
402 * extract the extremes from a range of ipv4 addresses.
403 * addr_lo[-addr_hi][:port_lo[-port_hi]]
406 extract_ip_range(struct ip_range *r, int af)
408 char *name, *ap, start[INET6_ADDRSTRLEN];
409 char end[INET6_ADDRSTRLEN];
414 D("extract IP range from %s", r->name);
416 name = strdup(r->name);
421 /* the first - splits start/end of range */
422 ap = strchr(name, '-');
425 r->port0 = 1234; /* default port */
426 if (af == AF_INET6) {
427 r->ipv6.sgroup = 7; /* default group */
428 extract_ipv6_addr(name, &r->ipv6.start, &r->port0,
431 extract_ipv4_addr(name, &r->ipv4.start, &r->port0);
434 if (af == AF_INET6) {
436 r->ipv6.egroup = r->ipv6.sgroup;
437 extract_ipv6_addr(ap, &r->ipv6.end, &r->port1,
440 r->ipv6.end = r->ipv6.start;
441 r->ipv6.egroup = r->ipv6.sgroup;
445 extract_ipv4_addr(ap, &r->ipv4.end, &r->port1);
446 if (r->ipv4.start > r->ipv4.end) {
448 r->ipv4.end = r->ipv4.start;
452 r->ipv4.end = r->ipv4.start;
455 if (r->port0 > r->port1) {
461 a.s_addr = htonl(r->ipv4.start);
462 inet_ntop(af, &a, start, sizeof(start));
463 a.s_addr = htonl(r->ipv4.end);
464 inet_ntop(af, &a, end, sizeof(end));
466 inet_ntop(af, &r->ipv6.start, start, sizeof(start));
467 inet_ntop(af, &r->ipv6.end, end, sizeof(end));
470 D("range is %s:%d to %s:%d", start, r->port0, end, r->port1);
472 D("range is %d@[%s]:%d to %d@[%s]:%d", r->ipv6.sgroup,
473 start, r->port0, r->ipv6.egroup, end, r->port1);
476 if (r->port0 != r->port1 ||
477 (af == AF_INET && r->ipv4.start != r->ipv4.end) ||
479 !IN6_ARE_ADDR_EQUAL(&r->ipv6.start, &r->ipv6.end)))
485 extract_mac_range(struct mac_range *r)
487 struct ether_addr *e;
489 D("extract MAC range from %s", r->name);
491 e = ether_aton(r->name);
493 D("invalid MAC address '%s'", r->name);
496 bcopy(e, &r->start, 6);
497 bcopy(e, &r->end, 6);
499 bcopy(targ->src_mac, eh->ether_shost, 6);
500 p = index(targ->g->src_mac, '-');
502 targ->src_mac_range = atoi(p+1);
504 bcopy(ether_aton(targ->g->dst_mac), targ->dst_mac, 6);
505 bcopy(targ->dst_mac, eh->ether_dhost, 6);
506 p = index(targ->g->dst_mac, '-');
508 targ->dst_mac_range = atoi(p+1);
511 D("%s starts at %s", r->name, ether_ntoa(&r->start));
516 get_if_mtu(const struct glob_arg *g)
518 char ifname[IFNAMSIZ];
522 if (!strncmp(g->ifname, "netmap:", 7) && !strchr(g->ifname, '{')
523 && !strchr(g->ifname, '}')) {
524 /* Parse the interface name and ask the kernel for the
526 strncpy(ifname, g->ifname+7, IFNAMSIZ-1);
527 ifname[strcspn(ifname, "-*^{}/@")] = '\0';
529 s = socket(AF_INET, SOCK_DGRAM, 0);
531 D("socket() failed: %s", strerror(errno));
535 memset(&ifreq, 0, sizeof(ifreq));
536 strncpy(ifreq.ifr_name, ifname, IFNAMSIZ);
538 ret = ioctl(s, SIOCGIFMTU, &ifreq);
540 D("ioctl(SIOCGIFMTU) failed: %s", strerror(errno));
543 return ifreq.ifr_mtu;
546 /* This is a pipe or a VALE port, where the MTU is very large,
547 * so we use some practical limit. */
551 static struct targ *targs;
552 static int global_nthreads;
554 /* control-C handler */
560 (void)sig; /* UNUSED */
561 D("received control-C on thread %p", (void *)pthread_self());
562 for (i = 0; i < global_nthreads; i++) {
567 /* sysctl wrapper to return the number of active CPUs */
572 #if defined (__FreeBSD__)
573 int mib[2] = { CTL_HW, HW_NCPU };
574 size_t len = sizeof(mib);
575 sysctl(mib, 2, &ncpus, &len, NULL, 0);
577 ncpus = sysconf(_SC_NPROCESSORS_ONLN);
578 #elif defined(_WIN32)
581 GetSystemInfo(&sysinfo);
582 ncpus = sysinfo.dwNumberOfProcessors;
591 #define sockaddr_dl sockaddr_ll
592 #define sdl_family sll_family
593 #define AF_LINK AF_PACKET
594 #define LLADDR(s) s->sll_addr;
595 #include <linux/if_tun.h>
596 #define TAP_CLONEDEV "/dev/net/tun"
597 #endif /* __linux__ */
600 #include <net/if_tun.h>
601 #define TAP_CLONEDEV "/dev/tap"
602 #endif /* __FreeBSD */
605 // #warning TAP not supported on apple ?
606 #include <net/if_utun.h>
607 #define TAP_CLONEDEV "/dev/tap"
608 #endif /* __APPLE__ */
612 * parse the vale configuration in conf and put it in nmr.
613 * Return the flag set if necessary.
614 * The configuration may consist of 1 to 4 numbers separated
615 * by commas: #tx-slots,#rx-slots,#tx-rings,#rx-rings.
616 * Missing numbers or zeroes stand for default values.
617 * As an additional convenience, if exactly one number
618 * is specified, then this is assigned to both #tx-slots and #rx-slots.
619 * If there is no 4th number, then the 3rd is assigned to both #tx-rings
623 parse_nmr_config(const char* conf, struct nmreq *nmr)
628 if (conf == NULL || ! *conf)
630 nmr->nr_tx_rings = nmr->nr_rx_rings = 0;
631 nmr->nr_tx_slots = nmr->nr_rx_slots = 0;
633 for (i = 0, tok = strtok(w, ","); tok; i++, tok = strtok(NULL, ",")) {
637 nmr->nr_tx_slots = nmr->nr_rx_slots = v;
640 nmr->nr_rx_slots = v;
643 nmr->nr_tx_rings = nmr->nr_rx_rings = v;
646 nmr->nr_rx_rings = v;
649 D("ignored config: %s", tok);
653 D("txr %d txd %d rxr %d rxd %d",
654 nmr->nr_tx_rings, nmr->nr_tx_slots,
655 nmr->nr_rx_rings, nmr->nr_rx_slots);
657 return (nmr->nr_tx_rings || nmr->nr_tx_slots ||
658 nmr->nr_rx_rings || nmr->nr_rx_slots) ?
659 NM_OPEN_RING_CFG : 0;
664 * locate the src mac address for our interface, put it
665 * into the user-supplied buffer. return 0 if ok, -1 on error.
668 source_hwaddr(const char *ifname, char *buf)
670 struct ifaddrs *ifaphead, *ifap;
672 if (getifaddrs(&ifaphead) != 0) {
673 D("getifaddrs %s failed", ifname);
677 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
678 struct sockaddr_dl *sdl =
679 (struct sockaddr_dl *)ifap->ifa_addr;
682 if (!sdl || sdl->sdl_family != AF_LINK)
684 if (strncmp(ifap->ifa_name, ifname, IFNAMSIZ) != 0)
686 mac = (uint8_t *)LLADDR(sdl);
687 sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
688 mac[0], mac[1], mac[2],
689 mac[3], mac[4], mac[5]);
691 D("source hwaddr %s", buf);
694 freeifaddrs(ifaphead);
699 /* set the thread affinity. */
701 setaffinity(pthread_t me, int i)
708 /* Set thread affinity affinity.*/
710 CPU_SET(i, &cpumask);
712 if (pthread_setaffinity_np(me, sizeof(cpuset_t), &cpumask) != 0) {
713 D("Unable to set affinity: %s", strerror(errno));
720 /* Compute the checksum of the given ip header. */
722 checksum(const void *data, uint16_t len, uint32_t sum)
724 const uint8_t *addr = data;
727 /* Checksum all the pairs of bytes first... */
728 for (i = 0; i < (len & ~1U); i += 2) {
729 sum += (uint16_t)ntohs(*((const uint16_t *)(addr + i)));
734 * If there's a single byte left over, checksum it, too.
735 * Network byte order is big-endian, so the remaining byte is
747 wrapsum(uint32_t sum)
753 /* Check the payload of the packet for errors (use it for debug).
754 * Look for consecutive ascii representations of the size of the packet.
757 dump_payload(const char *_p, int len, struct netmap_ring *ring, int cur)
761 const unsigned char *p = (const unsigned char *)_p;
763 /* get the length in ASCII of the length of the packet. */
765 printf("ring %p cur %5d [buf %6d flags 0x%04x len %5d]\n",
766 ring, cur, ring->slot[cur].buf_idx,
767 ring->slot[cur].flags, len);
768 /* hexdump routine */
769 for (i = 0; i < len; ) {
770 memset(buf, ' ', sizeof(buf));
771 sprintf(buf, "%5d: ", i);
773 for (j=0; j < 16 && i < len; i++, j++)
774 sprintf(buf+7+j*3, "%02x ", (uint8_t)(p[i]));
776 for (j=0; j < 16 && i < len; i++, j++)
777 sprintf(buf+7+j + 48, "%c",
778 isprint(p[i]) ? p[i] : '.');
784 * Fill a packet with some payload.
785 * We create a UDP packet so the payload starts at
786 * 14+20+8 = 42 bytes.
789 #define uh_sport source
790 #define uh_dport dest
796 update_ip(struct pkt *pkt, struct targ *t)
798 struct glob_arg *g = t->g;
801 uint32_t oaddr, naddr;
802 uint16_t oport, nport;
803 uint16_t ip_sum, udp_sum;
805 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
806 memcpy(&udp, &pkt->ipv4.udp, sizeof(udp));
808 ip_sum = udp_sum = 0;
809 naddr = oaddr = ntohl(ip.ip_src.s_addr);
810 nport = oport = ntohs(udp.uh_sport);
811 if (g->options & OPT_RANDOM_SRC) {
812 ip.ip_src.s_addr = nrand48(t->seed);
813 udp.uh_sport = nrand48(t->seed);
814 naddr = ntohl(ip.ip_src.s_addr);
815 nport = ntohs(udp.uh_sport);
818 if (oport < g->src_ip.port1) {
820 udp.uh_sport = htons(nport);
823 nport = g->src_ip.port0;
824 udp.uh_sport = htons(nport);
825 if (oaddr < g->src_ip.ipv4.end) {
827 ip.ip_src.s_addr = htonl(naddr);
830 naddr = g->src_ip.ipv4.start;
831 ip.ip_src.s_addr = htonl(naddr);
833 /* update checksums if needed */
834 if (oaddr != naddr) {
835 ip_sum = cksum_add(ip_sum, ~oaddr >> 16);
836 ip_sum = cksum_add(ip_sum, ~oaddr & 0xffff);
837 ip_sum = cksum_add(ip_sum, naddr >> 16);
838 ip_sum = cksum_add(ip_sum, naddr & 0xffff);
840 if (oport != nport) {
841 udp_sum = cksum_add(udp_sum, ~oport);
842 udp_sum = cksum_add(udp_sum, nport);
845 naddr = oaddr = ntohl(ip.ip_dst.s_addr);
846 nport = oport = ntohs(udp.uh_dport);
847 if (g->options & OPT_RANDOM_DST) {
848 ip.ip_dst.s_addr = nrand48(t->seed);
849 udp.uh_dport = nrand48(t->seed);
850 naddr = ntohl(ip.ip_dst.s_addr);
851 nport = ntohs(udp.uh_dport);
854 if (oport < g->dst_ip.port1) {
856 udp.uh_dport = htons(nport);
859 nport = g->dst_ip.port0;
860 udp.uh_dport = htons(nport);
861 if (oaddr < g->dst_ip.ipv4.end) {
863 ip.ip_dst.s_addr = htonl(naddr);
866 naddr = g->dst_ip.ipv4.start;
867 ip.ip_dst.s_addr = htonl(naddr);
869 /* update checksums */
870 if (oaddr != naddr) {
871 ip_sum = cksum_add(ip_sum, ~oaddr >> 16);
872 ip_sum = cksum_add(ip_sum, ~oaddr & 0xffff);
873 ip_sum = cksum_add(ip_sum, naddr >> 16);
874 ip_sum = cksum_add(ip_sum, naddr & 0xffff);
876 if (oport != nport) {
877 udp_sum = cksum_add(udp_sum, ~oport);
878 udp_sum = cksum_add(udp_sum, nport);
881 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(udp_sum));
883 ip.ip_sum = ~cksum_add(~ip.ip_sum, htons(ip_sum));
884 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(ip_sum));
886 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
887 memcpy(&pkt->ipv4.udp, &udp, sizeof(udp));
891 #define s6_addr16 __u6_addr.__u6_addr16
894 update_ip6(struct pkt *pkt, struct targ *t)
896 struct glob_arg *g = t->g;
900 uint16_t oaddr, naddr;
901 uint16_t oport, nport;
904 memcpy(&ip6, &pkt->ipv6.ip, sizeof(ip6));
905 memcpy(&udp, &pkt->ipv6.udp, sizeof(udp));
908 group = g->src_ip.ipv6.sgroup;
909 naddr = oaddr = ntohs(ip6.ip6_src.s6_addr16[group]);
910 nport = oport = ntohs(udp.uh_sport);
911 if (g->options & OPT_RANDOM_SRC) {
912 ip6.ip6_src.s6_addr16[group] = nrand48(t->seed);
913 udp.uh_sport = nrand48(t->seed);
914 naddr = ntohs(ip6.ip6_src.s6_addr16[group]);
915 nport = ntohs(udp.uh_sport);
918 if (oport < g->src_ip.port1) {
920 udp.uh_sport = htons(nport);
923 nport = g->src_ip.port0;
924 udp.uh_sport = htons(nport);
925 if (oaddr < ntohs(g->src_ip.ipv6.end.s6_addr16[group])) {
927 ip6.ip6_src.s6_addr16[group] = htons(naddr);
930 naddr = ntohs(g->src_ip.ipv6.start.s6_addr16[group]);
931 ip6.ip6_src.s6_addr16[group] = htons(naddr);
933 /* update checksums if needed */
935 udp_sum = cksum_add(~oaddr, naddr);
937 udp_sum = cksum_add(udp_sum,
938 cksum_add(~oport, nport));
940 group = g->dst_ip.ipv6.egroup;
941 naddr = oaddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
942 nport = oport = ntohs(udp.uh_dport);
943 if (g->options & OPT_RANDOM_DST) {
944 ip6.ip6_dst.s6_addr16[group] = nrand48(t->seed);
945 udp.uh_dport = nrand48(t->seed);
946 naddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
947 nport = ntohs(udp.uh_dport);
950 if (oport < g->dst_ip.port1) {
952 udp.uh_dport = htons(nport);
955 nport = g->dst_ip.port0;
956 udp.uh_dport = htons(nport);
957 if (oaddr < ntohs(g->dst_ip.ipv6.end.s6_addr16[group])) {
959 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
962 naddr = ntohs(g->dst_ip.ipv6.start.s6_addr16[group]);
963 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
965 /* update checksums */
967 udp_sum = cksum_add(udp_sum,
968 cksum_add(~oaddr, naddr));
970 udp_sum = cksum_add(udp_sum,
971 cksum_add(~oport, nport));
973 udp.uh_sum = ~cksum_add(~udp.uh_sum, udp_sum);
974 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
975 memcpy(&pkt->ipv6.udp, &udp, sizeof(udp));
979 update_addresses(struct pkt *pkt, struct targ *t)
982 if (t->g->af == AF_INET)
988 * initialize one packet and prepare for the next one.
989 * The copy could be done better instead of repeating it each time.
992 initialize_packet(struct targ *targ)
994 struct pkt *pkt = &targ->pkt;
995 struct ether_header *eh;
1002 const char *payload = targ->g->options & OPT_INDIRECT ?
1003 indirect_payload : default_payload;
1004 int i, l0 = strlen(payload);
1007 char errbuf[PCAP_ERRBUF_SIZE];
1009 struct pcap_pkthdr *header;
1010 const unsigned char *packet;
1012 /* Read a packet from a PCAP file if asked. */
1013 if (targ->g->packet_file != NULL) {
1014 if ((file = pcap_open_offline(targ->g->packet_file,
1016 D("failed to open pcap file %s",
1017 targ->g->packet_file);
1018 if (pcap_next_ex(file, &header, &packet) < 0)
1019 D("failed to read packet from %s",
1020 targ->g->packet_file);
1021 if ((targ->frame = malloc(header->caplen)) == NULL)
1023 bcopy(packet, (unsigned char *)targ->frame, header->caplen);
1024 targ->g->pkt_size = header->caplen;
1030 paylen = targ->g->pkt_size - sizeof(*eh) -
1031 (targ->g->af == AF_INET ? sizeof(ip): sizeof(ip6));
1033 /* create a nice NUL-terminated string */
1034 for (i = 0; i < paylen; i += l0) {
1035 if (l0 > paylen - i)
1036 l0 = paylen - i; // last round
1037 bcopy(payload, PKT(pkt, body, targ->g->af) + i, l0);
1039 PKT(pkt, body, targ->g->af)[i - 1] = '\0';
1041 /* prepare the headers */
1043 bcopy(&targ->g->src_mac.start, eh->ether_shost, 6);
1044 bcopy(&targ->g->dst_mac.start, eh->ether_dhost, 6);
1046 if (targ->g->af == AF_INET) {
1047 eh->ether_type = htons(ETHERTYPE_IP);
1048 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
1049 udp_ptr = &pkt->ipv4.udp;
1050 ip.ip_v = IPVERSION;
1051 ip.ip_hl = sizeof(ip) >> 2;
1053 ip.ip_tos = IPTOS_LOWDELAY;
1054 ip.ip_len = htons(targ->g->pkt_size - sizeof(*eh));
1056 ip.ip_off = htons(IP_DF); /* Don't fragment */
1057 ip.ip_ttl = IPDEFTTL;
1058 ip.ip_p = IPPROTO_UDP;
1059 ip.ip_dst.s_addr = htonl(targ->g->dst_ip.ipv4.start);
1060 ip.ip_src.s_addr = htonl(targ->g->src_ip.ipv4.start);
1061 ip.ip_sum = wrapsum(checksum(&ip, sizeof(ip), 0));
1062 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1064 eh->ether_type = htons(ETHERTYPE_IPV6);
1065 memcpy(&ip6, &pkt->ipv4.ip, sizeof(ip6));
1066 udp_ptr = &pkt->ipv6.udp;
1068 ip6.ip6_plen = htons(paylen);
1069 ip6.ip6_vfc = IPV6_VERSION;
1070 ip6.ip6_nxt = IPPROTO_UDP;
1071 ip6.ip6_hlim = IPV6_DEFHLIM;
1072 ip6.ip6_src = targ->g->src_ip.ipv6.start;
1073 ip6.ip6_dst = targ->g->dst_ip.ipv6.start;
1075 memcpy(&udp, udp_ptr, sizeof(udp));
1077 udp.uh_sport = htons(targ->g->src_ip.port0);
1078 udp.uh_dport = htons(targ->g->dst_ip.port0);
1079 udp.uh_ulen = htons(paylen);
1080 if (targ->g->af == AF_INET) {
1081 /* Magic: taken from sbin/dhclient/packet.c */
1082 udp.uh_sum = wrapsum(
1083 checksum(&udp, sizeof(udp), /* udp header */
1084 checksum(pkt->ipv4.body, /* udp payload */
1085 paylen - sizeof(udp),
1086 checksum(&pkt->ipv4.ip.ip_src, /* pseudo header */
1087 2 * sizeof(pkt->ipv4.ip.ip_src),
1088 IPPROTO_UDP + (u_int32_t)ntohs(udp.uh_ulen)))));
1089 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1091 /* Save part of pseudo header checksum into csum */
1092 csum = IPPROTO_UDP << 24;
1093 csum = checksum(&csum, sizeof(csum), paylen);
1094 udp.uh_sum = wrapsum(
1095 checksum(udp_ptr, sizeof(udp), /* udp header */
1096 checksum(pkt->ipv6.body, /* udp payload */
1097 paylen - sizeof(udp),
1098 checksum(&pkt->ipv6.ip.ip6_src, /* pseudo header */
1099 2 * sizeof(pkt->ipv6.ip.ip6_src), csum))));
1100 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
1102 memcpy(udp_ptr, &udp, sizeof(udp));
1104 bzero(&pkt->vh, sizeof(pkt->vh));
1105 // dump_payload((void *)pkt, targ->g->pkt_size, NULL, 0);
1109 get_vnet_hdr_len(struct glob_arg *g)
1114 memset(&req, 0, sizeof(req));
1115 bcopy(g->nmd->req.nr_name, req.nr_name, sizeof(req.nr_name));
1116 req.nr_version = NETMAP_API;
1117 req.nr_cmd = NETMAP_VNET_HDR_GET;
1118 err = ioctl(g->main_fd, NIOCREGIF, &req);
1120 D("Unable to get virtio-net header length");
1124 g->virt_header = req.nr_arg1;
1125 if (g->virt_header) {
1126 D("Port requires virtio-net header, length = %d",
1132 set_vnet_hdr_len(struct glob_arg *g)
1134 int err, l = g->virt_header;
1140 memset(&req, 0, sizeof(req));
1141 bcopy(g->nmd->req.nr_name, req.nr_name, sizeof(req.nr_name));
1142 req.nr_version = NETMAP_API;
1143 req.nr_cmd = NETMAP_BDG_VNET_HDR;
1145 err = ioctl(g->main_fd, NIOCREGIF, &req);
1147 D("Unable to set virtio-net header length %d", l);
1152 * create and enqueue a batch of packets on a ring.
1153 * On the last one set NS_REPORT to tell the driver to generate
1154 * an interrupt when done.
1157 send_packets(struct netmap_ring *ring, struct pkt *pkt, void *frame,
1158 int size, struct targ *t, u_int count, int options)
1160 u_int n, sent, head = ring->head;
1161 u_int frags = t->frags;
1162 u_int frag_size = t->frag_size;
1163 struct netmap_slot *slot = &ring->slot[head];
1165 n = nm_ring_space(ring);
1167 if (options & (OPT_COPY | OPT_PREFETCH) ) {
1168 for (sent = 0; sent < count; sent++) {
1169 struct netmap_slot *slot = &ring->slot[head];
1170 char *p = NETMAP_BUF(ring, slot->buf_idx);
1172 __builtin_prefetch(p);
1173 head = nm_ring_next(ring, head);
1178 for (sent = 0; sent < count && n >= frags; sent++, n--) {
1181 u_int tosend = size;
1183 slot = &ring->slot[head];
1184 p = NETMAP_BUF(ring, slot->buf_idx);
1185 buf_changed = slot->flags & NS_BUF_CHANGED;
1188 if (options & OPT_RUBBISH) {
1190 } else if (options & OPT_INDIRECT) {
1191 slot->flags |= NS_INDIRECT;
1192 slot->ptr = (uint64_t)((uintptr_t)frame);
1193 } else if (frags > 1) {
1195 const char *f = frame;
1197 for (i = 0; i < frags - 1; i++) {
1198 memcpy(fp, f, frag_size);
1199 slot->len = frag_size;
1200 slot->flags = NS_MOREFRAG;
1201 if (options & OPT_DUMP)
1202 dump_payload(fp, frag_size, ring, head);
1203 tosend -= frag_size;
1205 head = nm_ring_next(ring, head);
1206 slot = &ring->slot[head];
1207 fp = NETMAP_BUF(ring, slot->buf_idx);
1212 memcpy(p, f, tosend);
1213 update_addresses(pkt, t);
1214 } else if ((options & (OPT_COPY | OPT_MEMCPY)) || buf_changed) {
1215 if (options & OPT_COPY)
1216 nm_pkt_copy(frame, p, size);
1218 memcpy(p, frame, size);
1219 update_addresses(pkt, t);
1220 } else if (options & OPT_PREFETCH) {
1221 __builtin_prefetch(p);
1224 if (options & OPT_DUMP)
1225 dump_payload(p, tosend, ring, head);
1226 head = nm_ring_next(ring, head);
1229 slot->flags |= NS_REPORT;
1230 ring->head = ring->cur = head;
1233 /* tell netmap that we need more slots */
1234 ring->cur = ring->tail;
1241 * Index of the highest bit set
1246 uint64_t m = 1ULL << 63;
1249 for (i = 63; i >= 0; i--, m >>=1)
1256 * wait until ts, either busy or sleeping if more than 1ms.
1257 * Return wakeup time.
1259 static struct timespec
1260 wait_time(struct timespec ts)
1263 struct timespec w, cur;
1264 clock_gettime(CLOCK_REALTIME_PRECISE, &cur);
1265 w = timespec_sub(ts, cur);
1268 else if (w.tv_sec > 0 || w.tv_nsec > 1000000)
1274 * Send a packet, and wait for a response.
1275 * The payload (after UDP header, ofs 42) has a 4-byte sequence
1276 * followed by a struct timeval (or bintime?)
1280 ping_body(void *data)
1282 struct targ *targ = (struct targ *) data;
1283 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1284 struct netmap_if *nifp = targ->nmd->nifp;
1288 struct timespec ts, now, last_print;
1289 struct timespec nexttime = {0, 0}; /* silence compiler */
1290 uint64_t sent = 0, n = targ->g->npackets;
1291 uint64_t count = 0, t_cur, t_min = ~0, av = 0;
1292 uint64_t g_min = ~0, g_av = 0;
1293 uint64_t buckets[64]; /* bins for delays, ns */
1294 int rate_limit = targ->g->tx_rate, tosend = 0;
1296 frame = (char*)&targ->pkt + sizeof(targ->pkt.vh) - targ->g->virt_header;
1297 size = targ->g->pkt_size + targ->g->virt_header;
1300 if (targ->g->nthreads > 1) {
1301 D("can only ping with 1 thread");
1305 bzero(&buckets, sizeof(buckets));
1306 clock_gettime(CLOCK_REALTIME_PRECISE, &last_print);
1309 targ->tic = timespec_add(now, (struct timespec){2,0});
1310 targ->tic.tv_nsec = 0;
1311 wait_time(targ->tic);
1312 nexttime = targ->tic;
1314 while (!targ->cancel && (n == 0 || sent < n)) {
1315 struct netmap_ring *ring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1316 struct netmap_slot *slot;
1319 uint64_t limit, event = 0;
1321 if (rate_limit && tosend <= 0) {
1322 tosend = targ->g->burst;
1323 nexttime = timespec_add(nexttime, targ->g->tx_period);
1324 wait_time(nexttime);
1327 limit = rate_limit ? tosend : targ->g->burst;
1328 if (n > 0 && n - sent < limit)
1330 for (m = 0; (unsigned)m < limit; m++) {
1331 slot = &ring->slot[ring->head];
1333 p = NETMAP_BUF(ring, slot->buf_idx);
1335 if (nm_ring_empty(ring)) {
1336 D("-- ouch, cannot send");
1340 nm_pkt_copy(frame, p, size);
1341 clock_gettime(CLOCK_REALTIME_PRECISE, &ts);
1342 bcopy(&sent, p+42, sizeof(sent));
1343 tp = (struct tstamp *)(p+46);
1344 tp->sec = (uint32_t)ts.tv_sec;
1345 tp->nsec = (uint32_t)ts.tv_nsec;
1347 ring->head = ring->cur = nm_ring_next(ring, ring->head);
1352 targ->ctr.pkts = sent;
1353 targ->ctr.bytes = sent*size;
1354 targ->ctr.events = event;
1358 rv = ioctl(pfd.fd, NIOCTXSYNC, NULL);
1360 D("TXSYNC error on queue %d: %s", targ->me,
1364 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1366 /* should use a parameter to decide how often to send */
1367 if ( (rv = poll(&pfd, 1, 3000)) <= 0) {
1368 D("poll error on queue %d: %s", targ->me,
1369 (rv ? strerror(errno) : "timeout"));
1372 #endif /* BUSYWAIT */
1373 /* see what we got back */
1375 for (i = targ->nmd->first_rx_ring;
1376 i <= targ->nmd->last_rx_ring; i++) {
1377 ring = NETMAP_RXRING(nifp, i);
1378 while (!nm_ring_empty(ring)) {
1383 slot = &ring->slot[ring->head];
1384 p = NETMAP_BUF(ring, slot->buf_idx);
1386 clock_gettime(CLOCK_REALTIME_PRECISE, &now);
1387 bcopy(p+42, &seq, sizeof(seq));
1388 tp = (struct tstamp *)(p+46);
1389 ts.tv_sec = (time_t)tp->sec;
1390 ts.tv_nsec = (long)tp->nsec;
1391 ts.tv_sec = now.tv_sec - ts.tv_sec;
1392 ts.tv_nsec = now.tv_nsec - ts.tv_nsec;
1393 if (ts.tv_nsec < 0) {
1394 ts.tv_nsec += 1000000000;
1397 if (0) D("seq %d/%llu delta %d.%09d", seq,
1398 (unsigned long long)sent,
1399 (int)ts.tv_sec, (int)ts.tv_nsec);
1400 t_cur = ts.tv_sec * 1000000000UL + ts.tv_nsec;
1407 /* now store it in a bucket */
1408 ring->head = ring->cur = nm_ring_next(ring, ring->head);
1412 //D("tx %d rx %d", sent, rx);
1414 ts.tv_sec = now.tv_sec - last_print.tv_sec;
1415 ts.tv_nsec = now.tv_nsec - last_print.tv_nsec;
1416 if (ts.tv_nsec < 0) {
1417 ts.tv_nsec += 1000000000;
1420 if (ts.tv_sec >= 1) {
1421 D("count %d RTT: min %d av %d ns",
1422 (int)count, (int)t_min, (int)(av/count));
1423 int k, j, kmin, off;
1426 for (kmin = 0; kmin < 64; kmin ++)
1429 for (k = 63; k >= kmin; k--)
1434 for (j = kmin; j <= k; j++) {
1435 off += sprintf(buf + off, " %5d", (int)buckets[j]);
1437 D("k: %d .. %d\n\t%s", 1<<kmin, 1<<k, buf);
1438 bzero(&buckets, sizeof(buckets));
1448 if (rx < m && ts.tv_sec <= 3 && !targ->cancel)
1450 #endif /* BUSYWAIT */
1454 D("RTT over %llu packets: min %d av %d ns",
1455 (long long unsigned)sent, (int)g_min,
1456 (int)((double)g_av/sent));
1458 targ->completed = 1;
1460 /* reset the ``used`` flag. */
1468 * reply to ping requests
1471 pong_body(void *data)
1473 struct targ *targ = (struct targ *) data;
1474 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1475 struct netmap_if *nifp = targ->nmd->nifp;
1476 struct netmap_ring *txring, *rxring;
1478 uint64_t sent = 0, n = targ->g->npackets;
1480 if (targ->g->nthreads > 1) {
1481 D("can only reply ping with 1 thread");
1485 D("understood ponger %llu but don't know how to do it",
1486 (unsigned long long)n);
1487 while (!targ->cancel && (n == 0 || sent < n)) {
1488 uint32_t txhead, txavail;
1491 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1494 if ( (rv = poll(&pfd, 1, 1000)) <= 0) {
1495 D("poll error on queue %d: %s", targ->me,
1496 rv ? strerror(errno) : "timeout");
1500 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1501 txhead = txring->head;
1502 txavail = nm_ring_space(txring);
1503 /* see what we got back */
1504 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1505 rxring = NETMAP_RXRING(nifp, i);
1506 while (!nm_ring_empty(rxring)) {
1507 uint16_t *spkt, *dpkt;
1508 uint32_t head = rxring->head;
1509 struct netmap_slot *slot = &rxring->slot[head];
1511 src = NETMAP_BUF(rxring, slot->buf_idx);
1512 //D("got pkt %p of size %d", src, slot->len);
1513 rxring->head = rxring->cur = nm_ring_next(rxring, head);
1517 dst = NETMAP_BUF(txring,
1518 txring->slot[txhead].buf_idx);
1520 dpkt = (uint16_t *)dst;
1521 spkt = (uint16_t *)src;
1522 nm_pkt_copy(src, dst, slot->len);
1523 /* swap source and destination MAC */
1530 txring->slot[txhead].len = slot->len;
1531 txhead = nm_ring_next(txring, txhead);
1536 txring->head = txring->cur = txhead;
1537 targ->ctr.pkts = sent;
1539 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1541 //D("tx %d rx %d", sent, rx);
1544 targ->completed = 1;
1546 /* reset the ``used`` flag. */
1554 sender_body(void *data)
1556 struct targ *targ = (struct targ *) data;
1557 struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1558 struct netmap_if *nifp;
1559 struct netmap_ring *txring = NULL;
1561 uint64_t n = targ->g->npackets / targ->g->nthreads;
1564 int options = targ->g->options | OPT_COPY;
1565 struct timespec nexttime = { 0, 0}; // XXX silence compiler
1566 int rate_limit = targ->g->tx_rate;
1567 struct pkt *pkt = &targ->pkt;
1571 if (targ->frame == NULL) {
1572 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1573 size = targ->g->pkt_size + targ->g->virt_header;
1575 frame = targ->frame;
1576 size = targ->g->pkt_size;
1579 D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1580 if (setaffinity(targ->thread, targ->affinity))
1584 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1586 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1587 targ->tic.tv_nsec = 0;
1588 wait_time(targ->tic);
1589 nexttime = targ->tic;
1591 if (targ->g->dev_type == DEV_TAP) {
1592 D("writing to file desc %d", targ->g->main_fd);
1594 for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1595 if (write(targ->g->main_fd, frame, size) != -1)
1597 update_addresses(pkt, targ);
1599 targ->ctr.pkts = sent;
1600 targ->ctr.bytes = sent*size;
1601 targ->ctr.events = sent;
1606 } else if (targ->g->dev_type == DEV_PCAP) {
1607 pcap_t *p = targ->g->p;
1609 for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1610 if (pcap_inject(p, frame, size) != -1)
1612 update_addresses(pkt, targ);
1614 targ->ctr.pkts = sent;
1615 targ->ctr.bytes = sent*size;
1616 targ->ctr.events = sent;
1620 #endif /* NO_PCAP */
1623 u_int bufsz, frag_size = targ->g->frag_size;
1625 nifp = targ->nmd->nifp;
1626 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1627 bufsz = txring->nr_buf_size;
1628 if (bufsz < frag_size)
1630 targ->frag_size = targ->g->pkt_size / targ->frags;
1631 if (targ->frag_size > frag_size) {
1632 targ->frags = targ->g->pkt_size / frag_size;
1633 targ->frag_size = frag_size;
1634 if (targ->g->pkt_size % frag_size != 0)
1637 D("frags %u frag_size %u", targ->frags, targ->frag_size);
1638 while (!targ->cancel && (n == 0 || sent < n)) {
1641 if (rate_limit && tosend <= 0) {
1642 tosend = targ->g->burst;
1643 nexttime = timespec_add(nexttime, targ->g->tx_period);
1644 wait_time(nexttime);
1648 * wait for available room in the send queue(s)
1652 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1653 D("ioctl error on queue %d: %s", targ->me,
1657 #else /* !BUSYWAIT */
1658 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
1661 D("poll error on queue %d: %s", targ->me,
1662 rv ? strerror(errno) : "timeout");
1665 if (pfd.revents & POLLERR) {
1666 D("poll error on %d ring %d-%d", pfd.fd,
1667 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
1670 #endif /* !BUSYWAIT */
1672 * scan our queues and send on those with room
1674 if (options & OPT_COPY && sent > 100000 && !(targ->g->options & OPT_COPY) ) {
1676 options &= ~OPT_COPY;
1678 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1680 uint64_t limit = rate_limit ? tosend : targ->g->burst;
1682 if (n > 0 && n == sent)
1685 if (n > 0 && n - sent < limit)
1687 txring = NETMAP_TXRING(nifp, i);
1688 if (nm_ring_empty(txring))
1691 if (targ->g->pkt_min_size > 0) {
1692 size = nrand48(targ->seed) %
1693 (targ->g->pkt_size - targ->g->pkt_min_size) +
1694 targ->g->pkt_min_size;
1696 m = send_packets(txring, pkt, frame, size, targ,
1698 ND("limit %lu tail %d m %d",
1699 limit, txring->tail, m);
1701 if (m > 0) //XXX-ste: can m be 0?
1703 targ->ctr.pkts = sent;
1704 targ->ctr.bytes += m*size;
1705 targ->ctr.events = event;
1713 /* flush any remaining packets */
1714 if (txring != NULL) {
1715 D("flush tail %d head %d on thread %p",
1716 txring->tail, txring->head,
1717 (void *)pthread_self());
1718 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1721 /* final part: wait all the TX queues to be empty. */
1722 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1723 txring = NETMAP_TXRING(nifp, i);
1724 while (!targ->cancel && nm_tx_pending(txring)) {
1725 RD(5, "pending tx tail %d head %d on ring %d",
1726 txring->tail, txring->head, i);
1727 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1728 usleep(1); /* wait 1 tick */
1731 } /* end DEV_NETMAP */
1733 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1734 targ->completed = 1;
1735 targ->ctr.pkts = sent;
1736 targ->ctr.bytes = sent*size;
1737 targ->ctr.events = event;
1739 /* reset the ``used`` flag. */
1748 receive_pcap(u_char *user, const struct pcap_pkthdr * h,
1749 const u_char * bytes)
1751 struct my_ctrs *ctr = (struct my_ctrs *)user;
1752 (void)bytes; /* UNUSED */
1753 ctr->bytes += h->len;
1756 #endif /* !NO_PCAP */
1760 receive_packets(struct netmap_ring *ring, u_int limit, int dump, uint64_t *bytes)
1770 n = nm_ring_space(ring);
1773 for (rx = 0; rx < limit; rx++) {
1774 struct netmap_slot *slot = &ring->slot[head];
1775 char *p = NETMAP_BUF(ring, slot->buf_idx);
1777 *bytes += slot->len;
1779 dump_payload(p, slot->len, ring, head);
1780 if (!(slot->flags & NS_MOREFRAG))
1783 head = nm_ring_next(ring, head);
1785 ring->head = ring->cur = head;
1791 receiver_body(void *data)
1793 struct targ *targ = (struct targ *) data;
1794 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1795 struct netmap_if *nifp;
1796 struct netmap_ring *rxring;
1800 memset(&cur, 0, sizeof(cur));
1802 if (setaffinity(targ->thread, targ->affinity))
1805 D("reading from %s fd %d main_fd %d",
1806 targ->g->ifname, targ->fd, targ->g->main_fd);
1807 /* unbounded wait for the first packet. */
1808 for (;!targ->cancel;) {
1809 i = poll(&pfd, 1, 1000);
1810 if (i > 0 && !(pfd.revents & POLLERR))
1813 D("poll() error: %s", strerror(errno));
1816 if (pfd.revents & POLLERR) {
1820 RD(1, "waiting for initial packets, poll returns %d %d",
1823 /* main loop, exit after 1s silence */
1824 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1825 if (targ->g->dev_type == DEV_TAP) {
1826 while (!targ->cancel) {
1827 char buf[MAX_BODYSIZE];
1828 /* XXX should we poll ? */
1829 i = read(targ->g->main_fd, buf, sizeof(buf));
1832 targ->ctr.bytes += i;
1837 } else if (targ->g->dev_type == DEV_PCAP) {
1838 while (!targ->cancel) {
1839 /* XXX should we poll ? */
1840 pcap_dispatch(targ->g->p, targ->g->burst, receive_pcap,
1841 (u_char *)&targ->ctr);
1844 #endif /* !NO_PCAP */
1846 int dump = targ->g->options & OPT_DUMP;
1848 nifp = targ->nmd->nifp;
1849 while (!targ->cancel) {
1850 /* Once we started to receive packets, wait at most 1 seconds
1853 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
1854 D("ioctl error on queue %d: %s", targ->me,
1858 #else /* !BUSYWAIT */
1859 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
1860 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1861 targ->toc.tv_sec -= 1; /* Subtract timeout time. */
1865 if (pfd.revents & POLLERR) {
1869 #endif /* !BUSYWAIT */
1870 uint64_t cur_space = 0;
1871 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1874 rxring = NETMAP_RXRING(nifp, i);
1875 /* compute free space in the ring */
1876 m = rxring->head + rxring->num_slots - rxring->tail;
1877 if (m >= (int) rxring->num_slots)
1878 m -= rxring->num_slots;
1880 if (nm_ring_empty(rxring))
1883 m = receive_packets(rxring, targ->g->burst, dump, &cur.bytes);
1888 cur.min_space = targ->ctr.min_space;
1889 if (cur_space < cur.min_space)
1890 cur.min_space = cur_space;
1895 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1897 #if !defined(BUSYWAIT)
1900 targ->completed = 1;
1904 /* reset the ``used`` flag. */
1911 txseq_body(void *data)
1913 struct targ *targ = (struct targ *) data;
1914 struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1915 struct netmap_ring *ring;
1918 int options = targ->g->options | OPT_COPY;
1919 struct timespec nexttime = {0, 0};
1920 int rate_limit = targ->g->tx_rate;
1921 struct pkt *pkt = &targ->pkt;
1922 int frags = targ->g->frags;
1923 uint32_t sequence = 0;
1928 if (targ->g->nthreads > 1) {
1929 D("can only txseq ping with 1 thread");
1933 if (targ->g->npackets > 0) {
1934 D("Ignoring -n argument");
1937 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1938 size = targ->g->pkt_size + targ->g->virt_header;
1940 D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1941 if (setaffinity(targ->thread, targ->affinity))
1944 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1946 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1947 targ->tic.tv_nsec = 0;
1948 wait_time(targ->tic);
1949 nexttime = targ->tic;
1952 /* Only use the first queue. */
1953 ring = NETMAP_TXRING(targ->nmd->nifp, targ->nmd->first_tx_ring);
1955 while (!targ->cancel) {
1964 budget = targ->g->burst;
1966 } else if (budget <= 0) {
1967 budget = targ->g->burst;
1968 nexttime = timespec_add(nexttime, targ->g->tx_period);
1969 wait_time(nexttime);
1972 /* wait for available room in the send queue */
1975 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1976 D("ioctl error on queue %d: %s", targ->me,
1980 #else /* !BUSYWAIT */
1981 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
1984 D("poll error on queue %d: %s", targ->me,
1985 rv ? strerror(errno) : "timeout");
1988 if (pfd.revents & POLLERR) {
1989 D("poll error on %d ring %d-%d", pfd.fd,
1990 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
1993 #endif /* !BUSYWAIT */
1995 /* If no room poll() again. */
1996 space = nm_ring_space(ring);
2003 if (space < limit) {
2007 /* Cut off ``limit`` to make sure is multiple of ``frags``. */
2009 limit = (limit / frags) * frags;
2012 limit = sent + limit; /* Convert to absolute. */
2014 for (fcnt = frags, head = ring->head;
2015 sent < limit; sent++, sequence++) {
2016 struct netmap_slot *slot = &ring->slot[head];
2017 char *p = NETMAP_BUF(ring, slot->buf_idx);
2018 uint16_t *w = (uint16_t *)PKT(pkt, body, targ->g->af), t;
2020 memcpy(&sum, targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, sizeof(sum));
2024 PKT(pkt, body, targ->g->af)[0] = sequence >> 24;
2025 PKT(pkt, body, targ->g->af)[1] = (sequence >> 16) & 0xff;
2026 sum = ~cksum_add(~sum, cksum_add(~t, *w));
2028 PKT(pkt, body, targ->g->af)[2] = (sequence >> 8) & 0xff;
2029 PKT(pkt, body, targ->g->af)[3] = sequence & 0xff;
2030 sum = ~cksum_add(~sum, cksum_add(~t, *w));
2031 memcpy(targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, &sum, sizeof(sum));
2032 nm_pkt_copy(frame, p, size);
2033 if (fcnt == frags) {
2034 update_addresses(pkt, targ);
2037 if (options & OPT_DUMP) {
2038 dump_payload(p, size, ring, head);
2044 slot->flags |= NS_MOREFRAG;
2049 if (sent == limit - 1) {
2050 /* Make sure we don't push an incomplete
2052 assert(!(slot->flags & NS_MOREFRAG));
2053 slot->flags |= NS_REPORT;
2056 head = nm_ring_next(ring, head);
2062 ring->cur = ring->head = head;
2065 targ->ctr.pkts = sent;
2066 targ->ctr.bytes = sent * size;
2067 targ->ctr.events = event;
2070 /* flush any remaining packets */
2071 D("flush tail %d head %d on thread %p",
2072 ring->tail, ring->head,
2073 (void *)pthread_self());
2074 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2076 /* final part: wait the TX queues to become empty. */
2077 while (!targ->cancel && nm_tx_pending(ring)) {
2078 RD(5, "pending tx tail %d head %d on ring %d",
2079 ring->tail, ring->head, targ->nmd->first_tx_ring);
2080 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2081 usleep(1); /* wait 1 tick */
2084 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2085 targ->completed = 1;
2086 targ->ctr.pkts = sent;
2087 targ->ctr.bytes = sent * size;
2088 targ->ctr.events = event;
2090 /* reset the ``used`` flag. */
2098 multi_slot_to_string(struct netmap_ring *ring, unsigned int head,
2099 unsigned int nfrags, char *strbuf, size_t strbuflen)
2104 for (f = 0; f < nfrags; f++) {
2105 struct netmap_slot *slot = &ring->slot[head];
2106 int m = snprintf(strbuf, strbuflen, "|%u,%x|", slot->len,
2108 if (m >= (int)strbuflen) {
2114 head = nm_ring_next(ring, head);
2121 rxseq_body(void *data)
2123 struct targ *targ = (struct targ *) data;
2124 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
2125 int dump = targ->g->options & OPT_DUMP;
2126 struct netmap_ring *ring;
2127 unsigned int frags_exp = 1;
2129 unsigned int frags = 0;
2130 int first_packet = 1;
2132 int i, j, af, nrings;
2133 uint32_t seq, *seq_exp = NULL;
2135 memset(&cur, 0, sizeof(cur));
2137 if (setaffinity(targ->thread, targ->affinity))
2140 nrings = targ->nmd->last_rx_ring - targ->nmd->first_rx_ring + 1;
2141 seq_exp = calloc(nrings, sizeof(uint32_t));
2142 if (seq_exp == NULL) {
2143 D("failed to allocate seq array");
2147 D("reading from %s fd %d main_fd %d",
2148 targ->g->ifname, targ->fd, targ->g->main_fd);
2149 /* unbounded wait for the first packet. */
2150 for (;!targ->cancel;) {
2151 i = poll(&pfd, 1, 1000);
2152 if (i > 0 && !(pfd.revents & POLLERR))
2154 RD(1, "waiting for initial packets, poll returns %d %d",
2158 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
2161 while (!targ->cancel) {
2166 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
2167 D("ioctl error on queue %d: %s", targ->me,
2171 #else /* !BUSYWAIT */
2172 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
2173 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2174 targ->toc.tv_sec -= 1; /* Subtract timeout time. */
2178 if (pfd.revents & POLLERR) {
2182 #endif /* !BUSYWAIT */
2184 for (j = targ->nmd->first_rx_ring; j <= targ->nmd->last_rx_ring; j++) {
2185 ring = NETMAP_RXRING(targ->nmd->nifp, j);
2186 if (nm_ring_empty(ring))
2189 limit = nm_ring_space(ring);
2190 if (limit > targ->g->burst)
2191 limit = targ->g->burst;
2195 * 1) we remove the early-return optimization from
2196 * the netmap poll implementation, or
2197 * 2) pipes get NS_MOREFRAG support.
2198 * With the current netmap implementation, an experiment like
2199 * pkt-gen -i vale:1{1 -f txseq -F 9
2200 * pkt-gen -i vale:1}1 -f rxseq
2201 * would get stuck as soon as we find nm_ring_space(ring) < 9,
2202 * since here limit is rounded to 0 and
2203 * pipe rxsync is not called anymore by the poll() of this loop.
2205 if (frags_exp > 1) {
2207 /* Cut off to the closest smaller multiple. */
2208 limit = (limit / frags_exp) * frags_exp;
2209 RD(2, "LIMIT %d --> %d", o, limit);
2213 for (head = ring->head, i = 0; i < limit; i++) {
2214 struct netmap_slot *slot = &ring->slot[head];
2215 char *p = NETMAP_BUF(ring, slot->buf_idx);
2216 int len = slot->len;
2220 dump_payload(p, slot->len, ring, head);
2224 if (!(slot->flags & NS_MOREFRAG)) {
2227 } else if (frags != frags_exp) {
2229 RD(1, "Received packets with %u frags, "
2230 "expected %u, '%s'", frags, frags_exp,
2231 multi_slot_to_string(ring, head-frags+1,
2233 prbuf, sizeof(prbuf)));
2240 p -= sizeof(pkt->vh) - targ->g->virt_header;
2241 len += sizeof(pkt->vh) - targ->g->virt_header;
2242 pkt = (struct pkt *)p;
2243 if (ntohs(pkt->eh.ether_type) == ETHERTYPE_IP)
2248 if ((char *)pkt + len < ((char *)PKT(pkt, body, af)) +
2250 RD(1, "%s: packet too small (len=%u)", __func__,
2253 seq = (PKT(pkt, body, af)[0] << 24) |
2254 (PKT(pkt, body, af)[1] << 16) |
2255 (PKT(pkt, body, af)[2] << 8) |
2256 PKT(pkt, body, af)[3];
2258 /* Grab the first one, whatever it
2262 } else if (seq != seq_exp[j]) {
2263 uint32_t delta = seq - seq_exp[j];
2265 if (delta < (0xFFFFFFFF >> 1)) {
2266 RD(2, "Sequence GAP: exp %u found %u",
2269 RD(2, "Sequence OUT OF ORDER: "
2270 "exp %u found %u", seq_exp[j], seq);
2277 cur.bytes += slot->len;
2278 head = nm_ring_next(ring, head);
2282 ring->cur = ring->head = head;
2288 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2292 #endif /* !BUSYWAIT */
2293 targ->completed = 1;
2297 if (seq_exp != NULL)
2299 /* reset the ``used`` flag. */
2307 tx_output(struct glob_arg *g, struct my_ctrs *cur, double delta, const char *msg)
2309 double bw, raw_bw, pps, abs;
2310 char b1[40], b2[80], b3[80];
2313 if (cur->pkts == 0) {
2314 printf("%s nothing.\n", msg);
2318 size = (int)(cur->bytes / cur->pkts);
2320 printf("%s %llu packets %llu bytes %llu events %d bytes each in %.2f seconds.\n",
2322 (unsigned long long)cur->pkts,
2323 (unsigned long long)cur->bytes,
2324 (unsigned long long)cur->events, size, delta);
2327 if (size < 60) /* correct for min packet size */
2329 pps = cur->pkts / delta;
2330 bw = (8.0 * cur->bytes) / delta;
2331 raw_bw = (8.0 * cur->bytes + cur->pkts * g->framing) / delta;
2332 abs = cur->pkts / (double)(cur->events);
2334 printf("Speed: %spps Bandwidth: %sbps (raw %sbps). Average batch: %.2f pkts\n",
2335 norm(b1, pps, normalize), norm(b2, bw, normalize), norm(b3, raw_bw, normalize), abs);
2341 /* This usage is generated from the pkt-gen man page:
2343 * and pasted here adding the string terminators and endlines with simple
2344 * regular expressions. */
2345 const char *cmd = "pkt-gen";
2349 " -h Show program usage and exit.\n"
2352 " Name of the network interface that pkt-gen operates on. It can be a system network interface\n"
2353 " (e.g., em0), the name of a vale(4) port (e.g., valeSSS:PPP), the name of a netmap pipe or\n"
2354 " monitor, or any valid netmap port name accepted by the nm_open library function, as docu-\n"
2355 " mented in netmap(4) (NIOCREGIF section).\n"
2358 " The function to be executed by pkt-gen. Specify tx for transmission, rx for reception, ping\n"
2359 " for client-side ping-pong operation, and pong for server-side ping-pong operation.\n"
2362 " Number of iterations of the pkt-gen function (with 0 meaning infinite). In case of tx or rx,\n"
2363 " count is the number of packets to receive or transmit. In case of ping or pong, count is the\n"
2364 " number of ping-pong transactions.\n"
2367 " Packet size in bytes excluding CRC. If passed a second time, use random sizes larger or\n"
2368 " equal than the second one and lower than the first one.\n"
2371 " Transmit or receive up to burst_size packets at a time.\n"
2373 " -4 Use IPv4 addresses.\n"
2375 " -6 Use IPv6 addresses.\n"
2377 " -d dst_ip[:port[-dst_ip:port]]\n"
2378 " Destination IPv4/IPv6 address and port, single or range.\n"
2380 " -s src_ip[:port[-src_ip:port]]\n"
2381 " Source IPv4/IPv6 address and port, single or range.\n"
2384 " Destination MAC address in colon notation (e.g., aa:bb:cc:dd:ee:00).\n"
2387 " Source MAC address in colon notation.\n"
2390 " Pin the first thread of pkt-gen to a particular CPU using pthread_setaffinity_np(3). If more\n"
2391 " threads are used, they are pinned to the subsequent CPUs, one per thread.\n"
2394 " Maximum number of CPUs to use (0 means to use all the available ones).\n"
2397 " Number of threads to use. By default, only a single thread is used to handle all the netmap\n"
2398 " rings. If threads is larger than one, each thread handles a single TX ring (in tx mode), a\n"
2399 " single RX ring (in rx mode), or a TX/RX ring pair. The number of threads must be less than or\n"
2400 " equal to the number of TX (or RX) rings available in the device specified by interface.\n"
2403 " Number of milliseconds between reports.\n"
2405 " -w wait_for_link_time\n"
2406 " Number of seconds to wait before starting the pkt-gen function, useful to make sure that the\n"
2407 " network link is up. A network device driver may take some time to enter netmap mode, or to\n"
2408 " create a new transmit/receive ring pair when netmap(4) requests one.\n"
2411 " Packet transmission rate. Not setting the packet transmission rate tells pkt-gen to transmit\n"
2412 " packets as quickly as possible. On servers from 2010 onward netmap(4) is able to com-\n"
2413 " pletely use all of the bandwidth of a 10 or 40Gbps link, so this option should be used unless\n"
2414 " your intention is to saturate the link.\n"
2416 " -X Dump payload of each packet transmitted or received.\n"
2418 " -H len Add empty virtio-net-header with size 'len'. Valid sizes are 0, 10 and 12. This option is\n"
2419 " only used with Virtual Machine technologies that use virtio as a network interface.\n"
2422 " Load the packet to be transmitted from a pcap file rather than constructing it within\n"
2425 " -z Use random IPv4/IPv6 src address/port.\n"
2427 " -Z Use random IPv4/IPv6 dst address/port.\n"
2429 " -N Do not normalize units (i.e., use bps, pps instead of Mbps, Kpps, etc.).\n"
2432 " Send multi-slot packets, each one with num_frags fragments. A multi-slot packet is repre-\n"
2433 " sented by two or more consecutive netmap slots with the NS_MOREFRAG flag set (except for the\n"
2434 " last slot). This is useful to transmit or receive packets larger than the netmap buffer\n"
2438 " In multi-slot mode, frag_size specifies the size of each fragment, if smaller than the packet\n"
2439 " length divided by num_frags.\n"
2441 " -I Use indirect buffers. It is only valid for transmitting on VALE ports, and it is implemented\n"
2442 " by setting the NS_INDIRECT flag in the netmap slots.\n"
2444 " -W Exit immediately if all the RX rings are empty the first time they are examined.\n"
2446 " -v Increase the verbosity level.\n"
2448 " -r In tx mode, do not initialize packets, but send whatever the content of the uninitialized\n"
2449 " netmap buffers is (rubbish mode).\n"
2451 " -A Compute mean and standard deviation (over a sliding window) for the transmit or receive rate.\n"
2453 " -B Take Ethernet framing and CRC into account when computing the average bps. This adds 4 bytes\n"
2454 " of CRC and 20 bytes of framing to each packet.\n"
2456 " -C tx_slots[,rx_slots[,tx_rings[,rx_rings]]]\n"
2457 " Configuration in terms of number of rings and slots to be used when opening the netmap port.\n"
2458 " Such configuration has an effect on software ports created on the fly, such as VALE ports and\n"
2459 " netmap pipes. The configuration may consist of 1 to 4 numbers separated by commas: tx_slots,\n"
2460 " rx_slots, tx_rings, rx_rings. Missing numbers or zeroes stand for default values. As an\n"
2461 " additional convenience, if exactly one number is specified, then this is assigned to both\n"
2462 " tx_slots and rx_slots. If there is no fourth number, then the third one is assigned to both\n"
2463 " tx_rings and rx_rings.\n"
2465 " -o options data generation options (parsed using atoi)\n"
2470 " OPT_TS 16 (add a timestamp)\n"
2471 " OPT_INDIRECT 32 (use indirect buffers)\n"
2472 " OPT_DUMP 64 (dump rx/tx traffic)\n"
2473 " OPT_RUBBISH 256\n"
2474 " (send whatever the buffers contain)\n"
2475 " OPT_RANDOM_SRC 512\n"
2476 " OPT_RANDOM_DST 1024\n"
2477 " OPT_PPS_STATS 2048\n"
2484 start_threads(struct glob_arg *g) {
2487 targs = calloc(g->nthreads, sizeof(*targs));
2490 * Now create the desired number of threads, each one
2491 * using a single descriptor.
2493 for (i = 0; i < g->nthreads; i++) {
2494 uint64_t seed = time(0) | (time(0) << 32);
2497 bzero(t, sizeof(*t));
2498 t->fd = -1; /* default, with pcap */
2500 memcpy(t->seed, &seed, sizeof(t->seed));
2502 if (g->dev_type == DEV_NETMAP) {
2503 struct nm_desc nmd = *g->nmd; /* copy, we overwrite ringid */
2504 uint64_t nmd_flags = 0;
2508 /* the first thread uses the fd opened by the main
2509 * thread, the other threads re-open /dev/netmap
2511 if (g->nthreads > 1) {
2513 g->nmd->req.nr_flags & ~NR_REG_MASK;
2514 nmd.req.nr_flags |= NR_REG_ONE_NIC;
2515 nmd.req.nr_ringid = i;
2517 /* Only touch one of the rings (rx is already ok) */
2518 if (g->td_type == TD_TYPE_RECEIVER)
2519 nmd_flags |= NETMAP_NO_TX_POLL;
2521 /* register interface. Override ifname and ringid etc. */
2522 t->nmd = nm_open(t->g->ifname, NULL, nmd_flags |
2523 NM_OPEN_IFNAME | NM_OPEN_NO_MMAP, &nmd);
2524 if (t->nmd == NULL) {
2525 D("Unable to open %s: %s",
2526 t->g->ifname, strerror(errno));
2533 t->frags = g->frags;
2535 targs[i].fd = g->main_fd;
2539 if (g->affinity >= 0) {
2540 t->affinity = (g->affinity + i) % g->cpus;
2544 /* default, init packets */
2545 initialize_packet(t);
2547 /* Wait for PHY reset. */
2548 D("Wait %d secs for phy reset", g->wait_link);
2549 sleep(g->wait_link);
2552 for (i = 0; i < g->nthreads; i++) {
2554 if (pthread_create(&t->thread, NULL, g->td_body, t) == -1) {
2555 D("Unable to create thread %d: %s", i, strerror(errno));
2562 main_thread(struct glob_arg *g)
2566 struct my_ctrs prev, cur;
2568 struct timeval tic, toc;
2570 prev.pkts = prev.bytes = prev.events = 0;
2571 gettimeofday(&prev.t, NULL);
2573 char b1[40], b2[40], b3[40], b4[100];
2579 usec = wait_for_next_report(&prev.t, &cur.t,
2580 g->report_interval);
2582 cur.pkts = cur.bytes = cur.events = 0;
2584 if (usec < 10000) /* too short to be meaningful */
2586 /* accumulate counts for all threads */
2587 for (i = 0; i < g->nthreads; i++) {
2588 cur.pkts += targs[i].ctr.pkts;
2589 cur.bytes += targs[i].ctr.bytes;
2590 cur.events += targs[i].ctr.events;
2591 cur.min_space += targs[i].ctr.min_space;
2592 targs[i].ctr.min_space = 99999;
2593 if (targs[i].used == 0)
2596 x.pkts = cur.pkts - prev.pkts;
2597 x.bytes = cur.bytes - prev.bytes;
2598 x.events = cur.events - prev.events;
2599 pps = (x.pkts*1000000 + usec/2) / usec;
2600 abs = (x.events > 0) ? (x.pkts / (double) x.events) : 0;
2602 if (!(g->options & OPT_PPS_STATS)) {
2605 /* Compute some pps stats using a sliding window. */
2606 double ppsavg = 0.0, ppsdev = 0.0;
2609 g->win[g->win_idx] = pps;
2610 g->win_idx = (g->win_idx + 1) % STATS_WIN;
2612 for (i = 0; i < STATS_WIN; i++) {
2613 ppsavg += g->win[i];
2620 for (i = 0; i < STATS_WIN; i++) {
2621 if (g->win[i] == 0) {
2624 ppsdev += (g->win[i] - ppsavg) * (g->win[i] - ppsavg);
2627 ppsdev = sqrt(ppsdev);
2629 snprintf(b4, sizeof(b4), "[avg/std %s/%s pps]",
2630 norm(b1, ppsavg, normalize), norm(b2, ppsdev, normalize));
2633 D("%spps %s(%spkts %sbps in %llu usec) %.2f avg_batch %d min_space",
2634 norm(b1, pps, normalize), b4,
2635 norm(b2, (double)x.pkts, normalize),
2636 norm(b3, 1000000*((double)x.bytes*8+(double)x.pkts*g->framing)/usec, normalize),
2637 (unsigned long long)usec,
2638 abs, (int)cur.min_space);
2641 if (done == g->nthreads)
2647 cur.pkts = cur.bytes = cur.events = 0;
2649 for (i = 0; i < g->nthreads; i++) {
2650 struct timespec t_tic, t_toc;
2652 * Join active threads, unregister interfaces and close
2656 pthread_join(targs[i].thread, NULL); /* blocking */
2657 if (g->dev_type == DEV_NETMAP) {
2658 nm_close(targs[i].nmd);
2659 targs[i].nmd = NULL;
2664 if (targs[i].completed == 0)
2665 D("ouch, thread %d exited with error", i);
2668 * Collect threads output and extract information about
2669 * how long it took to send all the packets.
2671 cur.pkts += targs[i].ctr.pkts;
2672 cur.bytes += targs[i].ctr.bytes;
2673 cur.events += targs[i].ctr.events;
2674 /* collect the largest start (tic) and end (toc) times,
2675 * XXX maybe we should do the earliest tic, or do a weighted
2678 t_tic = timeval2spec(&tic);
2679 t_toc = timeval2spec(&toc);
2680 if (!timerisset(&tic) || timespec_ge(&targs[i].tic, &t_tic))
2681 tic = timespec2val(&targs[i].tic);
2682 if (!timerisset(&toc) || timespec_ge(&targs[i].toc, &t_toc))
2683 toc = timespec2val(&targs[i].toc);
2687 timersub(&toc, &tic, &toc);
2688 delta_t = toc.tv_sec + 1e-6* toc.tv_usec;
2689 if (g->td_type == TD_TYPE_SENDER)
2690 tx_output(g, &cur, delta_t, "Sent");
2691 else if (g->td_type == TD_TYPE_RECEIVER)
2692 tx_output(g, &cur, delta_t, "Received");
2702 static struct td_desc func[] = {
2703 { TD_TYPE_RECEIVER, "rx", receiver_body, 512}, /* default */
2704 { TD_TYPE_SENDER, "tx", sender_body, 512 },
2705 { TD_TYPE_OTHER, "ping", ping_body, 1 },
2706 { TD_TYPE_OTHER, "pong", pong_body, 1 },
2707 { TD_TYPE_SENDER, "txseq", txseq_body, 512 },
2708 { TD_TYPE_RECEIVER, "rxseq", rxseq_body, 512 },
2709 { 0, NULL, NULL, 0 }
2713 tap_alloc(char *dev)
2717 const char *clonedev = TAP_CLONEDEV;
2721 /* Arguments taken by the function:
2723 * char *dev: the name of an interface (or '\0'). MUST have enough
2724 * space to hold the interface name if '\0' is passed
2725 * int flags: interface flags (eg, IFF_TUN etc.)
2729 if (dev[3]) { /* tapSomething */
2730 static char buf[128];
2731 snprintf(buf, sizeof(buf), "/dev/%s", dev);
2735 /* open the device */
2736 if( (fd = open(clonedev, O_RDWR)) < 0 ) {
2739 D("%s open successful", clonedev);
2741 /* preparation of the struct ifr, of type "struct ifreq" */
2742 memset(&ifr, 0, sizeof(ifr));
2745 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2748 /* if a device name was specified, put it in the structure; otherwise,
2749 * the kernel will try to allocate the "next" device of the
2751 size_t len = strlen(dev);
2752 if (len > IFNAMSIZ) {
2753 D("%s too long", dev);
2756 memcpy(ifr.ifr_name, dev, len);
2759 /* try to create the device */
2760 if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
2761 D("failed to to a TUNSETIFF: %s", strerror(errno));
2766 /* if the operation was successful, write back the name of the
2767 * interface to the variable "dev", so the caller can know
2768 * it. Note that the caller MUST reserve space in *dev (see calling
2770 strcpy(dev, ifr.ifr_name);
2771 D("new name is %s", dev);
2774 /* this is the special file descriptor that the caller will use to talk
2775 * with the virtual interface */
2780 main(int arc, char **argv)
2783 struct sigaction sa;
2789 int devqueues = 1; /* how many device queues */
2790 int wait_link_arg = 0;
2792 int pkt_size_done = 0;
2794 struct td_desc *fn = func;
2796 bzero(&g, sizeof(g));
2801 g.report_interval = 1000; /* report interval */
2803 /* ip addresses can also be a range x.x.x.x-x.x.x.y */
2804 g.af = AF_INET; /* default */
2805 g.src_ip.name = "10.0.0.1";
2806 g.dst_ip.name = "10.1.0.1";
2807 g.dst_mac.name = "ff:ff:ff:ff:ff:ff";
2808 g.src_mac.name = NULL;
2812 g.cpus = 1; /* default */
2816 g.frag_size = (u_int)-1; /* use the netmap buffer size by default */
2819 g.wait_link = 2; /* wait 2 seconds for physical ports */
2821 while ((ch = getopt(arc, argv, "46a:f:F:Nn:i:Il:d:s:D:S:b:c:o:p:"
2822 "T:w:WvR:XC:H:rP:zZAhBM:")) != -1) {
2826 D("bad option %c %s", ch, optarg);
2847 g.npackets = strtoull(optarg, NULL, 10);
2852 if (i < 1 || i > 63) {
2853 D("invalid frags %d [1..63], ignore", i);
2860 g.frag_size = atoi(optarg);
2864 for (fn = func; fn->key; fn++) {
2865 if (!strcmp(fn->key, optarg))
2872 D("unrecognised function %s", optarg);
2876 case 'o': /* data generation options */
2877 g.options |= atoi(optarg);
2880 case 'a': /* force affinity */
2881 g.affinity = atoi(optarg);
2884 case 'i': /* interface */
2885 /* a prefix of tap: netmap: or pcap: forces the mode.
2886 * otherwise we guess
2888 D("interface is %s", optarg);
2889 if (strlen(optarg) > MAX_IFNAMELEN - 8) {
2890 D("ifname too long %s", optarg);
2893 strcpy(g.ifname, optarg);
2894 if (!strcmp(optarg, "null")) {
2895 g.dev_type = DEV_NETMAP;
2897 } else if (!strncmp(optarg, "tap:", 4)) {
2898 g.dev_type = DEV_TAP;
2899 strcpy(g.ifname, optarg + 4);
2900 } else if (!strncmp(optarg, "pcap:", 5)) {
2901 g.dev_type = DEV_PCAP;
2902 strcpy(g.ifname, optarg + 5);
2903 } else if (!strncmp(optarg, "netmap:", 7) ||
2904 !strncmp(optarg, "vale", 4)) {
2905 g.dev_type = DEV_NETMAP;
2906 } else if (!strncmp(optarg, "tap", 3)) {
2907 g.dev_type = DEV_TAP;
2908 } else { /* prepend netmap: */
2909 g.dev_type = DEV_NETMAP;
2910 sprintf(g.ifname, "netmap:%s", optarg);
2915 g.options |= OPT_INDIRECT; /* use indirect buffers */
2918 case 'l': /* pkt_size */
2919 if (pkt_size_done) {
2920 g.pkt_min_size = atoi(optarg);
2922 g.pkt_size = atoi(optarg);
2928 g.dst_ip.name = optarg;
2932 g.src_ip.name = optarg;
2935 case 'T': /* report interval */
2936 g.report_interval = atoi(optarg);
2940 g.wait_link = atoi(optarg);
2945 g.forever = 0; /* exit RX with no traffic */
2948 case 'b': /* burst */
2949 g.burst = atoi(optarg);
2952 g.cpus = atoi(optarg);
2955 g.nthreads = atoi(optarg);
2958 case 'D': /* destination mac */
2959 g.dst_mac.name = optarg;
2962 case 'S': /* source mac */
2963 g.src_mac.name = optarg;
2969 g.tx_rate = atoi(optarg);
2972 g.options |= OPT_DUMP;
2975 D("WARNING: the 'C' option is deprecated, use the '+conf:' libnetmap option instead");
2976 g.nmr_config = strdup(optarg);
2979 g.virt_header = atoi(optarg);
2982 g.packet_file = strdup(optarg);
2985 g.options |= OPT_RUBBISH;
2988 g.options |= OPT_RANDOM_SRC;
2991 g.options |= OPT_RANDOM_DST;
2994 g.options |= OPT_PPS_STATS;
2997 /* raw packets have4 bytes crc + 20 bytes framing */
2998 // XXX maybe add an option to pass the IFG
3004 if (strlen(g.ifname) <=0 ) {
3005 D("missing ifname");
3010 g.burst = fn->default_burst;
3011 D("using default burst size: %d", g.burst);
3014 g.system_cpus = i = system_ncpus();
3015 if (g.cpus < 0 || g.cpus > i) {
3016 D("%d cpus is too high, have only %d cpus", g.cpus, i);
3019 D("running on %d cpus (have %d)", g.cpus, i);
3023 if (!wait_link_arg && !strncmp(g.ifname, "vale", 4)) {
3027 if (g.pkt_size < 16 || g.pkt_size > MAX_PKTSIZE) {
3028 D("bad pktsize %d [16..%d]\n", g.pkt_size, MAX_PKTSIZE);
3032 if (g.pkt_min_size > 0 && (g.pkt_min_size < 16 || g.pkt_min_size > g.pkt_size)) {
3033 D("bad pktminsize %d [16..%d]\n", g.pkt_min_size, g.pkt_size);
3037 if (g.src_mac.name == NULL) {
3038 static char mybuf[20] = "00:00:00:00:00:00";
3039 /* retrieve source mac address. */
3040 if (source_hwaddr(g.ifname, mybuf) == -1) {
3041 D("Unable to retrieve source mac");
3042 // continue, fail later
3044 g.src_mac.name = mybuf;
3046 /* extract address ranges */
3047 if (extract_mac_range(&g.src_mac) || extract_mac_range(&g.dst_mac))
3049 g.options |= extract_ip_range(&g.src_ip, g.af);
3050 g.options |= extract_ip_range(&g.dst_ip, g.af);
3052 if (g.virt_header != 0 && g.virt_header != VIRT_HDR_1
3053 && g.virt_header != VIRT_HDR_2) {
3054 D("bad virtio-net-header length");
3058 if (g.dev_type == DEV_TAP) {
3059 D("want to use tap %s", g.ifname);
3060 g.main_fd = tap_alloc(g.ifname);
3061 if (g.main_fd < 0) {
3062 D("cannot open tap %s", g.ifname);
3066 } else if (g.dev_type == DEV_PCAP) {
3067 char pcap_errbuf[PCAP_ERRBUF_SIZE];
3069 pcap_errbuf[0] = '\0'; // init the buffer
3070 g.p = pcap_open_live(g.ifname, 256 /* XXX */, 1, 100, pcap_errbuf);
3072 D("cannot open pcap on %s", g.ifname);
3075 g.main_fd = pcap_fileno(g.p);
3076 D("using pcap on %s fileno %d", g.ifname, g.main_fd);
3077 #endif /* !NO_PCAP */
3078 } else if (g.dummy_send) { /* but DEV_NETMAP */
3079 D("using a dummy send routine");
3081 struct nm_desc base_nmd;
3082 char errmsg[MAXERRMSG];
3085 bzero(&base_nmd, sizeof(base_nmd));
3087 parse_nmr_config(g.nmr_config, &base_nmd.req);
3089 base_nmd.req.nr_flags |= NR_ACCEPT_VNET_HDR;
3091 if (nm_parse(g.ifname, &base_nmd, errmsg) < 0) {
3092 D("Invalid name '%s': %s", g.ifname, errmsg);
3097 * Open the netmap device using nm_open().
3099 * protocol stack and may cause a reset of the card,
3100 * which in turn may take some time for the PHY to
3101 * reconfigure. We do the open here to have time to reset.
3103 flags = NM_OPEN_IFNAME | NM_OPEN_ARG1 | NM_OPEN_ARG2 |
3104 NM_OPEN_ARG3 | NM_OPEN_RING_CFG;
3105 if (g.nthreads > 1) {
3106 base_nmd.req.nr_flags &= ~NR_REG_MASK;
3107 base_nmd.req.nr_flags |= NR_REG_ONE_NIC;
3108 base_nmd.req.nr_ringid = 0;
3110 g.nmd = nm_open(g.ifname, NULL, flags, &base_nmd);
3111 if (g.nmd == NULL) {
3112 D("Unable to open %s: %s", g.ifname, strerror(errno));
3115 g.main_fd = g.nmd->fd;
3116 D("mapped %luKB at %p", (unsigned long)(g.nmd->req.nr_memsize>>10),
3119 if (g.virt_header) {
3120 /* Set the virtio-net header length, since the user asked
3121 * for it explicitely. */
3122 set_vnet_hdr_len(&g);
3124 /* Check whether the netmap port we opened requires us to send
3125 * and receive frames with virtio-net header. */
3126 get_vnet_hdr_len(&g);
3129 /* get num of queues in tx or rx */
3130 if (g.td_type == TD_TYPE_SENDER)
3131 devqueues = g.nmd->req.nr_tx_rings;
3133 devqueues = g.nmd->req.nr_rx_rings;
3135 /* validate provided nthreads. */
3136 if (g.nthreads < 1 || g.nthreads > devqueues) {
3137 D("bad nthreads %d, have %d queues", g.nthreads, devqueues);
3138 // continue, fail later
3141 if (g.td_type == TD_TYPE_SENDER) {
3142 int mtu = get_if_mtu(&g);
3144 if (mtu > 0 && g.pkt_size > mtu) {
3145 D("pkt_size (%d) must be <= mtu (%d)",
3152 struct netmap_if *nifp = g.nmd->nifp;
3153 struct nmreq *req = &g.nmd->req;
3155 D("nifp at offset %d, %d tx %d rx region %d",
3156 req->nr_offset, req->nr_tx_rings, req->nr_rx_rings,
3158 for (i = 0; i <= req->nr_tx_rings; i++) {
3159 struct netmap_ring *ring = NETMAP_TXRING(nifp, i);
3160 D(" TX%d at 0x%p slots %d", i,
3161 (void *)((char *)ring - (char *)nifp), ring->num_slots);
3163 for (i = 0; i <= req->nr_rx_rings; i++) {
3164 struct netmap_ring *ring = NETMAP_RXRING(nifp, i);
3165 D(" RX%d at 0x%p slots %d", i,
3166 (void *)((char *)ring - (char *)nifp), ring->num_slots);
3170 /* Print some debug information. */
3172 "%s %s: %d queues, %d threads and %d cpus.\n",
3173 (g.td_type == TD_TYPE_SENDER) ? "Sending on" :
3174 ((g.td_type == TD_TYPE_RECEIVER) ? "Receiving from" :
3180 if (g.td_type == TD_TYPE_SENDER) {
3181 fprintf(stdout, "%s -> %s (%s -> %s)\n",
3182 g.src_ip.name, g.dst_ip.name,
3183 g.src_mac.name, g.dst_mac.name);
3187 /* Exit if something went wrong. */
3188 if (g.main_fd < 0) {
3196 D("--- SPECIAL OPTIONS:%s%s%s%s%s%s\n",
3197 g.options & OPT_PREFETCH ? " prefetch" : "",
3198 g.options & OPT_ACCESS ? " access" : "",
3199 g.options & OPT_MEMCPY ? " memcpy" : "",
3200 g.options & OPT_INDIRECT ? " indirect" : "",
3201 g.options & OPT_COPY ? " copy" : "",
3202 g.options & OPT_RUBBISH ? " rubbish " : "");
3205 g.tx_period.tv_sec = g.tx_period.tv_nsec = 0;
3206 if (g.tx_rate > 0) {
3207 /* try to have at least something every second,
3208 * reducing the burst size to some 0.01s worth of data
3209 * (but no less than one full set of fragments)
3212 int lim = (g.tx_rate)/300;
3217 x = ((uint64_t)1000000000 * (uint64_t)g.burst) / (uint64_t) g.tx_rate;
3218 g.tx_period.tv_nsec = x;
3219 g.tx_period.tv_sec = g.tx_period.tv_nsec / 1000000000;
3220 g.tx_period.tv_nsec = g.tx_period.tv_nsec % 1000000000;
3222 if (g.td_type == TD_TYPE_SENDER)
3223 D("Sending %d packets every %ld.%09ld s",
3224 g.burst, g.tx_period.tv_sec, g.tx_period.tv_nsec);
3225 /* Install ^C handler. */
3226 global_nthreads = g.nthreads;
3228 sigaddset(&ss, SIGINT);
3229 /* block SIGINT now, so that all created threads will inherit the mask */
3230 if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0) {
3231 D("failed to block SIGINT: %s", strerror(errno));
3234 /* Install the handler and re-enable SIGINT for the main thread */
3235 memset(&sa, 0, sizeof(sa));
3236 sa.sa_handler = sigint_h;
3237 if (sigaction(SIGINT, &sa, NULL) < 0) {
3238 D("failed to install ^C handler: %s", strerror(errno));
3241 if (pthread_sigmask(SIG_UNBLOCK, &ss, NULL) < 0) {
3242 D("failed to re-enable SIGINT: %s", strerror(errno));