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() */
41 #include <arpa/inet.h> /* ntohs */
43 #include <ctype.h> // isprint()
46 #include <ifaddrs.h> /* getifaddrs */
47 #include <libnetmap.h>
49 #include <net/ethernet.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <netinet/ip6.h>
53 #include <netinet/udp.h>
55 #include <pcap/pcap.h>
62 #include <sys/ioctl.h>
65 #if !defined(_WIN32) && !defined(linux)
66 #include <sys/sysctl.h> /* sysctl */
68 #include <sys/types.h>
69 #include <unistd.h> // sysconf()
71 #define IPV6_VERSION 0x60
72 #define IPV6_DEFHLIM 64
77 static void usage(int);
80 #define cpuset_t DWORD_PTR //uint64_t
81 static inline void CPU_ZERO(cpuset_t *p)
86 static inline void CPU_SET(uint32_t i, cpuset_t *p)
91 #define pthread_setaffinity_np(a, b, c) !SetThreadAffinityMask(a, *c) //((void)a, 0)
92 #define TAP_CLONEDEV "/dev/tap"
93 #define AF_LINK 18 //defined in winsocks.h
94 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
95 #include <net/if_dl.h>
98 * Convert an ASCII representation of an ethernet address to
102 ether_aton(const char *a)
105 static struct ether_addr o;
106 unsigned int o0, o1, o2, o3, o4, o5;
108 i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o0, &o1, &o2, &o3, &o4, &o5);
120 return ((struct ether_addr *)&o);
124 * Convert a binary representation of an ethernet address to
128 ether_ntoa(const struct ether_addr *n)
133 i = sprintf(a, "%02x:%02x:%02x:%02x:%02x:%02x",
134 n->octet[0], n->octet[1], n->octet[2],
135 n->octet[3], n->octet[4], n->octet[5]);
136 return (i < 17 ? NULL : (char *)&a);
142 #define cpuset_t cpu_set_t
144 #define ifr_flagshigh ifr_flags /* only the low 16 bits here */
145 #define IFF_PPROMISC IFF_PROMISC /* IFF_PPROMISC does not exist */
146 #include <linux/ethtool.h>
147 #include <linux/sockios.h>
149 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
150 #include <netinet/ether.h> /* ether_aton */
151 #include <linux/if_packet.h> /* sockaddr_ll */
155 #include <sys/endian.h> /* le64toh */
156 #include <machine/param.h>
158 #include <pthread_np.h> /* pthread w/ affinity */
159 #include <sys/cpuset.h> /* cpu_set */
160 #include <net/if_dl.h> /* LLADDR */
161 #endif /* __FreeBSD__ */
165 #define cpuset_t uint64_t // XXX
166 static inline void CPU_ZERO(cpuset_t *p)
171 static inline void CPU_SET(uint32_t i, cpuset_t *p)
173 *p |= 1<< (i & 0x3f);
176 #define pthread_setaffinity_np(a, b, c) ((void)a, 0)
178 #define ifr_flagshigh ifr_flags // XXX
179 #define IFF_PPROMISC IFF_PROMISC
180 #include <net/if_dl.h> /* LLADDR */
181 #define clock_gettime(a,b) \
182 do {struct timespec t0 = {0,0}; *(b) = t0; } while (0)
183 #endif /* __APPLE__ */
185 static const char *default_payload = "netmap pkt-gen DIRECT payload\n"
186 "http://info.iet.unipi.it/~luigi/netmap/ ";
188 static const char *indirect_payload = "netmap pkt-gen indirect payload\n"
189 "http://info.iet.unipi.it/~luigi/netmap/ ";
191 static int verbose = 0;
192 static int normalize = 1;
194 #define VIRT_HDR_1 10 /* length of a base vnet-hdr */
195 #define VIRT_HDR_2 12 /* length of the extenede vnet-hdr */
196 #define VIRT_HDR_MAX VIRT_HDR_2
198 uint8_t fields[VIRT_HDR_MAX];
201 #define MAX_BODYSIZE 65536
204 struct virt_header vh;
205 struct ether_header eh;
210 uint8_t body[MAX_BODYSIZE]; /* hardwired */
215 uint8_t body[MAX_BODYSIZE]; /* hardwired */
218 } __attribute__((__packed__));
220 #define PKT(p, f, af) \
221 ((af) == AF_INET ? (p)->ipv4.f: (p)->ipv6.f)
227 uint32_t start, end; /* same as struct in_addr */
230 struct in6_addr start, end;
231 uint8_t sgroup, egroup;
234 uint16_t port0, port1;
239 struct ether_addr start, end;
242 /* ifname can be netmap:foo-xxxx */
243 #define MAX_IFNAMELEN 512 /* our buffer for ifname */
244 //#define MAX_PKTSIZE 1536
245 #define MAX_PKTSIZE MAX_BODYSIZE /* XXX: + IP_HDR + ETH_HDR */
247 /* compact timestamp to fit into 60 byte packet. (enough to obtain RTT) */
254 * global arguments for all threads
258 int af; /* address family AF_INET/AF_INET6 */
259 struct ip_range src_ip;
260 struct ip_range dst_ip;
261 struct mac_range dst_mac;
262 struct mac_range src_mac;
267 uint64_t npackets; /* total packets to send */
268 int frags; /* fragments per packet */
269 u_int frag_size; /* size of each fragment */
271 int cpus; /* cpus used for running */
272 int system_cpus; /* cpus on the system */
274 int options; /* testing */
275 #define OPT_PREFETCH 1
279 #define OPT_TS 16 /* add a timestamp */
280 #define OPT_INDIRECT 32 /* use indirect buffers, tx only */
281 #define OPT_DUMP 64 /* dump rx/tx traffic */
282 #define OPT_RUBBISH 256 /* send whatever the buffers contain */
283 #define OPT_RANDOM_SRC 512
284 #define OPT_RANDOM_DST 1024
285 #define OPT_PPS_STATS 2048
292 struct timespec tx_period;
296 struct nmport_d *nmd;
298 int report_interval; /* milliseconds between prints */
299 void *(*td_body)(void *);
302 char ifname[MAX_IFNAMELEN];
303 const char *nmr_config;
305 int virt_header; /* send also the virt_header */
306 char *packet_file; /* -P option */
309 int64_t win[STATS_WIN];
311 int framing; /* #bits of framing (for bw output) */
313 enum dev_type { DEV_NONE, DEV_NETMAP, DEV_PCAP, DEV_TAP };
322 * Arguments for a new thread. The same structure is used by
323 * the source and the sink
331 struct nmport_d *nmd;
332 /* these ought to be volatile, but they are
333 * only sampled and errors should not accumulate
337 struct timespec tic, toc;
349 static __inline uint16_t
350 cksum_add(uint16_t sum, uint16_t a)
355 return (res + (res < a));
359 extract_ipv4_addr(char *name, uint32_t *addr, uint16_t *port)
364 pp = strchr(name, ':');
365 if (pp != NULL) { /* do we have ports ? */
367 *port = (uint16_t)strtol(pp, NULL, 0);
370 inet_pton(AF_INET, name, &a);
371 *addr = ntohl(a.s_addr);
375 extract_ipv6_addr(char *name, struct in6_addr *addr, uint16_t *port,
381 * We accept IPv6 address in the following form:
382 * group@[2001:DB8::1001]:port (w/ brackets and port)
383 * group@[2001:DB8::1] (w/ brackets and w/o port)
384 * group@2001:DB8::1234 (w/o brackets and w/o port)
386 pp = strchr(name, '@');
389 *group = (uint8_t)strtol(name, NULL, 0);
396 pp = strchr(name, ']');
399 if (pp != NULL && *pp != ':')
401 if (pp != NULL) { /* do we have ports ? */
403 *port = (uint16_t)strtol(pp, NULL, 0);
405 inet_pton(AF_INET6, name, addr);
408 * extract the extremes from a range of ipv4 addresses.
409 * addr_lo[-addr_hi][:port_lo[-port_hi]]
412 extract_ip_range(struct ip_range *r, int af)
414 char *name, *ap, start[INET6_ADDRSTRLEN];
415 char end[INET6_ADDRSTRLEN];
420 D("extract IP range from %s", r->name);
422 name = strdup(r->name);
427 /* the first - splits start/end of range */
428 ap = strchr(name, '-');
431 r->port0 = 1234; /* default port */
432 if (af == AF_INET6) {
433 r->ipv6.sgroup = 7; /* default group */
434 extract_ipv6_addr(name, &r->ipv6.start, &r->port0,
437 extract_ipv4_addr(name, &r->ipv4.start, &r->port0);
440 if (af == AF_INET6) {
442 r->ipv6.egroup = r->ipv6.sgroup;
443 extract_ipv6_addr(ap, &r->ipv6.end, &r->port1,
446 r->ipv6.end = r->ipv6.start;
447 r->ipv6.egroup = r->ipv6.sgroup;
451 extract_ipv4_addr(ap, &r->ipv4.end, &r->port1);
452 if (r->ipv4.start > r->ipv4.end) {
454 r->ipv4.end = r->ipv4.start;
458 r->ipv4.end = r->ipv4.start;
461 if (r->port0 > r->port1) {
467 a.s_addr = htonl(r->ipv4.start);
468 inet_ntop(af, &a, start, sizeof(start));
469 a.s_addr = htonl(r->ipv4.end);
470 inet_ntop(af, &a, end, sizeof(end));
472 inet_ntop(af, &r->ipv6.start, start, sizeof(start));
473 inet_ntop(af, &r->ipv6.end, end, sizeof(end));
476 D("range is %s:%d to %s:%d", start, r->port0, end, r->port1);
478 D("range is %d@[%s]:%d to %d@[%s]:%d", r->ipv6.sgroup,
479 start, r->port0, r->ipv6.egroup, end, r->port1);
482 if (r->port0 != r->port1 ||
483 (af == AF_INET && r->ipv4.start != r->ipv4.end) ||
485 !IN6_ARE_ADDR_EQUAL(&r->ipv6.start, &r->ipv6.end)))
491 extract_mac_range(struct mac_range *r)
493 struct ether_addr *e;
495 D("extract MAC range from %s", r->name);
497 e = ether_aton(r->name);
499 D("invalid MAC address '%s'", r->name);
502 bcopy(e, &r->start, 6);
503 bcopy(e, &r->end, 6);
505 bcopy(targ->src_mac, eh->ether_shost, 6);
506 p = index(targ->g->src_mac, '-');
508 targ->src_mac_range = atoi(p+1);
510 bcopy(ether_aton(targ->g->dst_mac), targ->dst_mac, 6);
511 bcopy(targ->dst_mac, eh->ether_dhost, 6);
512 p = index(targ->g->dst_mac, '-');
514 targ->dst_mac_range = atoi(p+1);
517 D("%s starts at %s", r->name, ether_ntoa(&r->start));
522 get_if_mtu(const struct glob_arg *g)
526 const char *ifname = g->nmd->hdr.nr_name;
529 if (!strncmp(g->ifname, "netmap:", 7) && !strchr(ifname, '{')
530 && !strchr(ifname, '}')) {
532 len = strlen(ifname);
534 if (len > IFNAMSIZ) {
535 D("'%s' too long, cannot ask for MTU", ifname);
539 s = socket(AF_INET, SOCK_DGRAM, 0);
541 D("socket() failed: %s", strerror(errno));
545 memset(&ifreq, 0, sizeof(ifreq));
546 memcpy(ifreq.ifr_name, ifname, len);
548 ret = ioctl(s, SIOCGIFMTU, &ifreq);
550 D("ioctl(SIOCGIFMTU) failed: %s", strerror(errno));
555 return ifreq.ifr_mtu;
558 /* This is a pipe or a VALE port, where the MTU is very large,
559 * so we use some practical limit. */
563 static struct targ *targs;
564 static int global_nthreads;
566 /* control-C handler */
572 (void)sig; /* UNUSED */
573 D("received control-C on thread %p", (void *)pthread_self());
574 for (i = 0; i < global_nthreads; i++) {
579 /* sysctl wrapper to return the number of active CPUs */
584 #if defined (__FreeBSD__)
585 int mib[2] = { CTL_HW, HW_NCPU };
586 size_t len = sizeof(mib);
587 sysctl(mib, 2, &ncpus, &len, NULL, 0);
589 ncpus = sysconf(_SC_NPROCESSORS_ONLN);
590 #elif defined(_WIN32)
593 GetSystemInfo(&sysinfo);
594 ncpus = sysinfo.dwNumberOfProcessors;
603 #define sockaddr_dl sockaddr_ll
604 #define sdl_family sll_family
605 #define AF_LINK AF_PACKET
606 #define LLADDR(s) s->sll_addr;
607 #include <linux/if_tun.h>
608 #define TAP_CLONEDEV "/dev/net/tun"
609 #endif /* __linux__ */
612 #include <net/if_tun.h>
613 #define TAP_CLONEDEV "/dev/tap"
614 #endif /* __FreeBSD */
617 // #warning TAP not supported on apple ?
618 #include <net/if_utun.h>
619 #define TAP_CLONEDEV "/dev/tap"
620 #endif /* __APPLE__ */
624 * parse the vale configuration in conf and put it in nmr.
625 * Return the flag set if necessary.
626 * The configuration may consist of 1 to 4 numbers separated
627 * by commas: #tx-slots,#rx-slots,#tx-rings,#rx-rings.
628 * Missing numbers or zeroes stand for default values.
629 * As an additional convenience, if exactly one number
630 * is specified, then this is assigned to both #tx-slots and #rx-slots.
631 * If there is no 4th number, then the 3rd is assigned to both #tx-rings
635 parse_nmr_config(const char* conf, struct nmreq_register *nmr)
640 if (conf == NULL || ! *conf)
642 nmr->nr_tx_rings = nmr->nr_rx_rings = 0;
643 nmr->nr_tx_slots = nmr->nr_rx_slots = 0;
645 for (i = 0, tok = strtok(w, ","); tok; i++, tok = strtok(NULL, ",")) {
649 nmr->nr_tx_slots = nmr->nr_rx_slots = v;
652 nmr->nr_rx_slots = v;
655 nmr->nr_tx_rings = nmr->nr_rx_rings = v;
658 nmr->nr_rx_rings = v;
661 D("ignored config: %s", tok);
665 D("txr %d txd %d rxr %d rxd %d",
666 nmr->nr_tx_rings, nmr->nr_tx_slots,
667 nmr->nr_rx_rings, nmr->nr_rx_slots);
674 * locate the src mac address for our interface, put it
675 * into the user-supplied buffer. return 0 if ok, -1 on error.
678 source_hwaddr(const char *ifname, char *buf)
680 struct ifaddrs *ifaphead, *ifap;
682 if (getifaddrs(&ifaphead) != 0) {
683 D("getifaddrs %s failed", ifname);
687 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
688 struct sockaddr_dl *sdl =
689 (struct sockaddr_dl *)ifap->ifa_addr;
692 if (!sdl || sdl->sdl_family != AF_LINK)
694 if (strncmp(ifap->ifa_name, ifname, IFNAMSIZ) != 0)
696 mac = (uint8_t *)LLADDR(sdl);
697 sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
698 mac[0], mac[1], mac[2],
699 mac[3], mac[4], mac[5]);
701 D("source hwaddr %s", buf);
704 freeifaddrs(ifaphead);
709 /* set the thread affinity. */
711 setaffinity(pthread_t me, int i)
718 /* Set thread affinity affinity.*/
720 CPU_SET(i, &cpumask);
722 if (pthread_setaffinity_np(me, sizeof(cpuset_t), &cpumask) != 0) {
723 D("Unable to set affinity: %s", strerror(errno));
730 /* Compute the checksum of the given ip header. */
732 checksum(const void *data, uint16_t len, uint32_t sum)
734 const uint8_t *addr = data;
737 /* Checksum all the pairs of bytes first... */
738 for (i = 0; i < (len & ~1U); i += 2) {
739 sum += (uint16_t)ntohs(*((const uint16_t *)(addr + i)));
744 * If there's a single byte left over, checksum it, too.
745 * Network byte order is big-endian, so the remaining byte is
757 wrapsum(uint32_t sum)
763 /* Check the payload of the packet for errors (use it for debug).
764 * Look for consecutive ascii representations of the size of the packet.
767 dump_payload(const char *_p, int len, struct netmap_ring *ring, int cur)
771 const unsigned char *p = (const unsigned char *)_p;
773 /* get the length in ASCII of the length of the packet. */
775 printf("ring %p cur %5d [buf %6d flags 0x%04x len %5d]\n",
776 ring, cur, ring->slot[cur].buf_idx,
777 ring->slot[cur].flags, len);
778 /* hexdump routine */
779 for (i = 0; i < len; ) {
780 memset(buf, ' ', sizeof(buf));
781 sprintf(buf, "%5d: ", i);
783 for (j=0; j < 16 && i < len; i++, j++)
784 sprintf(buf+7+j*3, "%02x ", (uint8_t)(p[i]));
786 for (j=0; j < 16 && i < len; i++, j++)
787 sprintf(buf+7+j + 48, "%c",
788 isprint(p[i]) ? p[i] : '.');
794 * Fill a packet with some payload.
795 * We create a UDP packet so the payload starts at
796 * 14+20+8 = 42 bytes.
799 #define uh_sport source
800 #define uh_dport dest
806 new_ip_sum(uint16_t ip_sum, uint32_t oaddr, uint32_t naddr)
808 ip_sum = cksum_add(ip_sum, ~oaddr >> 16);
809 ip_sum = cksum_add(ip_sum, ~oaddr & 0xffff);
810 ip_sum = cksum_add(ip_sum, naddr >> 16);
811 ip_sum = cksum_add(ip_sum, naddr & 0xffff);
816 new_udp_sum(uint16_t udp_sum, uint16_t oport, uint16_t nport)
818 udp_sum = cksum_add(udp_sum, ~oport);
819 udp_sum = cksum_add(udp_sum, nport);
825 update_ip(struct pkt *pkt, struct targ *t)
827 struct glob_arg *g = t->g;
830 uint32_t oaddr, naddr;
831 uint16_t oport, nport;
832 uint16_t ip_sum = 0, udp_sum = 0;
834 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
835 memcpy(&udp, &pkt->ipv4.udp, sizeof(udp));
837 ip_sum = udp_sum = 0;
838 naddr = oaddr = ntohl(ip.ip_src.s_addr);
839 nport = oport = ntohs(udp.uh_sport);
840 if (g->options & OPT_RANDOM_SRC) {
841 ip.ip_src.s_addr = nrand48(t->seed);
842 udp.uh_sport = nrand48(t->seed);
843 naddr = ntohl(ip.ip_src.s_addr);
844 nport = ntohs(udp.uh_sport);
845 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
846 udp_sum = new_udp_sum(udp_sum, oport, nport);
848 if (oport < g->src_ip.port1) {
850 udp.uh_sport = htons(nport);
851 udp_sum = new_udp_sum(udp_sum, oport, nport);
854 nport = g->src_ip.port0;
855 udp.uh_sport = htons(nport);
856 if (oaddr < g->src_ip.ipv4.end) {
858 ip.ip_src.s_addr = htonl(naddr);
859 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
862 naddr = g->src_ip.ipv4.start;
863 ip.ip_src.s_addr = htonl(naddr);
864 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
867 naddr = oaddr = ntohl(ip.ip_dst.s_addr);
868 nport = oport = ntohs(udp.uh_dport);
869 if (g->options & OPT_RANDOM_DST) {
870 ip.ip_dst.s_addr = nrand48(t->seed);
871 udp.uh_dport = nrand48(t->seed);
872 naddr = ntohl(ip.ip_dst.s_addr);
873 nport = ntohs(udp.uh_dport);
874 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
875 udp_sum = new_udp_sum(udp_sum, oport, nport);
877 if (oport < g->dst_ip.port1) {
879 udp.uh_dport = htons(nport);
880 udp_sum = new_udp_sum(udp_sum, oport, nport);
883 nport = g->dst_ip.port0;
884 udp.uh_dport = htons(nport);
885 if (oaddr < g->dst_ip.ipv4.end) {
887 ip.ip_dst.s_addr = htonl(naddr);
888 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
891 naddr = g->dst_ip.ipv4.start;
892 ip.ip_dst.s_addr = htonl(naddr);
893 ip_sum = new_ip_sum(ip_sum, oaddr, naddr);
896 /* update checksums */
898 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(udp_sum));
900 ip.ip_sum = ~cksum_add(~ip.ip_sum, htons(ip_sum));
901 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(ip_sum));
903 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
904 memcpy(&pkt->ipv4.udp, &udp, sizeof(udp));
908 #define s6_addr16 __u6_addr.__u6_addr16
911 update_ip6(struct pkt *pkt, struct targ *t)
913 struct glob_arg *g = t->g;
917 uint16_t oaddr, naddr;
918 uint16_t oport, nport;
921 memcpy(&ip6, &pkt->ipv6.ip, sizeof(ip6));
922 memcpy(&udp, &pkt->ipv6.udp, sizeof(udp));
925 group = g->src_ip.ipv6.sgroup;
926 naddr = oaddr = ntohs(ip6.ip6_src.s6_addr16[group]);
927 nport = oport = ntohs(udp.uh_sport);
928 if (g->options & OPT_RANDOM_SRC) {
929 ip6.ip6_src.s6_addr16[group] = nrand48(t->seed);
930 udp.uh_sport = nrand48(t->seed);
931 naddr = ntohs(ip6.ip6_src.s6_addr16[group]);
932 nport = ntohs(udp.uh_sport);
935 if (oport < g->src_ip.port1) {
937 udp.uh_sport = htons(nport);
940 nport = g->src_ip.port0;
941 udp.uh_sport = htons(nport);
942 if (oaddr < ntohs(g->src_ip.ipv6.end.s6_addr16[group])) {
944 ip6.ip6_src.s6_addr16[group] = htons(naddr);
947 naddr = ntohs(g->src_ip.ipv6.start.s6_addr16[group]);
948 ip6.ip6_src.s6_addr16[group] = htons(naddr);
950 /* update checksums if needed */
952 udp_sum = cksum_add(~oaddr, naddr);
954 udp_sum = cksum_add(udp_sum,
955 cksum_add(~oport, nport));
957 group = g->dst_ip.ipv6.egroup;
958 naddr = oaddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
959 nport = oport = ntohs(udp.uh_dport);
960 if (g->options & OPT_RANDOM_DST) {
961 ip6.ip6_dst.s6_addr16[group] = nrand48(t->seed);
962 udp.uh_dport = nrand48(t->seed);
963 naddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
964 nport = ntohs(udp.uh_dport);
967 if (oport < g->dst_ip.port1) {
969 udp.uh_dport = htons(nport);
972 nport = g->dst_ip.port0;
973 udp.uh_dport = htons(nport);
974 if (oaddr < ntohs(g->dst_ip.ipv6.end.s6_addr16[group])) {
976 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
979 naddr = ntohs(g->dst_ip.ipv6.start.s6_addr16[group]);
980 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
982 /* update checksums */
984 udp_sum = cksum_add(udp_sum,
985 cksum_add(~oaddr, naddr));
987 udp_sum = cksum_add(udp_sum,
988 cksum_add(~oport, nport));
990 udp.uh_sum = ~cksum_add(~udp.uh_sum, udp_sum);
991 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
992 memcpy(&pkt->ipv6.udp, &udp, sizeof(udp));
996 update_addresses(struct pkt *pkt, struct targ *t)
999 if (t->g->af == AF_INET)
1005 * initialize one packet and prepare for the next one.
1006 * The copy could be done better instead of repeating it each time.
1009 initialize_packet(struct targ *targ)
1011 struct pkt *pkt = &targ->pkt;
1012 struct ether_header *eh;
1019 const char *payload = targ->g->options & OPT_INDIRECT ?
1020 indirect_payload : default_payload;
1021 int i, l0 = strlen(payload);
1024 char errbuf[PCAP_ERRBUF_SIZE];
1026 struct pcap_pkthdr *header;
1027 const unsigned char *packet;
1029 /* Read a packet from a PCAP file if asked. */
1030 if (targ->g->packet_file != NULL) {
1031 if ((file = pcap_open_offline(targ->g->packet_file,
1033 D("failed to open pcap file %s",
1034 targ->g->packet_file);
1035 if (pcap_next_ex(file, &header, &packet) < 0)
1036 D("failed to read packet from %s",
1037 targ->g->packet_file);
1038 if ((targ->frame = malloc(header->caplen)) == NULL)
1040 bcopy(packet, (unsigned char *)targ->frame, header->caplen);
1041 targ->g->pkt_size = header->caplen;
1047 paylen = targ->g->pkt_size - sizeof(*eh) -
1048 (targ->g->af == AF_INET ? sizeof(ip): sizeof(ip6));
1050 /* create a nice NUL-terminated string */
1051 for (i = 0; i < paylen; i += l0) {
1052 if (l0 > paylen - i)
1053 l0 = paylen - i; // last round
1054 bcopy(payload, PKT(pkt, body, targ->g->af) + i, l0);
1056 PKT(pkt, body, targ->g->af)[i - 1] = '\0';
1058 /* prepare the headers */
1060 bcopy(&targ->g->src_mac.start, eh->ether_shost, 6);
1061 bcopy(&targ->g->dst_mac.start, eh->ether_dhost, 6);
1063 if (targ->g->af == AF_INET) {
1064 eh->ether_type = htons(ETHERTYPE_IP);
1065 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
1066 udp_ptr = &pkt->ipv4.udp;
1067 ip.ip_v = IPVERSION;
1068 ip.ip_hl = sizeof(ip) >> 2;
1070 ip.ip_tos = IPTOS_LOWDELAY;
1071 ip.ip_len = htons(targ->g->pkt_size - sizeof(*eh));
1073 ip.ip_off = htons(IP_DF); /* Don't fragment */
1074 ip.ip_ttl = IPDEFTTL;
1075 ip.ip_p = IPPROTO_UDP;
1076 ip.ip_dst.s_addr = htonl(targ->g->dst_ip.ipv4.start);
1077 ip.ip_src.s_addr = htonl(targ->g->src_ip.ipv4.start);
1078 ip.ip_sum = wrapsum(checksum(&ip, sizeof(ip), 0));
1079 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1081 eh->ether_type = htons(ETHERTYPE_IPV6);
1082 memcpy(&ip6, &pkt->ipv4.ip, sizeof(ip6));
1083 udp_ptr = &pkt->ipv6.udp;
1085 ip6.ip6_plen = htons(paylen);
1086 ip6.ip6_vfc = IPV6_VERSION;
1087 ip6.ip6_nxt = IPPROTO_UDP;
1088 ip6.ip6_hlim = IPV6_DEFHLIM;
1089 ip6.ip6_src = targ->g->src_ip.ipv6.start;
1090 ip6.ip6_dst = targ->g->dst_ip.ipv6.start;
1092 memcpy(&udp, udp_ptr, sizeof(udp));
1094 udp.uh_sport = htons(targ->g->src_ip.port0);
1095 udp.uh_dport = htons(targ->g->dst_ip.port0);
1096 udp.uh_ulen = htons(paylen);
1097 if (targ->g->af == AF_INET) {
1098 /* Magic: taken from sbin/dhclient/packet.c */
1099 udp.uh_sum = wrapsum(
1100 checksum(&udp, sizeof(udp), /* udp header */
1101 checksum(pkt->ipv4.body, /* udp payload */
1102 paylen - sizeof(udp),
1103 checksum(&pkt->ipv4.ip.ip_src, /* pseudo header */
1104 2 * sizeof(pkt->ipv4.ip.ip_src),
1105 IPPROTO_UDP + (u_int32_t)ntohs(udp.uh_ulen)))));
1106 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1108 /* Save part of pseudo header checksum into csum */
1109 csum = IPPROTO_UDP << 24;
1110 csum = checksum(&csum, sizeof(csum), paylen);
1111 udp.uh_sum = wrapsum(
1112 checksum(udp_ptr, sizeof(udp), /* udp header */
1113 checksum(pkt->ipv6.body, /* udp payload */
1114 paylen - sizeof(udp),
1115 checksum(&pkt->ipv6.ip.ip6_src, /* pseudo header */
1116 2 * sizeof(pkt->ipv6.ip.ip6_src), csum))));
1117 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
1119 memcpy(udp_ptr, &udp, sizeof(udp));
1121 bzero(&pkt->vh, sizeof(pkt->vh));
1122 // dump_payload((void *)pkt, targ->g->pkt_size, NULL, 0);
1126 get_vnet_hdr_len(struct glob_arg *g)
1128 struct nmreq_header hdr;
1129 struct nmreq_port_hdr ph;
1132 hdr = g->nmd->hdr; /* copy name and version */
1133 hdr.nr_reqtype = NETMAP_REQ_PORT_HDR_GET;
1135 memset(&ph, 0, sizeof(ph));
1136 hdr.nr_body = (uintptr_t)&ph;
1137 err = ioctl(g->main_fd, NIOCCTRL, &hdr);
1139 D("Unable to get virtio-net header length");
1143 g->virt_header = ph.nr_hdr_len;
1144 if (g->virt_header) {
1145 D("Port requires virtio-net header, length = %d",
1151 set_vnet_hdr_len(struct glob_arg *g)
1153 int err, l = g->virt_header;
1154 struct nmreq_header hdr;
1155 struct nmreq_port_hdr ph;
1160 hdr = g->nmd->hdr; /* copy name and version */
1161 hdr.nr_reqtype = NETMAP_REQ_PORT_HDR_SET;
1163 memset(&ph, 0, sizeof(ph));
1164 hdr.nr_body = (uintptr_t)&ph;
1165 err = ioctl(g->main_fd, NIOCCTRL, &hdr);
1167 D("Unable to set virtio-net header length %d", l);
1172 * create and enqueue a batch of packets on a ring.
1173 * On the last one set NS_REPORT to tell the driver to generate
1174 * an interrupt when done.
1177 send_packets(struct netmap_ring *ring, struct pkt *pkt, void *frame,
1178 int size, struct targ *t, u_int count, int options)
1180 u_int n, sent, head = ring->head;
1181 u_int frags = t->frags;
1182 u_int frag_size = t->frag_size;
1183 struct netmap_slot *slot = &ring->slot[head];
1185 n = nm_ring_space(ring);
1187 if (options & (OPT_COPY | OPT_PREFETCH) ) {
1188 for (sent = 0; sent < count; sent++) {
1189 struct netmap_slot *slot = &ring->slot[head];
1190 char *p = NETMAP_BUF(ring, slot->buf_idx);
1192 __builtin_prefetch(p);
1193 head = nm_ring_next(ring, head);
1198 for (sent = 0; sent < count && n >= frags; sent++, n--) {
1201 u_int tosend = size;
1203 slot = &ring->slot[head];
1204 p = NETMAP_BUF(ring, slot->buf_idx);
1205 buf_changed = slot->flags & NS_BUF_CHANGED;
1208 if (options & OPT_RUBBISH) {
1210 } else if (options & OPT_INDIRECT) {
1211 slot->flags |= NS_INDIRECT;
1212 slot->ptr = (uint64_t)((uintptr_t)frame);
1213 } else if (frags > 1) {
1215 const char *f = frame;
1217 for (i = 0; i < frags - 1; i++) {
1218 memcpy(fp, f, frag_size);
1219 slot->len = frag_size;
1220 slot->flags = NS_MOREFRAG;
1221 if (options & OPT_DUMP)
1222 dump_payload(fp, frag_size, ring, head);
1223 tosend -= frag_size;
1225 head = nm_ring_next(ring, head);
1226 slot = &ring->slot[head];
1227 fp = NETMAP_BUF(ring, slot->buf_idx);
1232 memcpy(p, f, tosend);
1233 update_addresses(pkt, t);
1234 } else if ((options & (OPT_COPY | OPT_MEMCPY)) || buf_changed) {
1235 if (options & OPT_COPY)
1236 nm_pkt_copy(frame, p, size);
1238 memcpy(p, frame, size);
1239 update_addresses(pkt, t);
1240 } else if (options & OPT_PREFETCH) {
1241 __builtin_prefetch(p);
1244 if (options & OPT_DUMP)
1245 dump_payload(p, tosend, ring, head);
1246 head = nm_ring_next(ring, head);
1249 slot->flags |= NS_REPORT;
1250 ring->head = ring->cur = head;
1253 /* tell netmap that we need more slots */
1254 ring->cur = ring->tail;
1261 * Index of the highest bit set
1266 uint64_t m = 1ULL << 63;
1269 for (i = 63; i >= 0; i--, m >>=1)
1276 * wait until ts, either busy or sleeping if more than 1ms.
1277 * Return wakeup time.
1279 static struct timespec
1280 wait_time(struct timespec ts)
1283 struct timespec w, cur;
1284 clock_gettime(CLOCK_REALTIME_PRECISE, &cur);
1285 w = timespec_sub(ts, cur);
1288 else if (w.tv_sec > 0 || w.tv_nsec > 1000000)
1294 * Send a packet, and wait for a response.
1295 * The payload (after UDP header, ofs 42) has a 4-byte sequence
1296 * followed by a struct timeval (or bintime?)
1300 ping_body(void *data)
1302 struct targ *targ = (struct targ *) data;
1303 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1304 struct netmap_if *nifp = targ->nmd->nifp;
1308 struct timespec ts, now, last_print;
1309 struct timespec nexttime = {0, 0}; /* silence compiler */
1310 uint64_t sent = 0, n = targ->g->npackets;
1311 uint64_t count = 0, t_cur, t_min = ~0, av = 0;
1312 uint64_t g_min = ~0, g_av = 0;
1313 uint64_t buckets[64]; /* bins for delays, ns */
1314 int rate_limit = targ->g->tx_rate, tosend = 0;
1316 frame = (char*)&targ->pkt + sizeof(targ->pkt.vh) - targ->g->virt_header;
1317 size = targ->g->pkt_size + targ->g->virt_header;
1320 if (targ->g->nthreads > 1) {
1321 D("can only ping with 1 thread");
1325 bzero(&buckets, sizeof(buckets));
1326 clock_gettime(CLOCK_REALTIME_PRECISE, &last_print);
1329 targ->tic = timespec_add(now, (struct timespec){2,0});
1330 targ->tic.tv_nsec = 0;
1331 wait_time(targ->tic);
1332 nexttime = targ->tic;
1334 while (!targ->cancel && (n == 0 || sent < n)) {
1335 struct netmap_ring *ring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1336 struct netmap_slot *slot;
1339 uint64_t limit, event = 0;
1341 if (rate_limit && tosend <= 0) {
1342 tosend = targ->g->burst;
1343 nexttime = timespec_add(nexttime, targ->g->tx_period);
1344 wait_time(nexttime);
1347 limit = rate_limit ? tosend : targ->g->burst;
1348 if (n > 0 && n - sent < limit)
1350 for (m = 0; (unsigned)m < limit; m++) {
1351 slot = &ring->slot[ring->head];
1353 p = NETMAP_BUF(ring, slot->buf_idx);
1355 if (nm_ring_empty(ring)) {
1356 D("-- ouch, cannot send");
1360 nm_pkt_copy(frame, p, size);
1361 clock_gettime(CLOCK_REALTIME_PRECISE, &ts);
1362 bcopy(&sent, p+42, sizeof(sent));
1363 tp = (struct tstamp *)(p+46);
1364 tp->sec = (uint32_t)ts.tv_sec;
1365 tp->nsec = (uint32_t)ts.tv_nsec;
1367 ring->head = ring->cur = nm_ring_next(ring, ring->head);
1372 targ->ctr.pkts = sent;
1373 targ->ctr.bytes = sent*size;
1374 targ->ctr.events = event;
1378 rv = ioctl(pfd.fd, NIOCTXSYNC, NULL);
1380 D("TXSYNC error on queue %d: %s", targ->me,
1384 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1386 /* should use a parameter to decide how often to send */
1387 if ( (rv = poll(&pfd, 1, 3000)) <= 0) {
1388 D("poll error on queue %d: %s", targ->me,
1389 (rv ? strerror(errno) : "timeout"));
1392 #endif /* BUSYWAIT */
1393 /* see what we got back */
1395 for (i = targ->nmd->first_rx_ring;
1396 i <= targ->nmd->last_rx_ring; i++) {
1397 ring = NETMAP_RXRING(nifp, i);
1398 while (!nm_ring_empty(ring)) {
1403 slot = &ring->slot[ring->head];
1404 p = NETMAP_BUF(ring, slot->buf_idx);
1406 clock_gettime(CLOCK_REALTIME_PRECISE, &now);
1407 bcopy(p+42, &seq, sizeof(seq));
1408 tp = (struct tstamp *)(p+46);
1409 ts.tv_sec = (time_t)tp->sec;
1410 ts.tv_nsec = (long)tp->nsec;
1411 ts.tv_sec = now.tv_sec - ts.tv_sec;
1412 ts.tv_nsec = now.tv_nsec - ts.tv_nsec;
1413 if (ts.tv_nsec < 0) {
1414 ts.tv_nsec += 1000000000;
1417 if (0) D("seq %d/%llu delta %d.%09d", seq,
1418 (unsigned long long)sent,
1419 (int)ts.tv_sec, (int)ts.tv_nsec);
1420 t_cur = ts.tv_sec * 1000000000UL + ts.tv_nsec;
1427 /* now store it in a bucket */
1428 ring->head = ring->cur = nm_ring_next(ring, ring->head);
1432 //D("tx %d rx %d", sent, rx);
1434 ts.tv_sec = now.tv_sec - last_print.tv_sec;
1435 ts.tv_nsec = now.tv_nsec - last_print.tv_nsec;
1436 if (ts.tv_nsec < 0) {
1437 ts.tv_nsec += 1000000000;
1440 if (ts.tv_sec >= 1) {
1441 D("count %d RTT: min %d av %d ns",
1442 (int)count, (int)t_min, (int)(av/count));
1443 int k, j, kmin, off;
1446 for (kmin = 0; kmin < 64; kmin ++)
1449 for (k = 63; k >= kmin; k--)
1454 for (j = kmin; j <= k; j++) {
1455 off += sprintf(buf + off, " %5d", (int)buckets[j]);
1457 D("k: %d .. %d\n\t%s", 1<<kmin, 1<<k, buf);
1458 bzero(&buckets, sizeof(buckets));
1468 if (rx < m && ts.tv_sec <= 3 && !targ->cancel)
1470 #endif /* BUSYWAIT */
1474 D("RTT over %llu packets: min %d av %d ns",
1475 (long long unsigned)sent, (int)g_min,
1476 (int)((double)g_av/sent));
1478 targ->completed = 1;
1480 /* reset the ``used`` flag. */
1488 * reply to ping requests
1491 pong_body(void *data)
1493 struct targ *targ = (struct targ *) data;
1494 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1495 struct netmap_if *nifp = targ->nmd->nifp;
1496 struct netmap_ring *txring, *rxring;
1498 uint64_t sent = 0, n = targ->g->npackets;
1500 if (targ->g->nthreads > 1) {
1501 D("can only reply ping with 1 thread");
1505 D("understood ponger %llu but don't know how to do it",
1506 (unsigned long long)n);
1507 while (!targ->cancel && (n == 0 || sent < n)) {
1508 uint32_t txhead, txavail;
1511 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1514 if ( (rv = poll(&pfd, 1, 1000)) <= 0) {
1515 D("poll error on queue %d: %s", targ->me,
1516 rv ? strerror(errno) : "timeout");
1520 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1521 txhead = txring->head;
1522 txavail = nm_ring_space(txring);
1523 /* see what we got back */
1524 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1525 rxring = NETMAP_RXRING(nifp, i);
1526 while (!nm_ring_empty(rxring)) {
1527 uint16_t *spkt, *dpkt;
1528 uint32_t head = rxring->head;
1529 struct netmap_slot *slot = &rxring->slot[head];
1531 src = NETMAP_BUF(rxring, slot->buf_idx);
1532 //D("got pkt %p of size %d", src, slot->len);
1533 rxring->head = rxring->cur = nm_ring_next(rxring, head);
1537 dst = NETMAP_BUF(txring,
1538 txring->slot[txhead].buf_idx);
1540 dpkt = (uint16_t *)dst;
1541 spkt = (uint16_t *)src;
1542 nm_pkt_copy(src, dst, slot->len);
1543 /* swap source and destination MAC */
1550 txring->slot[txhead].len = slot->len;
1551 txhead = nm_ring_next(txring, txhead);
1556 txring->head = txring->cur = txhead;
1557 targ->ctr.pkts = sent;
1559 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1561 //D("tx %d rx %d", sent, rx);
1564 targ->completed = 1;
1566 /* reset the ``used`` flag. */
1574 sender_body(void *data)
1576 struct targ *targ = (struct targ *) data;
1577 struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1578 struct netmap_if *nifp;
1579 struct netmap_ring *txring = NULL;
1581 uint64_t n = targ->g->npackets / targ->g->nthreads;
1584 int options = targ->g->options | OPT_COPY;
1585 struct timespec nexttime = { 0, 0}; // XXX silence compiler
1586 int rate_limit = targ->g->tx_rate;
1587 struct pkt *pkt = &targ->pkt;
1591 if (targ->frame == NULL) {
1592 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1593 size = targ->g->pkt_size + targ->g->virt_header;
1595 frame = targ->frame;
1596 size = targ->g->pkt_size;
1599 D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1600 if (setaffinity(targ->thread, targ->affinity))
1604 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1606 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1607 targ->tic.tv_nsec = 0;
1608 wait_time(targ->tic);
1609 nexttime = targ->tic;
1611 if (targ->g->dev_type == DEV_TAP) {
1612 D("writing to file desc %d", targ->g->main_fd);
1614 for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1615 if (write(targ->g->main_fd, frame, size) != -1)
1617 update_addresses(pkt, targ);
1619 targ->ctr.pkts = sent;
1620 targ->ctr.bytes = sent*size;
1621 targ->ctr.events = sent;
1626 } else if (targ->g->dev_type == DEV_PCAP) {
1627 pcap_t *p = targ->g->p;
1629 for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1630 if (pcap_inject(p, frame, size) != -1)
1632 update_addresses(pkt, targ);
1634 targ->ctr.pkts = sent;
1635 targ->ctr.bytes = sent*size;
1636 targ->ctr.events = sent;
1640 #endif /* NO_PCAP */
1643 u_int bufsz, frag_size = targ->g->frag_size;
1645 nifp = targ->nmd->nifp;
1646 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1647 bufsz = txring->nr_buf_size;
1648 if (bufsz < frag_size)
1650 targ->frag_size = targ->g->pkt_size / targ->frags;
1651 if (targ->frag_size > frag_size) {
1652 targ->frags = targ->g->pkt_size / frag_size;
1653 targ->frag_size = frag_size;
1654 if (targ->g->pkt_size % frag_size != 0)
1657 D("frags %u frag_size %u", targ->frags, targ->frag_size);
1658 while (!targ->cancel && (n == 0 || sent < n)) {
1661 if (rate_limit && tosend <= 0) {
1662 tosend = targ->g->burst;
1663 nexttime = timespec_add(nexttime, targ->g->tx_period);
1664 wait_time(nexttime);
1668 * wait for available room in the send queue(s)
1672 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1673 D("ioctl error on queue %d: %s", targ->me,
1677 #else /* !BUSYWAIT */
1678 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
1681 D("poll error on queue %d: %s", targ->me,
1682 rv ? strerror(errno) : "timeout");
1685 if (pfd.revents & POLLERR) {
1686 D("poll error on %d ring %d-%d", pfd.fd,
1687 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
1690 #endif /* !BUSYWAIT */
1692 * scan our queues and send on those with room
1694 if (options & OPT_COPY && sent > 100000 && !(targ->g->options & OPT_COPY) ) {
1696 options &= ~OPT_COPY;
1698 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1700 uint64_t limit = rate_limit ? tosend : targ->g->burst;
1702 if (n > 0 && n == sent)
1705 if (n > 0 && n - sent < limit)
1707 txring = NETMAP_TXRING(nifp, i);
1708 if (nm_ring_empty(txring))
1711 if (targ->g->pkt_min_size > 0) {
1712 size = nrand48(targ->seed) %
1713 (targ->g->pkt_size - targ->g->pkt_min_size) +
1714 targ->g->pkt_min_size;
1716 m = send_packets(txring, pkt, frame, size, targ,
1718 ND("limit %lu tail %d m %d",
1719 limit, txring->tail, m);
1721 if (m > 0) //XXX-ste: can m be 0?
1723 targ->ctr.pkts = sent;
1724 targ->ctr.bytes += m*size;
1725 targ->ctr.events = event;
1733 /* flush any remaining packets */
1734 if (txring != NULL) {
1735 D("flush tail %d head %d on thread %p",
1736 txring->tail, txring->head,
1737 (void *)pthread_self());
1738 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1741 /* final part: wait all the TX queues to be empty. */
1742 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1743 txring = NETMAP_TXRING(nifp, i);
1744 while (!targ->cancel && nm_tx_pending(txring)) {
1745 RD(5, "pending tx tail %d head %d on ring %d",
1746 txring->tail, txring->head, i);
1747 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1748 usleep(1); /* wait 1 tick */
1751 } /* end DEV_NETMAP */
1753 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1754 targ->completed = 1;
1755 targ->ctr.pkts = sent;
1756 targ->ctr.bytes = sent*size;
1757 targ->ctr.events = event;
1759 /* reset the ``used`` flag. */
1768 receive_pcap(u_char *user, const struct pcap_pkthdr * h,
1769 const u_char * bytes)
1771 struct my_ctrs *ctr = (struct my_ctrs *)user;
1772 (void)bytes; /* UNUSED */
1773 ctr->bytes += h->len;
1776 #endif /* !NO_PCAP */
1780 receive_packets(struct netmap_ring *ring, u_int limit, int dump, uint64_t *bytes)
1790 n = nm_ring_space(ring);
1793 for (rx = 0; rx < limit; rx++) {
1794 struct netmap_slot *slot = &ring->slot[head];
1795 char *p = NETMAP_BUF(ring, slot->buf_idx);
1797 *bytes += slot->len;
1799 dump_payload(p, slot->len, ring, head);
1800 if (!(slot->flags & NS_MOREFRAG))
1803 head = nm_ring_next(ring, head);
1805 ring->head = ring->cur = head;
1811 receiver_body(void *data)
1813 struct targ *targ = (struct targ *) data;
1814 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1815 struct netmap_if *nifp;
1816 struct netmap_ring *rxring;
1820 memset(&cur, 0, sizeof(cur));
1822 if (setaffinity(targ->thread, targ->affinity))
1825 D("reading from %s fd %d main_fd %d",
1826 targ->g->ifname, targ->fd, targ->g->main_fd);
1827 /* unbounded wait for the first packet. */
1828 for (;!targ->cancel;) {
1829 i = poll(&pfd, 1, 1000);
1830 if (i > 0 && !(pfd.revents & POLLERR))
1833 D("poll() error: %s", strerror(errno));
1836 if (pfd.revents & POLLERR) {
1840 RD(1, "waiting for initial packets, poll returns %d %d",
1843 /* main loop, exit after 1s silence */
1844 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1845 if (targ->g->dev_type == DEV_TAP) {
1846 while (!targ->cancel) {
1847 char buf[MAX_BODYSIZE];
1848 /* XXX should we poll ? */
1849 i = read(targ->g->main_fd, buf, sizeof(buf));
1852 targ->ctr.bytes += i;
1857 } else if (targ->g->dev_type == DEV_PCAP) {
1858 while (!targ->cancel) {
1859 /* XXX should we poll ? */
1860 pcap_dispatch(targ->g->p, targ->g->burst, receive_pcap,
1861 (u_char *)&targ->ctr);
1864 #endif /* !NO_PCAP */
1866 int dump = targ->g->options & OPT_DUMP;
1868 nifp = targ->nmd->nifp;
1869 while (!targ->cancel) {
1870 /* Once we started to receive packets, wait at most 1 seconds
1873 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
1874 D("ioctl error on queue %d: %s", targ->me,
1878 #else /* !BUSYWAIT */
1879 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
1880 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1881 targ->toc.tv_sec -= 1; /* Subtract timeout time. */
1885 if (pfd.revents & POLLERR) {
1889 #endif /* !BUSYWAIT */
1890 uint64_t cur_space = 0;
1891 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1894 rxring = NETMAP_RXRING(nifp, i);
1895 /* compute free space in the ring */
1896 m = rxring->head + rxring->num_slots - rxring->tail;
1897 if (m >= (int) rxring->num_slots)
1898 m -= rxring->num_slots;
1900 if (nm_ring_empty(rxring))
1903 m = receive_packets(rxring, targ->g->burst, dump, &cur.bytes);
1908 cur.min_space = targ->ctr.min_space;
1909 if (cur_space < cur.min_space)
1910 cur.min_space = cur_space;
1915 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1917 #if !defined(BUSYWAIT)
1920 targ->completed = 1;
1924 /* reset the ``used`` flag. */
1931 txseq_body(void *data)
1933 struct targ *targ = (struct targ *) data;
1934 struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1935 struct netmap_ring *ring;
1938 int options = targ->g->options | OPT_COPY;
1939 struct timespec nexttime = {0, 0};
1940 int rate_limit = targ->g->tx_rate;
1941 struct pkt *pkt = &targ->pkt;
1942 int frags = targ->g->frags;
1943 uint32_t sequence = 0;
1948 if (targ->g->nthreads > 1) {
1949 D("can only txseq ping with 1 thread");
1953 if (targ->g->npackets > 0) {
1954 D("Ignoring -n argument");
1957 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1958 size = targ->g->pkt_size + targ->g->virt_header;
1960 D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1961 if (setaffinity(targ->thread, targ->affinity))
1964 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1966 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1967 targ->tic.tv_nsec = 0;
1968 wait_time(targ->tic);
1969 nexttime = targ->tic;
1972 /* Only use the first queue. */
1973 ring = NETMAP_TXRING(targ->nmd->nifp, targ->nmd->first_tx_ring);
1975 while (!targ->cancel) {
1984 budget = targ->g->burst;
1986 } else if (budget <= 0) {
1987 budget = targ->g->burst;
1988 nexttime = timespec_add(nexttime, targ->g->tx_period);
1989 wait_time(nexttime);
1992 /* wait for available room in the send queue */
1995 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1996 D("ioctl error on queue %d: %s", targ->me,
2000 #else /* !BUSYWAIT */
2001 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
2004 D("poll error on queue %d: %s", targ->me,
2005 rv ? strerror(errno) : "timeout");
2008 if (pfd.revents & POLLERR) {
2009 D("poll error on %d ring %d-%d", pfd.fd,
2010 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
2013 #endif /* !BUSYWAIT */
2015 /* If no room poll() again. */
2016 space = nm_ring_space(ring);
2023 if (space < limit) {
2027 /* Cut off ``limit`` to make sure is multiple of ``frags``. */
2029 limit = (limit / frags) * frags;
2032 limit = sent + limit; /* Convert to absolute. */
2034 for (fcnt = frags, head = ring->head;
2035 sent < limit; sent++, sequence++) {
2036 struct netmap_slot *slot = &ring->slot[head];
2037 char *p = NETMAP_BUF(ring, slot->buf_idx);
2038 uint16_t *w = (uint16_t *)PKT(pkt, body, targ->g->af), t;
2040 memcpy(&sum, targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, sizeof(sum));
2044 PKT(pkt, body, targ->g->af)[0] = sequence >> 24;
2045 PKT(pkt, body, targ->g->af)[1] = (sequence >> 16) & 0xff;
2046 sum = ~cksum_add(~sum, cksum_add(~t, *w));
2048 PKT(pkt, body, targ->g->af)[2] = (sequence >> 8) & 0xff;
2049 PKT(pkt, body, targ->g->af)[3] = sequence & 0xff;
2050 sum = ~cksum_add(~sum, cksum_add(~t, *w));
2051 memcpy(targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, &sum, sizeof(sum));
2052 nm_pkt_copy(frame, p, size);
2053 if (fcnt == frags) {
2054 update_addresses(pkt, targ);
2057 if (options & OPT_DUMP) {
2058 dump_payload(p, size, ring, head);
2064 slot->flags |= NS_MOREFRAG;
2069 if (sent == limit - 1) {
2070 /* Make sure we don't push an incomplete
2072 assert(!(slot->flags & NS_MOREFRAG));
2073 slot->flags |= NS_REPORT;
2076 head = nm_ring_next(ring, head);
2082 ring->cur = ring->head = head;
2085 targ->ctr.pkts = sent;
2086 targ->ctr.bytes = sent * size;
2087 targ->ctr.events = event;
2090 /* flush any remaining packets */
2091 D("flush tail %d head %d on thread %p",
2092 ring->tail, ring->head,
2093 (void *)pthread_self());
2094 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2096 /* final part: wait the TX queues to become empty. */
2097 while (!targ->cancel && nm_tx_pending(ring)) {
2098 RD(5, "pending tx tail %d head %d on ring %d",
2099 ring->tail, ring->head, targ->nmd->first_tx_ring);
2100 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2101 usleep(1); /* wait 1 tick */
2104 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2105 targ->completed = 1;
2106 targ->ctr.pkts = sent;
2107 targ->ctr.bytes = sent * size;
2108 targ->ctr.events = event;
2110 /* reset the ``used`` flag. */
2118 multi_slot_to_string(struct netmap_ring *ring, unsigned int head,
2119 unsigned int nfrags, char *strbuf, size_t strbuflen)
2124 for (f = 0; f < nfrags; f++) {
2125 struct netmap_slot *slot = &ring->slot[head];
2126 int m = snprintf(strbuf, strbuflen, "|%u,%x|", slot->len,
2128 if (m >= (int)strbuflen) {
2134 head = nm_ring_next(ring, head);
2141 rxseq_body(void *data)
2143 struct targ *targ = (struct targ *) data;
2144 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
2145 int dump = targ->g->options & OPT_DUMP;
2146 struct netmap_ring *ring;
2147 unsigned int frags_exp = 1;
2149 unsigned int frags = 0;
2150 int first_packet = 1;
2152 int i, j, af, nrings;
2153 uint32_t seq, *seq_exp = NULL;
2155 memset(&cur, 0, sizeof(cur));
2157 if (setaffinity(targ->thread, targ->affinity))
2160 nrings = targ->nmd->last_rx_ring - targ->nmd->first_rx_ring + 1;
2161 seq_exp = calloc(nrings, sizeof(uint32_t));
2162 if (seq_exp == NULL) {
2163 D("failed to allocate seq array");
2167 D("reading from %s fd %d main_fd %d",
2168 targ->g->ifname, targ->fd, targ->g->main_fd);
2169 /* unbounded wait for the first packet. */
2170 for (;!targ->cancel;) {
2171 i = poll(&pfd, 1, 1000);
2172 if (i > 0 && !(pfd.revents & POLLERR))
2174 RD(1, "waiting for initial packets, poll returns %d %d",
2178 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
2181 while (!targ->cancel) {
2186 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
2187 D("ioctl error on queue %d: %s", targ->me,
2191 #else /* !BUSYWAIT */
2192 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
2193 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2194 targ->toc.tv_sec -= 1; /* Subtract timeout time. */
2198 if (pfd.revents & POLLERR) {
2202 #endif /* !BUSYWAIT */
2204 for (j = targ->nmd->first_rx_ring; j <= targ->nmd->last_rx_ring; j++) {
2205 ring = NETMAP_RXRING(targ->nmd->nifp, j);
2206 if (nm_ring_empty(ring))
2209 limit = nm_ring_space(ring);
2210 if (limit > targ->g->burst)
2211 limit = targ->g->burst;
2215 * 1) we remove the early-return optimization from
2216 * the netmap poll implementation, or
2217 * 2) pipes get NS_MOREFRAG support.
2218 * With the current netmap implementation, an experiment like
2219 * pkt-gen -i vale:1{1 -f txseq -F 9
2220 * pkt-gen -i vale:1}1 -f rxseq
2221 * would get stuck as soon as we find nm_ring_space(ring) < 9,
2222 * since here limit is rounded to 0 and
2223 * pipe rxsync is not called anymore by the poll() of this loop.
2225 if (frags_exp > 1) {
2227 /* Cut off to the closest smaller multiple. */
2228 limit = (limit / frags_exp) * frags_exp;
2229 RD(2, "LIMIT %d --> %d", o, limit);
2233 for (head = ring->head, i = 0; i < limit; i++) {
2234 struct netmap_slot *slot = &ring->slot[head];
2235 char *p = NETMAP_BUF(ring, slot->buf_idx);
2236 int len = slot->len;
2240 dump_payload(p, slot->len, ring, head);
2244 if (!(slot->flags & NS_MOREFRAG)) {
2247 } else if (frags != frags_exp) {
2249 RD(1, "Received packets with %u frags, "
2250 "expected %u, '%s'", frags, frags_exp,
2251 multi_slot_to_string(ring, head-frags+1,
2253 prbuf, sizeof(prbuf)));
2260 p -= sizeof(pkt->vh) - targ->g->virt_header;
2261 len += sizeof(pkt->vh) - targ->g->virt_header;
2262 pkt = (struct pkt *)p;
2263 if (ntohs(pkt->eh.ether_type) == ETHERTYPE_IP)
2268 if ((char *)pkt + len < ((char *)PKT(pkt, body, af)) +
2270 RD(1, "%s: packet too small (len=%u)", __func__,
2273 seq = (PKT(pkt, body, af)[0] << 24) |
2274 (PKT(pkt, body, af)[1] << 16) |
2275 (PKT(pkt, body, af)[2] << 8) |
2276 PKT(pkt, body, af)[3];
2278 /* Grab the first one, whatever it
2282 } else if (seq != seq_exp[j]) {
2283 uint32_t delta = seq - seq_exp[j];
2285 if (delta < (0xFFFFFFFF >> 1)) {
2286 RD(2, "Sequence GAP: exp %u found %u",
2289 RD(2, "Sequence OUT OF ORDER: "
2290 "exp %u found %u", seq_exp[j], seq);
2297 cur.bytes += slot->len;
2298 head = nm_ring_next(ring, head);
2302 ring->cur = ring->head = head;
2308 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2312 #endif /* !BUSYWAIT */
2313 targ->completed = 1;
2317 if (seq_exp != NULL)
2319 /* reset the ``used`` flag. */
2327 tx_output(struct glob_arg *g, struct my_ctrs *cur, double delta, const char *msg)
2329 double bw, raw_bw, pps, abs;
2330 char b1[40], b2[80], b3[80];
2333 if (cur->pkts == 0) {
2334 printf("%s nothing.\n", msg);
2338 size = (int)(cur->bytes / cur->pkts);
2340 printf("%s %llu packets %llu bytes %llu events %d bytes each in %.2f seconds.\n",
2342 (unsigned long long)cur->pkts,
2343 (unsigned long long)cur->bytes,
2344 (unsigned long long)cur->events, size, delta);
2347 if (size < 60) /* correct for min packet size */
2349 pps = cur->pkts / delta;
2350 bw = (8.0 * cur->bytes) / delta;
2351 raw_bw = (8.0 * cur->bytes + cur->pkts * g->framing) / delta;
2352 abs = cur->pkts / (double)(cur->events);
2354 printf("Speed: %spps Bandwidth: %sbps (raw %sbps). Average batch: %.2f pkts\n",
2355 norm(b1, pps, normalize), norm(b2, bw, normalize), norm(b3, raw_bw, normalize), abs);
2361 /* This usage is generated from the pkt-gen man page:
2363 * and pasted here adding the string terminators and endlines with simple
2364 * regular expressions. */
2365 const char *cmd = "pkt-gen";
2369 " -h Show program usage and exit.\n"
2372 " Name of the network interface that pkt-gen operates on. It can be a system network interface\n"
2373 " (e.g., em0), the name of a vale(4) port (e.g., valeSSS:PPP), the name of a netmap pipe or\n"
2374 " monitor, or any valid netmap port name accepted by the nm_open library function, as docu-\n"
2375 " mented in netmap(4) (NIOCREGIF section).\n"
2378 " The function to be executed by pkt-gen. Specify tx for transmission, rx for reception, ping\n"
2379 " for client-side ping-pong operation, and pong for server-side ping-pong operation.\n"
2382 " Number of iterations of the pkt-gen function (with 0 meaning infinite). In case of tx or rx,\n"
2383 " count is the number of packets to receive or transmit. In case of ping or pong, count is the\n"
2384 " number of ping-pong transactions.\n"
2387 " Packet size in bytes excluding CRC. If passed a second time, use random sizes larger or\n"
2388 " equal than the second one and lower than the first one.\n"
2391 " Transmit or receive up to burst_size packets at a time.\n"
2393 " -4 Use IPv4 addresses.\n"
2395 " -6 Use IPv6 addresses.\n"
2397 " -d dst_ip[:port[-dst_ip:port]]\n"
2398 " Destination IPv4/IPv6 address and port, single or range.\n"
2400 " -s src_ip[:port[-src_ip:port]]\n"
2401 " Source IPv4/IPv6 address and port, single or range.\n"
2404 " Destination MAC address in colon notation (e.g., aa:bb:cc:dd:ee:00).\n"
2407 " Source MAC address in colon notation.\n"
2410 " Pin the first thread of pkt-gen to a particular CPU using pthread_setaffinity_np(3). If more\n"
2411 " threads are used, they are pinned to the subsequent CPUs, one per thread.\n"
2414 " Maximum number of CPUs to use (0 means to use all the available ones).\n"
2417 " Number of threads to use. By default, only a single thread is used to handle all the netmap\n"
2418 " rings. If threads is larger than one, each thread handles a single TX ring (in tx mode), a\n"
2419 " single RX ring (in rx mode), or a TX/RX ring pair. The number of threads must be less than or\n"
2420 " equal to the number of TX (or RX) rings available in the device specified by interface.\n"
2423 " Number of milliseconds between reports.\n"
2425 " -w wait_for_link_time\n"
2426 " Number of seconds to wait before starting the pkt-gen function, useful to make sure that the\n"
2427 " network link is up. A network device driver may take some time to enter netmap mode, or to\n"
2428 " create a new transmit/receive ring pair when netmap(4) requests one.\n"
2431 " Packet transmission rate. Not setting the packet transmission rate tells pkt-gen to transmit\n"
2432 " packets as quickly as possible. On servers from 2010 onward netmap(4) is able to com-\n"
2433 " pletely use all of the bandwidth of a 10 or 40Gbps link, so this option should be used unless\n"
2434 " your intention is to saturate the link.\n"
2436 " -X Dump payload of each packet transmitted or received.\n"
2438 " -H len Add empty virtio-net-header with size 'len'. Valid sizes are 0, 10 and 12. This option is\n"
2439 " only used with Virtual Machine technologies that use virtio as a network interface.\n"
2442 " Load the packet to be transmitted from a pcap file rather than constructing it within\n"
2445 " -z Use random IPv4/IPv6 src address/port.\n"
2447 " -Z Use random IPv4/IPv6 dst address/port.\n"
2449 " -N Do not normalize units (i.e., use bps, pps instead of Mbps, Kpps, etc.).\n"
2452 " Send multi-slot packets, each one with num_frags fragments. A multi-slot packet is repre-\n"
2453 " sented by two or more consecutive netmap slots with the NS_MOREFRAG flag set (except for the\n"
2454 " last slot). This is useful to transmit or receive packets larger than the netmap buffer\n"
2458 " In multi-slot mode, frag_size specifies the size of each fragment, if smaller than the packet\n"
2459 " length divided by num_frags.\n"
2461 " -I Use indirect buffers. It is only valid for transmitting on VALE ports, and it is implemented\n"
2462 " by setting the NS_INDIRECT flag in the netmap slots.\n"
2464 " -W Exit immediately if all the RX rings are empty the first time they are examined.\n"
2466 " -v Increase the verbosity level.\n"
2468 " -r In tx mode, do not initialize packets, but send whatever the content of the uninitialized\n"
2469 " netmap buffers is (rubbish mode).\n"
2471 " -A Compute mean and standard deviation (over a sliding window) for the transmit or receive rate.\n"
2473 " -B Take Ethernet framing and CRC into account when computing the average bps. This adds 4 bytes\n"
2474 " of CRC and 20 bytes of framing to each packet.\n"
2476 " -C tx_slots[,rx_slots[,tx_rings[,rx_rings]]]\n"
2477 " Configuration in terms of number of rings and slots to be used when opening the netmap port.\n"
2478 " Such configuration has an effect on software ports created on the fly, such as VALE ports and\n"
2479 " netmap pipes. The configuration may consist of 1 to 4 numbers separated by commas: tx_slots,\n"
2480 " rx_slots, tx_rings, rx_rings. Missing numbers or zeroes stand for default values. As an\n"
2481 " additional convenience, if exactly one number is specified, then this is assigned to both\n"
2482 " tx_slots and rx_slots. If there is no fourth number, then the third one is assigned to both\n"
2483 " tx_rings and rx_rings.\n"
2485 " -o options data generation options (parsed using atoi)\n"
2490 " OPT_TS 16 (add a timestamp)\n"
2491 " OPT_INDIRECT 32 (use indirect buffers)\n"
2492 " OPT_DUMP 64 (dump rx/tx traffic)\n"
2493 " OPT_RUBBISH 256\n"
2494 " (send whatever the buffers contain)\n"
2495 " OPT_RANDOM_SRC 512\n"
2496 " OPT_RANDOM_DST 1024\n"
2497 " OPT_PPS_STATS 2048\n"
2504 start_threads(struct glob_arg *g) {
2507 targs = calloc(g->nthreads, sizeof(*targs));
2510 * Now create the desired number of threads, each one
2511 * using a single descriptor.
2513 for (i = 0; i < g->nthreads; i++) {
2514 uint64_t seed = (uint64_t)time(0) | ((uint64_t)time(0) << 32);
2517 bzero(t, sizeof(*t));
2518 t->fd = -1; /* default, with pcap */
2520 memcpy(t->seed, &seed, sizeof(t->seed));
2522 if (g->dev_type == DEV_NETMAP) {
2526 * if the user wants both HW and SW rings, we need to
2527 * know when to switch from NR_REG_ONE_NIC to NR_REG_ONE_SW
2529 if (g->orig_mode == NR_REG_NIC_SW) {
2530 m = (g->td_type == TD_TYPE_RECEIVER ?
2531 g->nmd->reg.nr_rx_rings :
2532 g->nmd->reg.nr_tx_rings);
2537 /* the first thread uses the fd opened by the main
2538 * thread, the other threads re-open /dev/netmap
2540 t->nmd = nmport_clone(g->nmd);
2545 if (m > 0 && j >= m) {
2546 /* switch to the software rings */
2547 t->nmd->reg.nr_mode = NR_REG_ONE_SW;
2550 t->nmd->reg.nr_ringid = j & NETMAP_RING_MASK;
2551 /* Only touch one of the rings (rx is already ok) */
2552 if (g->td_type == TD_TYPE_RECEIVER)
2553 t->nmd->reg.nr_flags |= NETMAP_NO_TX_POLL;
2555 /* register interface. Override ifname and ringid etc. */
2556 if (nmport_open_desc(t->nmd) < 0) {
2557 nmport_undo_prepare(t->nmd);
2565 t->frags = g->frags;
2567 targs[i].fd = g->main_fd;
2571 if (g->affinity >= 0) {
2572 t->affinity = (g->affinity + i) % g->cpus;
2576 /* default, init packets */
2577 initialize_packet(t);
2579 /* Wait for PHY reset. */
2580 D("Wait %d secs for phy reset", g->wait_link);
2581 sleep(g->wait_link);
2584 for (i = 0; i < g->nthreads; i++) {
2586 if (pthread_create(&t->thread, NULL, g->td_body, t) == -1) {
2587 D("Unable to create thread %d: %s", i, strerror(errno));
2595 main_thread(struct glob_arg *g)
2599 struct my_ctrs prev, cur;
2601 struct timeval tic, toc;
2603 prev.pkts = prev.bytes = prev.events = 0;
2604 gettimeofday(&prev.t, NULL);
2606 char b1[40], b2[40], b3[40], b4[100];
2612 usec = wait_for_next_report(&prev.t, &cur.t,
2613 g->report_interval);
2615 cur.pkts = cur.bytes = cur.events = 0;
2617 if (usec < 10000) /* too short to be meaningful */
2619 /* accumulate counts for all threads */
2620 for (i = 0; i < g->nthreads; i++) {
2621 cur.pkts += targs[i].ctr.pkts;
2622 cur.bytes += targs[i].ctr.bytes;
2623 cur.events += targs[i].ctr.events;
2624 cur.min_space += targs[i].ctr.min_space;
2625 targs[i].ctr.min_space = 99999;
2626 if (targs[i].used == 0)
2629 x.pkts = cur.pkts - prev.pkts;
2630 x.bytes = cur.bytes - prev.bytes;
2631 x.events = cur.events - prev.events;
2632 pps = (x.pkts*1000000 + usec/2) / usec;
2633 abs = (x.events > 0) ? (x.pkts / (double) x.events) : 0;
2635 if (!(g->options & OPT_PPS_STATS)) {
2638 /* Compute some pps stats using a sliding window. */
2639 double ppsavg = 0.0, ppsdev = 0.0;
2642 g->win[g->win_idx] = pps;
2643 g->win_idx = (g->win_idx + 1) % STATS_WIN;
2645 for (i = 0; i < STATS_WIN; i++) {
2646 ppsavg += g->win[i];
2653 for (i = 0; i < STATS_WIN; i++) {
2654 if (g->win[i] == 0) {
2657 ppsdev += (g->win[i] - ppsavg) * (g->win[i] - ppsavg);
2660 ppsdev = sqrt(ppsdev);
2662 snprintf(b4, sizeof(b4), "[avg/std %s/%s pps]",
2663 norm(b1, ppsavg, normalize), norm(b2, ppsdev, normalize));
2666 D("%spps %s(%spkts %sbps in %llu usec) %.2f avg_batch %d min_space",
2667 norm(b1, pps, normalize), b4,
2668 norm(b2, (double)x.pkts, normalize),
2669 norm(b3, 1000000*((double)x.bytes*8+(double)x.pkts*g->framing)/usec, normalize),
2670 (unsigned long long)usec,
2671 abs, (int)cur.min_space);
2674 if (done == g->nthreads)
2680 cur.pkts = cur.bytes = cur.events = 0;
2682 for (i = 0; i < g->nthreads; i++) {
2683 struct timespec t_tic, t_toc;
2685 * Join active threads, unregister interfaces and close
2689 pthread_join(targs[i].thread, NULL); /* blocking */
2690 if (g->dev_type == DEV_NETMAP) {
2691 nmport_close(targs[i].nmd);
2692 targs[i].nmd = NULL;
2697 if (targs[i].completed == 0)
2698 D("ouch, thread %d exited with error", i);
2701 * Collect threads output and extract information about
2702 * how long it took to send all the packets.
2704 cur.pkts += targs[i].ctr.pkts;
2705 cur.bytes += targs[i].ctr.bytes;
2706 cur.events += targs[i].ctr.events;
2707 /* collect the largest start (tic) and end (toc) times,
2708 * XXX maybe we should do the earliest tic, or do a weighted
2711 t_tic = timeval2spec(&tic);
2712 t_toc = timeval2spec(&toc);
2713 if (!timerisset(&tic) || timespec_ge(&targs[i].tic, &t_tic))
2714 tic = timespec2val(&targs[i].tic);
2715 if (!timerisset(&toc) || timespec_ge(&targs[i].toc, &t_toc))
2716 toc = timespec2val(&targs[i].toc);
2720 timersub(&toc, &tic, &toc);
2721 delta_t = toc.tv_sec + 1e-6* toc.tv_usec;
2722 if (g->td_type == TD_TYPE_SENDER)
2723 tx_output(g, &cur, delta_t, "Sent");
2724 else if (g->td_type == TD_TYPE_RECEIVER)
2725 tx_output(g, &cur, delta_t, "Received");
2735 static struct td_desc func[] = {
2736 { TD_TYPE_RECEIVER, "rx", receiver_body, 512}, /* default */
2737 { TD_TYPE_SENDER, "tx", sender_body, 512 },
2738 { TD_TYPE_OTHER, "ping", ping_body, 1 },
2739 { TD_TYPE_OTHER, "pong", pong_body, 1 },
2740 { TD_TYPE_SENDER, "txseq", txseq_body, 512 },
2741 { TD_TYPE_RECEIVER, "rxseq", rxseq_body, 512 },
2742 { 0, NULL, NULL, 0 }
2746 tap_alloc(char *dev)
2750 const char *clonedev = TAP_CLONEDEV;
2754 /* Arguments taken by the function:
2756 * char *dev: the name of an interface (or '\0'). MUST have enough
2757 * space to hold the interface name if '\0' is passed
2758 * int flags: interface flags (eg, IFF_TUN etc.)
2762 if (dev[3]) { /* tapSomething */
2763 static char buf[128];
2764 snprintf(buf, sizeof(buf), "/dev/%s", dev);
2768 /* open the device */
2769 if( (fd = open(clonedev, O_RDWR)) < 0 ) {
2772 D("%s open successful", clonedev);
2774 /* preparation of the struct ifr, of type "struct ifreq" */
2775 memset(&ifr, 0, sizeof(ifr));
2778 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2781 /* if a device name was specified, put it in the structure; otherwise,
2782 * the kernel will try to allocate the "next" device of the
2784 size_t len = strlen(dev);
2785 if (len > IFNAMSIZ) {
2786 D("%s too long", dev);
2789 memcpy(ifr.ifr_name, dev, len);
2792 /* try to create the device */
2793 if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
2794 D("failed to to a TUNSETIFF: %s", strerror(errno));
2799 /* if the operation was successful, write back the name of the
2800 * interface to the variable "dev", so the caller can know
2801 * it. Note that the caller MUST reserve space in *dev (see calling
2803 strcpy(dev, ifr.ifr_name);
2804 D("new name is %s", dev);
2807 /* this is the special file descriptor that the caller will use to talk
2808 * with the virtual interface */
2813 main(int arc, char **argv)
2816 struct sigaction sa;
2822 int devqueues = 1; /* how many device queues */
2823 int wait_link_arg = 0;
2825 int pkt_size_done = 0;
2827 struct td_desc *fn = func;
2829 bzero(&g, sizeof(g));
2834 g.report_interval = 1000; /* report interval */
2836 /* ip addresses can also be a range x.x.x.x-x.x.x.y */
2837 g.af = AF_INET; /* default */
2838 g.src_ip.name = "10.0.0.1";
2839 g.dst_ip.name = "10.1.0.1";
2840 g.dst_mac.name = "ff:ff:ff:ff:ff:ff";
2841 g.src_mac.name = NULL;
2845 g.cpus = 1; /* default */
2849 g.frag_size = (u_int)-1; /* use the netmap buffer size by default */
2852 g.wait_link = 2; /* wait 2 seconds for physical ports */
2854 while ((ch = getopt(arc, argv, "46a:f:F:Nn:i:Il:d:s:D:S:b:c:o:p:"
2855 "T:w:WvR:XC:H:rP:zZAhBM:")) != -1) {
2859 D("bad option %c %s", ch, optarg);
2880 g.npackets = strtoull(optarg, NULL, 10);
2885 if (i < 1 || i > 63) {
2886 D("invalid frags %d [1..63], ignore", i);
2893 g.frag_size = atoi(optarg);
2897 for (fn = func; fn->key; fn++) {
2898 if (!strcmp(fn->key, optarg))
2905 D("unrecognised function %s", optarg);
2909 case 'o': /* data generation options */
2910 g.options |= atoi(optarg);
2913 case 'a': /* force affinity */
2914 g.affinity = atoi(optarg);
2917 case 'i': /* interface */
2918 /* a prefix of tap: netmap: or pcap: forces the mode.
2919 * otherwise we guess
2921 D("interface is %s", optarg);
2922 if (strlen(optarg) > MAX_IFNAMELEN - 8) {
2923 D("ifname too long %s", optarg);
2926 strcpy(g.ifname, optarg);
2927 if (!strcmp(optarg, "null")) {
2928 g.dev_type = DEV_NETMAP;
2930 } else if (!strncmp(optarg, "tap:", 4)) {
2931 g.dev_type = DEV_TAP;
2932 strcpy(g.ifname, optarg + 4);
2933 } else if (!strncmp(optarg, "pcap:", 5)) {
2934 g.dev_type = DEV_PCAP;
2935 strcpy(g.ifname, optarg + 5);
2936 } else if (!strncmp(optarg, "netmap:", 7) ||
2937 !strncmp(optarg, "vale", 4)) {
2938 g.dev_type = DEV_NETMAP;
2939 } else if (!strncmp(optarg, "tap", 3)) {
2940 g.dev_type = DEV_TAP;
2941 } else { /* prepend netmap: */
2942 g.dev_type = DEV_NETMAP;
2943 sprintf(g.ifname, "netmap:%s", optarg);
2948 g.options |= OPT_INDIRECT; /* use indirect buffers */
2951 case 'l': /* pkt_size */
2952 if (pkt_size_done) {
2953 g.pkt_min_size = atoi(optarg);
2955 g.pkt_size = atoi(optarg);
2961 g.dst_ip.name = optarg;
2965 g.src_ip.name = optarg;
2968 case 'T': /* report interval */
2969 g.report_interval = atoi(optarg);
2973 g.wait_link = atoi(optarg);
2978 g.forever = 0; /* exit RX with no traffic */
2981 case 'b': /* burst */
2982 g.burst = atoi(optarg);
2985 g.cpus = atoi(optarg);
2988 g.nthreads = atoi(optarg);
2991 case 'D': /* destination mac */
2992 g.dst_mac.name = optarg;
2995 case 'S': /* source mac */
2996 g.src_mac.name = optarg;
3002 g.tx_rate = atoi(optarg);
3005 g.options |= OPT_DUMP;
3008 D("WARNING: the 'C' option is deprecated, use the '+conf:' libnetmap option instead");
3009 g.nmr_config = strdup(optarg);
3012 g.virt_header = atoi(optarg);
3015 g.packet_file = strdup(optarg);
3018 g.options |= OPT_RUBBISH;
3021 g.options |= OPT_RANDOM_SRC;
3024 g.options |= OPT_RANDOM_DST;
3027 g.options |= OPT_PPS_STATS;
3030 /* raw packets have4 bytes crc + 20 bytes framing */
3031 // XXX maybe add an option to pass the IFG
3037 if (strlen(g.ifname) <=0 ) {
3038 D("missing ifname");
3043 g.burst = fn->default_burst;
3044 D("using default burst size: %d", g.burst);
3047 g.system_cpus = i = system_ncpus();
3048 if (g.cpus < 0 || g.cpus > i) {
3049 D("%d cpus is too high, have only %d cpus", g.cpus, i);
3052 D("running on %d cpus (have %d)", g.cpus, i);
3056 if (!wait_link_arg && !strncmp(g.ifname, "vale", 4)) {
3060 if (g.pkt_size < 16 || g.pkt_size > MAX_PKTSIZE) {
3061 D("bad pktsize %d [16..%d]\n", g.pkt_size, MAX_PKTSIZE);
3065 if (g.pkt_min_size > 0 && (g.pkt_min_size < 16 || g.pkt_min_size > g.pkt_size)) {
3066 D("bad pktminsize %d [16..%d]\n", g.pkt_min_size, g.pkt_size);
3070 if (g.src_mac.name == NULL) {
3071 static char mybuf[20] = "00:00:00:00:00:00";
3072 /* retrieve source mac address. */
3073 if (source_hwaddr(g.ifname, mybuf) == -1) {
3074 D("Unable to retrieve source mac");
3075 // continue, fail later
3077 g.src_mac.name = mybuf;
3079 /* extract address ranges */
3080 if (extract_mac_range(&g.src_mac) || extract_mac_range(&g.dst_mac))
3082 g.options |= extract_ip_range(&g.src_ip, g.af);
3083 g.options |= extract_ip_range(&g.dst_ip, g.af);
3085 if (g.virt_header != 0 && g.virt_header != VIRT_HDR_1
3086 && g.virt_header != VIRT_HDR_2) {
3087 D("bad virtio-net-header length");
3091 if (g.dev_type == DEV_TAP) {
3092 D("want to use tap %s", g.ifname);
3093 g.main_fd = tap_alloc(g.ifname);
3094 if (g.main_fd < 0) {
3095 D("cannot open tap %s", g.ifname);
3099 } else if (g.dev_type == DEV_PCAP) {
3100 char pcap_errbuf[PCAP_ERRBUF_SIZE];
3102 pcap_errbuf[0] = '\0'; // init the buffer
3103 g.p = pcap_open_live(g.ifname, 256 /* XXX */, 1, 100, pcap_errbuf);
3105 D("cannot open pcap on %s", g.ifname);
3108 g.main_fd = pcap_fileno(g.p);
3109 D("using pcap on %s fileno %d", g.ifname, g.main_fd);
3110 #endif /* !NO_PCAP */
3111 } else if (g.dummy_send) { /* but DEV_NETMAP */
3112 D("using a dummy send routine");
3114 g.nmd = nmport_prepare(g.ifname);
3118 parse_nmr_config(g.nmr_config, &g.nmd->reg);
3120 g.nmd->reg.nr_flags |= NR_ACCEPT_VNET_HDR;
3123 * Open the netmap device using nm_open().
3125 * protocol stack and may cause a reset of the card,
3126 * which in turn may take some time for the PHY to
3127 * reconfigure. We do the open here to have time to reset.
3129 g.orig_mode = g.nmd->reg.nr_mode;
3130 if (g.nthreads > 1) {
3131 switch (g.orig_mode) {
3132 case NR_REG_ALL_NIC:
3134 g.nmd->reg.nr_mode = NR_REG_ONE_NIC;
3137 g.nmd->reg.nr_mode = NR_REG_ONE_SW;
3142 g.nmd->reg.nr_ringid = 0;
3144 if (nmport_open_desc(g.nmd) < 0)
3146 g.main_fd = g.nmd->fd;
3147 ND("mapped %luKB at %p", (unsigned long)(g.nmd->req.nr_memsize>>10),
3150 if (g.virt_header) {
3151 /* Set the virtio-net header length, since the user asked
3152 * for it explicitely. */
3153 set_vnet_hdr_len(&g);
3155 /* Check whether the netmap port we opened requires us to send
3156 * and receive frames with virtio-net header. */
3157 get_vnet_hdr_len(&g);
3160 /* get num of queues in tx or rx */
3161 if (g.td_type == TD_TYPE_SENDER)
3162 devqueues = g.nmd->reg.nr_tx_rings + g.nmd->reg.nr_host_tx_rings;
3164 devqueues = g.nmd->reg.nr_rx_rings + g.nmd->reg.nr_host_rx_rings;
3166 /* validate provided nthreads. */
3167 if (g.nthreads < 1 || g.nthreads > devqueues) {
3168 D("bad nthreads %d, have %d queues", g.nthreads, devqueues);
3169 // continue, fail later
3172 if (g.td_type == TD_TYPE_SENDER) {
3173 int mtu = get_if_mtu(&g);
3175 if (mtu > 0 && g.pkt_size > mtu) {
3176 D("pkt_size (%d) must be <= mtu (%d)",
3183 struct netmap_if *nifp = g.nmd->nifp;
3184 struct nmreq_register *req = &g.nmd->reg;
3186 D("nifp at offset %"PRIu64" ntxqs %d nrxqs %d memid %d",
3187 req->nr_offset, req->nr_tx_rings, req->nr_rx_rings,
3189 for (i = 0; i < req->nr_tx_rings + req->nr_host_tx_rings; i++) {
3190 struct netmap_ring *ring = NETMAP_TXRING(nifp, i);
3191 D(" TX%d at offset %p slots %d", i,
3192 (void *)((char *)ring - (char *)nifp), ring->num_slots);
3194 for (i = 0; i < req->nr_rx_rings + req->nr_host_rx_rings; i++) {
3195 struct netmap_ring *ring = NETMAP_RXRING(nifp, i);
3196 D(" RX%d at offset %p slots %d", i,
3197 (void *)((char *)ring - (char *)nifp), ring->num_slots);
3201 /* Print some debug information. */
3203 "%s %s: %d queues, %d threads and %d cpus.\n",
3204 (g.td_type == TD_TYPE_SENDER) ? "Sending on" :
3205 ((g.td_type == TD_TYPE_RECEIVER) ? "Receiving from" :
3211 if (g.td_type == TD_TYPE_SENDER) {
3212 fprintf(stdout, "%s -> %s (%s -> %s)\n",
3213 g.src_ip.name, g.dst_ip.name,
3214 g.src_mac.name, g.dst_mac.name);
3218 /* Exit if something went wrong. */
3219 if (g.main_fd < 0) {
3227 D("--- SPECIAL OPTIONS:%s%s%s%s%s%s\n",
3228 g.options & OPT_PREFETCH ? " prefetch" : "",
3229 g.options & OPT_ACCESS ? " access" : "",
3230 g.options & OPT_MEMCPY ? " memcpy" : "",
3231 g.options & OPT_INDIRECT ? " indirect" : "",
3232 g.options & OPT_COPY ? " copy" : "",
3233 g.options & OPT_RUBBISH ? " rubbish " : "");
3236 g.tx_period.tv_sec = g.tx_period.tv_nsec = 0;
3237 if (g.tx_rate > 0) {
3238 /* try to have at least something every second,
3239 * reducing the burst size to some 0.01s worth of data
3240 * (but no less than one full set of fragments)
3243 int lim = (g.tx_rate)/300;
3248 x = ((uint64_t)1000000000 * (uint64_t)g.burst) / (uint64_t) g.tx_rate;
3249 g.tx_period.tv_nsec = x;
3250 g.tx_period.tv_sec = g.tx_period.tv_nsec / 1000000000;
3251 g.tx_period.tv_nsec = g.tx_period.tv_nsec % 1000000000;
3253 if (g.td_type == TD_TYPE_SENDER)
3254 D("Sending %d packets every %ld.%09ld s",
3255 g.burst, g.tx_period.tv_sec, g.tx_period.tv_nsec);
3256 /* Install ^C handler. */
3257 global_nthreads = g.nthreads;
3259 sigaddset(&ss, SIGINT);
3260 /* block SIGINT now, so that all created threads will inherit the mask */
3261 if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0) {
3262 D("failed to block SIGINT: %s", strerror(errno));
3264 if (start_threads(&g) < 0)
3266 /* Install the handler and re-enable SIGINT for the main thread */
3267 memset(&sa, 0, sizeof(sa));
3268 sa.sa_handler = sigint_h;
3269 if (sigaction(SIGINT, &sa, NULL) < 0) {
3270 D("failed to install ^C handler: %s", strerror(errno));
3273 if (pthread_sigmask(SIG_UNBLOCK, &ss, NULL) < 0) {
3274 D("failed to re-enable SIGINT: %s", strerror(errno));