trafgen: Move common duplicate calls from xmit_*_or_die to main_loop
[netsniff-ng.git] / src / trafgen.c
blob9d1252d29b04df2ab9311c4c2ccead42b5186cd9
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/stat.h>
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <stdint.h>
35 #include <stdlib.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <net/ethernet.h>
40 #include "xmalloc.h"
41 #include "die.h"
42 #include "mac80211.h"
43 #include "xutils.h"
44 #include "xio.h"
45 #include "built_in.h"
46 #include "trafgen_conf.h"
47 #include "tprintf.h"
48 #include "ring_tx.h"
50 struct ctx {
51 char *device, *device_trans;
52 int cpu, rand, rfraw, jumbo_support, verbose;
53 unsigned long kpull, num, gap, reserve_size;
54 unsigned long tx_bytes, tx_packets;
57 sig_atomic_t sigint = 0;
59 struct packet *packets = NULL;
60 size_t plen = 0;
62 struct packet_dyn *packet_dyn = NULL;
63 size_t dlen = 0;
65 static const char *short_options = "d:c:n:t:vJhS:HQb:B:rk:i:o:VRA";
66 static const struct option long_options[] = {
67 {"dev", required_argument, NULL, 'd'},
68 {"out", required_argument, NULL, 'o'},
69 {"in", required_argument, NULL, 'i'},
70 {"conf", required_argument, NULL, 'c'},
71 {"num", required_argument, NULL, 'n'},
72 {"gap", required_argument, NULL, 't'},
73 {"ring-size", required_argument, NULL, 'S'},
74 {"bind-cpu", required_argument, NULL, 'b'},
75 {"unbind-cpu", required_argument, NULL, 'B'},
76 {"kernel-pull", required_argument, NULL, 'k'},
77 {"jumbo-support", no_argument, NULL, 'J'},
78 {"rfraw", no_argument, NULL, 'R'},
79 {"rand", no_argument, NULL, 'r'},
80 {"prio-high", no_argument, NULL, 'H'},
81 {"notouch-irq", no_argument, NULL, 'Q'},
82 {"verbose", no_argument, NULL, 'V'},
83 {"no-sock-mem", no_argument, NULL, 'A'},
84 {"version", no_argument, NULL, 'v'},
85 {"help", no_argument, NULL, 'h'},
86 {NULL, 0, NULL, 0}
89 static int sock;
91 static struct itimerval itimer;
93 static unsigned long interval = TX_KERNEL_PULL_INT;
95 #define set_system_socket_memory(vals) \
96 do { \
97 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX) \
98 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX); \
99 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF) \
100 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF); \
101 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX) \
102 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX); \
103 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF) \
104 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF); \
105 } while (0)
107 #define reset_system_socket_memory(vals) \
108 do { \
109 set_system_socket_mem(sock_rmem_max, vals[0]); \
110 set_system_socket_mem(sock_rmem_def, vals[1]); \
111 set_system_socket_mem(sock_wmem_max, vals[2]); \
112 set_system_socket_mem(sock_wmem_def, vals[3]); \
113 } while (0)
115 static void signal_handler(int number)
117 switch (number) {
118 case SIGINT:
119 sigint = 1;
120 case SIGHUP:
121 default:
122 break;
126 static void timer_elapsed(int number)
128 itimer.it_interval.tv_sec = 0;
129 itimer.it_interval.tv_usec = interval;
131 itimer.it_value.tv_sec = 0;
132 itimer.it_value.tv_usec = interval;
134 pull_and_flush_tx_ring(sock);
135 setitimer(ITIMER_REAL, &itimer, NULL);
138 static void header(void)
140 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
143 static void help(void)
145 printf("\ntrafgen %s, zero-copy network packet generator\n", VERSION_STRING);
146 puts("http://www.netsniff-ng.org\n\n"
147 "Usage: trafgen [options]\n"
148 "Options:\n"
149 /* " -o|-d|--out|--dev <netdev|pcap> Networking Device i.e., eth0 or pcap\n" */
150 " -o|-d|--out|--dev <netdev> Networking Device i.e., eth0\n"
151 " -i|-c|--in|--conf <cfg-file> Packet configuration file\n"
152 " -J|--jumbo-support Support for 64KB Super Jumbo Frames\n"
153 " Default TX slot: 2048Byte\n"
154 " -R|--rfraw Inject raw 802.11 frames\n"
155 " -n|--num <uint> Number of packets until exit\n"
156 " `-- 0 Loop until interrupt (default)\n"
157 " `- n Send n packets and done\n"
158 " -r|--rand Randomize packet selection process\n"
159 " Instead of a round robin selection\n"
160 " -t|--gap <uint> Interpacket gap in us (approx)\n"
161 " -A|--no-sock-mem Don't tune core socket memory\n"
162 " -S|--ring-size <size> Manually set ring size to <size>:\n"
163 " mmap space in KB/MB/GB, e.g. \'10MB\'\n"
164 " -k|--kernel-pull <uint> Kernel pull from user interval in us\n"
165 " Default is 10us where the TX_RING\n"
166 " is populated with payload from uspace\n"
167 " -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n"
168 " -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n"
169 " -H|--prio-high Make this high priority process\n"
170 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
171 " -V|--verbose Be more verbose\n"
172 " -v|--version Show version\n"
173 " -h|--help Guess what?!\n\n"
174 "Examples:\n"
175 " See trafgen.txf for configuration file examples.\n"
176 " trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0\n"
177 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf --bind-cpu 0 -A -V\n"
178 " trafgen --out eth0 --in trafgen.txf --bind-cpu 0\n"
179 /* " trafgen --out test.pcap --in trafgen.txf --bind-cpu 0\n" */
180 " trafgen --dev eth0 --conf trafgen.txf --rand --gap 1000\n"
181 " trafgen --dev eth0 --conf trafgen.txf --rand --num 1400000 -k1000\n"
182 " trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 10 --rand\n\n"
183 "Note:\n"
184 " This tool is targeted for network developers! You should\n"
185 " be aware of what you are doing and what these options above\n"
186 " mean! Only use this tool in an isolated LAN that you own!\n\n"
187 "Please report bugs to <bugs@netsniff-ng.org>\n"
188 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
189 "Swiss federal institute of technology (ETH Zurich)\n"
190 "License: GNU GPL version 2.0\n"
191 "This is free software: you are free to change and redistribute it.\n"
192 "There is NO WARRANTY, to the extent permitted by law.\n");
193 die();
196 static void version(void)
198 printf("\ntrafgen %s, zero-copy network packet generator\n", VERSION_STRING);
199 puts("http://www.netsniff-ng.org\n\n"
200 "Please report bugs to <bugs@netsniff-ng.org>\n"
201 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
202 "Swiss federal institute of technology (ETH Zurich)\n"
203 "License: GNU GPL version 2.0\n"
204 "This is free software: you are free to change and redistribute it.\n"
205 "There is NO WARRANTY, to the extent permitted by law.\n");
206 die();
209 static inline void apply_counter(int counter_id)
211 int j;
212 size_t counter_max = packet_dyn[counter_id].clen;
214 for (j = 0; j < counter_max; ++j) {
215 uint8_t val;
216 struct counter *counter;
218 counter = &packet_dyn[counter_id].cnt[j];
219 val = counter->val - counter->min;
221 switch (counter->type) {
222 case TYPE_INC:
223 val = (val + counter->inc) % (counter->max - counter->min + 1);
224 break;
225 case TYPE_DEC:
226 val = (val - counter->inc) % (counter->min - counter->max + 1);
227 break;
228 default:
229 bug();
232 counter->val = val + counter->min;
233 packets[counter_id].payload[counter->off] = val;
237 static inline void apply_randomizer(int rand_id)
239 int j;
240 size_t rand_max = packet_dyn[rand_id].rlen;
242 for (j = 0; j < rand_max; ++j) {
243 uint8_t val;
244 struct randomizer *randomizer;
246 val = (uint8_t) rand();
248 randomizer = &packet_dyn[rand_id].rnd[j];
249 randomizer->val = val;
251 packets[rand_id].payload[randomizer->off] = val;
255 static void xmit_precheck(const struct ctx *ctx)
257 int i;
258 size_t mtu;
260 if (!ctx)
261 panic("Panic, invalid args for TX trigger!\n");
262 if (plen == 0 || plen != dlen)
263 panic("Panic, invalid args for TX trigger!\n");
264 if (!ctx->rfraw && !device_up_and_running(ctx->device))
265 panic("Device not up and running!\n");
266 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
267 if (packets[i].len > mtu + 14)
268 panic("Device MTU < than your packet size!\n");
269 if (packets[i].len <= 14)
270 panic("Device packet size too short!\n");
274 static void xmit_slowpath_or_die(struct ctx *ctx)
276 int ret;
277 unsigned long num = 1, i = 0;
278 struct timeval start, end, diff;
279 struct sockaddr_ll saddr = {
280 .sll_family = PF_PACKET,
281 .sll_halen = ETH_ALEN,
284 if (ctx->rfraw) {
285 ctx->device_trans = xstrdup(ctx->device);
286 xfree(ctx->device);
288 enter_rfmon_mac80211(ctx->device_trans, &ctx->device);
291 if (ctx->num > 0)
292 num = ctx->num;
294 if (ctx->verbose) {
295 if (ctx->rand)
296 printf("Note: randomized output makes trafgen slower!\n");
297 printf("MD: TX sendto %s %luus", ctx->rand ? "RND" : "RR", ctx->gap);
298 if (ctx->rfraw)
299 printf(" 802.11 raw via %s", ctx->device);
300 printf("\n\n");
302 printf("Running! Hang up with ^C!\n\n");
303 fflush(stdout);
305 saddr.sll_ifindex = device_ifindex(ctx->device);
307 bug_on(gettimeofday(&start, NULL));
309 while (likely(sigint == 0) && likely(num > 0)) {
310 apply_counter(i);
311 apply_randomizer(i);
313 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
314 (struct sockaddr *) &saddr, sizeof(saddr));
315 if (ret < 0)
316 whine("sendto error!\n");
318 ctx->tx_bytes += packets[i].len;
319 ctx->tx_packets++;
321 if (!ctx->rand) {
322 i++;
323 atomic_cmp_swp(&i, plen, 0);
324 } else {
325 i = rand() % plen;
328 if (ctx->num > 0)
329 num--;
331 if (ctx->gap > 0)
332 usleep(ctx->gap);
335 bug_on(gettimeofday(&end, NULL));
336 diff = tv_subtract(end, start);
338 if (ctx->rfraw)
339 leave_rfmon_mac80211(ctx->device_trans, ctx->device);
341 fflush(stdout);
342 printf("\n");
343 printf("\r%12lu frames outgoing\n", ctx->tx_packets);
344 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
345 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
349 static void xmit_fastpath_or_die(struct ctx *ctx)
351 int irq, ifindex;
352 uint8_t *out = NULL;
353 unsigned int it = 0;
354 unsigned long num = 1, i = 0, size;
355 struct ring tx_ring;
356 struct frame_map *hdr;
357 struct timeval start, end, diff;
359 if (ctx->rfraw) {
360 ctx->device_trans = xstrdup(ctx->device);
361 xfree(ctx->device);
363 enter_rfmon_mac80211(ctx->device_trans, &ctx->device);
366 fmemset(&tx_ring, 0, sizeof(tx_ring));
368 ifindex = device_ifindex(ctx->device);
369 size = ring_size(ctx->device, ctx->reserve_size);
371 set_sock_prio(sock, 512);
372 set_packet_loss_discard(sock);
374 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
375 create_tx_ring(sock, &tx_ring, ctx->verbose);
376 mmap_tx_ring(sock, &tx_ring);
377 alloc_tx_ring_frames(&tx_ring);
378 bind_tx_ring(sock, &tx_ring, ifindex);
380 if (ctx->cpu >= 0 && ifindex > 0) {
381 irq = device_irq_number(ctx->device);
382 device_bind_irq_to_cpu(irq, ctx->cpu);
384 if (ctx->verbose)
385 printf("IRQ: %s:%d > CPU%d\n",
386 ctx->device, irq, ctx->cpu);
389 if (ctx->kpull)
390 interval = ctx->kpull;
391 if (ctx->num > 0)
392 num = ctx->num;
394 if (ctx->verbose) {
395 if (ctx->rand)
396 printf("Note: randomized output makes trafgen slower!\n");
397 printf("MD: TX fastpath %s %luus", ctx->rand ? "RND" : "RR", interval);
398 if (ctx->rfraw)
399 printf(" 802.11 raw via %s", ctx->device);
400 printf("\n\n");
402 printf("Running! Hang up with ^C!\n\n");
403 fflush(stdout);
405 itimer.it_interval.tv_sec = 0;
406 itimer.it_interval.tv_usec = interval;
408 itimer.it_value.tv_sec = 0;
409 itimer.it_value.tv_usec = interval;
411 setitimer(ITIMER_REAL, &itimer, NULL);
413 bug_on(gettimeofday(&start, NULL));
415 while (likely(sigint == 0) && likely(num > 0)) {
416 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) &&
417 likely(num > 0)) {
418 hdr = tx_ring.frames[it].iov_base;
420 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
421 * sizeof(struct sockaddr_ll); */
422 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
424 hdr->tp_h.tp_snaplen = packets[i].len;
425 hdr->tp_h.tp_len = packets[i].len;
427 apply_counter(i);
428 apply_randomizer(i);
430 fmemcpy(out, packets[i].payload, packets[i].len);
432 ctx->tx_bytes += packets[i].len;
433 ctx->tx_packets++;
435 if (!ctx->rand) {
436 i++;
437 atomic_cmp_swp(&i, plen, 0);
438 } else {
439 i = rand() % plen;
442 kernel_may_pull_from_tx(&hdr->tp_h);
443 next_slot(&it, &tx_ring);
445 if (ctx->num > 0)
446 num--;
448 if (unlikely(sigint == 1))
449 break;
453 bug_on(gettimeofday(&end, NULL));
454 diff = tv_subtract(end, start);
456 destroy_tx_ring(sock, &tx_ring);
458 if (ctx->rfraw)
459 leave_rfmon_mac80211(ctx->device_trans, ctx->device);
461 fflush(stdout);
462 printf("\n");
463 printf("\r%12lu frames outgoing\n", ctx->tx_packets);
464 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
465 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
468 static void main_loop(struct ctx *ctx, char *confname, bool slow)
470 xmit_precheck(ctx);
471 compile_packets(confname, ctx->verbose);
473 sock = pf_socket();
475 if (slow)
476 xmit_slowpath_or_die(ctx);
477 else
478 xmit_fastpath_or_die(ctx);
480 close(sock);
482 cleanup_packets();
485 int main(int argc, char **argv)
487 int c, opt_index, i, j, vals[4] = {0};
488 char *confname = NULL, *ptr;
489 bool prio_high = false, setsockmem = true, slow = false;
490 struct ctx ctx;
492 srand(time(NULL));
494 fmemset(&ctx, 0, sizeof(ctx));
495 ctx.cpu = -1;
497 while ((c = getopt_long(argc, argv, short_options, long_options,
498 &opt_index)) != EOF) {
499 switch (c) {
500 case 'h':
501 help();
502 break;
503 case 'v':
504 version();
505 break;
506 case 'V':
507 ctx.verbose = 1;
508 break;
509 case 'd':
510 case 'o':
511 ctx.device = xstrndup(optarg, IFNAMSIZ);
512 break;
513 case 'r':
514 ctx.rand = 1;
515 break;
516 case 'R':
517 ctx.rfraw = 1;
518 break;
519 case 'J':
520 ctx.jumbo_support = 1;
521 break;
522 case 'c':
523 case 'i':
524 confname = xstrdup(optarg);
525 break;
526 case 'k':
527 ctx.kpull = atol(optarg);
528 break;
529 case 'n':
530 ctx.num = atol(optarg);
531 break;
532 case 't':
533 slow = true;
534 ctx.gap = atol(optarg);
535 break;
536 case 'A':
537 setsockmem = false;
538 break;
539 case 'S':
540 ptr = optarg;
541 ctx.reserve_size = 0;
543 for (j = i = strlen(optarg); i > 0; --i) {
544 if (!isdigit(optarg[j - i]))
545 break;
546 ptr++;
549 if (!strncmp(ptr, "KB", strlen("KB")))
550 ctx.reserve_size = 1 << 10;
551 else if (!strncmp(ptr, "MB", strlen("MB")))
552 ctx.reserve_size = 1 << 20;
553 else if (!strncmp(ptr, "GB", strlen("GB")))
554 ctx.reserve_size = 1 << 30;
555 else
556 panic("Syntax error in ring size param!\n");
557 *ptr = 0;
559 ctx.reserve_size *= strtol(optarg, NULL, 0);
560 break;
561 case 'b':
562 set_cpu_affinity(optarg, 0);
563 /* Take the first CPU for rebinding the IRQ */
564 if (ctx.cpu != -2)
565 ctx.cpu = strtol(optarg, NULL, 0);
566 break;
567 case 'B':
568 set_cpu_affinity(optarg, 1);
569 break;
570 case 'H':
571 prio_high = true;
572 break;
573 case 'Q':
574 ctx.cpu = -2;
575 break;
576 case '?':
577 switch (optopt) {
578 case 'd':
579 case 'c':
580 case 'n':
581 case 'S':
582 case 'b':
583 case 'o':
584 case 'i':
585 case 'k':
586 case 'B':
587 case 't':
588 panic("Option -%c requires an argument!\n",
589 optopt);
590 default:
591 if (isprint(optopt))
592 whine("Unknown option character "
593 "`0x%X\'!\n", optopt);
594 die();
596 default:
597 break;
601 if (argc < 5)
602 help();
603 if (ctx.device == NULL)
604 panic("No networking device given!\n");
605 if (confname == NULL)
606 panic("No configuration file given!\n");
607 if (device_mtu(ctx.device) == 0)
608 panic("This is no networking device!\n");
609 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
610 panic("Networking device not running!\n");
612 register_signal(SIGINT, signal_handler);
613 register_signal(SIGHUP, signal_handler);
614 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
616 header();
618 if (prio_high) {
619 set_proc_prio(get_default_proc_prio());
620 set_sched_status(get_default_sched_policy(), get_default_sched_prio());
623 if (setsockmem)
624 set_system_socket_memory(vals);
626 main_loop(&ctx, confname, slow);
628 if (setsockmem)
629 reset_system_socket_memory(vals);
631 free(ctx.device);
632 free(ctx.device_trans);
633 free(confname);
635 return 0;