trafgen: give note about tc(8) usage
[netsniff-ng.git] / src / trafgen.c
blob51649cb509bc61bad6a4a3800ac3735a032c3f84
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 struct sockaddr_in dest;
66 uid_t uid;
67 gid_t gid;
68 char *device, *device_trans, *rhost;
71 struct cpu_stats {
72 unsigned long tv_sec, tv_usec;
73 unsigned long long tx_packets, tx_bytes;
74 unsigned long long cf_packets, cf_bytes;
75 unsigned long long cd_packets;
76 sig_atomic_t state;
79 sig_atomic_t sigint = 0;
81 struct packet *packets = NULL;
82 size_t plen = 0;
84 struct packet_dyn *packet_dyn = NULL;
85 size_t dlen = 0;
87 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRsP:eE:pu:g:";
88 static const struct option long_options[] = {
89 {"dev", required_argument, NULL, 'd'},
90 {"out", required_argument, NULL, 'o'},
91 {"in", required_argument, NULL, 'i'},
92 {"conf", required_argument, NULL, 'c'},
93 {"num", required_argument, NULL, 'n'},
94 {"gap", required_argument, NULL, 't'},
95 {"cpus", required_argument, NULL, 'P'},
96 {"ring-size", required_argument, NULL, 'S'},
97 {"kernel-pull", required_argument, NULL, 'k'},
98 {"smoke-test", required_argument, NULL, 's'},
99 {"seed", required_argument, NULL, 'E'},
100 {"user", required_argument, NULL, 'u'},
101 {"group", required_argument, NULL, 'g'},
102 {"jumbo-support", no_argument, NULL, 'J'},
103 {"cpp", no_argument, NULL, 'p'},
104 {"rfraw", no_argument, NULL, 'R'},
105 {"rand", no_argument, NULL, 'r'},
106 {"verbose", no_argument, NULL, 'V'},
107 {"version", no_argument, NULL, 'v'},
108 {"example", no_argument, NULL, 'e'},
109 {"help", no_argument, NULL, 'h'},
110 {NULL, 0, NULL, 0}
113 static int sock;
115 static struct itimerval itimer;
117 static unsigned long interval = TX_KERNEL_PULL_INT;
119 static struct cpu_stats *stats;
121 unsigned int seed;
123 #define CPU_STATS_STATE_CFG 1
124 #define CPU_STATS_STATE_CHK 2
125 #define CPU_STATS_STATE_RES 4
127 #define set_system_socket_memory(vals) \
128 do { \
129 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX) \
130 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX); \
131 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF) \
132 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF); \
133 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX) \
134 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX); \
135 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF) \
136 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF); \
137 } while (0)
139 #define reset_system_socket_memory(vals) \
140 do { \
141 set_system_socket_mem(sock_rmem_max, vals[0]); \
142 set_system_socket_mem(sock_rmem_def, vals[1]); \
143 set_system_socket_mem(sock_wmem_max, vals[2]); \
144 set_system_socket_mem(sock_wmem_def, vals[3]); \
145 } while (0)
147 #ifndef ICMP_FILTER
148 # define ICMP_FILTER 1
150 struct icmp_filter {
151 __u32 data;
153 #endif
155 static void signal_handler(int number)
157 switch (number) {
158 case SIGINT:
159 sigint = 1;
160 case SIGHUP:
161 default:
162 break;
166 static void timer_elapsed(int number)
168 itimer.it_interval.tv_sec = 0;
169 itimer.it_interval.tv_usec = interval;
171 itimer.it_value.tv_sec = 0;
172 itimer.it_value.tv_usec = interval;
174 pull_and_flush_tx_ring(sock);
175 setitimer(ITIMER_REAL, &itimer, NULL);
178 static void header(void)
180 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
183 static void help(void)
185 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
186 puts("http://www.netsniff-ng.org\n\n"
187 "Usage: trafgen [options]\n"
188 "Options:\n"
189 " -o|-d|--out|--dev <netdev> Networking Device i.e., eth0\n"
190 " -i|-c|--in|--conf <cfg-file/-> Packet configuration file/stdin\n"
191 " -p|--cpp Run packet config through preprocessor\n"
192 " -J|--jumbo-support Support 64KB Super Jumbo Frames (def: 2048B)\n"
193 " -R|--rfraw Inject raw 802.11 frames\n"
194 " -s|--smoke-test <ipv4-receiver> Test if machine survived packet\n"
195 " -n|--num <uint> Number of packets until exit (def: 0)\n"
196 " -r|--rand Randomize packet selection (def: round robin)\n"
197 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
198 " -t|--gap <uint> Interpacket gap in us (approx)\n"
199 " -S|--ring-size <size> Manually set mmap size (KB/MB/GB): e.g.\'10MB\'\n"
200 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
201 " -E|--seed <uint> Manually set srand(3) seed\n"
202 " -u|--user <userid> Drop privileges and change to userid\n"
203 " -g|--group <groupid> Drop privileges and change to groupid\n"
204 " -V|--verbose Be more verbose\n"
205 " -v|--version Show version\n"
206 " -e|--example Show built-in packet config example\n"
207 " -h|--help Guess what?!\n\n"
208 "Examples:\n"
209 " See trafgen.txf for configuration file examples.\n"
210 " trafgen --dev eth0 --conf trafgen.cfg\n"
211 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
212 " trafgen --dev eth0 --conf trafgen.cfg --smoke-test 10.0.0.1\n"
213 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
214 " trafgen --dev eth0 --conf trafgen.cfg --rand --gap 1000\n"
215 " trafgen --dev eth0 --conf trafgen.cfg --rand --num 1400000 -k1000\n"
216 " trafgen --dev eth0 --conf trafgen.cfg -u `id -u bob` -g `id -g bob`\n\n"
217 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
218 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
219 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
220 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
221 "Note:\n"
222 " Smoke test example: machine A, 10.0.0.2 (trafgen) is directly\n"
223 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
224 " we assume the kernel crashed, thus we print the packet and quit.\n"
225 " In case you find a ping-of-death, please mention trafgen in your\n"
226 " commit message of the fix!\n\n"
227 " For introducing bit errors, delays with random variation and more,\n"
228 " make use of tc(8) with its difference disciplines (e.g. netem)\n\n"
229 "Please report bugs to <bugs@netsniff-ng.org>\n"
230 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
231 "Swiss federal institute of technology (ETH Zurich)\n"
232 "License: GNU GPL version 2.0\n"
233 "This is free software: you are free to change and redistribute it.\n"
234 "There is NO WARRANTY, to the extent permitted by law.\n");
235 die();
238 static void example(void)
240 const char *e =
241 "/* Note: dynamic elements make trafgen slower! */\n\n"
242 "#define ETH_P_IP 0x0800\n\n"
243 "#define SYN (1 << 1)\n"
244 "#define ECN (1 << 6)\n\n"
245 "{\n"
246 " /* MAC Destination */\n"
247 " fill(0xff, 6),\n"
248 " /* MAC Source */\n"
249 " 0x00, 0x02, 0xb3, drnd(3),\n"
250 " /* IPv4 Protocol */\n"
251 " c16(ETH_P_IP),\n"
252 " /* IPv4 Version, IHL, TOS */\n"
253 " 0b01000101, 0,\n"
254 " /* IPv4 Total Len */\n"
255 " c16(59),\n"
256 " /* IPv4 Ident */\n"
257 " drnd(2),\n"
258 " /* IPv4 Flags, Frag Off */\n"
259 " 0b01000000, 0,\n"
260 " /* IPv4 TTL */\n"
261 " 64,\n"
262 " /* Proto TCP */\n"
263 " 0x06,\n"
264 " /* IPv4 Checksum (IP header from, to) */\n"
265 " csumip(14, 33),\n"
266 " /* Source IP */\n"
267 " drnd(4),\n"
268 " /* Dest IP */\n"
269 " drnd(4),\n"
270 " /* TCP Source Port */\n"
271 " drnd(2),\n"
272 " /* TCP Dest Port */\n"
273 " c16(80),\n"
274 " /* TCP Sequence Number */\n"
275 " drnd(4),\n"
276 " /* TCP Ackn. Number */\n"
277 " c32(0),\n"
278 " /* TCP Header length + TCP SYN/ECN Flag */\n"
279 " c16((0x8 << 12) | SYN | ECN)\n"
280 " /* Window Size */\n"
281 " c16(16),\n"
282 " /* TCP Checksum (offset IP, offset TCP) */\n"
283 " csumtcp(14, 34),\n"
284 " /* TCP Options */\n"
285 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
286 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
287 " /* Data blob */\n"
288 " \"gotcha!\",\n"
289 "}";
290 puts(e);
291 die();
294 static void version(void)
296 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
297 puts("http://www.netsniff-ng.org\n\n"
298 "Please report bugs to <bugs@netsniff-ng.org>\n"
299 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
300 "Swiss federal institute of technology (ETH Zurich)\n"
301 "License: GNU GPL version 2.0\n"
302 "This is free software: you are free to change and redistribute it.\n"
303 "There is NO WARRANTY, to the extent permitted by law.\n");
304 die();
307 static void apply_counter(int counter_id)
309 int j, i = counter_id;
310 size_t counter_max = packet_dyn[i].clen;
312 for (j = 0; j < counter_max; ++j) {
313 uint8_t val;
314 struct counter *counter = &packet_dyn[i].cnt[j];
316 val = counter->val - counter->min;
318 switch (counter->type) {
319 case TYPE_INC:
320 val = (val + counter->inc) % (counter->max - counter->min + 1);
321 break;
322 case TYPE_DEC:
323 val = (val - counter->inc) % (counter->min - counter->max + 1);
324 break;
325 default:
326 bug();
329 counter->val = val + counter->min;
330 packets[i].payload[counter->off] = val;
334 static void apply_randomizer(int rand_id)
336 int j, i = rand_id;
337 size_t rand_max = packet_dyn[i].rlen;
339 for (j = 0; j < rand_max; ++j) {
340 uint8_t val = (uint8_t) rand();
341 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
343 packets[i].payload[randomizer->off] = val;
347 /* Taken and modified from tcpdump, Copyright belongs to them! */
349 struct cksum_vec {
350 const u8 *ptr;
351 int len;
354 #define ADDCARRY(x) \
355 do { if ((x) > 65535) \
356 (x) -= 65535; \
357 } while (0)
359 #define REDUCE \
360 do { \
361 l_util.l = sum; \
362 sum = l_util.s[0] + l_util.s[1]; \
363 ADDCARRY(sum); \
364 } while (0)
366 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
368 register const u16 *w;
369 register int sum = 0, mlen = 0;
370 int byte_swapped = 0;
371 union {
372 u8 c[2];
373 u16 s;
374 } s_util;
375 union {
376 u16 s[2];
377 u32 l;
378 } l_util;
380 for (; veclen != 0; vec++, veclen--) {
381 if (vec->len == 0)
382 continue;
384 w = (const u16 *) (void *) vec->ptr;
386 if (mlen == -1) {
387 s_util.c[1] = *(const u8 *) w;
388 sum += s_util.s;
389 w = (const u16 *) (void *) ((const u8 *) w + 1);
390 mlen = vec->len - 1;
391 } else
392 mlen = vec->len;
394 if ((1 & (unsigned long) w) && (mlen > 0)) {
395 REDUCE;
396 sum <<= 8;
397 s_util.c[0] = *(const u8 *) w;
398 w = (const u16 *) (void *) ((const u8 *) w + 1);
399 mlen--;
400 byte_swapped = 1;
403 while ((mlen -= 32) >= 0) {
404 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
405 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
406 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
407 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
408 w += 16;
411 mlen += 32;
413 while ((mlen -= 8) >= 0) {
414 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
415 w += 4;
418 mlen += 8;
420 if (mlen == 0 && byte_swapped == 0)
421 continue;
423 REDUCE;
425 while ((mlen -= 2) >= 0) {
426 sum += *w++;
429 if (byte_swapped) {
430 REDUCE;
431 sum <<= 8;
432 byte_swapped = 0;
434 if (mlen == -1) {
435 s_util.c[1] = *(const u8 *) w;
436 sum += s_util.s;
437 mlen = 0;
438 } else
439 mlen = -1;
440 } else if (mlen == -1)
441 s_util.c[0] = *(const u8 *) w;
444 if (mlen == -1) {
445 s_util.c[1] = 0;
446 sum += s_util.s;
449 REDUCE;
451 return (~sum & 0xffff);
454 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
455 u8 next_proto)
457 struct cksum_vec vec[2];
458 struct pseudo_hdr {
459 u32 src;
460 u32 dst;
461 u8 mbz;
462 u8 proto;
463 u16 len;
464 } ph;
466 memset(&ph, 0, sizeof(ph));
467 ph.len = htons(len);
468 ph.mbz = 0;
469 ph.proto = next_proto;
470 ph.src = ip->ip_src.s_addr;
471 ph.dst = ip->ip_dst.s_addr;
473 vec[0].ptr = (const u8 *) (void *) &ph;
474 vec[0].len = sizeof(ph);
476 vec[1].ptr = data;
477 vec[1].len = len;
479 return __in_cksum(vec, 2);
482 static void apply_csum16(int csum_id)
484 int j, i = csum_id;
485 size_t csum_max = packet_dyn[i].slen;
487 for (j = 0; j < csum_max; ++j) {
488 uint16_t sum = 0;
489 struct csum16 *csum = &packet_dyn[i].csum[j];
491 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
493 switch (csum->which) {
494 case CSUM_IP:
495 if (csum->to >= packets[i].len)
496 csum->to = packets[i].len - 1;
497 sum = calc_csum(packets[i].payload + csum->from,
498 csum->to - csum->from + 1, 0);
499 break;
500 case CSUM_UDP:
501 sum = p4_csum((void *) packets[i].payload + csum->from,
502 packets[i].payload + csum->to,
503 (packets[i].len - csum->to),
504 IPPROTO_UDP);
505 break;
506 case CSUM_TCP:
507 sum = p4_csum((void *) packets[i].payload + csum->from,
508 packets[i].payload + csum->to,
509 (packets[i].len - csum->to),
510 IPPROTO_TCP);
511 break;
514 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
518 static struct cpu_stats *setup_shared_var(unsigned long cpus)
520 int fd;
521 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
522 struct cpu_stats *buff;
524 fmemset(zbuff, 0, sizeof(zbuff));
525 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
527 fd = creat(file, S_IRUSR | S_IWUSR);
528 bug_on(fd < 0);
529 close(fd);
531 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
532 S_IRUSR | S_IWUSR);
533 write_or_die(fd, zbuff, sizeof(zbuff));
535 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
536 MAP_SHARED, fd, 0);
537 if (buff == (void *) -1)
538 panic("Cannot setup shared variable!\n");
540 close(fd);
541 unlink(file);
543 memset(buff, 0, sizeof(zbuff));
545 return buff;
548 static void destroy_shared_var(void *buff, unsigned long cpus)
550 munmap(buff, cpus * sizeof(struct cpu_stats));
553 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
555 int i;
557 printf("{");
558 for (i = 0; i < len; ++i) {
559 if (i % 15 == 0)
560 printf("\n ");
561 printf("0x%02x, ", payload[i]);
563 printf("\n}\n");
564 fflush(stdout);
567 static inline unsigned short csum(unsigned short *buf, int nwords)
569 unsigned long sum;
571 for (sum = 0; nwords > 0; nwords--)
572 sum += *buf++;
573 sum = (sum >> 16) + (sum & 0xffff);
574 sum += (sum >> 16);
576 return ~sum;
579 static int xmit_smoke_setup(struct ctx *ctx)
581 int icmp_sock, ret, ttl = 64;
582 struct icmp_filter filter;
584 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
585 if (icmp_sock < 0)
586 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
588 filter.data = ~(1 << ICMP_ECHOREPLY);
590 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
591 if (ret < 0)
592 panic("Cannot install filter!\n");
594 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
595 if (ret < 0)
596 panic("Cannot set TTL!\n");
598 memset(&ctx->dest, 0, sizeof(ctx->dest));
599 ctx->dest.sin_family = AF_INET;
600 ctx->dest.sin_port = 0;
602 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
603 if (ret < 0)
604 panic("Cannot resolv address!\n");
606 return icmp_sock;
609 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
611 int ret, i, probes = 5;
612 short ident, cnt = 1;
613 uint8_t outpack[512], *data;
614 struct icmphdr *icmp;
615 struct iphdr *ip;
616 size_t len = sizeof(*icmp) + 56;
617 struct sockaddr_in from;
618 socklen_t from_len;
619 struct pollfd fds = {
620 .fd = icmp_sock,
621 .events = POLLIN,
624 while (probes-- > 0) {
625 ident = htons((short) rand());
627 memset(outpack, 0, sizeof(outpack));
628 icmp = (void *) outpack;
629 icmp->type = ICMP_ECHO;
630 icmp->code = 0;
631 icmp->checksum = 0;
632 icmp->un.echo.id = ident;
633 icmp->un.echo.sequence = htons(cnt++);
635 data = ((uint8_t *) outpack + sizeof(*icmp));
636 for (i = 0; i < 56; ++i)
637 data[i] = (uint8_t) rand();
639 icmp->checksum = csum((unsigned short *) outpack,
640 len / sizeof(unsigned short));
642 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
643 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
644 if (unlikely(ret != len))
645 panic("Cannot send out probe: %s!\n", strerror(errno));
647 ret = poll(&fds, 1, 500);
648 if (ret < 0)
649 panic("Poll failed!\n");
651 if (fds.revents & POLLIN) {
652 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
653 (struct sockaddr *) &from, &from_len);
654 if (unlikely(ret <= 0))
655 panic("Probe receive failed!\n");
656 if (unlikely(from_len != sizeof(ctx->dest)))
657 continue;
658 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
659 continue;
660 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
661 continue;
662 ip = (void *) outpack;
663 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
664 continue;
665 icmp = (void *) outpack + ip->ihl * 4;
666 if (unlikely(icmp->un.echo.id != ident))
667 continue;
669 return 0;
673 return -1;
676 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
678 int ret, icmp_sock = -1;
679 unsigned long num = 1, i = 0;
680 struct timeval start, end, diff;
681 unsigned long long tx_bytes = 0, tx_packets = 0;
682 struct packet_dyn *pktd;
683 struct sockaddr_ll saddr = {
684 .sll_family = PF_PACKET,
685 .sll_halen = ETH_ALEN,
686 .sll_ifindex = device_ifindex(ctx->device),
689 if (ctx->num > 0)
690 num = ctx->num;
692 if (ctx->smoke_test)
693 icmp_sock = xmit_smoke_setup(ctx);
695 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
697 bug_on(gettimeofday(&start, NULL));
699 while (likely(sigint == 0) && likely(num > 0)) {
700 pktd = &packet_dyn[i];
701 if (pktd->clen + pktd->rlen + pktd->slen) {
702 apply_counter(i);
703 apply_randomizer(i);
704 apply_csum16(i);
706 retry:
707 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
708 (struct sockaddr *) &saddr, sizeof(saddr));
709 if (unlikely(ret < 0)) {
710 if (errno == ENOBUFS) {
711 sched_yield();
712 goto retry;
715 panic("Sendto error: %s!\n", strerror(errno));
718 tx_bytes += packets[i].len;
719 tx_packets++;
721 if (ctx->smoke_test) {
722 ret = xmit_smoke_probe(icmp_sock, ctx);
723 if (unlikely(ret < 0)) {
724 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
725 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
726 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
727 i, seed);
729 dump_trafgen_snippet(packets[i].payload, packets[i].len);
730 break;
734 if (!ctx->rand) {
735 i++;
736 if (i >= plen)
737 i = 0;
738 } else
739 i = rand() % plen;
741 if (ctx->num > 0)
742 num--;
744 if (ctx->gap > 0)
745 usleep(ctx->gap);
748 bug_on(gettimeofday(&end, NULL));
749 diff = tv_subtract(end, start);
751 if (ctx->smoke_test)
752 close(icmp_sock);
754 stats[cpu].tx_packets = tx_packets;
755 stats[cpu].tx_bytes = tx_bytes;
756 stats[cpu].tv_sec = diff.tv_sec;
757 stats[cpu].tv_usec = diff.tv_usec;
759 stats[cpu].state |= CPU_STATS_STATE_RES;
762 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
764 int ifindex = device_ifindex(ctx->device);
765 uint8_t *out = NULL;
766 unsigned int it = 0;
767 unsigned long num = 1, i = 0, size;
768 struct ring tx_ring;
769 struct frame_map *hdr;
770 struct timeval start, end, diff;
771 struct packet_dyn *pktd;
772 unsigned long long tx_bytes = 0, tx_packets = 0;
774 fmemset(&tx_ring, 0, sizeof(tx_ring));
776 size = ring_size(ctx->device, ctx->reserve_size);
778 set_sock_prio(sock, 512);
779 set_packet_loss_discard(sock);
781 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
782 create_tx_ring(sock, &tx_ring, ctx->verbose);
783 mmap_tx_ring(sock, &tx_ring);
784 alloc_tx_ring_frames(&tx_ring);
785 bind_tx_ring(sock, &tx_ring, ifindex);
787 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
789 if (ctx->kpull)
790 interval = ctx->kpull;
791 if (ctx->num > 0)
792 num = ctx->num;
794 itimer.it_interval.tv_sec = 0;
795 itimer.it_interval.tv_usec = interval;
797 itimer.it_value.tv_sec = 0;
798 itimer.it_value.tv_usec = interval;
800 setitimer(ITIMER_REAL, &itimer, NULL);
802 bug_on(gettimeofday(&start, NULL));
804 while (likely(sigint == 0) && likely(num > 0)) {
805 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
806 hdr = tx_ring.frames[it].iov_base;
808 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
809 * sizeof(struct sockaddr_ll); */
810 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
812 hdr->tp_h.tp_snaplen = packets[i].len;
813 hdr->tp_h.tp_len = packets[i].len;
815 pktd = &packet_dyn[i];
816 if (pktd->clen + pktd->rlen + pktd->slen) {
817 apply_counter(i);
818 apply_randomizer(i);
819 apply_csum16(i);
822 fmemcpy(out, packets[i].payload, packets[i].len);
824 tx_bytes += packets[i].len;
825 tx_packets++;
827 if (!ctx->rand) {
828 i++;
829 if (i >= plen)
830 i = 0;
831 } else
832 i = rand() % plen;
834 kernel_may_pull_from_tx(&hdr->tp_h);
836 it++;
837 if (it >= tx_ring.layout.tp_frame_nr)
838 it = 0;
840 if (ctx->num > 0)
841 num--;
843 if (unlikely(sigint == 1))
844 break;
848 bug_on(gettimeofday(&end, NULL));
849 diff = tv_subtract(end, start);
851 destroy_tx_ring(sock, &tx_ring);
853 stats[cpu].tx_packets = tx_packets;
854 stats[cpu].tx_bytes = tx_bytes;
855 stats[cpu].tv_sec = diff.tv_sec;
856 stats[cpu].tv_usec = diff.tv_usec;
858 stats[cpu].state |= CPU_STATS_STATE_RES;
861 static inline void __set_state(int cpu, sig_atomic_t s)
863 stats[cpu].state = s;
866 static inline sig_atomic_t __get_state(int cpu)
868 return stats[cpu].state;
871 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
873 int i;
874 unsigned long total;
876 for (i = 0, total = plen; i < ctx->cpus; i++) {
877 if (i == cpu)
878 continue;
880 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
881 sigint == 0)
882 sched_yield();
884 total += stats[i].cf_packets;
887 return total;
890 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
892 int i, cpu_sel;
893 unsigned long total;
894 long long delta_correction = 0;
896 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
897 if (i == cpu)
898 continue;
900 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
901 sigint == 0)
902 sched_yield();
904 total += stats[i].cd_packets;
907 if (total > orig)
908 delta_correction = -1 * ((long long) total - orig);
909 if (total < orig)
910 delta_correction = +1 * ((long long) orig - total);
912 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
913 if (stats[i].cd_packets > 0) {
914 if ((long long) stats[i].cd_packets +
915 delta_correction > 0) {
916 cpu_sel = i;
917 break;
922 if (cpu == cpu_sel)
923 ctx->num += delta_correction;
926 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
927 sig_atomic_t s)
929 stats[cpu].cf_packets = p;
930 stats[cpu].cf_bytes = b;
931 stats[cpu].state = s;
934 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
936 stats[cpu].cd_packets = p;
937 stats[cpu].state = s;
940 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
942 int i;
943 unsigned long plen_total, orig = ctx->num;
944 size_t mtu, total_len = 0;
946 bug_on(plen != dlen);
948 for (i = 0; i < plen; ++i)
949 total_len += packets[i].len;
951 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
952 plen_total = __wait_and_sum_others(ctx, cpu);
954 if (orig > 0) {
955 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
957 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
958 CPU_STATS_STATE_CFG);
959 __correct_global_delta(ctx, cpu, orig);
962 if (plen == 0) {
963 __set_state(cpu, CPU_STATS_STATE_RES);
964 return -1;
967 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
968 if (packets[i].len > mtu + 14)
969 panic("Device MTU < than packet%d's size!\n", i);
970 if (packets[i].len <= 14)
971 panic("Packet%d's size too short!\n", i);
974 return 0;
977 static void main_loop(struct ctx *ctx, char *confname, bool slow,
978 int cpu, bool invoke_cpp)
980 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
981 if (xmit_packet_precheck(ctx, cpu) < 0)
982 return;
984 if (cpu == 0) {
985 int i;
986 size_t total_len = 0, total_pkts = 0;
988 for (i = 0; i < ctx->cpus; ++i) {
989 total_len += stats[i].cf_bytes;
990 total_pkts += stats[i].cf_packets;
993 printf("%6zu packets to schedule\n", total_pkts);
994 printf("%6zu bytes in total\n", total_len);
995 printf("Running! Hang up with ^C!\n\n");
996 fflush(stdout);
999 sock = pf_socket();
1001 if (slow)
1002 xmit_slowpath_or_die(ctx, cpu);
1003 else
1004 xmit_fastpath_or_die(ctx, cpu);
1006 close(sock);
1008 cleanup_packets();
1011 static unsigned int generate_srand_seed(void)
1013 int fd;
1014 unsigned int seed;
1016 fd = open("/dev/random", O_RDONLY);
1017 if (fd < 0)
1018 return time(0);
1020 read_or_die(fd, &seed, sizeof(seed));
1022 close(fd);
1023 return seed;
1026 int main(int argc, char **argv)
1028 bool slow = false, invoke_cpp = false, reseed = true;
1029 int c, opt_index, i, j, vals[4] = {0}, irq;
1030 char *confname = NULL, *ptr;
1031 unsigned long cpus_tmp;
1032 unsigned long long tx_packets, tx_bytes;
1033 struct ctx ctx;
1035 fmemset(&ctx, 0, sizeof(ctx));
1036 ctx.cpus = get_number_cpus_online();
1037 ctx.uid = getuid();
1038 ctx.gid = getgid();
1040 while ((c = getopt_long(argc, argv, short_options, long_options,
1041 &opt_index)) != EOF) {
1042 switch (c) {
1043 case 'h':
1044 help();
1045 break;
1046 case 'v':
1047 version();
1048 break;
1049 case 'e':
1050 example();
1051 break;
1052 case 'p':
1053 invoke_cpp = true;
1054 break;
1055 case 'V':
1056 ctx.verbose = true;
1057 break;
1058 case 'P':
1059 cpus_tmp = strtoul(optarg, NULL, 0);
1060 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1061 ctx.cpus = cpus_tmp;
1062 break;
1063 case 'd':
1064 case 'o':
1065 ctx.device = xstrndup(optarg, IFNAMSIZ);
1066 break;
1067 case 'r':
1068 ctx.rand = true;
1069 break;
1070 case 's':
1071 slow = true;
1072 ctx.cpus = 1;
1073 ctx.smoke_test = true;
1074 ctx.rhost = xstrdup(optarg);
1075 break;
1076 case 'R':
1077 ctx.rfraw = true;
1078 break;
1079 case 'J':
1080 ctx.jumbo_support = true;
1081 break;
1082 case 'c':
1083 case 'i':
1084 confname = xstrdup(optarg);
1085 if (!strncmp("-", confname, strlen("-")))
1086 ctx.cpus = 1;
1087 break;
1088 case 'u':
1089 ctx.uid = strtoul(optarg, NULL, 0);
1090 ctx.enforce = true;
1091 break;
1092 case 'g':
1093 ctx.gid = strtoul(optarg, NULL, 0);
1094 ctx.enforce = true;
1095 break;
1096 case 'k':
1097 ctx.kpull = strtoul(optarg, NULL, 0);
1098 break;
1099 case 'E':
1100 seed = strtoul(optarg, NULL, 0);
1101 reseed = false;
1102 break;
1103 case 'n':
1104 ctx.num = strtoul(optarg, NULL, 0);
1105 break;
1106 case 't':
1107 slow = true;
1108 ctx.gap = strtoul(optarg, NULL, 0);
1109 if (ctx.gap > 0)
1110 /* Fall back to single core to not
1111 * mess up correct timing. We are slow
1112 * anyway!
1114 ctx.cpus = 1;
1115 break;
1116 case 'S':
1117 ptr = optarg;
1118 ctx.reserve_size = 0;
1120 for (j = i = strlen(optarg); i > 0; --i) {
1121 if (!isdigit(optarg[j - i]))
1122 break;
1123 ptr++;
1126 if (!strncmp(ptr, "KB", strlen("KB")))
1127 ctx.reserve_size = 1 << 10;
1128 else if (!strncmp(ptr, "MB", strlen("MB")))
1129 ctx.reserve_size = 1 << 20;
1130 else if (!strncmp(ptr, "GB", strlen("GB")))
1131 ctx.reserve_size = 1 << 30;
1132 else
1133 panic("Syntax error in ring size param!\n");
1134 *ptr = 0;
1136 ctx.reserve_size *= strtol(optarg, NULL, 0);
1137 break;
1138 case '?':
1139 switch (optopt) {
1140 case 'd':
1141 case 'c':
1142 case 'n':
1143 case 'S':
1144 case 's':
1145 case 'P':
1146 case 'o':
1147 case 'E':
1148 case 'i':
1149 case 'k':
1150 case 'u':
1151 case 'g':
1152 case 't':
1153 panic("Option -%c requires an argument!\n",
1154 optopt);
1155 default:
1156 if (isprint(optopt))
1157 whine("Unknown option character "
1158 "`0x%X\'!\n", optopt);
1159 die();
1161 default:
1162 break;
1166 if (argc < 5)
1167 help();
1168 if (ctx.device == NULL)
1169 panic("No networking device given!\n");
1170 if (confname == NULL)
1171 panic("No configuration file given!\n");
1172 if (device_mtu(ctx.device) == 0)
1173 panic("This is no networking device!\n");
1174 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1175 panic("Networking device not running!\n");
1177 register_signal(SIGINT, signal_handler);
1178 register_signal(SIGHUP, signal_handler);
1179 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1181 header();
1183 set_system_socket_memory(vals);
1184 xlockme();
1186 if (ctx.rfraw) {
1187 ctx.device_trans = xstrdup(ctx.device);
1188 xfree(ctx.device);
1190 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1191 sleep(0);
1194 irq = device_irq_number(ctx.device);
1195 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1197 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1198 ctx.cpus = 1;
1200 stats = setup_shared_var(ctx.cpus);
1202 for (i = 0; i < ctx.cpus; i++) {
1203 pid_t pid = fork();
1205 switch (pid) {
1206 case 0:
1207 if (reseed)
1208 seed = generate_srand_seed();
1209 srand(seed);
1211 cpu_affinity(i);
1212 main_loop(&ctx, confname, slow, i, invoke_cpp);
1214 goto thread_out;
1215 case -1:
1216 panic("Cannot fork processes!\n");
1220 for (i = 0; i < ctx.cpus; i++) {
1221 int status;
1223 wait(&status);
1224 if (WEXITSTATUS(status) == EXIT_FAILURE)
1225 die();
1228 if (ctx.rfraw)
1229 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1231 reset_system_socket_memory(vals);
1233 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1234 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1235 sched_yield();
1237 tx_packets += stats[i].tx_packets;
1238 tx_bytes += stats[i].tx_bytes;
1241 fflush(stdout);
1242 printf("\n");
1243 printf("\r%12llu packets outgoing\n", tx_packets);
1244 printf("\r%12llu bytes outgoing\n", tx_bytes);
1245 for (i = 0; i < ctx.cpus; i++) {
1246 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1247 stats[i].tv_sec, stats[i].tv_usec, i,
1248 stats[i].tx_packets);
1251 thread_out:
1252 xunlockme();
1253 destroy_shared_var(stats, ctx.cpus);
1255 free(ctx.device);
1256 free(ctx.device_trans);
1257 free(ctx.rhost);
1258 free(confname);
1260 return 0;