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>
46 #include <ctype.h> // isprint()
47 #include <unistd.h> // sysconf()
49 #include <arpa/inet.h> /* ntohs */
51 #include <sys/sysctl.h> /* sysctl */
53 #include <ifaddrs.h> /* getifaddrs */
54 #include <net/ethernet.h>
55 #include <netinet/in.h>
56 #include <netinet/ip.h>
57 #include <netinet/udp.h>
58 #include <netinet/ip6.h>
60 #define IPV6_VERSION 0x60
61 #define IPV6_DEFHLIM 64
69 #include <pcap/pcap.h>
74 static void usage(int);
77 #define cpuset_t DWORD_PTR //uint64_t
78 static inline void CPU_ZERO(cpuset_t *p)
83 static inline void CPU_SET(uint32_t i, cpuset_t *p)
88 #define pthread_setaffinity_np(a, b, c) !SetThreadAffinityMask(a, *c) //((void)a, 0)
89 #define TAP_CLONEDEV "/dev/tap"
90 #define AF_LINK 18 //defined in winsocks.h
91 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
92 #include <net/if_dl.h>
95 * Convert an ASCII representation of an ethernet address to
99 ether_aton(const char *a)
102 static struct ether_addr o;
103 unsigned int o0, o1, o2, o3, o4, o5;
105 i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o0, &o1, &o2, &o3, &o4, &o5);
117 return ((struct ether_addr *)&o);
121 * Convert a binary representation of an ethernet address to
125 ether_ntoa(const struct ether_addr *n)
130 i = sprintf(a, "%02x:%02x:%02x:%02x:%02x:%02x",
131 n->octet[0], n->octet[1], n->octet[2],
132 n->octet[3], n->octet[4], n->octet[5]);
133 return (i < 17 ? NULL : (char *)&a);
139 #define cpuset_t cpu_set_t
141 #define ifr_flagshigh ifr_flags /* only the low 16 bits here */
142 #define IFF_PPROMISC IFF_PROMISC /* IFF_PPROMISC does not exist */
143 #include <linux/ethtool.h>
144 #include <linux/sockios.h>
146 #define CLOCK_REALTIME_PRECISE CLOCK_REALTIME
147 #include <netinet/ether.h> /* ether_aton */
148 #include <linux/if_packet.h> /* sockaddr_ll */
152 #include <sys/endian.h> /* le64toh */
153 #include <machine/param.h>
155 #include <pthread_np.h> /* pthread w/ affinity */
156 #include <sys/cpuset.h> /* cpu_set */
157 #include <net/if_dl.h> /* LLADDR */
158 #endif /* __FreeBSD__ */
162 #define cpuset_t uint64_t // XXX
163 static inline void CPU_ZERO(cpuset_t *p)
168 static inline void CPU_SET(uint32_t i, cpuset_t *p)
170 *p |= 1<< (i & 0x3f);
173 #define pthread_setaffinity_np(a, b, c) ((void)a, 0)
175 #define ifr_flagshigh ifr_flags // XXX
176 #define IFF_PPROMISC IFF_PROMISC
177 #include <net/if_dl.h> /* LLADDR */
178 #define clock_gettime(a,b) \
179 do {struct timespec t0 = {0,0}; *(b) = t0; } while (0)
180 #endif /* __APPLE__ */
182 const char *default_payload="netmap pkt-gen DIRECT payload\n"
183 "http://info.iet.unipi.it/~luigi/netmap/ ";
185 const char *indirect_payload="netmap pkt-gen indirect payload\n"
186 "http://info.iet.unipi.it/~luigi/netmap/ ";
191 #define VIRT_HDR_1 10 /* length of a base vnet-hdr */
192 #define VIRT_HDR_2 12 /* length of the extenede vnet-hdr */
193 #define VIRT_HDR_MAX VIRT_HDR_2
195 uint8_t fields[VIRT_HDR_MAX];
198 #define MAX_BODYSIZE 16384
201 struct virt_header vh;
202 struct ether_header eh;
207 uint8_t body[MAX_BODYSIZE]; /* hardwired */
212 uint8_t body[MAX_BODYSIZE]; /* hardwired */
215 } __attribute__((__packed__));
217 #define PKT(p, f, af) \
218 ((af) == AF_INET ? (p)->ipv4.f: (p)->ipv6.f)
224 uint32_t start, end; /* same as struct in_addr */
227 struct in6_addr start, end;
228 uint8_t sgroup, egroup;
231 uint16_t port0, port1;
236 struct ether_addr start, end;
239 /* ifname can be netmap:foo-xxxx */
240 #define MAX_IFNAMELEN 64 /* our buffer for ifname */
241 //#define MAX_PKTSIZE 1536
242 #define MAX_PKTSIZE MAX_BODYSIZE /* XXX: + IP_HDR + ETH_HDR */
244 /* compact timestamp to fit into 60 byte packet. (enough to obtain RTT) */
251 * global arguments for all threads
255 int af; /* address family AF_INET/AF_INET6 */
256 struct ip_range src_ip;
257 struct ip_range dst_ip;
258 struct mac_range dst_mac;
259 struct mac_range src_mac;
264 uint64_t npackets; /* total packets to send */
265 int frags; /* fragments per packet */
266 u_int mtu; /* size of each fragment */
268 int cpus; /* cpus used for running */
269 int system_cpus; /* cpus on the system */
271 int options; /* testing */
272 #define OPT_PREFETCH 1
276 #define OPT_TS 16 /* add a timestamp */
277 #define OPT_INDIRECT 32 /* use indirect buffers, tx only */
278 #define OPT_DUMP 64 /* dump rx/tx traffic */
279 #define OPT_RUBBISH 256 /* send wathever the buffers contain */
280 #define OPT_RANDOM_SRC 512
281 #define OPT_RANDOM_DST 1024
282 #define OPT_PPS_STATS 2048
289 struct timespec tx_period;
294 int report_interval; /* milliseconds between prints */
295 void *(*td_body)(void *);
298 char ifname[MAX_IFNAMELEN];
301 int virt_header; /* send also the virt_header */
302 char *packet_file; /* -P option */
305 int64_t win[STATS_WIN];
307 int framing; /* #bits of framing (for bw output) */
309 enum dev_type { DEV_NONE, DEV_NETMAP, DEV_PCAP, DEV_TAP };
313 * Arguments for a new thread. The same structure is used by
314 * the source and the sink
323 /* these ought to be volatile, but they are
324 * only sampled and errors should not accumulate
328 struct timespec tic, toc;
340 static __inline uint16_t
341 cksum_add(uint16_t sum, uint16_t a)
346 return (res + (res < a));
350 extract_ipv4_addr(char *name, uint32_t *addr, uint16_t *port)
355 pp = strchr(name, ':');
356 if (pp != NULL) { /* do we have ports ? */
358 *port = (uint16_t)strtol(pp, NULL, 0);
361 inet_pton(AF_INET, name, &a);
362 *addr = ntohl(a.s_addr);
366 extract_ipv6_addr(char *name, struct in6_addr *addr, uint16_t *port,
372 * We accept IPv6 address in the following form:
373 * group@[2001:DB8::1001]:port (w/ brackets and port)
374 * group@[2001:DB8::1] (w/ brackets and w/o port)
375 * group@2001:DB8::1234 (w/o brackets and w/o port)
377 pp = strchr(name, '@');
380 *group = (uint8_t)strtol(name, NULL, 0);
387 pp = strchr(name, ']');
390 if (pp != NULL && *pp != ':')
392 if (pp != NULL) { /* do we have ports ? */
394 *port = (uint16_t)strtol(pp, NULL, 0);
396 inet_pton(AF_INET6, name, addr);
399 * extract the extremes from a range of ipv4 addresses.
400 * addr_lo[-addr_hi][:port_lo[-port_hi]]
403 extract_ip_range(struct ip_range *r, int af)
405 char *name, *ap, start[INET6_ADDRSTRLEN];
406 char end[INET6_ADDRSTRLEN];
411 D("extract IP range from %s", r->name);
413 name = strdup(r->name);
418 /* the first - splits start/end of range */
419 ap = strchr(name, '-');
422 r->port0 = 1234; /* default port */
423 if (af == AF_INET6) {
424 r->ipv6.sgroup = 7; /* default group */
425 extract_ipv6_addr(name, &r->ipv6.start, &r->port0,
428 extract_ipv4_addr(name, &r->ipv4.start, &r->port0);
431 if (af == AF_INET6) {
433 r->ipv6.egroup = r->ipv6.sgroup;
434 extract_ipv6_addr(ap, &r->ipv6.end, &r->port1,
437 r->ipv6.end = r->ipv6.start;
438 r->ipv6.egroup = r->ipv6.sgroup;
442 extract_ipv4_addr(ap, &r->ipv4.end, &r->port1);
443 if (r->ipv4.start > r->ipv4.end) {
445 r->ipv4.end = r->ipv4.start;
449 r->ipv4.end = r->ipv4.start;
452 if (r->port0 > r->port1) {
458 a.s_addr = htonl(r->ipv4.start);
459 inet_ntop(af, &a, start, sizeof(start));
460 a.s_addr = htonl(r->ipv4.end);
461 inet_ntop(af, &a, end, sizeof(end));
463 inet_ntop(af, &r->ipv6.start, start, sizeof(start));
464 inet_ntop(af, &r->ipv6.end, end, sizeof(end));
467 D("range is %s:%d to %s:%d", start, r->port0, end, r->port1);
469 D("range is %d@[%s]:%d to %d@[%s]:%d", r->ipv6.sgroup,
470 start, r->port0, r->ipv6.egroup, end, r->port1);
473 if (r->port0 != r->port1 ||
474 (af == AF_INET && r->ipv4.start != r->ipv4.end) ||
476 !IN6_ARE_ADDR_EQUAL(&r->ipv6.start, &r->ipv6.end)))
482 extract_mac_range(struct mac_range *r)
484 struct ether_addr *e;
486 D("extract MAC range from %s", r->name);
488 e = ether_aton(r->name);
490 D("invalid MAC address '%s'", r->name);
493 bcopy(e, &r->start, 6);
494 bcopy(e, &r->end, 6);
496 bcopy(targ->src_mac, eh->ether_shost, 6);
497 p = index(targ->g->src_mac, '-');
499 targ->src_mac_range = atoi(p+1);
501 bcopy(ether_aton(targ->g->dst_mac), targ->dst_mac, 6);
502 bcopy(targ->dst_mac, eh->ether_dhost, 6);
503 p = index(targ->g->dst_mac, '-');
505 targ->dst_mac_range = atoi(p+1);
508 D("%s starts at %s", r->name, ether_ntoa(&r->start));
512 static struct targ *targs;
513 static int global_nthreads;
515 /* control-C handler */
521 (void)sig; /* UNUSED */
522 D("received control-C on thread %p", (void *)pthread_self());
523 for (i = 0; i < global_nthreads; i++) {
528 /* sysctl wrapper to return the number of active CPUs */
533 #if defined (__FreeBSD__)
534 int mib[2] = { CTL_HW, HW_NCPU };
535 size_t len = sizeof(mib);
536 sysctl(mib, 2, &ncpus, &len, NULL, 0);
538 ncpus = sysconf(_SC_NPROCESSORS_ONLN);
539 #elif defined(_WIN32)
542 GetSystemInfo(&sysinfo);
543 ncpus = sysinfo.dwNumberOfProcessors;
552 #define sockaddr_dl sockaddr_ll
553 #define sdl_family sll_family
554 #define AF_LINK AF_PACKET
555 #define LLADDR(s) s->sll_addr;
556 #include <linux/if_tun.h>
557 #define TAP_CLONEDEV "/dev/net/tun"
558 #endif /* __linux__ */
561 #include <net/if_tun.h>
562 #define TAP_CLONEDEV "/dev/tap"
563 #endif /* __FreeBSD */
566 // #warning TAP not supported on apple ?
567 #include <net/if_utun.h>
568 #define TAP_CLONEDEV "/dev/tap"
569 #endif /* __APPLE__ */
573 * parse the vale configuration in conf and put it in nmr.
574 * Return the flag set if necessary.
575 * The configuration may consist of 1 to 4 numbers separated
576 * by commas: #tx-slots,#rx-slots,#tx-rings,#rx-rings.
577 * Missing numbers or zeroes stand for default values.
578 * As an additional convenience, if exactly one number
579 * is specified, then this is assigned to both #tx-slots and #rx-slots.
580 * If there is no 4th number, then the 3rd is assigned to both #tx-rings
584 parse_nmr_config(const char* conf, struct nmreq *nmr)
589 nmr->nr_tx_rings = nmr->nr_rx_rings = 0;
590 nmr->nr_tx_slots = nmr->nr_rx_slots = 0;
591 if (conf == NULL || ! *conf)
594 for (i = 0, tok = strtok(w, ","); tok; i++, tok = strtok(NULL, ",")) {
598 nmr->nr_tx_slots = nmr->nr_rx_slots = v;
601 nmr->nr_rx_slots = v;
604 nmr->nr_tx_rings = nmr->nr_rx_rings = v;
607 nmr->nr_rx_rings = v;
610 D("ignored config: %s", tok);
614 D("txr %d txd %d rxr %d rxd %d",
615 nmr->nr_tx_rings, nmr->nr_tx_slots,
616 nmr->nr_rx_rings, nmr->nr_rx_slots);
618 return (nmr->nr_tx_rings || nmr->nr_tx_slots ||
619 nmr->nr_rx_rings || nmr->nr_rx_slots) ?
620 NM_OPEN_RING_CFG : 0;
625 * locate the src mac address for our interface, put it
626 * into the user-supplied buffer. return 0 if ok, -1 on error.
629 source_hwaddr(const char *ifname, char *buf)
631 struct ifaddrs *ifaphead, *ifap;
633 if (getifaddrs(&ifaphead) != 0) {
634 D("getifaddrs %s failed", ifname);
638 for (ifap = ifaphead; ifap; ifap = ifap->ifa_next) {
639 struct sockaddr_dl *sdl =
640 (struct sockaddr_dl *)ifap->ifa_addr;
643 if (!sdl || sdl->sdl_family != AF_LINK)
645 if (strncmp(ifap->ifa_name, ifname, IFNAMSIZ) != 0)
647 mac = (uint8_t *)LLADDR(sdl);
648 sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
649 mac[0], mac[1], mac[2],
650 mac[3], mac[4], mac[5]);
652 D("source hwaddr %s", buf);
655 freeifaddrs(ifaphead);
660 /* set the thread affinity. */
662 setaffinity(pthread_t me, int i)
669 /* Set thread affinity affinity.*/
671 CPU_SET(i, &cpumask);
673 if (pthread_setaffinity_np(me, sizeof(cpuset_t), &cpumask) != 0) {
674 D("Unable to set affinity: %s", strerror(errno));
681 /* Compute the checksum of the given ip header. */
683 checksum(const void *data, uint16_t len, uint32_t sum)
685 const uint8_t *addr = data;
688 /* Checksum all the pairs of bytes first... */
689 for (i = 0; i < (len & ~1U); i += 2) {
690 sum += (u_int16_t)ntohs(*((u_int16_t *)(addr + i)));
695 * If there's a single byte left over, checksum it, too.
696 * Network byte order is big-endian, so the remaining byte is
708 wrapsum(uint32_t sum)
714 /* Check the payload of the packet for errors (use it for debug).
715 * Look for consecutive ascii representations of the size of the packet.
718 dump_payload(const char *_p, int len, struct netmap_ring *ring, int cur)
722 const unsigned char *p = (const unsigned char *)_p;
724 /* get the length in ASCII of the length of the packet. */
726 printf("ring %p cur %5d [buf %6d flags 0x%04x len %5d]\n",
727 ring, cur, ring->slot[cur].buf_idx,
728 ring->slot[cur].flags, len);
729 /* hexdump routine */
730 for (i = 0; i < len; ) {
731 memset(buf, ' ', sizeof(buf));
732 sprintf(buf, "%5d: ", i);
734 for (j=0; j < 16 && i < len; i++, j++)
735 sprintf(buf+7+j*3, "%02x ", (uint8_t)(p[i]));
737 for (j=0; j < 16 && i < len; i++, j++)
738 sprintf(buf+7+j + 48, "%c",
739 isprint(p[i]) ? p[i] : '.');
745 * Fill a packet with some payload.
746 * We create a UDP packet so the payload starts at
747 * 14+20+8 = 42 bytes.
750 #define uh_sport source
751 #define uh_dport dest
757 update_ip(struct pkt *pkt, struct targ *t)
759 struct glob_arg *g = t->g;
762 uint32_t oaddr, naddr;
763 uint16_t oport, nport;
764 uint16_t ip_sum, udp_sum;
766 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
767 memcpy(&udp, &pkt->ipv4.udp, sizeof(udp));
769 ip_sum = udp_sum = 0;
770 naddr = oaddr = ntohl(ip.ip_src.s_addr);
771 nport = oport = ntohs(udp.uh_sport);
772 if (g->options & OPT_RANDOM_SRC) {
773 ip.ip_src.s_addr = nrand48(t->seed);
774 udp.uh_sport = nrand48(t->seed);
775 naddr = ntohl(ip.ip_src.s_addr);
776 nport = ntohs(udp.uh_sport);
779 if (oport < g->src_ip.port1) {
781 udp.uh_sport = htons(nport);
784 nport = g->src_ip.port0;
785 udp.uh_sport = htons(nport);
786 if (oaddr < g->src_ip.ipv4.end) {
788 ip.ip_src.s_addr = htonl(naddr);
791 naddr = g->src_ip.ipv4.start;
792 ip.ip_src.s_addr = htonl(naddr);
794 /* update checksums if needed */
795 if (oaddr != naddr) {
796 ip_sum = cksum_add(ip_sum, ~oaddr >> 16);
797 ip_sum = cksum_add(ip_sum, ~oaddr & 0xffff);
798 ip_sum = cksum_add(ip_sum, naddr >> 16);
799 ip_sum = cksum_add(ip_sum, naddr & 0xffff);
801 if (oport != nport) {
802 udp_sum = cksum_add(udp_sum, ~oport);
803 udp_sum = cksum_add(udp_sum, nport);
806 naddr = oaddr = ntohl(ip.ip_dst.s_addr);
807 nport = oport = ntohs(udp.uh_dport);
808 if (g->options & OPT_RANDOM_DST) {
809 ip.ip_dst.s_addr = nrand48(t->seed);
810 udp.uh_dport = nrand48(t->seed);
811 naddr = ntohl(ip.ip_dst.s_addr);
812 nport = ntohs(udp.uh_dport);
815 if (oport < g->dst_ip.port1) {
817 udp.uh_dport = htons(nport);
820 nport = g->dst_ip.port0;
821 udp.uh_dport = htons(nport);
822 if (oaddr < g->dst_ip.ipv4.end) {
824 ip.ip_dst.s_addr = htonl(naddr);
827 naddr = g->dst_ip.ipv4.start;
828 ip.ip_dst.s_addr = htonl(naddr);
830 /* update checksums */
831 if (oaddr != naddr) {
832 ip_sum = cksum_add(ip_sum, ~oaddr >> 16);
833 ip_sum = cksum_add(ip_sum, ~oaddr & 0xffff);
834 ip_sum = cksum_add(ip_sum, naddr >> 16);
835 ip_sum = cksum_add(ip_sum, naddr & 0xffff);
837 if (oport != nport) {
838 udp_sum = cksum_add(udp_sum, ~oport);
839 udp_sum = cksum_add(udp_sum, nport);
842 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(udp_sum));
844 ip.ip_sum = ~cksum_add(~ip.ip_sum, htons(ip_sum));
845 udp.uh_sum = ~cksum_add(~udp.uh_sum, htons(ip_sum));
847 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
848 memcpy(&pkt->ipv4.udp, &udp, sizeof(udp));
852 #define s6_addr16 __u6_addr.__u6_addr16
855 update_ip6(struct pkt *pkt, struct targ *t)
857 struct glob_arg *g = t->g;
861 uint16_t oaddr, naddr;
862 uint16_t oport, nport;
865 memcpy(&ip6, &pkt->ipv6.ip, sizeof(ip6));
866 memcpy(&udp, &pkt->ipv6.udp, sizeof(udp));
869 group = g->src_ip.ipv6.sgroup;
870 naddr = oaddr = ntohs(ip6.ip6_src.s6_addr16[group]);
871 nport = oport = ntohs(udp.uh_sport);
872 if (g->options & OPT_RANDOM_SRC) {
873 ip6.ip6_src.s6_addr16[group] = nrand48(t->seed);
874 udp.uh_sport = nrand48(t->seed);
875 naddr = ntohs(ip6.ip6_src.s6_addr16[group]);
876 nport = ntohs(udp.uh_sport);
879 if (oport < g->src_ip.port1) {
881 udp.uh_sport = htons(nport);
884 nport = g->src_ip.port0;
885 udp.uh_sport = htons(nport);
886 if (oaddr < ntohs(g->src_ip.ipv6.end.s6_addr16[group])) {
888 ip6.ip6_src.s6_addr16[group] = htons(naddr);
891 naddr = ntohs(g->src_ip.ipv6.start.s6_addr16[group]);
892 ip6.ip6_src.s6_addr16[group] = htons(naddr);
894 /* update checksums if needed */
896 udp_sum = cksum_add(~oaddr, naddr);
898 udp_sum = cksum_add(udp_sum,
899 cksum_add(~oport, nport));
901 group = g->dst_ip.ipv6.egroup;
902 naddr = oaddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
903 nport = oport = ntohs(udp.uh_dport);
904 if (g->options & OPT_RANDOM_DST) {
905 ip6.ip6_dst.s6_addr16[group] = nrand48(t->seed);
906 udp.uh_dport = nrand48(t->seed);
907 naddr = ntohs(ip6.ip6_dst.s6_addr16[group]);
908 nport = ntohs(udp.uh_dport);
911 if (oport < g->dst_ip.port1) {
913 udp.uh_dport = htons(nport);
916 nport = g->dst_ip.port0;
917 udp.uh_dport = htons(nport);
918 if (oaddr < ntohs(g->dst_ip.ipv6.end.s6_addr16[group])) {
920 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
923 naddr = ntohs(g->dst_ip.ipv6.start.s6_addr16[group]);
924 ip6.ip6_dst.s6_addr16[group] = htons(naddr);
926 /* update checksums */
928 udp_sum = cksum_add(udp_sum,
929 cksum_add(~oaddr, naddr));
931 udp_sum = cksum_add(udp_sum,
932 cksum_add(~oport, nport));
934 udp.uh_sum = ~cksum_add(~udp.uh_sum, udp_sum);
935 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
936 memcpy(&pkt->ipv6.udp, &udp, sizeof(udp));
940 update_addresses(struct pkt *pkt, struct targ *t)
943 if (t->g->af == AF_INET)
949 * initialize one packet and prepare for the next one.
950 * The copy could be done better instead of repeating it each time.
953 initialize_packet(struct targ *targ)
955 struct pkt *pkt = &targ->pkt;
956 struct ether_header *eh;
963 const char *payload = targ->g->options & OPT_INDIRECT ?
964 indirect_payload : default_payload;
965 int i, l0 = strlen(payload);
968 char errbuf[PCAP_ERRBUF_SIZE];
970 struct pcap_pkthdr *header;
971 const unsigned char *packet;
973 /* Read a packet from a PCAP file if asked. */
974 if (targ->g->packet_file != NULL) {
975 if ((file = pcap_open_offline(targ->g->packet_file,
977 D("failed to open pcap file %s",
978 targ->g->packet_file);
979 if (pcap_next_ex(file, &header, &packet) < 0)
980 D("failed to read packet from %s",
981 targ->g->packet_file);
982 if ((targ->frame = malloc(header->caplen)) == NULL)
984 bcopy(packet, (unsigned char *)targ->frame, header->caplen);
985 targ->g->pkt_size = header->caplen;
991 paylen = targ->g->pkt_size - sizeof(*eh) -
992 (targ->g->af == AF_INET ? sizeof(ip): sizeof(ip6));
994 /* create a nice NUL-terminated string */
995 for (i = 0; i < paylen; i += l0) {
997 l0 = paylen - i; // last round
998 bcopy(payload, PKT(pkt, body, targ->g->af) + i, l0);
1000 PKT(pkt, body, targ->g->af)[i - 1] = '\0';
1002 /* prepare the headers */
1004 bcopy(&targ->g->src_mac.start, eh->ether_shost, 6);
1005 bcopy(&targ->g->dst_mac.start, eh->ether_dhost, 6);
1007 if (targ->g->af == AF_INET) {
1008 eh->ether_type = htons(ETHERTYPE_IP);
1009 memcpy(&ip, &pkt->ipv4.ip, sizeof(ip));
1010 udp_ptr = &pkt->ipv4.udp;
1011 ip.ip_v = IPVERSION;
1012 ip.ip_hl = sizeof(ip) >> 2;
1014 ip.ip_tos = IPTOS_LOWDELAY;
1015 ip.ip_len = htons(targ->g->pkt_size - sizeof(*eh));
1017 ip.ip_off = htons(IP_DF); /* Don't fragment */
1018 ip.ip_ttl = IPDEFTTL;
1019 ip.ip_p = IPPROTO_UDP;
1020 ip.ip_dst.s_addr = htonl(targ->g->dst_ip.ipv4.start);
1021 ip.ip_src.s_addr = htonl(targ->g->src_ip.ipv4.start);
1022 ip.ip_sum = wrapsum(checksum(&ip, sizeof(ip), 0));
1023 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1025 eh->ether_type = htons(ETHERTYPE_IPV6);
1026 memcpy(&ip6, &pkt->ipv4.ip, sizeof(ip6));
1027 udp_ptr = &pkt->ipv6.udp;
1029 ip6.ip6_plen = htons(paylen);
1030 ip6.ip6_vfc = IPV6_VERSION;
1031 ip6.ip6_nxt = IPPROTO_UDP;
1032 ip6.ip6_hlim = IPV6_DEFHLIM;
1033 ip6.ip6_src = targ->g->src_ip.ipv6.start;
1034 ip6.ip6_dst = targ->g->dst_ip.ipv6.start;
1036 memcpy(&udp, udp_ptr, sizeof(udp));
1038 udp.uh_sport = htons(targ->g->src_ip.port0);
1039 udp.uh_dport = htons(targ->g->dst_ip.port0);
1040 udp.uh_ulen = htons(paylen);
1041 if (targ->g->af == AF_INET) {
1042 /* Magic: taken from sbin/dhclient/packet.c */
1043 udp.uh_sum = wrapsum(
1044 checksum(&udp, sizeof(udp), /* udp header */
1045 checksum(pkt->ipv4.body, /* udp payload */
1046 paylen - sizeof(udp),
1047 checksum(&pkt->ipv4.ip.ip_src, /* pseudo header */
1048 2 * sizeof(pkt->ipv4.ip.ip_src),
1049 IPPROTO_UDP + (u_int32_t)ntohs(udp.uh_ulen)))));
1050 memcpy(&pkt->ipv4.ip, &ip, sizeof(ip));
1052 /* Save part of pseudo header checksum into csum */
1053 csum = IPPROTO_UDP << 24;
1054 csum = checksum(&csum, sizeof(csum), paylen);
1055 udp.uh_sum = wrapsum(
1056 checksum(udp_ptr, sizeof(udp), /* udp header */
1057 checksum(pkt->ipv6.body, /* udp payload */
1058 paylen - sizeof(udp),
1059 checksum(&pkt->ipv6.ip.ip6_src, /* pseudo header */
1060 2 * sizeof(pkt->ipv6.ip.ip6_src), csum))));
1061 memcpy(&pkt->ipv6.ip, &ip6, sizeof(ip6));
1063 memcpy(udp_ptr, &udp, sizeof(udp));
1065 bzero(&pkt->vh, sizeof(pkt->vh));
1066 // dump_payload((void *)pkt, targ->g->pkt_size, NULL, 0);
1070 get_vnet_hdr_len(struct glob_arg *g)
1075 memset(&req, 0, sizeof(req));
1076 bcopy(g->nmd->req.nr_name, req.nr_name, sizeof(req.nr_name));
1077 req.nr_version = NETMAP_API;
1078 req.nr_cmd = NETMAP_VNET_HDR_GET;
1079 err = ioctl(g->main_fd, NIOCREGIF, &req);
1081 D("Unable to get virtio-net header length");
1085 g->virt_header = req.nr_arg1;
1086 if (g->virt_header) {
1087 D("Port requires virtio-net header, length = %d",
1093 set_vnet_hdr_len(struct glob_arg *g)
1095 int err, l = g->virt_header;
1101 memset(&req, 0, sizeof(req));
1102 bcopy(g->nmd->req.nr_name, req.nr_name, sizeof(req.nr_name));
1103 req.nr_version = NETMAP_API;
1104 req.nr_cmd = NETMAP_BDG_VNET_HDR;
1106 err = ioctl(g->main_fd, NIOCREGIF, &req);
1108 D("Unable to set virtio-net header length %d", l);
1113 * create and enqueue a batch of packets on a ring.
1114 * On the last one set NS_REPORT to tell the driver to generate
1115 * an interrupt when done.
1118 send_packets(struct netmap_ring *ring, struct pkt *pkt, void *frame,
1119 int size, struct targ *t, u_int count, int options)
1121 u_int n, sent, cur = ring->cur;
1122 u_int frags = t->frags;
1123 u_int frag_size = t->frag_size;
1124 struct netmap_slot *slot = &ring->slot[cur];
1126 n = nm_ring_space(ring);
1128 if (options & (OPT_COPY | OPT_PREFETCH) ) {
1129 for (sent = 0; sent < count; sent++) {
1130 struct netmap_slot *slot = &ring->slot[cur];
1131 char *p = NETMAP_BUF(ring, slot->buf_idx);
1133 __builtin_prefetch(p);
1134 cur = nm_ring_next(ring, cur);
1139 for (sent = 0; sent < count && n >= frags; sent++, n--) {
1142 u_int tosend = size;
1144 slot = &ring->slot[cur];
1145 p = NETMAP_BUF(ring, slot->buf_idx);
1146 buf_changed = slot->flags & NS_BUF_CHANGED;
1149 if (options & OPT_RUBBISH) {
1151 } else if (options & OPT_INDIRECT) {
1152 slot->flags |= NS_INDIRECT;
1153 slot->ptr = (uint64_t)((uintptr_t)frame);
1154 } else if (frags > 1) {
1156 const char *f = frame;
1158 for (i = 0; i < frags - 1; i++) {
1159 memcpy(fp, f, frag_size);
1160 slot->len = frag_size;
1161 slot->flags = NS_MOREFRAG;
1162 if (options & OPT_DUMP)
1163 dump_payload(fp, frag_size, ring, cur);
1164 tosend -= frag_size;
1166 cur = nm_ring_next(ring, cur);
1167 slot = &ring->slot[cur];
1168 fp = NETMAP_BUF(ring, slot->buf_idx);
1173 memcpy(p, f, tosend);
1174 update_addresses(pkt, t);
1175 } else if ((options & (OPT_COPY | OPT_MEMCPY)) || buf_changed) {
1176 if (options & OPT_COPY)
1177 nm_pkt_copy(frame, p, size);
1179 memcpy(p, frame, size);
1180 update_addresses(pkt, t);
1181 } else if (options & OPT_PREFETCH) {
1182 __builtin_prefetch(p);
1185 if (options & OPT_DUMP)
1186 dump_payload(p, tosend, ring, cur);
1187 cur = nm_ring_next(ring, cur);
1190 slot->flags |= NS_REPORT;
1191 ring->head = ring->cur = cur;
1194 /* tell netmap that we need more slots */
1195 ring->cur = ring->tail;
1202 * Index of the highest bit set
1207 uint64_t m = 1ULL << 63;
1210 for (i = 63; i >= 0; i--, m >>=1)
1217 * wait until ts, either busy or sleeping if more than 1ms.
1218 * Return wakeup time.
1220 static struct timespec
1221 wait_time(struct timespec ts)
1224 struct timespec w, cur;
1225 clock_gettime(CLOCK_REALTIME_PRECISE, &cur);
1226 w = timespec_sub(ts, cur);
1229 else if (w.tv_sec > 0 || w.tv_nsec > 1000000)
1235 * Send a packet, and wait for a response.
1236 * The payload (after UDP header, ofs 42) has a 4-byte sequence
1237 * followed by a struct timeval (or bintime?)
1241 ping_body(void *data)
1243 struct targ *targ = (struct targ *) data;
1244 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1245 struct netmap_if *nifp = targ->nmd->nifp;
1249 struct timespec ts, now, last_print;
1250 struct timespec nexttime = {0, 0}; /* silence compiler */
1251 uint64_t sent = 0, n = targ->g->npackets;
1252 uint64_t count = 0, t_cur, t_min = ~0, av = 0;
1253 uint64_t g_min = ~0, g_av = 0;
1254 uint64_t buckets[64]; /* bins for delays, ns */
1255 int rate_limit = targ->g->tx_rate, tosend = 0;
1257 frame = (char*)&targ->pkt + sizeof(targ->pkt.vh) - targ->g->virt_header;
1258 size = targ->g->pkt_size + targ->g->virt_header;
1261 if (targ->g->nthreads > 1) {
1262 D("can only ping with 1 thread");
1266 bzero(&buckets, sizeof(buckets));
1267 clock_gettime(CLOCK_REALTIME_PRECISE, &last_print);
1270 targ->tic = timespec_add(now, (struct timespec){2,0});
1271 targ->tic.tv_nsec = 0;
1272 wait_time(targ->tic);
1273 nexttime = targ->tic;
1275 while (!targ->cancel && (n == 0 || sent < n)) {
1276 struct netmap_ring *ring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1277 struct netmap_slot *slot;
1280 uint64_t limit, event = 0;
1282 if (rate_limit && tosend <= 0) {
1283 tosend = targ->g->burst;
1284 nexttime = timespec_add(nexttime, targ->g->tx_period);
1285 wait_time(nexttime);
1288 limit = rate_limit ? tosend : targ->g->burst;
1289 if (n > 0 && n - sent < limit)
1291 for (m = 0; (unsigned)m < limit; m++) {
1292 slot = &ring->slot[ring->cur];
1294 p = NETMAP_BUF(ring, slot->buf_idx);
1296 if (nm_ring_empty(ring)) {
1297 D("-- ouch, cannot send");
1301 nm_pkt_copy(frame, p, size);
1302 clock_gettime(CLOCK_REALTIME_PRECISE, &ts);
1303 bcopy(&sent, p+42, sizeof(sent));
1304 tp = (struct tstamp *)(p+46);
1305 tp->sec = (uint32_t)ts.tv_sec;
1306 tp->nsec = (uint32_t)ts.tv_nsec;
1308 ring->head = ring->cur = nm_ring_next(ring, ring->cur);
1313 targ->ctr.pkts = sent;
1314 targ->ctr.bytes = sent*size;
1315 targ->ctr.events = event;
1319 rv = ioctl(pfd.fd, NIOCTXSYNC, NULL);
1321 D("TXSYNC error on queue %d: %s", targ->me,
1325 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1327 /* should use a parameter to decide how often to send */
1328 if ( (rv = poll(&pfd, 1, 3000)) <= 0) {
1329 D("poll error on queue %d: %s", targ->me,
1330 (rv ? strerror(errno) : "timeout"));
1333 #endif /* BUSYWAIT */
1334 /* see what we got back */
1336 for (i = targ->nmd->first_rx_ring;
1337 i <= targ->nmd->last_rx_ring; i++) {
1338 ring = NETMAP_RXRING(nifp, i);
1339 while (!nm_ring_empty(ring)) {
1344 slot = &ring->slot[ring->cur];
1345 p = NETMAP_BUF(ring, slot->buf_idx);
1347 clock_gettime(CLOCK_REALTIME_PRECISE, &now);
1348 bcopy(p+42, &seq, sizeof(seq));
1349 tp = (struct tstamp *)(p+46);
1350 ts.tv_sec = (time_t)tp->sec;
1351 ts.tv_nsec = (long)tp->nsec;
1352 ts.tv_sec = now.tv_sec - ts.tv_sec;
1353 ts.tv_nsec = now.tv_nsec - ts.tv_nsec;
1354 if (ts.tv_nsec < 0) {
1355 ts.tv_nsec += 1000000000;
1358 if (0) D("seq %d/%llu delta %d.%09d", seq,
1359 (unsigned long long)sent,
1360 (int)ts.tv_sec, (int)ts.tv_nsec);
1361 t_cur = ts.tv_sec * 1000000000UL + ts.tv_nsec;
1368 /* now store it in a bucket */
1369 ring->head = ring->cur = nm_ring_next(ring, ring->cur);
1373 //D("tx %d rx %d", sent, rx);
1375 ts.tv_sec = now.tv_sec - last_print.tv_sec;
1376 ts.tv_nsec = now.tv_nsec - last_print.tv_nsec;
1377 if (ts.tv_nsec < 0) {
1378 ts.tv_nsec += 1000000000;
1381 if (ts.tv_sec >= 1) {
1382 D("count %d RTT: min %d av %d ns",
1383 (int)count, (int)t_min, (int)(av/count));
1384 int k, j, kmin, off;
1387 for (kmin = 0; kmin < 64; kmin ++)
1390 for (k = 63; k >= kmin; k--)
1395 for (j = kmin; j <= k; j++) {
1396 off += sprintf(buf + off, " %5d", (int)buckets[j]);
1398 D("k: %d .. %d\n\t%s", 1<<kmin, 1<<k, buf);
1399 bzero(&buckets, sizeof(buckets));
1409 if (rx < m && ts.tv_sec <= 3 && !targ->cancel)
1411 #endif /* BUSYWAIT */
1415 D("RTT over %llu packets: min %d av %d ns",
1416 (long long unsigned)sent, (int)g_min,
1417 (int)((double)g_av/sent));
1419 targ->completed = 1;
1421 /* reset the ``used`` flag. */
1429 * reply to ping requests
1432 pong_body(void *data)
1434 struct targ *targ = (struct targ *) data;
1435 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1436 struct netmap_if *nifp = targ->nmd->nifp;
1437 struct netmap_ring *txring, *rxring;
1439 uint64_t sent = 0, n = targ->g->npackets;
1441 if (targ->g->nthreads > 1) {
1442 D("can only reply ping with 1 thread");
1446 D("understood ponger %llu but don't know how to do it",
1447 (unsigned long long)n);
1448 while (!targ->cancel && (n == 0 || sent < n)) {
1449 uint32_t txcur, txavail;
1452 ioctl(pfd.fd, NIOCRXSYNC, NULL);
1455 if ( (rv = poll(&pfd, 1, 1000)) <= 0) {
1456 D("poll error on queue %d: %s", targ->me,
1457 rv ? strerror(errno) : "timeout");
1461 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1462 txcur = txring->cur;
1463 txavail = nm_ring_space(txring);
1464 /* see what we got back */
1465 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1466 rxring = NETMAP_RXRING(nifp, i);
1467 while (!nm_ring_empty(rxring)) {
1468 uint16_t *spkt, *dpkt;
1469 uint32_t cur = rxring->cur;
1470 struct netmap_slot *slot = &rxring->slot[cur];
1472 src = NETMAP_BUF(rxring, slot->buf_idx);
1473 //D("got pkt %p of size %d", src, slot->len);
1474 rxring->head = rxring->cur = nm_ring_next(rxring, cur);
1478 dst = NETMAP_BUF(txring,
1479 txring->slot[txcur].buf_idx);
1481 dpkt = (uint16_t *)dst;
1482 spkt = (uint16_t *)src;
1483 nm_pkt_copy(src, dst, slot->len);
1484 /* swap source and destination MAC */
1491 txring->slot[txcur].len = slot->len;
1492 txcur = nm_ring_next(txring, txcur);
1497 txring->head = txring->cur = txcur;
1498 targ->ctr.pkts = sent;
1500 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1502 //D("tx %d rx %d", sent, rx);
1505 targ->completed = 1;
1507 /* reset the ``used`` flag. */
1515 sender_body(void *data)
1517 struct targ *targ = (struct targ *) data;
1518 struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1519 struct netmap_if *nifp;
1520 struct netmap_ring *txring = NULL;
1522 uint64_t n = targ->g->npackets / targ->g->nthreads;
1525 int options = targ->g->options | OPT_COPY;
1526 struct timespec nexttime = { 0, 0}; // XXX silence compiler
1527 int rate_limit = targ->g->tx_rate;
1528 struct pkt *pkt = &targ->pkt;
1532 if (targ->frame == NULL) {
1533 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1534 size = targ->g->pkt_size + targ->g->virt_header;
1536 frame = targ->frame;
1537 size = targ->g->pkt_size;
1540 D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1541 if (setaffinity(targ->thread, targ->affinity))
1545 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1547 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1548 targ->tic.tv_nsec = 0;
1549 wait_time(targ->tic);
1550 nexttime = targ->tic;
1552 if (targ->g->dev_type == DEV_TAP) {
1553 D("writing to file desc %d", targ->g->main_fd);
1555 for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1556 if (write(targ->g->main_fd, frame, size) != -1)
1558 update_addresses(pkt, targ);
1560 targ->ctr.pkts = sent;
1561 targ->ctr.bytes = sent*size;
1562 targ->ctr.events = sent;
1567 } else if (targ->g->dev_type == DEV_PCAP) {
1568 pcap_t *p = targ->g->p;
1570 for (i = 0; !targ->cancel && (n == 0 || sent < n); i++) {
1571 if (pcap_inject(p, frame, size) != -1)
1573 update_addresses(pkt, targ);
1575 targ->ctr.pkts = sent;
1576 targ->ctr.bytes = sent*size;
1577 targ->ctr.events = sent;
1581 #endif /* NO_PCAP */
1584 u_int bufsz, mtu = targ->g->mtu;
1586 nifp = targ->nmd->nifp;
1587 txring = NETMAP_TXRING(nifp, targ->nmd->first_tx_ring);
1588 bufsz = txring->nr_buf_size;
1591 targ->frag_size = targ->g->pkt_size / targ->frags;
1592 if (targ->frag_size > mtu) {
1593 targ->frags = targ->g->pkt_size / mtu;
1594 targ->frag_size = mtu;
1595 if (targ->g->pkt_size % mtu != 0)
1598 D("frags %u frag_size %u", targ->frags, targ->frag_size);
1599 while (!targ->cancel && (n == 0 || sent < n)) {
1602 if (rate_limit && tosend <= 0) {
1603 tosend = targ->g->burst;
1604 nexttime = timespec_add(nexttime, targ->g->tx_period);
1605 wait_time(nexttime);
1609 * wait for available room in the send queue(s)
1613 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1614 D("ioctl error on queue %d: %s", targ->me,
1618 #else /* !BUSYWAIT */
1619 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
1622 D("poll error on queue %d: %s", targ->me,
1623 rv ? strerror(errno) : "timeout");
1626 if (pfd.revents & POLLERR) {
1627 D("poll error on %d ring %d-%d", pfd.fd,
1628 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
1631 #endif /* !BUSYWAIT */
1633 * scan our queues and send on those with room
1635 if (options & OPT_COPY && sent > 100000 && !(targ->g->options & OPT_COPY) ) {
1637 options &= ~OPT_COPY;
1639 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1641 uint64_t limit = rate_limit ? tosend : targ->g->burst;
1643 if (n > 0 && n == sent)
1646 if (n > 0 && n - sent < limit)
1648 txring = NETMAP_TXRING(nifp, i);
1649 if (nm_ring_empty(txring))
1652 if (targ->g->pkt_min_size > 0) {
1653 size = nrand48(targ->seed) %
1654 (targ->g->pkt_size - targ->g->pkt_min_size) +
1655 targ->g->pkt_min_size;
1657 m = send_packets(txring, pkt, frame, size, targ,
1659 ND("limit %lu tail %d m %d",
1660 limit, txring->tail, m);
1662 if (m > 0) //XXX-ste: can m be 0?
1664 targ->ctr.pkts = sent;
1665 targ->ctr.bytes += m*size;
1666 targ->ctr.events = event;
1674 /* flush any remaining packets */
1675 if (txring != NULL) {
1676 D("flush tail %d head %d on thread %p",
1677 txring->tail, txring->head,
1678 (void *)pthread_self());
1679 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1682 /* final part: wait all the TX queues to be empty. */
1683 for (i = targ->nmd->first_tx_ring; i <= targ->nmd->last_tx_ring; i++) {
1684 txring = NETMAP_TXRING(nifp, i);
1685 while (!targ->cancel && nm_tx_pending(txring)) {
1686 RD(5, "pending tx tail %d head %d on ring %d",
1687 txring->tail, txring->head, i);
1688 ioctl(pfd.fd, NIOCTXSYNC, NULL);
1689 usleep(1); /* wait 1 tick */
1692 } /* end DEV_NETMAP */
1694 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1695 targ->completed = 1;
1696 targ->ctr.pkts = sent;
1697 targ->ctr.bytes = sent*size;
1698 targ->ctr.events = event;
1700 /* reset the ``used`` flag. */
1709 receive_pcap(u_char *user, const struct pcap_pkthdr * h,
1710 const u_char * bytes)
1712 struct my_ctrs *ctr = (struct my_ctrs *)user;
1713 (void)bytes; /* UNUSED */
1714 ctr->bytes += h->len;
1717 #endif /* !NO_PCAP */
1721 receive_packets(struct netmap_ring *ring, u_int limit, int dump, uint64_t *bytes)
1731 n = nm_ring_space(ring);
1734 for (rx = 0; rx < limit; rx++) {
1735 struct netmap_slot *slot = &ring->slot[cur];
1736 char *p = NETMAP_BUF(ring, slot->buf_idx);
1738 *bytes += slot->len;
1740 dump_payload(p, slot->len, ring, cur);
1741 if (!(slot->flags & NS_MOREFRAG))
1744 cur = nm_ring_next(ring, cur);
1746 ring->head = ring->cur = cur;
1752 receiver_body(void *data)
1754 struct targ *targ = (struct targ *) data;
1755 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
1756 struct netmap_if *nifp;
1757 struct netmap_ring *rxring;
1761 memset(&cur, 0, sizeof(cur));
1763 if (setaffinity(targ->thread, targ->affinity))
1766 D("reading from %s fd %d main_fd %d",
1767 targ->g->ifname, targ->fd, targ->g->main_fd);
1768 /* unbounded wait for the first packet. */
1769 for (;!targ->cancel;) {
1770 i = poll(&pfd, 1, 1000);
1771 if (i > 0 && !(pfd.revents & POLLERR))
1774 D("poll() error: %s", strerror(errno));
1777 if (pfd.revents & POLLERR) {
1781 RD(1, "waiting for initial packets, poll returns %d %d",
1784 /* main loop, exit after 1s silence */
1785 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1786 if (targ->g->dev_type == DEV_TAP) {
1787 while (!targ->cancel) {
1788 char buf[MAX_BODYSIZE];
1789 /* XXX should we poll ? */
1790 i = read(targ->g->main_fd, buf, sizeof(buf));
1793 targ->ctr.bytes += i;
1798 } else if (targ->g->dev_type == DEV_PCAP) {
1799 while (!targ->cancel) {
1800 /* XXX should we poll ? */
1801 pcap_dispatch(targ->g->p, targ->g->burst, receive_pcap,
1802 (u_char *)&targ->ctr);
1805 #endif /* !NO_PCAP */
1807 int dump = targ->g->options & OPT_DUMP;
1809 nifp = targ->nmd->nifp;
1810 while (!targ->cancel) {
1811 /* Once we started to receive packets, wait at most 1 seconds
1814 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
1815 D("ioctl error on queue %d: %s", targ->me,
1819 #else /* !BUSYWAIT */
1820 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
1821 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1822 targ->toc.tv_sec -= 1; /* Subtract timeout time. */
1826 if (pfd.revents & POLLERR) {
1830 #endif /* !BUSYWAIT */
1831 uint64_t cur_space = 0;
1832 for (i = targ->nmd->first_rx_ring; i <= targ->nmd->last_rx_ring; i++) {
1835 rxring = NETMAP_RXRING(nifp, i);
1836 /* compute free space in the ring */
1837 m = rxring->head + rxring->num_slots - rxring->tail;
1838 if (m >= (int) rxring->num_slots)
1839 m -= rxring->num_slots;
1841 if (nm_ring_empty(rxring))
1844 m = receive_packets(rxring, targ->g->burst, dump, &cur.bytes);
1849 cur.min_space = targ->ctr.min_space;
1850 if (cur_space < cur.min_space)
1851 cur.min_space = cur_space;
1856 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
1858 #if !defined(BUSYWAIT)
1861 targ->completed = 1;
1865 /* reset the ``used`` flag. */
1872 txseq_body(void *data)
1874 struct targ *targ = (struct targ *) data;
1875 struct pollfd pfd = { .fd = targ->fd, .events = POLLOUT };
1876 struct netmap_ring *ring;
1879 int options = targ->g->options | OPT_COPY;
1880 struct timespec nexttime = {0, 0};
1881 int rate_limit = targ->g->tx_rate;
1882 struct pkt *pkt = &targ->pkt;
1883 int frags = targ->g->frags;
1884 uint32_t sequence = 0;
1889 if (targ->g->nthreads > 1) {
1890 D("can only txseq ping with 1 thread");
1894 if (targ->g->npackets > 0) {
1895 D("Ignoring -n argument");
1898 frame = (char *)pkt + sizeof(pkt->vh) - targ->g->virt_header;
1899 size = targ->g->pkt_size + targ->g->virt_header;
1901 D("start, fd %d main_fd %d", targ->fd, targ->g->main_fd);
1902 if (setaffinity(targ->thread, targ->affinity))
1905 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
1907 targ->tic = timespec_add(targ->tic, (struct timespec){2,0});
1908 targ->tic.tv_nsec = 0;
1909 wait_time(targ->tic);
1910 nexttime = targ->tic;
1913 /* Only use the first queue. */
1914 ring = NETMAP_TXRING(targ->nmd->nifp, targ->nmd->first_tx_ring);
1916 while (!targ->cancel) {
1925 budget = targ->g->burst;
1927 } else if (budget <= 0) {
1928 budget = targ->g->burst;
1929 nexttime = timespec_add(nexttime, targ->g->tx_period);
1930 wait_time(nexttime);
1933 /* wait for available room in the send queue */
1936 if (ioctl(pfd.fd, NIOCTXSYNC, NULL) < 0) {
1937 D("ioctl error on queue %d: %s", targ->me,
1941 #else /* !BUSYWAIT */
1942 if ( (rv = poll(&pfd, 1, 2000)) <= 0) {
1945 D("poll error on queue %d: %s", targ->me,
1946 rv ? strerror(errno) : "timeout");
1949 if (pfd.revents & POLLERR) {
1950 D("poll error on %d ring %d-%d", pfd.fd,
1951 targ->nmd->first_tx_ring, targ->nmd->last_tx_ring);
1954 #endif /* !BUSYWAIT */
1956 /* If no room poll() again. */
1957 space = nm_ring_space(ring);
1964 if (space < limit) {
1968 /* Cut off ``limit`` to make sure is multiple of ``frags``. */
1970 limit = (limit / frags) * frags;
1973 limit = sent + limit; /* Convert to absolute. */
1975 for (fcnt = frags, head = ring->head;
1976 sent < limit; sent++, sequence++) {
1977 struct netmap_slot *slot = &ring->slot[head];
1978 char *p = NETMAP_BUF(ring, slot->buf_idx);
1979 uint16_t *w = (uint16_t *)PKT(pkt, body, targ->g->af), t;
1981 memcpy(&sum, targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, sizeof(sum));
1985 PKT(pkt, body, targ->g->af)[0] = sequence >> 24;
1986 PKT(pkt, body, targ->g->af)[1] = (sequence >> 16) & 0xff;
1987 sum = ~cksum_add(~sum, cksum_add(~t, *w));
1989 PKT(pkt, body, targ->g->af)[2] = (sequence >> 8) & 0xff;
1990 PKT(pkt, body, targ->g->af)[3] = sequence & 0xff;
1991 sum = ~cksum_add(~sum, cksum_add(~t, *w));
1992 memcpy(targ->g->af == AF_INET ? &pkt->ipv4.udp.uh_sum : &pkt->ipv6.udp.uh_sum, &sum, sizeof(sum));
1993 nm_pkt_copy(frame, p, size);
1994 if (fcnt == frags) {
1995 update_addresses(pkt, targ);
1998 if (options & OPT_DUMP) {
1999 dump_payload(p, size, ring, head);
2005 slot->flags |= NS_MOREFRAG;
2010 if (sent == limit - 1) {
2011 /* Make sure we don't push an incomplete
2013 assert(!(slot->flags & NS_MOREFRAG));
2014 slot->flags |= NS_REPORT;
2017 head = nm_ring_next(ring, head);
2023 ring->cur = ring->head = head;
2026 targ->ctr.pkts = sent;
2027 targ->ctr.bytes = sent * size;
2028 targ->ctr.events = event;
2031 /* flush any remaining packets */
2032 D("flush tail %d head %d on thread %p",
2033 ring->tail, ring->head,
2034 (void *)pthread_self());
2035 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2037 /* final part: wait the TX queues to become empty. */
2038 while (!targ->cancel && nm_tx_pending(ring)) {
2039 RD(5, "pending tx tail %d head %d on ring %d",
2040 ring->tail, ring->head, targ->nmd->first_tx_ring);
2041 ioctl(pfd.fd, NIOCTXSYNC, NULL);
2042 usleep(1); /* wait 1 tick */
2045 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2046 targ->completed = 1;
2047 targ->ctr.pkts = sent;
2048 targ->ctr.bytes = sent * size;
2049 targ->ctr.events = event;
2051 /* reset the ``used`` flag. */
2059 multi_slot_to_string(struct netmap_ring *ring, unsigned int head,
2060 unsigned int nfrags, char *strbuf, size_t strbuflen)
2065 for (f = 0; f < nfrags; f++) {
2066 struct netmap_slot *slot = &ring->slot[head];
2067 int m = snprintf(strbuf, strbuflen, "|%u,%x|", slot->len,
2069 if (m >= (int)strbuflen) {
2075 head = nm_ring_next(ring, head);
2082 rxseq_body(void *data)
2084 struct targ *targ = (struct targ *) data;
2085 struct pollfd pfd = { .fd = targ->fd, .events = POLLIN };
2086 int dump = targ->g->options & OPT_DUMP;
2087 struct netmap_ring *ring;
2088 unsigned int frags_exp = 1;
2090 unsigned int frags = 0;
2091 int first_packet = 1;
2093 int i, j, af, nrings;
2094 uint32_t seq, *seq_exp = NULL;
2096 memset(&cur, 0, sizeof(cur));
2098 if (setaffinity(targ->thread, targ->affinity))
2101 nrings = targ->nmd->last_rx_ring - targ->nmd->first_rx_ring + 1;
2102 seq_exp = calloc(nrings, sizeof(uint32_t));
2103 if (seq_exp == NULL) {
2104 D("failed to allocate seq array");
2108 D("reading from %s fd %d main_fd %d",
2109 targ->g->ifname, targ->fd, targ->g->main_fd);
2110 /* unbounded wait for the first packet. */
2111 for (;!targ->cancel;) {
2112 i = poll(&pfd, 1, 1000);
2113 if (i > 0 && !(pfd.revents & POLLERR))
2115 RD(1, "waiting for initial packets, poll returns %d %d",
2119 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->tic);
2122 while (!targ->cancel) {
2127 if (ioctl(pfd.fd, NIOCRXSYNC, NULL) < 0) {
2128 D("ioctl error on queue %d: %s", targ->me,
2132 #else /* !BUSYWAIT */
2133 if (poll(&pfd, 1, 1 * 1000) <= 0 && !targ->g->forever) {
2134 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2135 targ->toc.tv_sec -= 1; /* Subtract timeout time. */
2139 if (pfd.revents & POLLERR) {
2143 #endif /* !BUSYWAIT */
2145 for (j = targ->nmd->first_rx_ring; j <= targ->nmd->last_rx_ring; j++) {
2146 ring = NETMAP_RXRING(targ->nmd->nifp, j);
2147 if (nm_ring_empty(ring))
2150 limit = nm_ring_space(ring);
2151 if (limit > targ->g->burst)
2152 limit = targ->g->burst;
2156 * 1) we remove the early-return optimization from
2157 * the netmap poll implementation, or
2158 * 2) pipes get NS_MOREFRAG support.
2159 * With the current netmap implementation, an experiment like
2160 * pkt-gen -i vale:1{1 -f txseq -F 9
2161 * pkt-gen -i vale:1}1 -f rxseq
2162 * would get stuck as soon as we find nm_ring_space(ring) < 9,
2163 * since here limit is rounded to 0 and
2164 * pipe rxsync is not called anymore by the poll() of this loop.
2166 if (frags_exp > 1) {
2168 /* Cut off to the closest smaller multiple. */
2169 limit = (limit / frags_exp) * frags_exp;
2170 RD(2, "LIMIT %d --> %d", o, limit);
2174 for (head = ring->head, i = 0; i < limit; i++) {
2175 struct netmap_slot *slot = &ring->slot[head];
2176 char *p = NETMAP_BUF(ring, slot->buf_idx);
2177 int len = slot->len;
2181 dump_payload(p, slot->len, ring, head);
2185 if (!(slot->flags & NS_MOREFRAG)) {
2188 } else if (frags != frags_exp) {
2190 RD(1, "Received packets with %u frags, "
2191 "expected %u, '%s'", frags, frags_exp,
2192 multi_slot_to_string(ring, head-frags+1,
2194 prbuf, sizeof(prbuf)));
2201 p -= sizeof(pkt->vh) - targ->g->virt_header;
2202 len += sizeof(pkt->vh) - targ->g->virt_header;
2203 pkt = (struct pkt *)p;
2204 if (ntohs(pkt->eh.ether_type) == ETHERTYPE_IP)
2209 if ((char *)pkt + len < ((char *)PKT(pkt, body, af)) +
2211 RD(1, "%s: packet too small (len=%u)", __func__,
2214 seq = (PKT(pkt, body, af)[0] << 24) |
2215 (PKT(pkt, body, af)[1] << 16) |
2216 (PKT(pkt, body, af)[2] << 8) |
2217 PKT(pkt, body, af)[3];
2219 /* Grab the first one, whatever it
2223 } else if (seq != seq_exp[j]) {
2224 uint32_t delta = seq - seq_exp[j];
2226 if (delta < (0xFFFFFFFF >> 1)) {
2227 RD(2, "Sequence GAP: exp %u found %u",
2230 RD(2, "Sequence OUT OF ORDER: "
2231 "exp %u found %u", seq_exp[j], seq);
2238 cur.bytes += slot->len;
2239 head = nm_ring_next(ring, head);
2243 ring->cur = ring->head = head;
2249 clock_gettime(CLOCK_REALTIME_PRECISE, &targ->toc);
2253 #endif /* !BUSYWAIT */
2254 targ->completed = 1;
2258 if (seq_exp != NULL)
2260 /* reset the ``used`` flag. */
2268 tx_output(struct glob_arg *g, struct my_ctrs *cur, double delta, const char *msg)
2270 double bw, raw_bw, pps, abs;
2271 char b1[40], b2[80], b3[80];
2274 if (cur->pkts == 0) {
2275 printf("%s nothing.\n", msg);
2279 size = (int)(cur->bytes / cur->pkts);
2281 printf("%s %llu packets %llu bytes %llu events %d bytes each in %.2f seconds.\n",
2283 (unsigned long long)cur->pkts,
2284 (unsigned long long)cur->bytes,
2285 (unsigned long long)cur->events, size, delta);
2288 if (size < 60) /* correct for min packet size */
2290 pps = cur->pkts / delta;
2291 bw = (8.0 * cur->bytes) / delta;
2292 raw_bw = (8.0 * cur->bytes + cur->pkts * g->framing) / delta;
2293 abs = cur->pkts / (double)(cur->events);
2295 printf("Speed: %spps Bandwidth: %sbps (raw %sbps). Average batch: %.2f pkts\n",
2296 norm(b1, pps, normalize), norm(b2, bw, normalize), norm(b3, raw_bw, normalize), abs);
2302 /* This usage is generated from the pkt-gen man page:
2304 * and pasted here adding the string terminators and endlines with simple
2305 * regular expressions. */
2306 const char *cmd = "pkt-gen";
2310 " -h Show program usage and exit.\n"
2313 " Name of the network interface that pkt-gen operates on. It can be a system network interface\n"
2314 " (e.g., em0), the name of a vale(4) port (e.g., valeSSS:PPP), the name of a netmap pipe or\n"
2315 " monitor, or any valid netmap port name accepted by the nm_open library function, as docu-\n"
2316 " mented in netmap(4) (NIOCREGIF section).\n"
2319 " The function to be executed by pkt-gen. Specify tx for transmission, rx for reception, ping\n"
2320 " for client-side ping-pong operation, and pong for server-side ping-pong operation.\n"
2323 " Number of iterations of the pkt-gen function, with 0 meaning infinite). In case of tx or rx,\n"
2324 " count is the number of packets to receive or transmit. In case of ping or pong, count is the\n"
2325 " number of ping-pong transactions.\n"
2328 " Packet size in bytes excluding CRC. If passed a second time, use random sizes larger or\n"
2329 " equal than the second one and lower than the first one.\n"
2332 " Transmit or receive up to burst_size packets at a time.\n"
2334 " -4 Use IPv4 addresses.\n"
2336 " -6 Use IPv6 addresses.\n"
2338 " -d dst_ip[:port[-dst_ip:port]]\n"
2339 " Destination IPv4/IPv6 address and port, single or range.\n"
2341 " -s src_ip[:port[-src_ip:port]]\n"
2342 " Source IPv4/IPv6 address and port, single or range.\n"
2345 " Destination MAC address in colon notation (e.g., aa:bb:cc:dd:ee:00).\n"
2348 " Source MAC address in colon notation.\n"
2351 " Pin the first thread of pkt-gen to a particular CPU using pthread_setaffinity_np(3). If more\n"
2352 " threads are used, they are pinned to the subsequent CPUs, one per thread.\n"
2355 " Maximum number of CPUs to use (0 means to use all the available ones).\n"
2358 " Number of threads to use. By default, only a single thread is used to handle all the netmap\n"
2359 " rings. If threads is larger than one, each thread handles a single TX ring (in tx mode), a\n"
2360 " single RX ring (in rx mode), or a TX/RX ring couple. The number of threads must be less or\n"
2361 " equal than the number of TX (or RX) ring available in the device specified by interface.\n"
2364 " Number of milliseconds between reports.\n"
2366 " -w wait_for_link_time\n"
2367 " Number of seconds to wait before starting the pkt-gen function, useuful to make sure that the\n"
2368 " network link is up. A network device driver may take some time to enter netmap mode, or to\n"
2369 " create a new transmit/receive ring pair when netmap(4) requests one.\n"
2372 " Packet transmission rate. Not setting the packet transmission rate tells pkt-gen to transmit\n"
2373 " packets as quickly as possible. On servers from 2010 on-wards netmap(4) is able to com-\n"
2374 " pletely use all of the bandwidth of a 10 or 40Gbps link, so this option should be used unless\n"
2375 " your intention is to saturate the link.\n"
2377 " -X Dump payload of each packet transmitted or received.\n"
2379 " -H len Add empty virtio-net-header with size 'len'. Valid sizes are 0, 10 and 12. This option is\n"
2380 " only used with Virtual Machine technologies that use virtio as a network interface.\n"
2383 " Load the packet to be transmitted from a pcap file rather than constructing it within\n"
2386 " -z Use random IPv4/IPv6 src address/port.\n"
2388 " -Z Use random IPv4/IPv6 dst address/port.\n"
2390 " -N Do not normalize units (i.e., use bps, pps instead of Mbps, Kpps, etc.).\n"
2393 " Send multi-slot packets, each one with num_frags fragments. A multi-slot packet is repre-\n"
2394 " sented by two or more consecutive netmap slots with the NS_MOREFRAG flag set (except for the\n"
2395 " last slot). This is useful to transmit or receive packets larger than the netmap buffer\n"
2399 " In multi-slot mode, frag_size specifies the size of each fragment, if smaller than the packet\n"
2400 " length divided by num_frags.\n"
2402 " -I Use indirect buffers. It is only valid for transmitting on VALE ports, and it is implemented\n"
2403 " by setting the NS_INDIRECT flag in the netmap slots.\n"
2405 " -W Exit immediately if all the RX rings are empty the first time they are examined.\n"
2407 " -v Increase the verbosity level.\n"
2409 " -r In tx mode, do not initialize packets, but send whatever the content of the uninitialized\n"
2410 " netmap buffers is (rubbish mode).\n"
2412 " -A Compute mean and standard deviation (over a sliding window) for the transmit or receive rate.\n"
2414 " -B Take Ethernet framing and CRC into account when computing the average bps. This adds 4 bytes\n"
2415 " of CRC and 20 bytes of framing to each packet.\n"
2417 " -C tx_slots[,rx_slots[,tx_rings[,rx_rings]]]\n"
2418 " Configuration in terms of number of rings and slots to be used when opening the netmap port.\n"
2419 " Such configuration has effect on software ports created on the fly, such as VALE ports and\n"
2420 " netmap pipes. The configuration may consist of 1 to 4 numbers separated by commas: tx_slots,\n"
2421 " rx_slots, tx_rings, rx_rings. Missing numbers or zeroes stand for default values. As an\n"
2422 " additional convenience, if exactly one number is specified, then this is assigned to both\n"
2423 " tx_slots and rx_slots. If there is no fourth number, then the third one is assigned to both\n"
2424 " tx_rings and rx_rings.\n"
2426 " -o options data generation options (parsed using atoi)\n"
2431 " OPT_TS 16 (add a timestamp)\n"
2432 " OPT_INDIRECT 32 (use indirect buffers)\n"
2433 " OPT_DUMP 64 (dump rx/tx traffic)\n"
2434 " OPT_RUBBISH 256\n"
2435 " (send wathever the buffers contain)\n"
2436 " OPT_RANDOM_SRC 512\n"
2437 " OPT_RANDOM_DST 1024\n"
2438 " OPT_PPS_STATS 2048\n"
2451 start_threads(struct glob_arg *g) {
2454 targs = calloc(g->nthreads, sizeof(*targs));
2457 * Now create the desired number of threads, each one
2458 * using a single descriptor.
2460 for (i = 0; i < g->nthreads; i++) {
2461 uint64_t seed = time(0) | (time(0) << 32);
2464 bzero(t, sizeof(*t));
2465 t->fd = -1; /* default, with pcap */
2467 memcpy(t->seed, &seed, sizeof(t->seed));
2469 if (g->dev_type == DEV_NETMAP) {
2470 struct nm_desc nmd = *g->nmd; /* copy, we overwrite ringid */
2471 uint64_t nmd_flags = 0;
2475 /* the first thread uses the fd opened by the main
2476 * thread, the other threads re-open /dev/netmap
2478 if (g->nthreads > 1) {
2480 g->nmd->req.nr_flags & ~NR_REG_MASK;
2481 nmd.req.nr_flags |= NR_REG_ONE_NIC;
2482 nmd.req.nr_ringid = i;
2484 /* Only touch one of the rings (rx is already ok) */
2485 if (g->td_type == TD_TYPE_RECEIVER)
2486 nmd_flags |= NETMAP_NO_TX_POLL;
2488 /* register interface. Override ifname and ringid etc. */
2489 t->nmd = nm_open(t->g->ifname, NULL, nmd_flags |
2490 NM_OPEN_IFNAME | NM_OPEN_NO_MMAP, &nmd);
2491 if (t->nmd == NULL) {
2492 D("Unable to open %s: %s",
2493 t->g->ifname, strerror(errno));
2500 t->frags = g->frags;
2502 targs[i].fd = g->main_fd;
2506 if (g->affinity >= 0) {
2507 t->affinity = (g->affinity + i) % g->cpus;
2511 /* default, init packets */
2512 initialize_packet(t);
2514 /* Wait for PHY reset. */
2515 D("Wait %d secs for phy reset", g->wait_link);
2516 sleep(g->wait_link);
2519 for (i = 0; i < g->nthreads; i++) {
2521 if (pthread_create(&t->thread, NULL, g->td_body, t) == -1) {
2522 D("Unable to create thread %d: %s", i, strerror(errno));
2529 main_thread(struct glob_arg *g)
2533 struct my_ctrs prev, cur;
2535 struct timeval tic, toc;
2537 prev.pkts = prev.bytes = prev.events = 0;
2538 gettimeofday(&prev.t, NULL);
2540 char b1[40], b2[40], b3[40], b4[100];
2546 usec = wait_for_next_report(&prev.t, &cur.t,
2547 g->report_interval);
2549 cur.pkts = cur.bytes = cur.events = 0;
2551 if (usec < 10000) /* too short to be meaningful */
2553 /* accumulate counts for all threads */
2554 for (i = 0; i < g->nthreads; i++) {
2555 cur.pkts += targs[i].ctr.pkts;
2556 cur.bytes += targs[i].ctr.bytes;
2557 cur.events += targs[i].ctr.events;
2558 cur.min_space += targs[i].ctr.min_space;
2559 targs[i].ctr.min_space = 99999;
2560 if (targs[i].used == 0)
2563 x.pkts = cur.pkts - prev.pkts;
2564 x.bytes = cur.bytes - prev.bytes;
2565 x.events = cur.events - prev.events;
2566 pps = (x.pkts*1000000 + usec/2) / usec;
2567 abs = (x.events > 0) ? (x.pkts / (double) x.events) : 0;
2569 if (!(g->options & OPT_PPS_STATS)) {
2572 /* Compute some pps stats using a sliding window. */
2573 double ppsavg = 0.0, ppsdev = 0.0;
2576 g->win[g->win_idx] = pps;
2577 g->win_idx = (g->win_idx + 1) % STATS_WIN;
2579 for (i = 0; i < STATS_WIN; i++) {
2580 ppsavg += g->win[i];
2587 for (i = 0; i < STATS_WIN; i++) {
2588 if (g->win[i] == 0) {
2591 ppsdev += (g->win[i] - ppsavg) * (g->win[i] - ppsavg);
2594 ppsdev = sqrt(ppsdev);
2596 snprintf(b4, sizeof(b4), "[avg/std %s/%s pps]",
2597 norm(b1, ppsavg, normalize), norm(b2, ppsdev, normalize));
2600 D("%spps %s(%spkts %sbps in %llu usec) %.2f avg_batch %d min_space",
2601 norm(b1, pps, normalize), b4,
2602 norm(b2, (double)x.pkts, normalize),
2603 norm(b3, (double)x.bytes*8+(double)x.pkts*g->framing, normalize),
2604 (unsigned long long)usec,
2605 abs, (int)cur.min_space);
2608 if (done == g->nthreads)
2614 cur.pkts = cur.bytes = cur.events = 0;
2616 for (i = 0; i < g->nthreads; i++) {
2617 struct timespec t_tic, t_toc;
2619 * Join active threads, unregister interfaces and close
2623 pthread_join(targs[i].thread, NULL); /* blocking */
2624 if (g->dev_type == DEV_NETMAP) {
2625 nm_close(targs[i].nmd);
2626 targs[i].nmd = NULL;
2631 if (targs[i].completed == 0)
2632 D("ouch, thread %d exited with error", i);
2635 * Collect threads output and extract information about
2636 * how long it took to send all the packets.
2638 cur.pkts += targs[i].ctr.pkts;
2639 cur.bytes += targs[i].ctr.bytes;
2640 cur.events += targs[i].ctr.events;
2641 /* collect the largest start (tic) and end (toc) times,
2642 * XXX maybe we should do the earliest tic, or do a weighted
2645 t_tic = timeval2spec(&tic);
2646 t_toc = timeval2spec(&toc);
2647 if (!timerisset(&tic) || timespec_ge(&targs[i].tic, &t_tic))
2648 tic = timespec2val(&targs[i].tic);
2649 if (!timerisset(&toc) || timespec_ge(&targs[i].toc, &t_toc))
2650 toc = timespec2val(&targs[i].toc);
2654 timersub(&toc, &tic, &toc);
2655 delta_t = toc.tv_sec + 1e-6* toc.tv_usec;
2656 if (g->td_type == TD_TYPE_SENDER)
2657 tx_output(g, &cur, delta_t, "Sent");
2658 else if (g->td_type == TD_TYPE_RECEIVER)
2659 tx_output(g, &cur, delta_t, "Received");
2669 static struct td_desc func[] = {
2670 { TD_TYPE_RECEIVER, "rx", receiver_body, 512}, /* default */
2671 { TD_TYPE_SENDER, "tx", sender_body, 512 },
2672 { TD_TYPE_OTHER, "ping", ping_body, 1 },
2673 { TD_TYPE_OTHER, "pong", pong_body, 1 },
2674 { TD_TYPE_SENDER, "txseq", txseq_body, 512 },
2675 { TD_TYPE_RECEIVER, "rxseq", rxseq_body, 512 },
2676 { 0, NULL, NULL, 0 }
2680 tap_alloc(char *dev)
2684 char *clonedev = TAP_CLONEDEV;
2688 /* Arguments taken by the function:
2690 * char *dev: the name of an interface (or '\0'). MUST have enough
2691 * space to hold the interface name if '\0' is passed
2692 * int flags: interface flags (eg, IFF_TUN etc.)
2696 if (dev[3]) { /* tapSomething */
2697 static char buf[128];
2698 snprintf(buf, sizeof(buf), "/dev/%s", dev);
2702 /* open the device */
2703 if( (fd = open(clonedev, O_RDWR)) < 0 ) {
2706 D("%s open successful", clonedev);
2708 /* preparation of the struct ifr, of type "struct ifreq" */
2709 memset(&ifr, 0, sizeof(ifr));
2712 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2715 /* if a device name was specified, put it in the structure; otherwise,
2716 * the kernel will try to allocate the "next" device of the
2718 size_t len = strlen(dev);
2719 if (len > IFNAMSIZ) {
2720 D("%s too long", dev);
2723 memcpy(ifr.ifr_name, dev, len);
2726 /* try to create the device */
2727 if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ) {
2728 D("failed to to a TUNSETIFF: %s", strerror(errno));
2733 /* if the operation was successful, write back the name of the
2734 * interface to the variable "dev", so the caller can know
2735 * it. Note that the caller MUST reserve space in *dev (see calling
2737 strcpy(dev, ifr.ifr_name);
2738 D("new name is %s", dev);
2741 /* this is the special file descriptor that the caller will use to talk
2742 * with the virtual interface */
2747 main(int arc, char **argv)
2750 struct sigaction sa;
2756 int devqueues = 1; /* how many device queues */
2757 int wait_link_arg = 0;
2759 int pkt_size_done = 0;
2761 struct td_desc *fn = func;
2763 bzero(&g, sizeof(g));
2768 g.report_interval = 1000; /* report interval */
2770 /* ip addresses can also be a range x.x.x.x-x.x.x.y */
2771 g.af = AF_INET; /* default */
2772 g.src_ip.name = "10.0.0.1";
2773 g.dst_ip.name = "10.1.0.1";
2774 g.dst_mac.name = "ff:ff:ff:ff:ff:ff";
2775 g.src_mac.name = NULL;
2779 g.cpus = 1; /* default */
2786 g.wait_link = 2; /* wait 2 seconds for physical ports */
2788 while ((ch = getopt(arc, argv, "46a:f:F:Nn:i:Il:d:s:D:S:b:c:o:p:"
2789 "T:w:WvR:XC:H:rP:zZAhBM:")) != -1) {
2793 D("bad option %c %s", ch, optarg);
2814 g.npackets = strtoull(optarg, NULL, 10);
2819 if (i < 1 || i > 63) {
2820 D("invalid frags %d [1..63], ignore", i);
2827 g.mtu = atoi(optarg);
2831 for (fn = func; fn->key; fn++) {
2832 if (!strcmp(fn->key, optarg))
2839 D("unrecognised function %s", optarg);
2843 case 'o': /* data generation options */
2844 g.options |= atoi(optarg);
2847 case 'a': /* force affinity */
2848 g.affinity = atoi(optarg);
2851 case 'i': /* interface */
2852 /* a prefix of tap: netmap: or pcap: forces the mode.
2853 * otherwise we guess
2855 D("interface is %s", optarg);
2856 if (strlen(optarg) > MAX_IFNAMELEN - 8) {
2857 D("ifname too long %s", optarg);
2860 strcpy(g.ifname, optarg);
2861 if (!strcmp(optarg, "null")) {
2862 g.dev_type = DEV_NETMAP;
2864 } else if (!strncmp(optarg, "tap:", 4)) {
2865 g.dev_type = DEV_TAP;
2866 strcpy(g.ifname, optarg + 4);
2867 } else if (!strncmp(optarg, "pcap:", 5)) {
2868 g.dev_type = DEV_PCAP;
2869 strcpy(g.ifname, optarg + 5);
2870 } else if (!strncmp(optarg, "netmap:", 7) ||
2871 !strncmp(optarg, "vale", 4)) {
2872 g.dev_type = DEV_NETMAP;
2873 } else if (!strncmp(optarg, "tap", 3)) {
2874 g.dev_type = DEV_TAP;
2875 } else { /* prepend netmap: */
2876 g.dev_type = DEV_NETMAP;
2877 sprintf(g.ifname, "netmap:%s", optarg);
2882 g.options |= OPT_INDIRECT; /* use indirect buffers */
2885 case 'l': /* pkt_size */
2886 if (pkt_size_done) {
2887 g.pkt_min_size = atoi(optarg);
2889 g.pkt_size = atoi(optarg);
2895 g.dst_ip.name = optarg;
2899 g.src_ip.name = optarg;
2902 case 'T': /* report interval */
2903 g.report_interval = atoi(optarg);
2907 g.wait_link = atoi(optarg);
2912 g.forever = 0; /* exit RX with no traffic */
2915 case 'b': /* burst */
2916 g.burst = atoi(optarg);
2919 g.cpus = atoi(optarg);
2922 g.nthreads = atoi(optarg);
2925 case 'D': /* destination mac */
2926 g.dst_mac.name = optarg;
2929 case 'S': /* source mac */
2930 g.src_mac.name = optarg;
2936 g.tx_rate = atoi(optarg);
2939 g.options |= OPT_DUMP;
2942 g.nmr_config = strdup(optarg);
2945 g.virt_header = atoi(optarg);
2948 g.packet_file = strdup(optarg);
2951 g.options |= OPT_RUBBISH;
2954 g.options |= OPT_RANDOM_SRC;
2957 g.options |= OPT_RANDOM_DST;
2960 g.options |= OPT_PPS_STATS;
2963 /* raw packets have4 bytes crc + 20 bytes framing */
2964 // XXX maybe add an option to pass the IFG
2970 if (strlen(g.ifname) <=0 ) {
2971 D("missing ifname");
2976 g.burst = fn->default_burst;
2977 D("using default burst size: %d", g.burst);
2980 g.system_cpus = i = system_ncpus();
2981 if (g.cpus < 0 || g.cpus > i) {
2982 D("%d cpus is too high, have only %d cpus", g.cpus, i);
2985 D("running on %d cpus (have %d)", g.cpus, i);
2989 if (!wait_link_arg && !strncmp(g.ifname, "vale", 4)) {
2993 if (g.pkt_size < 16 || g.pkt_size > MAX_PKTSIZE) {
2994 D("bad pktsize %d [16..%d]\n", g.pkt_size, MAX_PKTSIZE);
2998 if (g.pkt_min_size > 0 && (g.pkt_min_size < 16 || g.pkt_min_size > g.pkt_size)) {
2999 D("bad pktminsize %d [16..%d]\n", g.pkt_min_size, g.pkt_size);
3003 if (g.src_mac.name == NULL) {
3004 static char mybuf[20] = "00:00:00:00:00:00";
3005 /* retrieve source mac address. */
3006 if (source_hwaddr(g.ifname, mybuf) == -1) {
3007 D("Unable to retrieve source mac");
3008 // continue, fail later
3010 g.src_mac.name = mybuf;
3012 /* extract address ranges */
3013 if (extract_mac_range(&g.src_mac) || extract_mac_range(&g.dst_mac))
3015 g.options |= extract_ip_range(&g.src_ip, g.af);
3016 g.options |= extract_ip_range(&g.dst_ip, g.af);
3018 if (g.virt_header != 0 && g.virt_header != VIRT_HDR_1
3019 && g.virt_header != VIRT_HDR_2) {
3020 D("bad virtio-net-header length");
3024 if (g.dev_type == DEV_TAP) {
3025 D("want to use tap %s", g.ifname);
3026 g.main_fd = tap_alloc(g.ifname);
3027 if (g.main_fd < 0) {
3028 D("cannot open tap %s", g.ifname);
3032 } else if (g.dev_type == DEV_PCAP) {
3033 char pcap_errbuf[PCAP_ERRBUF_SIZE];
3035 pcap_errbuf[0] = '\0'; // init the buffer
3036 g.p = pcap_open_live(g.ifname, 256 /* XXX */, 1, 100, pcap_errbuf);
3038 D("cannot open pcap on %s", g.ifname);
3041 g.main_fd = pcap_fileno(g.p);
3042 D("using pcap on %s fileno %d", g.ifname, g.main_fd);
3043 #endif /* !NO_PCAP */
3044 } else if (g.dummy_send) { /* but DEV_NETMAP */
3045 D("using a dummy send routine");
3047 struct nm_desc base_nmd;
3048 char errmsg[MAXERRMSG];
3051 bzero(&base_nmd, sizeof(base_nmd));
3053 parse_nmr_config(g.nmr_config, &base_nmd.req);
3055 base_nmd.req.nr_flags |= NR_ACCEPT_VNET_HDR;
3057 if (nm_parse(g.ifname, &base_nmd, errmsg) < 0) {
3058 D("Invalid name '%s': %s", g.ifname, errmsg);
3063 * Open the netmap device using nm_open().
3065 * protocol stack and may cause a reset of the card,
3066 * which in turn may take some time for the PHY to
3067 * reconfigure. We do the open here to have time to reset.
3069 flags = NM_OPEN_IFNAME | NM_OPEN_ARG1 | NM_OPEN_ARG2 |
3070 NM_OPEN_ARG3 | NM_OPEN_RING_CFG;
3071 if (g.nthreads > 1) {
3072 base_nmd.req.nr_flags &= ~NR_REG_MASK;
3073 base_nmd.req.nr_flags |= NR_REG_ONE_NIC;
3074 base_nmd.req.nr_ringid = 0;
3076 g.nmd = nm_open(g.ifname, NULL, flags, &base_nmd);
3077 if (g.nmd == NULL) {
3078 D("Unable to open %s: %s", g.ifname, strerror(errno));
3081 g.main_fd = g.nmd->fd;
3082 D("mapped %luKB at %p", (unsigned long)(g.nmd->req.nr_memsize>>10),
3085 if (g.virt_header) {
3086 /* Set the virtio-net header length, since the user asked
3087 * for it explicitely. */
3088 set_vnet_hdr_len(&g);
3090 /* Check whether the netmap port we opened requires us to send
3091 * and receive frames with virtio-net header. */
3092 get_vnet_hdr_len(&g);
3095 /* get num of queues in tx or rx */
3096 if (g.td_type == TD_TYPE_SENDER)
3097 devqueues = g.nmd->req.nr_tx_rings;
3099 devqueues = g.nmd->req.nr_rx_rings;
3101 /* validate provided nthreads. */
3102 if (g.nthreads < 1 || g.nthreads > devqueues) {
3103 D("bad nthreads %d, have %d queues", g.nthreads, devqueues);
3104 // continue, fail later
3108 struct netmap_if *nifp = g.nmd->nifp;
3109 struct nmreq *req = &g.nmd->req;
3111 D("nifp at offset %d, %d tx %d rx region %d",
3112 req->nr_offset, req->nr_tx_rings, req->nr_rx_rings,
3114 for (i = 0; i <= req->nr_tx_rings; i++) {
3115 struct netmap_ring *ring = NETMAP_TXRING(nifp, i);
3116 D(" TX%d at 0x%p slots %d", i,
3117 (void *)((char *)ring - (char *)nifp), ring->num_slots);
3119 for (i = 0; i <= req->nr_rx_rings; i++) {
3120 struct netmap_ring *ring = NETMAP_RXRING(nifp, i);
3121 D(" RX%d at 0x%p slots %d", i,
3122 (void *)((char *)ring - (char *)nifp), ring->num_slots);
3126 /* Print some debug information. */
3128 "%s %s: %d queues, %d threads and %d cpus.\n",
3129 (g.td_type == TD_TYPE_SENDER) ? "Sending on" :
3130 ((g.td_type == TD_TYPE_RECEIVER) ? "Receiving from" :
3136 if (g.td_type == TD_TYPE_SENDER) {
3137 fprintf(stdout, "%s -> %s (%s -> %s)\n",
3138 g.src_ip.name, g.dst_ip.name,
3139 g.src_mac.name, g.dst_mac.name);
3143 /* Exit if something went wrong. */
3144 if (g.main_fd < 0) {
3152 D("--- SPECIAL OPTIONS:%s%s%s%s%s%s\n",
3153 g.options & OPT_PREFETCH ? " prefetch" : "",
3154 g.options & OPT_ACCESS ? " access" : "",
3155 g.options & OPT_MEMCPY ? " memcpy" : "",
3156 g.options & OPT_INDIRECT ? " indirect" : "",
3157 g.options & OPT_COPY ? " copy" : "",
3158 g.options & OPT_RUBBISH ? " rubbish " : "");
3161 g.tx_period.tv_sec = g.tx_period.tv_nsec = 0;
3162 if (g.tx_rate > 0) {
3163 /* try to have at least something every second,
3164 * reducing the burst size to some 0.01s worth of data
3165 * (but no less than one full set of fragments)
3168 int lim = (g.tx_rate)/300;
3173 x = ((uint64_t)1000000000 * (uint64_t)g.burst) / (uint64_t) g.tx_rate;
3174 g.tx_period.tv_nsec = x;
3175 g.tx_period.tv_sec = g.tx_period.tv_nsec / 1000000000;
3176 g.tx_period.tv_nsec = g.tx_period.tv_nsec % 1000000000;
3178 if (g.td_type == TD_TYPE_SENDER)
3179 D("Sending %d packets every %ld.%09ld s",
3180 g.burst, g.tx_period.tv_sec, g.tx_period.tv_nsec);
3181 /* Install ^C handler. */
3182 global_nthreads = g.nthreads;
3184 sigaddset(&ss, SIGINT);
3185 /* block SIGINT now, so that all created threads will inherit the mask */
3186 if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0) {
3187 D("failed to block SIGINT: %s", strerror(errno));
3190 /* Install the handler and re-enable SIGINT for the main thread */
3191 memset(&sa, 0, sizeof(sa));
3192 sa.sa_handler = sigint_h;
3193 if (sigaction(SIGINT, &sa, NULL) < 0) {
3194 D("failed to install ^C handler: %s", strerror(errno));
3197 if (pthread_sigmask(SIG_UNBLOCK, &ss, NULL) < 0) {
3198 D("failed to re-enable SIGINT: %s", strerror(errno));