trafgen: do not reseed when manually set
[netsniff-ng.git] / src / trafgen.c
blobdbfc1e336d44bc847493eeb100d025ccd2fe9c00
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 " This tool is targeted for network developers! You should\n"
228 " be aware of what you are doing and what these options above\n"
229 " mean! Only use this tool in an isolated LAN that you own!\n\n"
230 "Please report bugs to <bugs@netsniff-ng.org>\n"
231 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
232 "Swiss federal institute of technology (ETH Zurich)\n"
233 "License: GNU GPL version 2.0\n"
234 "This is free software: you are free to change and redistribute it.\n"
235 "There is NO WARRANTY, to the extent permitted by law.\n");
236 die();
239 static void example(void)
241 const char *e =
242 "/* Note: dynamic elements make trafgen slower! */\n\n"
243 "#define ETH_P_IP 0x0800\n\n"
244 "#define SYN (1 << 1)\n"
245 "#define ECN (1 << 6)\n\n"
246 "{\n"
247 " /* MAC Destination */\n"
248 " fill(0xff, 6),\n"
249 " /* MAC Source */\n"
250 " 0x00, 0x02, 0xb3, drnd(3),\n"
251 " /* IPv4 Protocol */\n"
252 " c16(ETH_P_IP),\n"
253 " /* IPv4 Version, IHL, TOS */\n"
254 " 0b01000101, 0,\n"
255 " /* IPv4 Total Len */\n"
256 " c16(59),\n"
257 " /* IPv4 Ident */\n"
258 " drnd(2),\n"
259 " /* IPv4 Flags, Frag Off */\n"
260 " 0b01000000, 0,\n"
261 " /* IPv4 TTL */\n"
262 " 64,\n"
263 " /* Proto TCP */\n"
264 " 0x06,\n"
265 " /* IPv4 Checksum (IP header from, to) */\n"
266 " csumip(14, 33),\n"
267 " /* Source IP */\n"
268 " drnd(4),\n"
269 " /* Dest IP */\n"
270 " drnd(4),\n"
271 " /* TCP Source Port */\n"
272 " drnd(2),\n"
273 " /* TCP Dest Port */\n"
274 " c16(80),\n"
275 " /* TCP Sequence Number */\n"
276 " drnd(4),\n"
277 " /* TCP Ackn. Number */\n"
278 " c32(0),\n"
279 " /* TCP Header length + TCP SYN/ECN Flag */\n"
280 " c16((0x8 << 12) | SYN | ECN)\n"
281 " /* Window Size */\n"
282 " c16(16),\n"
283 " /* TCP Checksum (offset IP, offset TCP) */\n"
284 " csumtcp(14, 34),\n"
285 " /* TCP Options */\n"
286 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
287 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
288 " /* Data blob */\n"
289 " \"gotcha!\",\n"
290 "}";
291 puts(e);
292 die();
295 static void version(void)
297 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
298 puts("http://www.netsniff-ng.org\n\n"
299 "Please report bugs to <bugs@netsniff-ng.org>\n"
300 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
301 "Swiss federal institute of technology (ETH Zurich)\n"
302 "License: GNU GPL version 2.0\n"
303 "This is free software: you are free to change and redistribute it.\n"
304 "There is NO WARRANTY, to the extent permitted by law.\n");
305 die();
308 static void apply_counter(int counter_id)
310 int j, i = counter_id;
311 size_t counter_max = packet_dyn[i].clen;
313 for (j = 0; j < counter_max; ++j) {
314 uint8_t val;
315 struct counter *counter = &packet_dyn[i].cnt[j];
317 val = counter->val - counter->min;
319 switch (counter->type) {
320 case TYPE_INC:
321 val = (val + counter->inc) % (counter->max - counter->min + 1);
322 break;
323 case TYPE_DEC:
324 val = (val - counter->inc) % (counter->min - counter->max + 1);
325 break;
326 default:
327 bug();
330 counter->val = val + counter->min;
331 packets[i].payload[counter->off] = val;
335 static void apply_randomizer(int rand_id)
337 int j, i = rand_id;
338 size_t rand_max = packet_dyn[i].rlen;
340 for (j = 0; j < rand_max; ++j) {
341 uint8_t val = (uint8_t) rand();
342 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
344 packets[i].payload[randomizer->off] = val;
348 /* Taken and modified from tcpdump, Copyright belongs to them! */
350 struct cksum_vec {
351 const u8 *ptr;
352 int len;
355 #define ADDCARRY(x) \
356 do { if ((x) > 65535) \
357 (x) -= 65535; \
358 } while (0)
360 #define REDUCE \
361 do { \
362 l_util.l = sum; \
363 sum = l_util.s[0] + l_util.s[1]; \
364 ADDCARRY(sum); \
365 } while (0)
367 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
369 register const u16 *w;
370 register int sum = 0, mlen = 0;
371 int byte_swapped = 0;
372 union {
373 u8 c[2];
374 u16 s;
375 } s_util;
376 union {
377 u16 s[2];
378 u32 l;
379 } l_util;
381 for (; veclen != 0; vec++, veclen--) {
382 if (vec->len == 0)
383 continue;
385 w = (const u16 *) (void *) vec->ptr;
387 if (mlen == -1) {
388 s_util.c[1] = *(const u8 *) w;
389 sum += s_util.s;
390 w = (const u16 *) (void *) ((const u8 *) w + 1);
391 mlen = vec->len - 1;
392 } else
393 mlen = vec->len;
395 if ((1 & (unsigned long) w) && (mlen > 0)) {
396 REDUCE;
397 sum <<= 8;
398 s_util.c[0] = *(const u8 *) w;
399 w = (const u16 *) (void *) ((const u8 *) w + 1);
400 mlen--;
401 byte_swapped = 1;
404 while ((mlen -= 32) >= 0) {
405 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
406 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
407 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
408 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
409 w += 16;
412 mlen += 32;
414 while ((mlen -= 8) >= 0) {
415 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
416 w += 4;
419 mlen += 8;
421 if (mlen == 0 && byte_swapped == 0)
422 continue;
424 REDUCE;
426 while ((mlen -= 2) >= 0) {
427 sum += *w++;
430 if (byte_swapped) {
431 REDUCE;
432 sum <<= 8;
433 byte_swapped = 0;
435 if (mlen == -1) {
436 s_util.c[1] = *(const u8 *) w;
437 sum += s_util.s;
438 mlen = 0;
439 } else
440 mlen = -1;
441 } else if (mlen == -1)
442 s_util.c[0] = *(const u8 *) w;
445 if (mlen == -1) {
446 s_util.c[1] = 0;
447 sum += s_util.s;
450 REDUCE;
452 return (~sum & 0xffff);
455 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
456 u8 next_proto)
458 struct cksum_vec vec[2];
459 struct pseudo_hdr {
460 u32 src;
461 u32 dst;
462 u8 mbz;
463 u8 proto;
464 u16 len;
465 } ph;
467 memset(&ph, 0, sizeof(ph));
468 ph.len = htons(len);
469 ph.mbz = 0;
470 ph.proto = next_proto;
471 ph.src = ip->ip_src.s_addr;
472 ph.dst = ip->ip_dst.s_addr;
474 vec[0].ptr = (const u8 *) (void *) &ph;
475 vec[0].len = sizeof(ph);
477 vec[1].ptr = data;
478 vec[1].len = len;
480 return __in_cksum(vec, 2);
483 static void apply_csum16(int csum_id)
485 int j, i = csum_id;
486 size_t csum_max = packet_dyn[i].slen;
488 for (j = 0; j < csum_max; ++j) {
489 uint16_t sum = 0;
490 struct csum16 *csum = &packet_dyn[i].csum[j];
492 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
494 switch (csum->which) {
495 case CSUM_IP:
496 if (csum->to >= packets[i].len)
497 csum->to = packets[i].len - 1;
498 sum = calc_csum(packets[i].payload + csum->from,
499 csum->to - csum->from + 1, 0);
500 break;
501 case CSUM_UDP:
502 sum = p4_csum((void *) packets[i].payload + csum->from,
503 packets[i].payload + csum->to,
504 (packets[i].len - csum->to),
505 IPPROTO_UDP);
506 break;
507 case CSUM_TCP:
508 sum = p4_csum((void *) packets[i].payload + csum->from,
509 packets[i].payload + csum->to,
510 (packets[i].len - csum->to),
511 IPPROTO_TCP);
512 break;
515 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
519 static struct cpu_stats *setup_shared_var(unsigned long cpus)
521 int fd;
522 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
523 struct cpu_stats *buff;
525 fmemset(zbuff, 0, sizeof(zbuff));
526 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
528 fd = creat(file, S_IRUSR | S_IWUSR);
529 bug_on(fd < 0);
530 close(fd);
532 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
533 S_IRUSR | S_IWUSR);
534 write_or_die(fd, zbuff, sizeof(zbuff));
536 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
537 MAP_SHARED, fd, 0);
538 if (buff == (void *) -1)
539 panic("Cannot setup shared variable!\n");
541 close(fd);
542 unlink(file);
544 memset(buff, 0, sizeof(zbuff));
546 return buff;
549 static void destroy_shared_var(void *buff, unsigned long cpus)
551 munmap(buff, cpus * sizeof(struct cpu_stats));
554 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
556 int i;
558 printf("{");
559 for (i = 0; i < len; ++i) {
560 if (i % 15 == 0)
561 printf("\n ");
562 printf("0x%02x, ", payload[i]);
564 printf("\n}\n");
565 fflush(stdout);
568 static inline unsigned short csum(unsigned short *buf, int nwords)
570 unsigned long sum;
572 for (sum = 0; nwords > 0; nwords--)
573 sum += *buf++;
574 sum = (sum >> 16) + (sum & 0xffff);
575 sum += (sum >> 16);
577 return ~sum;
580 static int xmit_smoke_setup(struct ctx *ctx)
582 int icmp_sock, ret, ttl = 64;
583 struct icmp_filter filter;
585 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
586 if (icmp_sock < 0)
587 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
589 filter.data = ~(1 << ICMP_ECHOREPLY);
591 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
592 if (ret < 0)
593 panic("Cannot install filter!\n");
595 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
596 if (ret < 0)
597 panic("Cannot set TTL!\n");
599 memset(&ctx->dest, 0, sizeof(ctx->dest));
600 ctx->dest.sin_family = AF_INET;
601 ctx->dest.sin_port = 0;
603 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
604 if (ret < 0)
605 panic("Cannot resolv address!\n");
607 return icmp_sock;
610 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
612 int ret, i, probes = 5;
613 short ident, cnt = 1;
614 uint8_t outpack[512], *data;
615 struct icmphdr *icmp;
616 struct iphdr *ip;
617 size_t len = sizeof(*icmp) + 56;
618 struct sockaddr_in from;
619 socklen_t from_len;
620 struct pollfd fds = {
621 .fd = icmp_sock,
622 .events = POLLIN,
625 while (probes-- > 0) {
626 ident = htons((short) rand());
628 memset(outpack, 0, sizeof(outpack));
629 icmp = (void *) outpack;
630 icmp->type = ICMP_ECHO;
631 icmp->code = 0;
632 icmp->checksum = 0;
633 icmp->un.echo.id = ident;
634 icmp->un.echo.sequence = htons(cnt++);
636 data = ((uint8_t *) outpack + sizeof(*icmp));
637 for (i = 0; i < 56; ++i)
638 data[i] = (uint8_t) rand();
640 icmp->checksum = csum((unsigned short *) outpack,
641 len / sizeof(unsigned short));
643 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
644 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
645 if (unlikely(ret != len))
646 panic("Cannot send out probe: %s!\n", strerror(errno));
648 ret = poll(&fds, 1, 500);
649 if (ret < 0)
650 panic("Poll failed!\n");
652 if (fds.revents & POLLIN) {
653 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
654 (struct sockaddr *) &from, &from_len);
655 if (unlikely(ret <= 0))
656 panic("Probe receive failed!\n");
657 if (unlikely(from_len != sizeof(ctx->dest)))
658 continue;
659 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
660 continue;
661 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
662 continue;
663 ip = (void *) outpack;
664 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
665 continue;
666 icmp = (void *) outpack + ip->ihl * 4;
667 if (unlikely(icmp->un.echo.id != ident))
668 continue;
670 return 0;
674 return -1;
677 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
679 int ret, icmp_sock = -1;
680 unsigned long num = 1, i = 0;
681 struct timeval start, end, diff;
682 unsigned long long tx_bytes = 0, tx_packets = 0;
683 struct packet_dyn *pktd;
684 struct sockaddr_ll saddr = {
685 .sll_family = PF_PACKET,
686 .sll_halen = ETH_ALEN,
687 .sll_ifindex = device_ifindex(ctx->device),
690 if (ctx->num > 0)
691 num = ctx->num;
693 if (ctx->smoke_test)
694 icmp_sock = xmit_smoke_setup(ctx);
696 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
698 bug_on(gettimeofday(&start, NULL));
700 while (likely(sigint == 0) && likely(num > 0)) {
701 pktd = &packet_dyn[i];
702 if (pktd->clen + pktd->rlen + pktd->slen) {
703 apply_counter(i);
704 apply_randomizer(i);
705 apply_csum16(i);
707 retry:
708 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
709 (struct sockaddr *) &saddr, sizeof(saddr));
710 if (unlikely(ret < 0)) {
711 if (errno == ENOBUFS) {
712 sched_yield();
713 goto retry;
716 panic("Sendto error: %s!\n", strerror(errno));
719 tx_bytes += packets[i].len;
720 tx_packets++;
722 if (ctx->smoke_test) {
723 ret = xmit_smoke_probe(icmp_sock, ctx);
724 if (unlikely(ret < 0)) {
725 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
726 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
727 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
728 i, seed);
730 dump_trafgen_snippet(packets[i].payload, packets[i].len);
731 break;
735 if (!ctx->rand) {
736 i++;
737 if (i >= plen)
738 i = 0;
739 } else
740 i = rand() % plen;
742 if (ctx->num > 0)
743 num--;
745 if (ctx->gap > 0)
746 usleep(ctx->gap);
749 bug_on(gettimeofday(&end, NULL));
750 diff = tv_subtract(end, start);
752 if (ctx->smoke_test)
753 close(icmp_sock);
755 stats[cpu].tx_packets = tx_packets;
756 stats[cpu].tx_bytes = tx_bytes;
757 stats[cpu].tv_sec = diff.tv_sec;
758 stats[cpu].tv_usec = diff.tv_usec;
760 stats[cpu].state |= CPU_STATS_STATE_RES;
763 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
765 int ifindex = device_ifindex(ctx->device);
766 uint8_t *out = NULL;
767 unsigned int it = 0;
768 unsigned long num = 1, i = 0, size;
769 struct ring tx_ring;
770 struct frame_map *hdr;
771 struct timeval start, end, diff;
772 struct packet_dyn *pktd;
773 unsigned long long tx_bytes = 0, tx_packets = 0;
775 fmemset(&tx_ring, 0, sizeof(tx_ring));
777 size = ring_size(ctx->device, ctx->reserve_size);
779 set_sock_prio(sock, 512);
780 set_packet_loss_discard(sock);
782 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
783 create_tx_ring(sock, &tx_ring, ctx->verbose);
784 mmap_tx_ring(sock, &tx_ring);
785 alloc_tx_ring_frames(&tx_ring);
786 bind_tx_ring(sock, &tx_ring, ifindex);
788 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
790 if (ctx->kpull)
791 interval = ctx->kpull;
792 if (ctx->num > 0)
793 num = ctx->num;
795 itimer.it_interval.tv_sec = 0;
796 itimer.it_interval.tv_usec = interval;
798 itimer.it_value.tv_sec = 0;
799 itimer.it_value.tv_usec = interval;
801 setitimer(ITIMER_REAL, &itimer, NULL);
803 bug_on(gettimeofday(&start, NULL));
805 while (likely(sigint == 0) && likely(num > 0)) {
806 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
807 hdr = tx_ring.frames[it].iov_base;
809 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
810 * sizeof(struct sockaddr_ll); */
811 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
813 hdr->tp_h.tp_snaplen = packets[i].len;
814 hdr->tp_h.tp_len = packets[i].len;
816 pktd = &packet_dyn[i];
817 if (pktd->clen + pktd->rlen + pktd->slen) {
818 apply_counter(i);
819 apply_randomizer(i);
820 apply_csum16(i);
823 fmemcpy(out, packets[i].payload, packets[i].len);
825 tx_bytes += packets[i].len;
826 tx_packets++;
828 if (!ctx->rand) {
829 i++;
830 if (i >= plen)
831 i = 0;
832 } else
833 i = rand() % plen;
835 kernel_may_pull_from_tx(&hdr->tp_h);
837 it++;
838 if (it >= tx_ring.layout.tp_frame_nr)
839 it = 0;
841 if (ctx->num > 0)
842 num--;
844 if (unlikely(sigint == 1))
845 break;
849 bug_on(gettimeofday(&end, NULL));
850 diff = tv_subtract(end, start);
852 destroy_tx_ring(sock, &tx_ring);
854 stats[cpu].tx_packets = tx_packets;
855 stats[cpu].tx_bytes = tx_bytes;
856 stats[cpu].tv_sec = diff.tv_sec;
857 stats[cpu].tv_usec = diff.tv_usec;
859 stats[cpu].state |= CPU_STATS_STATE_RES;
862 static inline void __set_state(int cpu, sig_atomic_t s)
864 stats[cpu].state = s;
867 static inline sig_atomic_t __get_state(int cpu)
869 return stats[cpu].state;
872 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
874 int i;
875 unsigned long total;
877 for (i = 0, total = plen; i < ctx->cpus; i++) {
878 if (i == cpu)
879 continue;
881 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
882 sigint == 0)
883 sched_yield();
885 total += stats[i].cf_packets;
888 return total;
891 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
893 int i, cpu_sel;
894 unsigned long total;
895 long long delta_correction = 0;
897 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
898 if (i == cpu)
899 continue;
901 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
902 sigint == 0)
903 sched_yield();
905 total += stats[i].cd_packets;
908 if (total > orig)
909 delta_correction = -1 * ((long long) total - orig);
910 if (total < orig)
911 delta_correction = +1 * ((long long) orig - total);
913 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
914 if (stats[i].cd_packets > 0) {
915 if ((long long) stats[i].cd_packets +
916 delta_correction > 0) {
917 cpu_sel = i;
918 break;
923 if (cpu == cpu_sel)
924 ctx->num += delta_correction;
927 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
928 sig_atomic_t s)
930 stats[cpu].cf_packets = p;
931 stats[cpu].cf_bytes = b;
932 stats[cpu].state = s;
935 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
937 stats[cpu].cd_packets = p;
938 stats[cpu].state = s;
941 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
943 int i;
944 unsigned long plen_total, orig = ctx->num;
945 size_t mtu, total_len = 0;
947 bug_on(plen != dlen);
949 for (i = 0; i < plen; ++i)
950 total_len += packets[i].len;
952 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
953 plen_total = __wait_and_sum_others(ctx, cpu);
955 if (orig > 0) {
956 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
958 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
959 CPU_STATS_STATE_CFG);
960 __correct_global_delta(ctx, cpu, orig);
963 if (plen == 0) {
964 __set_state(cpu, CPU_STATS_STATE_RES);
965 return -1;
968 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
969 if (packets[i].len > mtu + 14)
970 panic("Device MTU < than packet%d's size!\n", i);
971 if (packets[i].len <= 14)
972 panic("Packet%d's size too short!\n", i);
975 return 0;
978 static void main_loop(struct ctx *ctx, char *confname, bool slow,
979 int cpu, bool invoke_cpp)
981 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
982 if (xmit_packet_precheck(ctx, cpu) < 0)
983 return;
985 if (cpu == 0) {
986 int i;
987 size_t total_len = 0, total_pkts = 0;
989 for (i = 0; i < ctx->cpus; ++i) {
990 total_len += stats[i].cf_bytes;
991 total_pkts += stats[i].cf_packets;
994 printf("%6zu packets to schedule\n", total_pkts);
995 printf("%6zu bytes in total\n", total_len);
996 printf("Running! Hang up with ^C!\n\n");
997 fflush(stdout);
1000 sock = pf_socket();
1002 if (slow)
1003 xmit_slowpath_or_die(ctx, cpu);
1004 else
1005 xmit_fastpath_or_die(ctx, cpu);
1007 close(sock);
1009 cleanup_packets();
1012 static unsigned int generate_srand_seed(void)
1014 int fd;
1015 unsigned int seed;
1017 fd = open("/dev/random", O_RDONLY);
1018 if (fd < 0)
1019 return time(0);
1021 read_or_die(fd, &seed, sizeof(seed));
1023 close(fd);
1024 return seed;
1027 int main(int argc, char **argv)
1029 bool slow = false, invoke_cpp = false, reseed = true;
1030 int c, opt_index, i, j, vals[4] = {0}, irq;
1031 char *confname = NULL, *ptr;
1032 unsigned long cpus_tmp;
1033 unsigned long long tx_packets, tx_bytes;
1034 struct ctx ctx;
1036 fmemset(&ctx, 0, sizeof(ctx));
1037 ctx.cpus = get_number_cpus_online();
1038 ctx.uid = getuid();
1039 ctx.gid = getgid();
1041 while ((c = getopt_long(argc, argv, short_options, long_options,
1042 &opt_index)) != EOF) {
1043 switch (c) {
1044 case 'h':
1045 help();
1046 break;
1047 case 'v':
1048 version();
1049 break;
1050 case 'e':
1051 example();
1052 break;
1053 case 'p':
1054 invoke_cpp = true;
1055 break;
1056 case 'V':
1057 ctx.verbose = true;
1058 break;
1059 case 'P':
1060 cpus_tmp = strtoul(optarg, NULL, 0);
1061 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1062 ctx.cpus = cpus_tmp;
1063 break;
1064 case 'd':
1065 case 'o':
1066 ctx.device = xstrndup(optarg, IFNAMSIZ);
1067 break;
1068 case 'r':
1069 ctx.rand = true;
1070 break;
1071 case 's':
1072 slow = true;
1073 ctx.cpus = 1;
1074 ctx.smoke_test = true;
1075 ctx.rhost = xstrdup(optarg);
1076 break;
1077 case 'R':
1078 ctx.rfraw = true;
1079 break;
1080 case 'J':
1081 ctx.jumbo_support = true;
1082 break;
1083 case 'c':
1084 case 'i':
1085 confname = xstrdup(optarg);
1086 break;
1087 case 'u':
1088 ctx.uid = strtoul(optarg, NULL, 0);
1089 ctx.enforce = true;
1090 break;
1091 case 'g':
1092 ctx.gid = strtoul(optarg, NULL, 0);
1093 ctx.enforce = true;
1094 break;
1095 case 'k':
1096 ctx.kpull = strtoul(optarg, NULL, 0);
1097 break;
1098 case 'E':
1099 seed = strtoul(optarg, NULL, 0);
1100 reseed = false;
1101 break;
1102 case 'n':
1103 ctx.num = strtoul(optarg, NULL, 0);
1104 break;
1105 case 't':
1106 slow = true;
1107 ctx.gap = strtoul(optarg, NULL, 0);
1108 if (ctx.gap > 0)
1109 /* Fall back to single core to not
1110 * mess up correct timing. We are slow
1111 * anyway!
1113 ctx.cpus = 1;
1114 break;
1115 case 'S':
1116 ptr = optarg;
1117 ctx.reserve_size = 0;
1119 for (j = i = strlen(optarg); i > 0; --i) {
1120 if (!isdigit(optarg[j - i]))
1121 break;
1122 ptr++;
1125 if (!strncmp(ptr, "KB", strlen("KB")))
1126 ctx.reserve_size = 1 << 10;
1127 else if (!strncmp(ptr, "MB", strlen("MB")))
1128 ctx.reserve_size = 1 << 20;
1129 else if (!strncmp(ptr, "GB", strlen("GB")))
1130 ctx.reserve_size = 1 << 30;
1131 else
1132 panic("Syntax error in ring size param!\n");
1133 *ptr = 0;
1135 ctx.reserve_size *= strtol(optarg, NULL, 0);
1136 break;
1137 case '?':
1138 switch (optopt) {
1139 case 'd':
1140 case 'c':
1141 case 'n':
1142 case 'S':
1143 case 's':
1144 case 'P':
1145 case 'o':
1146 case 'E':
1147 case 'i':
1148 case 'k':
1149 case 'u':
1150 case 'g':
1151 case 't':
1152 panic("Option -%c requires an argument!\n",
1153 optopt);
1154 default:
1155 if (isprint(optopt))
1156 whine("Unknown option character "
1157 "`0x%X\'!\n", optopt);
1158 die();
1160 default:
1161 break;
1165 if (argc < 5)
1166 help();
1167 if (ctx.device == NULL)
1168 panic("No networking device given!\n");
1169 if (confname == NULL)
1170 panic("No configuration file given!\n");
1171 if (device_mtu(ctx.device) == 0)
1172 panic("This is no networking device!\n");
1173 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1174 panic("Networking device not running!\n");
1176 register_signal(SIGINT, signal_handler);
1177 register_signal(SIGHUP, signal_handler);
1178 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1180 header();
1182 set_system_socket_memory(vals);
1184 if (ctx.rfraw) {
1185 ctx.device_trans = xstrdup(ctx.device);
1186 xfree(ctx.device);
1188 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1189 sleep(0);
1192 irq = device_irq_number(ctx.device);
1193 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1195 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1196 ctx.cpus = 1;
1198 stats = setup_shared_var(ctx.cpus);
1200 for (i = 0; i < ctx.cpus; i++) {
1201 pid_t pid = fork();
1203 switch (pid) {
1204 case 0:
1205 if (reseed)
1206 seed = generate_srand_seed();
1207 srand(seed);
1209 cpu_affinity(i);
1210 main_loop(&ctx, confname, slow, i, invoke_cpp);
1212 goto thread_out;
1213 case -1:
1214 panic("Cannot fork processes!\n");
1218 for (i = 0; i < ctx.cpus; i++) {
1219 int status;
1221 wait(&status);
1222 if (WEXITSTATUS(status) == EXIT_FAILURE)
1223 die();
1226 if (ctx.rfraw)
1227 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1229 reset_system_socket_memory(vals);
1231 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1232 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1233 sched_yield();
1235 tx_packets += stats[i].tx_packets;
1236 tx_bytes += stats[i].tx_bytes;
1239 fflush(stdout);
1240 printf("\n");
1241 printf("\r%12llu packets outgoing\n", tx_packets);
1242 printf("\r%12llu bytes outgoing\n", tx_bytes);
1243 for (i = 0; i < ctx.cpus; i++) {
1244 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1245 stats[i].tv_sec, stats[i].tv_usec, i,
1246 stats[i].tx_packets);
1249 thread_out:
1250 destroy_shared_var(stats, ctx.cpus);
1252 free(ctx.device);
1253 free(ctx.device_trans);
1254 free(ctx.rhost);
1255 free(confname);
1257 return 0;