trafgen: add pkt-conf preprocessor, read from stdin
[netsniff-ng.git] / src / trafgen.c
blob39c48471471250f71c077204c212f60dc574e84f
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>
50 #include "xmalloc.h"
51 #include "die.h"
52 #include "mac80211.h"
53 #include "xutils.h"
54 #include "xio.h"
55 #include "built_in.h"
56 #include "trafgen_conf.h"
57 #include "tprintf.h"
58 #include "ring_tx.h"
59 #include "csum.h"
61 struct ctx {
62 bool rand, rfraw, jumbo_support, verbose, smoke_test;
63 unsigned long kpull, num, gap, reserve_size, cpus;
64 struct sockaddr_in dest;
65 char *device, *device_trans, *rhost;
68 struct cpu_stats {
69 unsigned long tv_sec, tv_usec;
70 unsigned long long tx_packets, tx_bytes;
71 unsigned long long cf_packets, cf_bytes;
72 unsigned long long cd_packets;
73 sig_atomic_t state;
76 sig_atomic_t sigint = 0;
78 struct packet *packets = NULL;
79 size_t plen = 0;
81 struct packet_dyn *packet_dyn = NULL;
82 size_t dlen = 0;
84 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRsP:eE:p";
85 static const struct option long_options[] = {
86 {"dev", required_argument, NULL, 'd'},
87 {"out", required_argument, NULL, 'o'},
88 {"in", required_argument, NULL, 'i'},
89 {"conf", required_argument, NULL, 'c'},
90 {"num", required_argument, NULL, 'n'},
91 {"gap", required_argument, NULL, 't'},
92 {"cpus", required_argument, NULL, 'P'},
93 {"ring-size", required_argument, NULL, 'S'},
94 {"kernel-pull", required_argument, NULL, 'k'},
95 {"smoke-test", required_argument, NULL, 's'},
96 {"seed", required_argument, NULL, 'E'},
97 {"jumbo-support", no_argument, NULL, 'J'},
98 {"cpp", no_argument, NULL, 'p'},
99 {"rfraw", no_argument, NULL, 'R'},
100 {"rand", no_argument, NULL, 'r'},
101 {"verbose", no_argument, NULL, 'V'},
102 {"version", no_argument, NULL, 'v'},
103 {"example", no_argument, NULL, 'e'},
104 {"help", no_argument, NULL, 'h'},
105 {NULL, 0, NULL, 0}
108 static int sock;
110 static struct itimerval itimer;
112 static unsigned long interval = TX_KERNEL_PULL_INT;
114 static struct cpu_stats *stats;
116 unsigned int seed;
118 #define CPU_STATS_STATE_CFG 1
119 #define CPU_STATS_STATE_CHK 2
120 #define CPU_STATS_STATE_RES 4
122 #define set_system_socket_memory(vals) \
123 do { \
124 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX) \
125 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX); \
126 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF) \
127 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF); \
128 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX) \
129 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX); \
130 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF) \
131 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF); \
132 } while (0)
134 #define reset_system_socket_memory(vals) \
135 do { \
136 set_system_socket_mem(sock_rmem_max, vals[0]); \
137 set_system_socket_mem(sock_rmem_def, vals[1]); \
138 set_system_socket_mem(sock_wmem_max, vals[2]); \
139 set_system_socket_mem(sock_wmem_def, vals[3]); \
140 } while (0)
142 #ifndef ICMP_FILTER
143 # define ICMP_FILTER 1
145 struct icmp_filter {
146 __u32 data;
148 #endif
150 static void signal_handler(int number)
152 switch (number) {
153 case SIGINT:
154 sigint = 1;
155 case SIGHUP:
156 default:
157 break;
161 static void timer_elapsed(int number)
163 itimer.it_interval.tv_sec = 0;
164 itimer.it_interval.tv_usec = interval;
166 itimer.it_value.tv_sec = 0;
167 itimer.it_value.tv_usec = interval;
169 pull_and_flush_tx_ring(sock);
170 setitimer(ITIMER_REAL, &itimer, NULL);
173 static void header(void)
175 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
178 static void help(void)
180 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
181 puts("http://www.netsniff-ng.org\n\n"
182 "Usage: trafgen [options]\n"
183 "Options:\n"
184 " -o|-d|--out|--dev <netdev> Networking Device i.e., eth0\n"
185 " -i|-c|--in|--conf <cfg-file/-> Packet configuration file/stdin\n"
186 " -p|--cpp Run packet config through preprocessor\n"
187 " -J|--jumbo-support Support 64KB Super Jumbo Frames (def: 2048B)\n"
188 " -R|--rfraw Inject raw 802.11 frames\n"
189 " -s|--smoke-test <ipv4-receiver> Test if machine survived packet\n"
190 " -n|--num <uint> Number of packets until exit (def: 0)\n"
191 " -r|--rand Randomize packet selection (def: round robin)\n"
192 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
193 " -t|--gap <uint> Interpacket gap in us (approx)\n"
194 " -S|--ring-size <size> Manually set mmap size (KB/MB/GB): e.g.\'10MB\'\n"
195 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
196 " -E|--seed <uint> Manually set srand(3) seed\n"
197 " -V|--verbose Be more verbose\n"
198 " -v|--version Show version\n"
199 " -e|--example Show built-in packet config example\n"
200 " -h|--help Guess what?!\n\n"
201 "Examples:\n"
202 " See trafgen.txf for configuration file examples.\n"
203 " trafgen --dev eth0 --conf trafgen.cfg\n"
204 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
205 " trafgen --dev eth0 --conf trafgen.cfg --smoke-test 10.0.0.1\n"
206 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
207 " trafgen --dev eth0 --conf trafgen.cfg --rand --gap 1000\n"
208 " trafgen --dev eth0 --conf trafgen.cfg --rand --num 1400000 -k1000\n\n"
209 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
210 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
211 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
212 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
213 "Note:\n"
214 " Smoke test example: machine A, 10.0.0.2 (trafgen) is directly\n"
215 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
216 " we assume the kernel crashed, thus we print the packet and quit.\n"
217 " In case you find a ping-of-death, please mention trafgen in your\n"
218 " commit message of the fix!\n\n"
219 " This tool is targeted for network developers! You should\n"
220 " be aware of what you are doing and what these options above\n"
221 " mean! Only use this tool in an isolated LAN that you own!\n\n"
222 "Please report bugs to <bugs@netsniff-ng.org>\n"
223 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
224 "Swiss federal institute of technology (ETH Zurich)\n"
225 "License: GNU GPL version 2.0\n"
226 "This is free software: you are free to change and redistribute it.\n"
227 "There is NO WARRANTY, to the extent permitted by law.\n");
228 die();
231 static void example(void)
233 const char *e =
234 "/* Note: dynamic elements make trafgen slower! */\n\n"
235 "#define ETH_P_IP 0x0800\n\n"
236 "#define SYN (1 << 1)\n"
237 "#define ECN (1 << 6)\n\n"
238 "{\n"
239 " /* MAC Destination */\n"
240 " fill(0xff, 6),\n"
241 " /* MAC Source */\n"
242 " 0x00, 0x02, 0xb3, drnd(3),\n"
243 " /* IPv4 Protocol */\n"
244 " c16(ETH_P_IP),\n"
245 " /* IPv4 Version, IHL, TOS */\n"
246 " 0b01000101, 0,\n"
247 " /* IPv4 Total Len */\n"
248 " c16(59),\n"
249 " /* IPv4 Ident */\n"
250 " drnd(2),\n"
251 " /* IPv4 Flags, Frag Off */\n"
252 " 0b01000000, 0,\n"
253 " /* IPv4 TTL */\n"
254 " 64,\n"
255 " /* Proto TCP */\n"
256 " 0x06,\n"
257 " /* IPv4 Checksum (IP header from, to) */\n"
258 " csumip(14, 33),\n"
259 " /* Source IP */\n"
260 " drnd(4),\n"
261 " /* Dest IP */\n"
262 " drnd(4),\n"
263 " /* TCP Source Port */\n"
264 " drnd(2),\n"
265 " /* TCP Dest Port */\n"
266 " c16(80),\n"
267 " /* TCP Sequence Number */\n"
268 " drnd(4),\n"
269 " /* TCP Ackn. Number */\n"
270 " c32(0),\n"
271 " /* TCP Header length + TCP SYN/ECN Flag */\n"
272 " c16((0x8 << 12) | SYN | ECN)\n"
273 " /* Window Size */\n"
274 " c16(16),\n"
275 " /* TCP Checksum (offset IP, offset TCP) */\n"
276 " csumtcp(14, 34),\n"
277 " /* TCP Options */\n"
278 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
279 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
280 " /* Data blob */\n"
281 " \"gotcha!\",\n"
282 "}";
283 puts(e);
284 die();
287 static void version(void)
289 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
290 puts("http://www.netsniff-ng.org\n\n"
291 "Please report bugs to <bugs@netsniff-ng.org>\n"
292 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
293 "Swiss federal institute of technology (ETH Zurich)\n"
294 "License: GNU GPL version 2.0\n"
295 "This is free software: you are free to change and redistribute it.\n"
296 "There is NO WARRANTY, to the extent permitted by law.\n");
297 die();
300 static void apply_counter(int counter_id)
302 int j, i = counter_id;
303 size_t counter_max = packet_dyn[i].clen;
305 for (j = 0; j < counter_max; ++j) {
306 uint8_t val;
307 struct counter *counter = &packet_dyn[i].cnt[j];
309 val = counter->val - counter->min;
311 switch (counter->type) {
312 case TYPE_INC:
313 val = (val + counter->inc) % (counter->max - counter->min + 1);
314 break;
315 case TYPE_DEC:
316 val = (val - counter->inc) % (counter->min - counter->max + 1);
317 break;
318 default:
319 bug();
322 counter->val = val + counter->min;
323 packets[i].payload[counter->off] = val;
327 static void apply_randomizer(int rand_id)
329 int j, i = rand_id;
330 size_t rand_max = packet_dyn[i].rlen;
332 for (j = 0; j < rand_max; ++j) {
333 uint8_t val = (uint8_t) rand();
334 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
336 packets[i].payload[randomizer->off] = val;
340 /* Taken and modified from tcpdump, Copyright belongs to them! */
342 struct cksum_vec {
343 const u8 *ptr;
344 int len;
347 #define ADDCARRY(x) \
348 do { if ((x) > 65535) \
349 (x) -= 65535; \
350 } while (0)
352 #define REDUCE \
353 do { \
354 l_util.l = sum; \
355 sum = l_util.s[0] + l_util.s[1]; \
356 ADDCARRY(sum); \
357 } while (0)
359 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
361 register const u16 *w;
362 register int sum = 0, mlen = 0;
363 int byte_swapped = 0;
364 union {
365 u8 c[2];
366 u16 s;
367 } s_util;
368 union {
369 u16 s[2];
370 u32 l;
371 } l_util;
373 for (; veclen != 0; vec++, veclen--) {
374 if (vec->len == 0)
375 continue;
377 w = (const u16 *) (void *) vec->ptr;
379 if (mlen == -1) {
380 s_util.c[1] = *(const u8 *) w;
381 sum += s_util.s;
382 w = (const u16 *) (void *) ((const u8 *) w + 1);
383 mlen = vec->len - 1;
384 } else
385 mlen = vec->len;
387 if ((1 & (unsigned long) w) && (mlen > 0)) {
388 REDUCE;
389 sum <<= 8;
390 s_util.c[0] = *(const u8 *) w;
391 w = (const u16 *) (void *) ((const u8 *) w + 1);
392 mlen--;
393 byte_swapped = 1;
396 while ((mlen -= 32) >= 0) {
397 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
398 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
399 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
400 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
401 w += 16;
404 mlen += 32;
406 while ((mlen -= 8) >= 0) {
407 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
408 w += 4;
411 mlen += 8;
413 if (mlen == 0 && byte_swapped == 0)
414 continue;
416 REDUCE;
418 while ((mlen -= 2) >= 0) {
419 sum += *w++;
422 if (byte_swapped) {
423 REDUCE;
424 sum <<= 8;
425 byte_swapped = 0;
427 if (mlen == -1) {
428 s_util.c[1] = *(const u8 *) w;
429 sum += s_util.s;
430 mlen = 0;
431 } else
432 mlen = -1;
433 } else if (mlen == -1)
434 s_util.c[0] = *(const u8 *) w;
437 if (mlen == -1) {
438 s_util.c[1] = 0;
439 sum += s_util.s;
442 REDUCE;
444 return (~sum & 0xffff);
447 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
448 u8 next_proto)
450 struct cksum_vec vec[2];
451 struct pseudo_hdr {
452 u32 src;
453 u32 dst;
454 u8 mbz;
455 u8 proto;
456 u16 len;
457 } ph;
459 memset(&ph, 0, sizeof(ph));
460 ph.len = htons(len);
461 ph.mbz = 0;
462 ph.proto = next_proto;
463 ph.src = ip->ip_src.s_addr;
464 ph.dst = ip->ip_dst.s_addr;
466 vec[0].ptr = (const u8 *) (void *) &ph;
467 vec[0].len = sizeof(ph);
469 vec[1].ptr = data;
470 vec[1].len = len;
472 return __in_cksum(vec, 2);
475 static void apply_csum16(int csum_id)
477 int j, i = csum_id;
478 size_t csum_max = packet_dyn[i].slen;
480 for (j = 0; j < csum_max; ++j) {
481 uint16_t sum = 0;
482 struct csum16 *csum = &packet_dyn[i].csum[j];
484 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
486 switch (csum->which) {
487 case CSUM_IP:
488 if (csum->to >= packets[i].len)
489 csum->to = packets[i].len - 1;
490 sum = calc_csum(packets[i].payload + csum->from,
491 csum->to - csum->from + 1, 0);
492 break;
493 case CSUM_UDP:
494 sum = p4_csum((void *) packets[i].payload + csum->from,
495 packets[i].payload + csum->to,
496 (packets[i].len - csum->to),
497 IPPROTO_UDP);
498 break;
499 case CSUM_TCP:
500 sum = p4_csum((void *) packets[i].payload + csum->from,
501 packets[i].payload + csum->to,
502 (packets[i].len - csum->to),
503 IPPROTO_TCP);
504 break;
507 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
511 static struct cpu_stats *setup_shared_var(unsigned long cpus)
513 int fd;
514 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
515 struct cpu_stats *buff;
517 fmemset(zbuff, 0, sizeof(zbuff));
518 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
520 fd = creat(file, S_IRUSR | S_IWUSR);
521 bug_on(fd < 0);
522 close(fd);
524 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
525 S_IRUSR | S_IWUSR);
526 write_or_die(fd, zbuff, sizeof(zbuff));
528 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
529 MAP_SHARED, fd, 0);
530 if (buff == (void *) -1)
531 panic("Cannot setup shared variable!\n");
533 close(fd);
534 unlink(file);
536 memset(buff, 0, sizeof(zbuff));
538 return buff;
541 static void destroy_shared_var(void *buff, unsigned long cpus)
543 munmap(buff, cpus * sizeof(struct cpu_stats));
546 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
548 int i;
550 printf("{");
551 for (i = 0; i < len; ++i) {
552 if (i % 15 == 0)
553 printf("\n ");
554 printf("0x%02x, ", payload[i]);
556 printf("\n}\n");
557 fflush(stdout);
560 static inline unsigned short csum(unsigned short *buf, int nwords)
562 unsigned long sum;
564 for (sum = 0; nwords > 0; nwords--)
565 sum += *buf++;
566 sum = (sum >> 16) + (sum & 0xffff);
567 sum += (sum >> 16);
569 return ~sum;
572 static int xmit_smoke_setup(struct ctx *ctx)
574 int icmp_sock, ret, ttl = 64;
575 struct icmp_filter filter;
577 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
578 if (icmp_sock < 0)
579 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
581 filter.data = ~(1 << ICMP_ECHOREPLY);
583 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
584 if (ret < 0)
585 panic("Cannot install filter!\n");
587 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
588 if (ret < 0)
589 panic("Cannot set TTL!\n");
591 memset(&ctx->dest, 0, sizeof(ctx->dest));
592 ctx->dest.sin_family = AF_INET;
593 ctx->dest.sin_port = 0;
595 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
596 if (ret < 0)
597 panic("Cannot resolv address!\n");
599 return icmp_sock;
602 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
604 int ret, i, probes = 5;
605 short ident, cnt = 1;
606 uint8_t outpack[512], *data;
607 struct icmphdr *icmp;
608 struct iphdr *ip;
609 size_t len = sizeof(*icmp) + 56;
610 struct sockaddr_in from;
611 socklen_t from_len;
612 struct pollfd fds = {
613 .fd = icmp_sock,
614 .events = POLLIN,
617 while (probes-- > 0) {
618 ident = htons((short) rand());
620 memset(outpack, 0, sizeof(outpack));
621 icmp = (void *) outpack;
622 icmp->type = ICMP_ECHO;
623 icmp->code = 0;
624 icmp->checksum = 0;
625 icmp->un.echo.id = ident;
626 icmp->un.echo.sequence = htons(cnt++);
628 data = ((uint8_t *) outpack + sizeof(*icmp));
629 for (i = 0; i < 56; ++i)
630 data[i] = (uint8_t) rand();
632 icmp->checksum = csum((unsigned short *) outpack,
633 len / sizeof(unsigned short));
635 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
636 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
637 if (unlikely(ret != len))
638 panic("Cannot send out probe: %s!\n", strerror(errno));
640 ret = poll(&fds, 1, 500);
641 if (ret < 0)
642 panic("Poll failed!\n");
644 if (fds.revents & POLLIN) {
645 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
646 (struct sockaddr *) &from, &from_len);
647 if (unlikely(ret <= 0))
648 panic("Probe receive failed!\n");
649 if (unlikely(from_len != sizeof(ctx->dest)))
650 continue;
651 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
652 continue;
653 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
654 continue;
655 ip = (void *) outpack;
656 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
657 continue;
658 icmp = (void *) outpack + ip->ihl * 4;
659 if (unlikely(icmp->un.echo.id != ident))
660 continue;
662 return 0;
666 return -1;
669 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
671 int ret, icmp_sock = -1;
672 unsigned long num = 1, i = 0;
673 struct timeval start, end, diff;
674 unsigned long long tx_bytes = 0, tx_packets = 0;
675 struct packet_dyn *pktd;
676 struct sockaddr_ll saddr = {
677 .sll_family = PF_PACKET,
678 .sll_halen = ETH_ALEN,
679 .sll_ifindex = device_ifindex(ctx->device),
682 if (ctx->num > 0)
683 num = ctx->num;
685 if (ctx->smoke_test)
686 icmp_sock = xmit_smoke_setup(ctx);
688 bug_on(gettimeofday(&start, NULL));
690 while (likely(sigint == 0) && likely(num > 0)) {
691 pktd = &packet_dyn[i];
692 if (pktd->clen + pktd->rlen + pktd->slen) {
693 apply_counter(i);
694 apply_randomizer(i);
695 apply_csum16(i);
697 retry:
698 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
699 (struct sockaddr *) &saddr, sizeof(saddr));
700 if (unlikely(ret < 0)) {
701 if (errno == ENOBUFS) {
702 sched_yield();
703 goto retry;
706 panic("Sendto error: %s!\n", strerror(errno));
709 tx_bytes += packets[i].len;
710 tx_packets++;
712 if (ctx->smoke_test) {
713 ret = xmit_smoke_probe(icmp_sock, ctx);
714 if (unlikely(ret < 0)) {
715 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
716 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
717 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
718 i, seed);
720 dump_trafgen_snippet(packets[i].payload, packets[i].len);
721 break;
725 if (!ctx->rand) {
726 i++;
727 if (i >= plen)
728 i = 0;
729 } else
730 i = rand() % plen;
732 if (ctx->num > 0)
733 num--;
735 if (ctx->gap > 0)
736 usleep(ctx->gap);
739 bug_on(gettimeofday(&end, NULL));
740 diff = tv_subtract(end, start);
742 if (ctx->smoke_test)
743 close(icmp_sock);
745 stats[cpu].tx_packets = tx_packets;
746 stats[cpu].tx_bytes = tx_bytes;
747 stats[cpu].tv_sec = diff.tv_sec;
748 stats[cpu].tv_usec = diff.tv_usec;
750 stats[cpu].state |= CPU_STATS_STATE_RES;
753 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
755 int ifindex = device_ifindex(ctx->device);
756 uint8_t *out = NULL;
757 unsigned int it = 0;
758 unsigned long num = 1, i = 0, size;
759 struct ring tx_ring;
760 struct frame_map *hdr;
761 struct timeval start, end, diff;
762 struct packet_dyn *pktd;
763 unsigned long long tx_bytes = 0, tx_packets = 0;
765 fmemset(&tx_ring, 0, sizeof(tx_ring));
767 size = ring_size(ctx->device, ctx->reserve_size);
769 set_sock_prio(sock, 512);
770 set_packet_loss_discard(sock);
772 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
773 create_tx_ring(sock, &tx_ring, ctx->verbose);
774 mmap_tx_ring(sock, &tx_ring);
775 alloc_tx_ring_frames(&tx_ring);
776 bind_tx_ring(sock, &tx_ring, ifindex);
778 if (ctx->kpull)
779 interval = ctx->kpull;
780 if (ctx->num > 0)
781 num = ctx->num;
783 itimer.it_interval.tv_sec = 0;
784 itimer.it_interval.tv_usec = interval;
786 itimer.it_value.tv_sec = 0;
787 itimer.it_value.tv_usec = interval;
789 setitimer(ITIMER_REAL, &itimer, NULL);
791 bug_on(gettimeofday(&start, NULL));
793 while (likely(sigint == 0) && likely(num > 0)) {
794 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
795 hdr = tx_ring.frames[it].iov_base;
797 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
798 * sizeof(struct sockaddr_ll); */
799 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
801 hdr->tp_h.tp_snaplen = packets[i].len;
802 hdr->tp_h.tp_len = packets[i].len;
804 pktd = &packet_dyn[i];
805 if (pktd->clen + pktd->rlen + pktd->slen) {
806 apply_counter(i);
807 apply_randomizer(i);
808 apply_csum16(i);
811 fmemcpy(out, packets[i].payload, packets[i].len);
813 tx_bytes += packets[i].len;
814 tx_packets++;
816 if (!ctx->rand) {
817 i++;
818 if (i >= plen)
819 i = 0;
820 } else
821 i = rand() % plen;
823 kernel_may_pull_from_tx(&hdr->tp_h);
825 it++;
826 if (it >= tx_ring.layout.tp_frame_nr)
827 it = 0;
829 if (ctx->num > 0)
830 num--;
832 if (unlikely(sigint == 1))
833 break;
837 bug_on(gettimeofday(&end, NULL));
838 diff = tv_subtract(end, start);
840 destroy_tx_ring(sock, &tx_ring);
842 stats[cpu].tx_packets = tx_packets;
843 stats[cpu].tx_bytes = tx_bytes;
844 stats[cpu].tv_sec = diff.tv_sec;
845 stats[cpu].tv_usec = diff.tv_usec;
847 stats[cpu].state |= CPU_STATS_STATE_RES;
850 static inline void __set_state(int cpu, sig_atomic_t s)
852 stats[cpu].state = s;
855 static inline sig_atomic_t __get_state(int cpu)
857 return stats[cpu].state;
860 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
862 int i;
863 unsigned long total;
865 for (i = 0, total = plen; i < ctx->cpus; i++) {
866 if (i == cpu)
867 continue;
869 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
870 sigint == 0)
871 sched_yield();
873 total += stats[i].cf_packets;
876 return total;
879 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
881 int i, cpu_sel;
882 unsigned long total;
883 long long delta_correction = 0;
885 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
886 if (i == cpu)
887 continue;
889 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
890 sigint == 0)
891 sched_yield();
893 total += stats[i].cd_packets;
896 if (total > orig)
897 delta_correction = -1 * ((long long) total - orig);
898 if (total < orig)
899 delta_correction = +1 * ((long long) orig - total);
901 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
902 if (stats[i].cd_packets > 0) {
903 if ((long long) stats[i].cd_packets +
904 delta_correction > 0) {
905 cpu_sel = i;
906 break;
911 if (cpu == cpu_sel)
912 ctx->num += delta_correction;
915 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
916 sig_atomic_t s)
918 stats[cpu].cf_packets = p;
919 stats[cpu].cf_bytes = b;
920 stats[cpu].state = s;
923 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
925 stats[cpu].cd_packets = p;
926 stats[cpu].state = s;
929 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
931 int i;
932 unsigned long plen_total, orig = ctx->num;
933 size_t mtu, total_len = 0;
935 bug_on(plen != dlen);
937 for (i = 0; i < plen; ++i)
938 total_len += packets[i].len;
940 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
941 plen_total = __wait_and_sum_others(ctx, cpu);
943 if (orig > 0) {
944 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
946 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
947 CPU_STATS_STATE_CFG);
948 __correct_global_delta(ctx, cpu, orig);
951 if (plen == 0) {
952 __set_state(cpu, CPU_STATS_STATE_RES);
953 return -1;
956 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
957 if (packets[i].len > mtu + 14)
958 panic("Device MTU < than packet%d's size!\n", i);
959 if (packets[i].len <= 14)
960 panic("Packet%d's size too short!\n", i);
963 return 0;
966 static void main_loop(struct ctx *ctx, char *confname, bool slow,
967 int cpu, bool invoke_cpp)
969 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
970 if (xmit_packet_precheck(ctx, cpu) < 0)
971 return;
973 if (cpu == 0) {
974 int i;
975 size_t total_len = 0, total_pkts = 0;
977 for (i = 0; i < ctx->cpus; ++i) {
978 total_len += stats[i].cf_bytes;
979 total_pkts += stats[i].cf_packets;
982 printf("%6zu packets to schedule\n", total_pkts);
983 printf("%6zu bytes in total\n", total_len);
984 printf("Running! Hang up with ^C!\n\n");
985 fflush(stdout);
988 sock = pf_socket();
990 if (slow)
991 xmit_slowpath_or_die(ctx, cpu);
992 else
993 xmit_fastpath_or_die(ctx, cpu);
995 close(sock);
997 cleanup_packets();
1000 static unsigned int generate_srand_seed(void)
1002 int fd;
1003 unsigned int seed;
1005 fd = open("/dev/random", O_RDONLY);
1006 if (fd < 0)
1007 return time(0);
1009 read_or_die(fd, &seed, sizeof(seed));
1011 close(fd);
1012 return seed;
1015 int main(int argc, char **argv)
1017 bool slow = false, invoke_cpp = false;
1018 int c, opt_index, i, j, vals[4] = {0}, irq;
1019 char *confname = NULL, *ptr;
1020 unsigned long cpus_tmp;
1021 unsigned long long tx_packets, tx_bytes;
1022 struct ctx ctx;
1024 setfsuid(getuid());
1025 setfsgid(getgid());
1027 fmemset(&ctx, 0, sizeof(ctx));
1028 ctx.cpus = get_number_cpus_online();
1030 seed = generate_srand_seed();
1032 while ((c = getopt_long(argc, argv, short_options, long_options,
1033 &opt_index)) != EOF) {
1034 switch (c) {
1035 case 'h':
1036 help();
1037 break;
1038 case 'v':
1039 version();
1040 break;
1041 case 'e':
1042 example();
1043 break;
1044 case 'p':
1045 invoke_cpp = true;
1046 break;
1047 case 'V':
1048 ctx.verbose = true;
1049 break;
1050 case 'P':
1051 cpus_tmp = strtoul(optarg, NULL, 0);
1052 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1053 ctx.cpus = cpus_tmp;
1054 break;
1055 case 'd':
1056 case 'o':
1057 ctx.device = xstrndup(optarg, IFNAMSIZ);
1058 break;
1059 case 'r':
1060 ctx.rand = true;
1061 break;
1062 case 's':
1063 slow = true;
1064 ctx.cpus = 1;
1065 ctx.smoke_test = true;
1066 ctx.rhost = xstrdup(optarg);
1067 break;
1068 case 'R':
1069 ctx.rfraw = true;
1070 break;
1071 case 'J':
1072 ctx.jumbo_support = true;
1073 break;
1074 case 'c':
1075 case 'i':
1076 confname = xstrdup(optarg);
1077 break;
1078 case 'k':
1079 ctx.kpull = strtoul(optarg, NULL, 0);
1080 break;
1081 case 'E':
1082 seed = strtoul(optarg, NULL, 0);
1083 break;
1084 case 'n':
1085 ctx.num = strtoul(optarg, NULL, 0);
1086 break;
1087 case 't':
1088 slow = true;
1089 ctx.gap = strtoul(optarg, NULL, 0);
1090 if (ctx.gap > 0)
1091 /* Fall back to single core to not
1092 * mess up correct timing. We are slow
1093 * anyway!
1095 ctx.cpus = 1;
1096 break;
1097 case 'S':
1098 ptr = optarg;
1099 ctx.reserve_size = 0;
1101 for (j = i = strlen(optarg); i > 0; --i) {
1102 if (!isdigit(optarg[j - i]))
1103 break;
1104 ptr++;
1107 if (!strncmp(ptr, "KB", strlen("KB")))
1108 ctx.reserve_size = 1 << 10;
1109 else if (!strncmp(ptr, "MB", strlen("MB")))
1110 ctx.reserve_size = 1 << 20;
1111 else if (!strncmp(ptr, "GB", strlen("GB")))
1112 ctx.reserve_size = 1 << 30;
1113 else
1114 panic("Syntax error in ring size param!\n");
1115 *ptr = 0;
1117 ctx.reserve_size *= strtol(optarg, NULL, 0);
1118 break;
1119 case '?':
1120 switch (optopt) {
1121 case 'd':
1122 case 'c':
1123 case 'n':
1124 case 'S':
1125 case 's':
1126 case 'P':
1127 case 'o':
1128 case 'E':
1129 case 'i':
1130 case 'k':
1131 case 't':
1132 panic("Option -%c requires an argument!\n",
1133 optopt);
1134 default:
1135 if (isprint(optopt))
1136 whine("Unknown option character "
1137 "`0x%X\'!\n", optopt);
1138 die();
1140 default:
1141 break;
1145 if (argc < 5)
1146 help();
1147 if (ctx.device == NULL)
1148 panic("No networking device given!\n");
1149 if (confname == NULL)
1150 panic("No configuration file given!\n");
1151 if (device_mtu(ctx.device) == 0)
1152 panic("This is no networking device!\n");
1153 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1154 panic("Networking device not running!\n");
1156 register_signal(SIGINT, signal_handler);
1157 register_signal(SIGHUP, signal_handler);
1158 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1160 header();
1162 srand(seed);
1164 set_system_socket_memory(vals);
1166 if (ctx.rfraw) {
1167 ctx.device_trans = xstrdup(ctx.device);
1168 xfree(ctx.device);
1170 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1171 sleep(0);
1174 irq = device_irq_number(ctx.device);
1175 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1177 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1178 ctx.cpus = 1;
1180 stats = setup_shared_var(ctx.cpus);
1182 for (i = 0; i < ctx.cpus; i++) {
1183 pid_t pid = fork();
1185 switch (pid) {
1186 case 0:
1187 cpu_affinity(i);
1188 main_loop(&ctx, confname, slow, i, invoke_cpp);
1190 goto thread_out;
1191 case -1:
1192 panic("Cannot fork processes!\n");
1196 for (i = 0; i < ctx.cpus; i++) {
1197 int status;
1199 wait(&status);
1200 if (WEXITSTATUS(status) == EXIT_FAILURE)
1201 die();
1204 if (ctx.rfraw)
1205 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1207 reset_system_socket_memory(vals);
1209 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1210 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1211 sched_yield();
1213 tx_packets += stats[i].tx_packets;
1214 tx_bytes += stats[i].tx_bytes;
1217 fflush(stdout);
1218 printf("\n");
1219 printf("\r%12llu packets outgoing\n", tx_packets);
1220 printf("\r%12llu bytes outgoing\n", tx_bytes);
1221 for (i = 0; i < ctx.cpus; i++) {
1222 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1223 stats[i].tv_sec, stats[i].tv_usec, i,
1224 stats[i].tx_packets);
1227 thread_out:
1228 destroy_shared_var(stats, ctx.cpus);
1230 free(ctx.device);
1231 free(ctx.device_trans);
1232 free(ctx.rhost);
1233 free(confname);
1235 return 0;