xutils: Add common code to set up struct itimerval interval and value
[netsniff-ng.git] / trafgen.c
blob67c9b4e398aa5fd0c321ba1fe3d8f5969abd16b1
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 - 2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
5 * Swiss federal institute of technology (ETH Zurich)
6 * Subject to the GPL, version 2.
8 * A high-performance network traffic generator that uses the zero-copy
9 * kernelspace TX_RING for network I/O. On comodity Gigabit hardware up
10 * to 1,488,095 pps 64 Byte pps have been achieved with 2 trafgen instances
11 * bound to different CPUs from the userspace and turned off pause frames,
12 * ask Ronald from NST (Network Security Toolkit) for more details. ;-)
13 * So, this line-rate result is the very same as pktgen from kernelspace!
15 * Who can now hold the fords when the King of the Nine Riders comes? And
16 * other armies will come. I am too late. All is lost. I tarried on the
17 * way. All is lost. Even if my errand is performed, no one will ever
18 * know. There will be no one I can tell. It will be in vain.
20 * -- The Lord of the Rings, Frodo thinking,
21 * Chapter 'The Stairs of Cirith Ungol'.
24 #include <stdio.h>
25 #include <string.h>
26 #include <getopt.h>
27 #include <ctype.h>
28 #include <stdbool.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 #include <sys/fsuid.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <sys/wait.h>
35 #include <sys/mman.h>
36 #include <net/ethernet.h>
37 #include <netinet/in.h>
38 #include <netinet/ip.h>
39 #include <linux/icmp.h>
40 #include <arpa/inet.h>
41 #include <signal.h>
42 #include <stdint.h>
43 #include <stdlib.h>
44 #include <fcntl.h>
45 #include <time.h>
46 #include <poll.h>
47 #include <netdb.h>
48 #include <math.h>
49 #include <unistd.h>
51 #include "xmalloc.h"
52 #include "die.h"
53 #include "mac80211.h"
54 #include "xutils.h"
55 #include "xio.h"
56 #include "built_in.h"
57 #include "trafgen_conf.h"
58 #include "tprintf.h"
59 #include "ring_tx.h"
60 #include "csum.h"
62 struct ctx {
63 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
64 unsigned long kpull, num, gap, reserve_size, cpus;
65 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
66 struct sockaddr_in dest;
69 struct cpu_stats {
70 unsigned long tv_sec, tv_usec;
71 unsigned long long tx_packets, tx_bytes;
72 unsigned long long cf_packets, cf_bytes;
73 unsigned long long cd_packets;
74 sig_atomic_t state;
77 sig_atomic_t sigint = 0;
79 struct packet *packets = NULL;
80 size_t plen = 0;
82 struct packet_dyn *packet_dyn = NULL;
83 size_t dlen = 0;
85 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRsP:eE:pu:g:";
86 static const struct option long_options[] = {
87 {"dev", required_argument, NULL, 'd'},
88 {"out", required_argument, NULL, 'o'},
89 {"in", required_argument, NULL, 'i'},
90 {"conf", required_argument, NULL, 'c'},
91 {"num", required_argument, NULL, 'n'},
92 {"gap", required_argument, NULL, 't'},
93 {"cpus", required_argument, NULL, 'P'},
94 {"ring-size", required_argument, NULL, 'S'},
95 {"kernel-pull", required_argument, NULL, 'k'},
96 {"smoke-test", required_argument, NULL, 's'},
97 {"seed", required_argument, NULL, 'E'},
98 {"user", required_argument, NULL, 'u'},
99 {"group", required_argument, NULL, 'g'},
100 {"jumbo-support", no_argument, NULL, 'J'},
101 {"cpp", no_argument, NULL, 'p'},
102 {"rfraw", no_argument, NULL, 'R'},
103 {"rand", no_argument, NULL, 'r'},
104 {"verbose", no_argument, NULL, 'V'},
105 {"version", no_argument, NULL, 'v'},
106 {"example", no_argument, NULL, 'e'},
107 {"help", no_argument, NULL, 'h'},
108 {NULL, 0, NULL, 0}
111 static int sock;
113 static struct itimerval itimer;
115 static unsigned long interval = TX_KERNEL_PULL_INT;
117 static struct cpu_stats *stats;
119 unsigned int seed;
121 #define CPU_STATS_STATE_CFG 1
122 #define CPU_STATS_STATE_CHK 2
123 #define CPU_STATS_STATE_RES 4
125 #ifndef ICMP_FILTER
126 # define ICMP_FILTER 1
128 struct icmp_filter {
129 __u32 data;
131 #endif
133 static void signal_handler(int number)
135 switch (number) {
136 case SIGINT:
137 sigint = 1;
138 case SIGHUP:
139 default:
140 break;
144 static void timer_elapsed(int number)
146 set_itimer_interval_value(&itimer, 0, interval);
147 pull_and_flush_tx_ring(sock);
148 setitimer(ITIMER_REAL, &itimer, NULL);
151 static void header(void)
153 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
156 static void help(void)
158 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
159 puts("http://www.netsniff-ng.org\n\n"
160 "Usage: trafgen [options]\n"
161 "Options:\n"
162 " -i|-c|--in|--conf <cfg-file/-> Packet configuration file/stdin\n"
163 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
164 " -p|--cpp Run packet config through C preprocessor\n"
165 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
166 " -R|--rfraw Inject raw 802.11 frames\n"
167 " -s|--smoke-test <ipv4-receiver> Probe if machine survived fuzz-tested packet\n"
168 " -n|--num <uint> Number of packets until exit (def: 0)\n"
169 " -r|--rand Randomize packet selection (def: round robin)\n"
170 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
171 " -t|--gap <uint> Interpacket gap in us (approx)\n"
172 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
173 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
174 " -E|--seed <uint> Manually set srand(3) seed\n"
175 " -u|--user <userid> Drop privileges and change to userid\n"
176 " -g|--group <groupid> Drop privileges and change to groupid\n"
177 " -V|--verbose Be more verbose\n"
178 " -v|--version Show version\n"
179 " -e|--example Show built-in packet config example\n"
180 " -h|--help Guess what?!\n\n"
181 "Examples:\n"
182 " See trafgen.txf for configuration file examples.\n"
183 " trafgen --dev eth0 --conf trafgen.cfg\n"
184 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
185 " trafgen --dev eth0 --conf trafgen.cfg --smoke-test 10.0.0.1\n"
186 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
187 " trafgen --dev eth0 --conf trafgen.cfg --rand --gap 1000\n"
188 " trafgen --dev eth0 --conf trafgen.cfg --rand --num 1400000 -k1000\n"
189 " trafgen --dev eth0 --conf trafgen.cfg -u `id -u bob` -g `id -g bob`\n\n"
190 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
191 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
192 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
193 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
194 "Note:\n"
195 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
196 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
197 " we assume the kernel crashed, thus we print the packet and quit.\n"
198 " In case you find a ping-of-death, please mention trafgen in your\n"
199 " commit message of the fix!\n\n"
200 " For introducing bit errors, delays with random variation and more,\n"
201 " make use of tc(8) with its difference disciplines (e.g. netem).\n\n"
202 " For generating different package distributions, you can use some\n"
203 " scripting to generate a trafgen config file with packet ratios as:\n\n"
204 " IMIX 64:7, 570:4, 1518:1\n"
205 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
206 " Cisco 64:7, 594:4, 1518:1\n"
207 " RPR Trimodal 64:60, 512:20, 1518:20\n"
208 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
209 "Please report bugs to <bugs@netsniff-ng.org>\n"
210 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
211 "Swiss federal institute of technology (ETH Zurich)\n"
212 "License: GNU GPL version 2.0\n"
213 "This is free software: you are free to change and redistribute it.\n"
214 "There is NO WARRANTY, to the extent permitted by law.\n");
215 die();
218 static void example(void)
220 const char *e =
221 "/* Note: dynamic elements make trafgen slower! */\n\n"
222 "#define ETH_P_IP 0x0800\n\n"
223 "#define SYN (1 << 1)\n"
224 "#define ECN (1 << 6)\n\n"
225 "{\n"
226 " /* MAC Destination */\n"
227 " fill(0xff, 6),\n"
228 " /* MAC Source */\n"
229 " 0x00, 0x02, 0xb3, drnd(3),\n"
230 " /* IPv4 Protocol */\n"
231 " c16(ETH_P_IP),\n"
232 " /* IPv4 Version, IHL, TOS */\n"
233 " 0b01000101, 0,\n"
234 " /* IPv4 Total Len */\n"
235 " c16(59),\n"
236 " /* IPv4 Ident */\n"
237 " drnd(2),\n"
238 " /* IPv4 Flags, Frag Off */\n"
239 " 0b01000000, 0,\n"
240 " /* IPv4 TTL */\n"
241 " 64,\n"
242 " /* Proto TCP */\n"
243 " 0x06,\n"
244 " /* IPv4 Checksum (IP header from, to) */\n"
245 " csumip(14, 33),\n"
246 " /* Source IP */\n"
247 " drnd(4),\n"
248 " /* Dest IP */\n"
249 " drnd(4),\n"
250 " /* TCP Source Port */\n"
251 " drnd(2),\n"
252 " /* TCP Dest Port */\n"
253 " c16(80),\n"
254 " /* TCP Sequence Number */\n"
255 " drnd(4),\n"
256 " /* TCP Ackn. Number */\n"
257 " c32(0),\n"
258 " /* TCP Header length + TCP SYN/ECN Flag */\n"
259 " c16((0x8 << 12) | SYN | ECN)\n"
260 " /* Window Size */\n"
261 " c16(16),\n"
262 " /* TCP Checksum (offset IP, offset TCP) */\n"
263 " csumtcp(14, 34),\n"
264 " /* TCP Options */\n"
265 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
266 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
267 " /* Data blob */\n"
268 " \"gotcha!\",\n"
269 "}";
270 puts(e);
271 die();
274 static void version(void)
276 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
277 puts("http://www.netsniff-ng.org\n\n"
278 "Please report bugs to <bugs@netsniff-ng.org>\n"
279 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
280 "Swiss federal institute of technology (ETH Zurich)\n"
281 "License: GNU GPL version 2.0\n"
282 "This is free software: you are free to change and redistribute it.\n"
283 "There is NO WARRANTY, to the extent permitted by law.\n");
284 die();
287 static void apply_counter(int counter_id)
289 int j, i = counter_id;
290 size_t counter_max = packet_dyn[i].clen;
292 for (j = 0; j < counter_max; ++j) {
293 uint8_t val;
294 struct counter *counter = &packet_dyn[i].cnt[j];
296 val = counter->val - counter->min;
298 switch (counter->type) {
299 case TYPE_INC:
300 val = (val + counter->inc) % (counter->max - counter->min + 1);
301 break;
302 case TYPE_DEC:
303 val = (val - counter->inc) % (counter->min - counter->max + 1);
304 break;
305 default:
306 bug();
309 counter->val = val + counter->min;
310 packets[i].payload[counter->off] = val;
314 static void apply_randomizer(int rand_id)
316 int j, i = rand_id;
317 size_t rand_max = packet_dyn[i].rlen;
319 for (j = 0; j < rand_max; ++j) {
320 uint8_t val = (uint8_t) rand();
321 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
323 packets[i].payload[randomizer->off] = val;
327 /* Taken and modified from tcpdump, Copyright belongs to them! */
329 struct cksum_vec {
330 const u8 *ptr;
331 int len;
334 #define ADDCARRY(x) \
335 do { if ((x) > 65535) \
336 (x) -= 65535; \
337 } while (0)
339 #define REDUCE \
340 do { \
341 l_util.l = sum; \
342 sum = l_util.s[0] + l_util.s[1]; \
343 ADDCARRY(sum); \
344 } while (0)
346 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
348 register const u16 *w;
349 register int sum = 0, mlen = 0;
350 int byte_swapped = 0;
351 union {
352 u8 c[2];
353 u16 s;
354 } s_util;
355 union {
356 u16 s[2];
357 u32 l;
358 } l_util;
360 for (; veclen != 0; vec++, veclen--) {
361 if (vec->len == 0)
362 continue;
364 w = (const u16 *) (void *) vec->ptr;
366 if (mlen == -1) {
367 s_util.c[1] = *(const u8 *) w;
368 sum += s_util.s;
369 w = (const u16 *) (void *) ((const u8 *) w + 1);
370 mlen = vec->len - 1;
371 } else
372 mlen = vec->len;
374 if ((1 & (unsigned long) w) && (mlen > 0)) {
375 REDUCE;
376 sum <<= 8;
377 s_util.c[0] = *(const u8 *) w;
378 w = (const u16 *) (void *) ((const u8 *) w + 1);
379 mlen--;
380 byte_swapped = 1;
383 while ((mlen -= 32) >= 0) {
384 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
385 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
386 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
387 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
388 w += 16;
391 mlen += 32;
393 while ((mlen -= 8) >= 0) {
394 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
395 w += 4;
398 mlen += 8;
400 if (mlen == 0 && byte_swapped == 0)
401 continue;
403 REDUCE;
405 while ((mlen -= 2) >= 0) {
406 sum += *w++;
409 if (byte_swapped) {
410 REDUCE;
411 sum <<= 8;
412 byte_swapped = 0;
414 if (mlen == -1) {
415 s_util.c[1] = *(const u8 *) w;
416 sum += s_util.s;
417 mlen = 0;
418 } else
419 mlen = -1;
420 } else if (mlen == -1)
421 s_util.c[0] = *(const u8 *) w;
424 if (mlen == -1) {
425 s_util.c[1] = 0;
426 sum += s_util.s;
429 REDUCE;
431 return (~sum & 0xffff);
434 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
435 u8 next_proto)
437 struct cksum_vec vec[2];
438 struct pseudo_hdr {
439 u32 src;
440 u32 dst;
441 u8 mbz;
442 u8 proto;
443 u16 len;
444 } ph;
446 memset(&ph, 0, sizeof(ph));
447 ph.len = htons(len);
448 ph.mbz = 0;
449 ph.proto = next_proto;
450 ph.src = ip->ip_src.s_addr;
451 ph.dst = ip->ip_dst.s_addr;
453 vec[0].ptr = (const u8 *) (void *) &ph;
454 vec[0].len = sizeof(ph);
456 vec[1].ptr = data;
457 vec[1].len = len;
459 return __in_cksum(vec, 2);
462 static void apply_csum16(int csum_id)
464 int j, i = csum_id;
465 size_t csum_max = packet_dyn[i].slen;
467 for (j = 0; j < csum_max; ++j) {
468 uint16_t sum = 0;
469 struct csum16 *csum = &packet_dyn[i].csum[j];
471 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
473 switch (csum->which) {
474 case CSUM_IP:
475 if (csum->to >= packets[i].len)
476 csum->to = packets[i].len - 1;
477 sum = calc_csum(packets[i].payload + csum->from,
478 csum->to - csum->from + 1, 0);
479 break;
480 case CSUM_UDP:
481 sum = p4_csum((void *) packets[i].payload + csum->from,
482 packets[i].payload + csum->to,
483 (packets[i].len - csum->to),
484 IPPROTO_UDP);
485 break;
486 case CSUM_TCP:
487 sum = p4_csum((void *) packets[i].payload + csum->from,
488 packets[i].payload + csum->to,
489 (packets[i].len - csum->to),
490 IPPROTO_TCP);
491 break;
494 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
498 static struct cpu_stats *setup_shared_var(unsigned long cpus)
500 int fd;
501 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
502 struct cpu_stats *buff;
504 fmemset(zbuff, 0, sizeof(zbuff));
505 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
507 fd = creat(file, S_IRUSR | S_IWUSR);
508 bug_on(fd < 0);
509 close(fd);
511 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
512 S_IRUSR | S_IWUSR);
513 write_or_die(fd, zbuff, sizeof(zbuff));
515 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
516 MAP_SHARED, fd, 0);
517 if (buff == (void *) -1)
518 panic("Cannot setup shared variable!\n");
520 close(fd);
521 unlink(file);
523 memset(buff, 0, sizeof(zbuff));
525 return buff;
528 static void destroy_shared_var(void *buff, unsigned long cpus)
530 munmap(buff, cpus * sizeof(struct cpu_stats));
533 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
535 int i;
537 printf("{");
538 for (i = 0; i < len; ++i) {
539 if (i % 15 == 0)
540 printf("\n ");
541 printf("0x%02x, ", payload[i]);
543 printf("\n}\n");
544 fflush(stdout);
547 static inline unsigned short csum(unsigned short *buf, int nwords)
549 unsigned long sum;
551 for (sum = 0; nwords > 0; nwords--)
552 sum += *buf++;
553 sum = (sum >> 16) + (sum & 0xffff);
554 sum += (sum >> 16);
556 return ~sum;
559 static int xmit_smoke_setup(struct ctx *ctx)
561 int icmp_sock, ret, ttl = 64;
562 struct icmp_filter filter;
564 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
565 if (icmp_sock < 0)
566 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
568 filter.data = ~(1 << ICMP_ECHOREPLY);
570 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
571 if (ret < 0)
572 panic("Cannot install filter!\n");
574 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
575 if (ret < 0)
576 panic("Cannot set TTL!\n");
578 memset(&ctx->dest, 0, sizeof(ctx->dest));
579 ctx->dest.sin_family = AF_INET;
580 ctx->dest.sin_port = 0;
582 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
583 if (ret < 0)
584 panic("Cannot resolv address!\n");
586 return icmp_sock;
589 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
591 int ret, i, probes = 5;
592 short ident, cnt = 1;
593 uint8_t outpack[512], *data;
594 struct icmphdr *icmp;
595 struct iphdr *ip;
596 size_t len = sizeof(*icmp) + 56;
597 struct sockaddr_in from;
598 socklen_t from_len;
599 struct pollfd fds = {
600 .fd = icmp_sock,
601 .events = POLLIN,
604 while (probes-- > 0) {
605 ident = htons((short) rand());
607 memset(outpack, 0, sizeof(outpack));
608 icmp = (void *) outpack;
609 icmp->type = ICMP_ECHO;
610 icmp->code = 0;
611 icmp->checksum = 0;
612 icmp->un.echo.id = ident;
613 icmp->un.echo.sequence = htons(cnt++);
615 data = ((uint8_t *) outpack + sizeof(*icmp));
616 for (i = 0; i < 56; ++i)
617 data[i] = (uint8_t) rand();
619 icmp->checksum = csum((unsigned short *) outpack,
620 len / sizeof(unsigned short));
622 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
623 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
624 if (unlikely(ret != len))
625 panic("Cannot send out probe: %s!\n", strerror(errno));
627 ret = poll(&fds, 1, 500);
628 if (ret < 0)
629 panic("Poll failed!\n");
631 if (fds.revents & POLLIN) {
632 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
633 (struct sockaddr *) &from, &from_len);
634 if (unlikely(ret <= 0))
635 panic("Probe receive failed!\n");
636 if (unlikely(from_len != sizeof(ctx->dest)))
637 continue;
638 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
639 continue;
640 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
641 continue;
642 ip = (void *) outpack;
643 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
644 continue;
645 icmp = (void *) outpack + ip->ihl * 4;
646 if (unlikely(icmp->un.echo.id != ident))
647 continue;
649 return 0;
653 return -1;
656 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
658 int ret, icmp_sock = -1;
659 unsigned long num = 1, i = 0;
660 struct timeval start, end, diff;
661 unsigned long long tx_bytes = 0, tx_packets = 0;
662 struct packet_dyn *pktd;
663 struct sockaddr_ll saddr = {
664 .sll_family = PF_PACKET,
665 .sll_halen = ETH_ALEN,
666 .sll_ifindex = device_ifindex(ctx->device),
669 if (ctx->num > 0)
670 num = ctx->num;
672 if (ctx->smoke_test)
673 icmp_sock = xmit_smoke_setup(ctx);
675 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
677 bug_on(gettimeofday(&start, NULL));
679 while (likely(sigint == 0) && likely(num > 0)) {
680 pktd = &packet_dyn[i];
681 if (pktd->clen + pktd->rlen + pktd->slen) {
682 apply_counter(i);
683 apply_randomizer(i);
684 apply_csum16(i);
686 retry:
687 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
688 (struct sockaddr *) &saddr, sizeof(saddr));
689 if (unlikely(ret < 0)) {
690 if (errno == ENOBUFS) {
691 sched_yield();
692 goto retry;
695 panic("Sendto error: %s!\n", strerror(errno));
698 tx_bytes += packets[i].len;
699 tx_packets++;
701 if (ctx->smoke_test) {
702 ret = xmit_smoke_probe(icmp_sock, ctx);
703 if (unlikely(ret < 0)) {
704 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
705 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
706 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
707 i, seed);
709 dump_trafgen_snippet(packets[i].payload, packets[i].len);
710 break;
714 if (!ctx->rand) {
715 i++;
716 if (i >= plen)
717 i = 0;
718 } else
719 i = rand() % plen;
721 if (ctx->num > 0)
722 num--;
724 if (ctx->gap > 0)
725 usleep(ctx->gap);
728 bug_on(gettimeofday(&end, NULL));
729 diff = tv_subtract(end, start);
731 if (ctx->smoke_test)
732 close(icmp_sock);
734 stats[cpu].tx_packets = tx_packets;
735 stats[cpu].tx_bytes = tx_bytes;
736 stats[cpu].tv_sec = diff.tv_sec;
737 stats[cpu].tv_usec = diff.tv_usec;
739 stats[cpu].state |= CPU_STATS_STATE_RES;
742 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
744 int ifindex = device_ifindex(ctx->device);
745 uint8_t *out = NULL;
746 unsigned int it = 0;
747 unsigned long num = 1, i = 0, size;
748 struct ring tx_ring;
749 struct frame_map *hdr;
750 struct timeval start, end, diff;
751 struct packet_dyn *pktd;
752 unsigned long long tx_bytes = 0, tx_packets = 0;
754 fmemset(&tx_ring, 0, sizeof(tx_ring));
756 size = ring_size(ctx->device, ctx->reserve_size);
758 set_sock_prio(sock, 512);
759 set_packet_loss_discard(sock);
761 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
762 create_tx_ring(sock, &tx_ring, ctx->verbose);
763 mmap_tx_ring(sock, &tx_ring);
764 alloc_tx_ring_frames(&tx_ring);
765 bind_tx_ring(sock, &tx_ring, ifindex);
767 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
769 if (ctx->kpull)
770 interval = ctx->kpull;
771 if (ctx->num > 0)
772 num = ctx->num;
774 set_itimer_interval_value(&itimer, 0, interval);
775 setitimer(ITIMER_REAL, &itimer, NULL);
777 bug_on(gettimeofday(&start, NULL));
779 while (likely(sigint == 0) && likely(num > 0)) {
780 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
781 hdr = tx_ring.frames[it].iov_base;
783 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
784 * sizeof(struct sockaddr_ll); */
785 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
787 hdr->tp_h.tp_snaplen = packets[i].len;
788 hdr->tp_h.tp_len = packets[i].len;
790 pktd = &packet_dyn[i];
791 if (pktd->clen + pktd->rlen + pktd->slen) {
792 apply_counter(i);
793 apply_randomizer(i);
794 apply_csum16(i);
797 fmemcpy(out, packets[i].payload, packets[i].len);
799 tx_bytes += packets[i].len;
800 tx_packets++;
802 if (!ctx->rand) {
803 i++;
804 if (i >= plen)
805 i = 0;
806 } else
807 i = rand() % plen;
809 kernel_may_pull_from_tx(&hdr->tp_h);
811 it++;
812 if (it >= tx_ring.layout.tp_frame_nr)
813 it = 0;
815 if (ctx->num > 0)
816 num--;
818 if (unlikely(sigint == 1))
819 break;
823 bug_on(gettimeofday(&end, NULL));
824 diff = tv_subtract(end, start);
826 destroy_tx_ring(sock, &tx_ring);
828 stats[cpu].tx_packets = tx_packets;
829 stats[cpu].tx_bytes = tx_bytes;
830 stats[cpu].tv_sec = diff.tv_sec;
831 stats[cpu].tv_usec = diff.tv_usec;
833 stats[cpu].state |= CPU_STATS_STATE_RES;
836 static inline void __set_state(int cpu, sig_atomic_t s)
838 stats[cpu].state = s;
841 static inline sig_atomic_t __get_state(int cpu)
843 return stats[cpu].state;
846 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
848 int i;
849 unsigned long total;
851 for (i = 0, total = plen; i < ctx->cpus; i++) {
852 if (i == cpu)
853 continue;
855 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
856 sigint == 0)
857 sched_yield();
859 total += stats[i].cf_packets;
862 return total;
865 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
867 int i, cpu_sel;
868 unsigned long total;
869 long long delta_correction = 0;
871 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
872 if (i == cpu)
873 continue;
875 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
876 sigint == 0)
877 sched_yield();
879 total += stats[i].cd_packets;
882 if (total > orig)
883 delta_correction = -1 * ((long long) total - orig);
884 if (total < orig)
885 delta_correction = +1 * ((long long) orig - total);
887 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
888 if (stats[i].cd_packets > 0) {
889 if ((long long) stats[i].cd_packets +
890 delta_correction > 0) {
891 cpu_sel = i;
892 break;
897 if (cpu == cpu_sel)
898 ctx->num += delta_correction;
901 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
902 sig_atomic_t s)
904 stats[cpu].cf_packets = p;
905 stats[cpu].cf_bytes = b;
906 stats[cpu].state = s;
909 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
911 stats[cpu].cd_packets = p;
912 stats[cpu].state = s;
915 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
917 int i;
918 unsigned long plen_total, orig = ctx->num;
919 size_t mtu, total_len = 0;
921 bug_on(plen != dlen);
923 for (i = 0; i < plen; ++i)
924 total_len += packets[i].len;
926 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
927 plen_total = __wait_and_sum_others(ctx, cpu);
929 if (orig > 0) {
930 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
932 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
933 CPU_STATS_STATE_CFG);
934 __correct_global_delta(ctx, cpu, orig);
937 if (plen == 0) {
938 __set_state(cpu, CPU_STATS_STATE_RES);
939 return -1;
942 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
943 if (packets[i].len > mtu + 14)
944 panic("Device MTU < than packet%d's size!\n", i);
945 if (packets[i].len <= 14)
946 panic("Packet%d's size too short!\n", i);
949 return 0;
952 static void main_loop(struct ctx *ctx, char *confname, bool slow,
953 int cpu, bool invoke_cpp)
955 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
956 if (xmit_packet_precheck(ctx, cpu) < 0)
957 return;
959 if (cpu == 0) {
960 int i;
961 size_t total_len = 0, total_pkts = 0;
963 for (i = 0; i < ctx->cpus; ++i) {
964 total_len += stats[i].cf_bytes;
965 total_pkts += stats[i].cf_packets;
968 printf("%6zu packets to schedule\n", total_pkts);
969 printf("%6zu bytes in total\n", total_len);
970 printf("Running! Hang up with ^C!\n\n");
971 fflush(stdout);
974 sock = pf_socket();
976 if (slow)
977 xmit_slowpath_or_die(ctx, cpu);
978 else
979 xmit_fastpath_or_die(ctx, cpu);
981 close(sock);
983 cleanup_packets();
986 static unsigned int generate_srand_seed(void)
988 int fd;
989 unsigned int seed;
991 fd = open("/dev/urandom", O_RDONLY);
992 if (fd < 0)
993 return time(0);
995 read_or_die(fd, &seed, sizeof(seed));
997 close(fd);
998 return seed;
1001 int main(int argc, char **argv)
1003 bool slow = false, invoke_cpp = false, reseed = true;
1004 int c, opt_index, i, j, vals[4] = {0}, irq;
1005 char *confname = NULL, *ptr;
1006 unsigned long cpus_tmp;
1007 unsigned long long tx_packets, tx_bytes;
1008 struct ctx ctx;
1010 fmemset(&ctx, 0, sizeof(ctx));
1011 ctx.cpus = get_number_cpus_online();
1012 ctx.uid = getuid();
1013 ctx.gid = getgid();
1015 while ((c = getopt_long(argc, argv, short_options, long_options,
1016 &opt_index)) != EOF) {
1017 switch (c) {
1018 case 'h':
1019 help();
1020 break;
1021 case 'v':
1022 version();
1023 break;
1024 case 'e':
1025 example();
1026 break;
1027 case 'p':
1028 invoke_cpp = true;
1029 break;
1030 case 'V':
1031 ctx.verbose = true;
1032 break;
1033 case 'P':
1034 cpus_tmp = strtoul(optarg, NULL, 0);
1035 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1036 ctx.cpus = cpus_tmp;
1037 break;
1038 case 'd':
1039 case 'o':
1040 ctx.device = xstrndup(optarg, IFNAMSIZ);
1041 break;
1042 case 'r':
1043 ctx.rand = true;
1044 break;
1045 case 's':
1046 slow = true;
1047 ctx.cpus = 1;
1048 ctx.smoke_test = true;
1049 ctx.rhost = xstrdup(optarg);
1050 break;
1051 case 'R':
1052 ctx.rfraw = true;
1053 break;
1054 case 'J':
1055 ctx.jumbo_support = true;
1056 break;
1057 case 'c':
1058 case 'i':
1059 confname = xstrdup(optarg);
1060 if (!strncmp("-", confname, strlen("-")))
1061 ctx.cpus = 1;
1062 break;
1063 case 'u':
1064 ctx.uid = strtoul(optarg, NULL, 0);
1065 ctx.enforce = true;
1066 break;
1067 case 'g':
1068 ctx.gid = strtoul(optarg, NULL, 0);
1069 ctx.enforce = true;
1070 break;
1071 case 'k':
1072 ctx.kpull = strtoul(optarg, NULL, 0);
1073 break;
1074 case 'E':
1075 seed = strtoul(optarg, NULL, 0);
1076 reseed = false;
1077 break;
1078 case 'n':
1079 ctx.num = strtoul(optarg, NULL, 0);
1080 break;
1081 case 't':
1082 slow = true;
1083 ctx.gap = strtoul(optarg, NULL, 0);
1084 if (ctx.gap > 0)
1085 /* Fall back to single core to not
1086 * mess up correct timing. We are slow
1087 * anyway!
1089 ctx.cpus = 1;
1090 break;
1091 case 'S':
1092 ptr = optarg;
1093 ctx.reserve_size = 0;
1095 for (j = i = strlen(optarg); i > 0; --i) {
1096 if (!isdigit(optarg[j - i]))
1097 break;
1098 ptr++;
1101 if (!strncmp(ptr, "KiB", strlen("KiB")))
1102 ctx.reserve_size = 1 << 10;
1103 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1104 ctx.reserve_size = 1 << 20;
1105 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1106 ctx.reserve_size = 1 << 30;
1107 else
1108 panic("Syntax error in ring size param!\n");
1109 *ptr = 0;
1111 ctx.reserve_size *= strtol(optarg, NULL, 0);
1112 break;
1113 case '?':
1114 switch (optopt) {
1115 case 'd':
1116 case 'c':
1117 case 'n':
1118 case 'S':
1119 case 's':
1120 case 'P':
1121 case 'o':
1122 case 'E':
1123 case 'i':
1124 case 'k':
1125 case 'u':
1126 case 'g':
1127 case 't':
1128 panic("Option -%c requires an argument!\n",
1129 optopt);
1130 default:
1131 if (isprint(optopt))
1132 printf("Unknown option character `0x%X\'!\n", optopt);
1133 die();
1135 default:
1136 break;
1140 if (argc < 5)
1141 help();
1142 if (ctx.device == NULL)
1143 panic("No networking device given!\n");
1144 if (confname == NULL)
1145 panic("No configuration file given!\n");
1146 if (device_mtu(ctx.device) == 0)
1147 panic("This is no networking device!\n");
1148 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1149 panic("Networking device not running!\n");
1151 register_signal(SIGINT, signal_handler);
1152 register_signal(SIGHUP, signal_handler);
1153 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1155 header();
1157 set_system_socket_memory(vals, array_size(vals));
1158 xlockme();
1160 if (ctx.rfraw) {
1161 ctx.device_trans = xstrdup(ctx.device);
1162 xfree(ctx.device);
1164 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1165 sleep(0);
1168 irq = device_irq_number(ctx.device);
1169 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1171 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1172 ctx.cpus = 1;
1174 stats = setup_shared_var(ctx.cpus);
1176 for (i = 0; i < ctx.cpus; i++) {
1177 pid_t pid = fork();
1179 switch (pid) {
1180 case 0:
1181 if (reseed)
1182 seed = generate_srand_seed();
1183 srand(seed);
1185 cpu_affinity(i);
1186 main_loop(&ctx, confname, slow, i, invoke_cpp);
1188 goto thread_out;
1189 case -1:
1190 panic("Cannot fork processes!\n");
1194 for (i = 0; i < ctx.cpus; i++) {
1195 int status;
1197 wait(&status);
1198 if (WEXITSTATUS(status) == EXIT_FAILURE)
1199 die();
1202 if (ctx.rfraw)
1203 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1205 reset_system_socket_memory(vals, array_size(vals));
1207 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1208 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1209 sched_yield();
1211 tx_packets += stats[i].tx_packets;
1212 tx_bytes += stats[i].tx_bytes;
1215 fflush(stdout);
1216 printf("\n");
1217 printf("\r%12llu packets outgoing\n", tx_packets);
1218 printf("\r%12llu bytes outgoing\n", tx_bytes);
1219 for (i = 0; i < ctx.cpus; i++) {
1220 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1221 stats[i].tv_sec, stats[i].tv_usec, i,
1222 stats[i].tx_packets);
1225 thread_out:
1226 xunlockme();
1227 destroy_shared_var(stats, ctx.cpus);
1229 free(ctx.device);
1230 free(ctx.device_trans);
1231 free(ctx.rhost);
1232 free(confname);
1234 return 0;