trafgen: moved cleanup into parser
[netsniff-ng-old.git] / src / trafgen.c
blobad66999120951c9755f49d903a57b27bdc8a56f5
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 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'.
26 =head1 NAME
28 trafgen - a high-performance zero-copy network packet generator
30 =head1 SYNOPSIS
32 trafgen [-d|--dev <netdev>][-c|--conf <file>][-J|--jumbo-support]
33 [-x|--interactive][-n|--num <uint>][-r|--rand][-t|--gap <usec>]
34 [-S|--ring-size <size>][-k|--kernel-pull <usec>][-b|--bind-cpu <cpu>]
35 [-B|--unbind-cpu <cpu>][-H|--prio-high][-Q|--notouch-irq][-v|--version]
36 [-h|--help]
38 =head1 DESCRIPTION
40 A high-performance network traffic generator that uses the zero-copy TX_RING
41 for network I/O. For instance, on comodity Gigabit hardware up to 1,488,095 pps
42 64 Byte pps have been achieved with trafgen.
44 =head1 OPTIONS
46 =over
48 =item trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0
50 Use packet configuration trafgen.txf, eth0 as transmission device and CPU0
51 for binding the process.
53 =back
55 =head1 OPTIONS
57 =over
59 =item -h|--help
61 Print help text and lists all options.
63 =item -v|--version
65 Print version.
67 =item -d|--dev <netdev>
69 Device for transmission i.e., eth0.
71 =item -c|--conf <conf>
73 Path to packet configuration file.
75 =item -x|--interactive
77 Start trafgen in interactive mode.
79 =item -J|--jumbo-support
81 Support for 64KB Super Jumbo Frames
83 =item -n|--num <uint>
85 Number of packets to generate before exiting.
86 0 means forever until SIGINT.
88 =item -r|--rand
90 Randomize packet selection process instead of round-robin.
92 =item -t|--gap <uint>
94 Interpacket gap in microseconds.
96 =item -S|--ring-size <size>
98 Manually set ring size to <size>: mmap space in KB/MB/GB.
100 =item -k|--kernel-pull <uint>
102 Kernel pull from user interval in microseconds.
103 Default value is 10 microseconds.
105 =item -b|--bind-cpu <cpu>
107 Bind to specific CPU (or CPU-range).
109 =item -B|--unbind-cpu <cpu>
111 Forbid to use specific CPU (or CPU-range).
113 =item -H|--prio-high
115 Make this high priority process.
117 =item -Q|--notouch-irq
119 Do not touch IRQ CPU affinity of NIC.
121 =back
123 =head1 EXAMPLES
125 =over
127 =item Generate traffic defined in trafgen.txf on eth0 using CPU 0
129 trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0
131 =item Generate traffic on eth0 using CPU 0, wait 100 us between packets
133 trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --gap 100
135 =item Generate 100,000 packet on eth0 using CPU 0
137 trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 100000
139 =back
141 =head1 AUTHOR
143 Written by Daniel Borkmann <daniel@netsniff-ng.org>
145 =head1 DOCUMENTATION
147 Documentation by Emmanuel Roullit <emmanuel@netsniff-ng.org>
149 =head1 BUGS
151 Please report bugs to <bugs@netsniff-ng.org>
153 =cut
157 #include <stdio.h>
158 #include <string.h>
159 #include <getopt.h>
160 #include <ctype.h>
161 #include <stdbool.h>
162 #include <sys/socket.h>
163 #include <sys/types.h>
164 #include <sys/stat.h>
165 #include <sys/time.h>
166 #include <signal.h>
167 #include <stdint.h>
168 #include <stdlib.h>
169 #include <fcntl.h>
170 #include <time.h>
171 #include <net/ethernet.h>
173 #include "xmalloc.h"
174 #include "xstring.h"
175 #include "die.h"
176 #include "xsys.h"
177 #include "xio.h"
178 #include "trafgen_conf.h"
179 #include "tprintf.h"
180 #include "mtrand.h"
181 #include "ring_tx.h"
183 struct stats {
184 unsigned long tx_bytes;
185 unsigned long tx_packets;
188 struct mode {
189 #define CPU_UNKNOWN -1
190 #define CPU_NOTOUCH -2
191 struct stats stats;
192 char *device;
193 int cpu;
194 int rand;
195 unsigned long kpull;
196 /* 0 for automatic, > 0 for manual */
197 unsigned int reserve_size;
198 int jumbo_support;
199 int verbose;
200 unsigned long num;
201 unsigned long gap;
204 static int sock;
205 static struct itimerval itimer;
206 static unsigned long interval = TX_KERNEL_PULL_INT;
208 __export sig_atomic_t sigint = 0;
210 __export struct packet *packets = NULL;
211 __export unsigned int packets_len = 0;
212 __export struct packet_dynamics *packet_dyns = NULL;
213 __export unsigned int packet_dyn_len = 0;
215 static const char *short_options = "d:c:n:t:vJhS:HQb:B:rk:xi:o:V";
217 static struct option long_options[] = {
218 {"dev", required_argument, 0, 'd'},
219 {"out", required_argument, 0, 'o'},
220 {"in", required_argument, 0, 'i'},
221 {"conf", required_argument, 0, 'c'},
222 {"num", required_argument, 0, 'n'},
223 {"gap", required_argument, 0, 't'},
224 {"ring-size", required_argument, 0, 'S'},
225 {"bind-cpu", required_argument, 0, 'b'},
226 {"unbind-cpu", required_argument, 0, 'B'},
227 {"kernel-pull", required_argument, 0, 'k'},
228 {"jumbo-support", no_argument, 0, 'J'},
229 {"interactive", no_argument, 0, 'x'},
230 {"rand", no_argument, 0, 'r'},
231 {"prio-high", no_argument, 0, 'H'},
232 {"notouch-irq", no_argument, 0, 'Q'},
233 {"verbose", no_argument, 0, 'V'},
234 {"version", no_argument, 0, 'v'},
235 {"help", no_argument, 0, 'h'},
236 {0, 0, 0, 0}
239 static void signal_handler(int number)
241 switch (number) {
242 case SIGINT:
243 sigint = 1;
244 break;
245 case SIGHUP:
246 default:
247 break;
251 static void timer_elapsed(int number)
253 itimer.it_interval.tv_sec = 0;
254 itimer.it_interval.tv_usec = interval;
255 itimer.it_value.tv_sec = 0;
256 itimer.it_value.tv_usec = interval;
258 pull_and_flush_tx_ring(sock);
259 setitimer(ITIMER_REAL, &itimer, NULL);
262 static void header(void)
264 printf("%s%s%s\n", colorize_start(bold), "trafgen "
265 VERSION_STRING, colorize_end());
268 static void help(void)
270 printf("\ntrafgen %s, high-perf zero-copy network packet generator\n",
271 VERSION_STRING);
272 printf("http://www.netsniff-ng.org\n\n");
273 printf("Usage: trafgen [options]\n");
274 printf("Options:\n");
275 printf(" -o|-d|--out|--dev <netdev|pcap> Networking Device i.e., eth0 or pcap\n");
276 printf(" -i|-c|--in|--conf <cfg-file> Packet configuration file\n");
277 printf(" -x|--interactive Start trafgen in interactive server mode\n");
278 printf(" -J|--jumbo-support Support for 64KB Super Jumbo Frames\n");
279 printf(" Default TX slot: 2048Byte\n");
280 printf(" -n|--num <uint> Number of packets until exit\n");
281 printf(" `-- 0 Loop until interrupt (default)\n");
282 printf(" `- n Send n packets and done\n");
283 printf(" -r|--rand Randomize packet selection process\n");
284 printf(" Instead of a round robin selection\n");
285 printf(" -t|--gap <uint> Interpacket gap in us (approx)\n");
286 printf(" -S|--ring-size <size> Manually set ring size to <size>:\n");
287 printf(" mmap space in KB/MB/GB, e.g. \'10MB\'\n");
288 printf(" -k|--kernel-pull <uint> Kernel pull from user interval in us\n");
289 printf(" Default is 10us where the TX_RING\n");
290 printf(" is populated with payload from uspace\n");
291 printf(" -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n");
292 printf(" -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n");
293 printf(" -H|--prio-high Make this high priority process\n");
294 printf(" -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n");
295 printf(" -v|--version Show version\n");
296 printf(" -h|--help Guess what?!\n");
297 printf("\n");
298 printf("Examples:\n");
299 printf(" See trafgen.txf for configuration file examples.\n");
300 printf(" trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0\n");
301 printf(" trafgen --out eth0 --in trafgen.txf --bind-cpu 0\n");
302 printf(" trafgen --out test.pcap --in trafgen.txf --bind-cpu 0\n");
303 printf(" trafgen --dev eth0 --conf trafgen.txf --rand --gap 1000\n");
304 printf(" trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 10 --rand\n");
305 printf(" trafgen --interactive\n");
306 printf(" trafgen --interactive --dev mgmt0 (only start server on mgmt0)\n");
307 printf(" trafgen --interactive --conf trafgen-cli.batch\n");
308 printf("\n");
309 printf("Note:\n");
310 printf(" This tool is targeted for network developers! You should\n");
311 printf(" be aware of what you are doing and what these options above\n");
312 printf(" mean! Only use this tool in an isolated LAN that you own!\n");
313 printf("\n");
314 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
315 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
316 printf("Swiss federal institute of technology (ETH Zurich)\n");
317 printf("License: GNU GPL version 2\n");
318 printf("This is free software: you are free to change and redistribute it.\n");
319 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
320 die();
323 static void version(void)
325 printf("\ntrafgen %s, high-perf zero-copy network packet generator\n",
326 VERSION_STRING);
327 printf("http://www.netsniff-ng.org\n\n");
328 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
329 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
330 printf("Swiss federal institute of technology (ETH Zurich)\n");
331 printf("License: GNU GPL version 2\n");
332 printf("This is free software: you are free to change and redistribute it.\n");
333 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
334 die();
337 static inline void apply_counter(int i)
339 int j;
341 for (j = 0; j < packet_dyns[i].counter_len; ++j) {
342 uint8_t val;
343 struct counter *counter = &packet_dyns[i].counter[j];
345 val = counter->val;
346 val -= counter->min;
348 if (counter->type == TYPE_INC)
349 val = (val + counter->inc) %
350 (counter->max - counter->min + 1);
351 else
352 val = (val - counter->inc) %
353 (counter->min - counter->max + 1);
355 val += counter->min;
356 counter->val = val;
358 packets[i].payload[counter->off] = val;
362 static inline void apply_randomizer(int i)
364 int j;
366 for (j = 0; j < packet_dyns[i].randomizer_len; ++j) {
367 uint8_t val = (uint8_t) mt_rand_int32();
368 struct randomizer *randomizer = &packet_dyns[i].randomizer[j];
370 randomizer->val = val;
371 packets[i].payload[randomizer->off] = val;
375 static void tx_precheck(struct mode *mode)
377 int i, mtu;
379 if (!mode)
380 panic("Panic over invalid args for TX trigger!\n");
381 if (packets_len == 0 || packets_len != packet_dyn_len)
382 panic("Panic over invalid args for TX trigger!\n");
383 if (!device_up_and_running(mode->device))
384 panic("Device not up and running!\n");
386 mtu = device_mtu(mode->device);
388 for (i = 0; i < packets_len; ++i) {
389 if (packets[i].len > mtu + 14)
390 panic("Device MTU < than your packet size!\n");
391 if (packets[i].len <= 14)
392 panic("Device packet size too short!\n");
396 static void tx_slowpath_or_die(struct mode *mode)
398 int ifindex, ret;
399 unsigned int i;
400 struct sockaddr_ll s_addr;
401 unsigned long num = 1;
403 tx_precheck(mode);
405 sock = pf_socket();
407 ifindex = device_ifindex(mode->device);
409 if (mode->num > 0)
410 num = mode->num;
411 if (mode->rand)
412 printf("Note: randomizes output makes trafgen slower!\n");
414 printf("MD: TX slowpath %s %luus\n\n", mode->rand ? "RND" : "RR", mode->gap);
415 printf("Running! Hang up with ^C!\n\n");
417 fmemset(&s_addr, 0, sizeof(s_addr));
418 s_addr.sll_family = PF_PACKET;
419 s_addr.sll_halen = ETH_ALEN;
420 s_addr.sll_ifindex = ifindex;
422 i = 0;
424 while (likely(sigint == 0) && likely(num > 0)) {
425 apply_counter(i);
426 apply_randomizer(i);
428 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
429 (struct sockaddr *) &s_addr, sizeof(s_addr));
430 if (ret < 0)
431 whine("sendto error!\n");
433 mode->stats.tx_bytes += packets[i].len;
434 mode->stats.tx_packets++;
436 if (mode->rand) {
437 i = mt_rand_int32() % packets_len;
438 } else {
439 i++;
440 atomic_cmp_swp(&i, packets_len, 0);
443 if (mode->num > 0)
444 num--;
446 usleep(mode->gap);
449 close(sock);
451 fflush(stdout);
452 printf("\n");
453 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
454 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
457 static void tx_fastpath_or_die(struct mode *mode)
459 int irq, ifindex;
460 unsigned int i, size, it = 0;
461 unsigned long num = 1;
462 uint8_t *out = NULL;
463 struct ring tx_ring;
464 struct frame_map *hdr;
466 tx_precheck(mode);
468 sock = pf_socket();
470 fmemset(&tx_ring, 0, sizeof(tx_ring));
471 ifindex = device_ifindex(mode->device);
472 size = ring_size(mode->device, mode->reserve_size);
474 set_packet_loss_discard(sock);
475 setup_tx_ring_layout(sock, &tx_ring, size, mode->jumbo_support);
476 create_tx_ring(sock, &tx_ring);
477 mmap_tx_ring(sock, &tx_ring);
478 alloc_tx_ring_frames(&tx_ring);
479 bind_tx_ring(sock, &tx_ring, ifindex);
481 if (mode->cpu >= 0 && ifindex > 0) {
482 irq = device_irq_number(mode->device);
483 device_bind_irq_to_cpu(mode->cpu, irq);
484 printf("IRQ: %s:%d > CPU%d\n", mode->device, irq,
485 mode->cpu);
488 if (mode->kpull)
489 interval = mode->kpull;
490 if (mode->num > 0)
491 num = mode->num;
492 if (mode->rand)
493 printf("Note: randomizes output makes trafgen slower!\n");
495 printf("MD: TX fastpath %s %luus\n\n", mode->rand ? "RND" : "RR", interval);
496 printf("Running! Hang up with ^C!\n\n");
498 itimer.it_interval.tv_sec = 0;
499 itimer.it_interval.tv_usec = interval;
500 itimer.it_value.tv_sec = 0;
501 itimer.it_value.tv_usec = interval;
502 setitimer(ITIMER_REAL, &itimer, NULL);
504 i = 0;
506 while (likely(sigint == 0) && likely(num > 0)) {
507 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) &&
508 likely(num > 0)) {
509 hdr = tx_ring.frames[it].iov_base;
511 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
512 * sizeof(struct sockaddr_ll); */
513 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
514 sizeof(struct sockaddr_ll);
516 hdr->tp_h.tp_snaplen = packets[i].len;
517 hdr->tp_h.tp_len = packets[i].len;
519 apply_counter(i);
520 apply_randomizer(i);
522 fmemcpy(out, packets[i].payload, packets[i].len);
524 mode->stats.tx_bytes += packets[i].len;
525 mode->stats.tx_packets++;
527 if (mode->rand) {
528 i = mt_rand_int32() % packets_len;
529 } else {
530 i++;
531 atomic_cmp_swp(&i, packets_len, 0);
534 kernel_may_pull_from_tx(&hdr->tp_h);
535 next_slot_prewr(&it, &tx_ring);
537 if (mode->num > 0)
538 num--;
539 if (unlikely(sigint == 1))
540 break;
544 destroy_tx_ring(sock, &tx_ring);
545 close(sock);
547 fflush(stdout);
548 printf("\n");
549 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
550 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
553 static void main_loop(struct mode *mode, char *confname)
555 compile_packets(confname, mode->verbose);
557 if (mode->gap > 0)
558 tx_slowpath_or_die(mode);
559 else
560 tx_fastpath_or_die(mode);
562 cleanup_packets();
565 int main(int argc, char **argv)
567 int c, opt_index, i, j, interactive = 0;
568 char *confname = NULL, *ptr;
569 bool prio_high = false;
570 struct mode mode;
572 check_for_root_maybe_die();
574 fmemset(&mode, 0, sizeof(mode));
575 mode.cpu = CPU_UNKNOWN;
576 mode.gap = 0;
577 mode.num = 0;
579 while ((c = getopt_long(argc, argv, short_options, long_options,
580 &opt_index)) != EOF) {
581 switch (c) {
582 case 'h':
583 help();
584 break;
585 case 'v':
586 version();
587 break;
588 case 'V':
589 mode.verbose = 1;
590 break;
591 case 'd':
592 case 'o':
593 mode.device = xstrndup(optarg, IFNAMSIZ);
594 break;
595 case 'x':
596 interactive = 1;
597 break;
598 case 'r':
599 mode.rand = 1;
600 break;
601 case 'J':
602 mode.jumbo_support = 1;
603 break;
604 case 'c':
605 case 'i':
606 confname = xstrdup(optarg);
607 break;
608 case 'k':
609 mode.kpull = atol(optarg);
610 break;
611 case 'n':
612 mode.num = atol(optarg);
613 break;
614 case 't':
615 mode.gap = atol(optarg);
616 break;
617 case 'S':
618 ptr = optarg;
619 mode.reserve_size = 0;
621 for (j = i = strlen(optarg); i > 0; --i) {
622 if (!isdigit(optarg[j - i]))
623 break;
624 ptr++;
627 if (!strncmp(ptr, "KB", strlen("KB")))
628 mode.reserve_size = 1 << 10;
629 else if (!strncmp(ptr, "MB", strlen("MB")))
630 mode.reserve_size = 1 << 20;
631 else if (!strncmp(ptr, "GB", strlen("GB")))
632 mode.reserve_size = 1 << 30;
633 else
634 panic("Syntax error in ring size param!\n");
635 *ptr = 0;
637 mode.reserve_size *= atoi(optarg);
638 break;
639 case 'b':
640 set_cpu_affinity(optarg, 0);
641 /* Take the first CPU for rebinding the IRQ */
642 if (mode.cpu != CPU_NOTOUCH)
643 mode.cpu = atoi(optarg);
644 break;
645 case 'B':
646 set_cpu_affinity(optarg, 1);
647 break;
648 case 'H':
649 prio_high = true;
650 break;
651 case 'Q':
652 mode.cpu = CPU_NOTOUCH;
653 break;
654 case '?':
655 switch (optopt) {
656 case 'd':
657 case 'c':
658 case 'n':
659 case 'S':
660 case 'b':
661 case 'o':
662 case 'i':
663 case 'k':
664 case 'B':
665 case 't':
666 panic("Option -%c requires an argument!\n",
667 optopt);
668 default:
669 if (isprint(optopt))
670 whine("Unknown option character "
671 "`0x%X\'!\n", optopt);
672 die();
674 default:
675 break;
679 if (!interactive && argc < 5)
680 help();
681 if (interactive && argc < 2)
682 help();
683 if (!interactive && mode.device == NULL)
684 panic("No networking device given!\n");
685 if (!interactive && confname == NULL)
686 panic("No configuration file given!\n");
687 if (!interactive && device_mtu(mode.device) == 0)
688 panic("This is no networking device!\n");
689 if (!interactive && device_up_and_running(mode.device) == 0)
690 panic("Networking device not running!\n");
692 register_signal(SIGINT, signal_handler);
693 register_signal(SIGHUP, signal_handler);
694 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
696 header();
698 if (prio_high == true) {
699 set_proc_prio(get_default_proc_prio());
700 set_sched_status(get_default_sched_policy(),
701 get_default_sched_prio());
704 if (interactive)
705 main_loop_interactive(&mode, confname);
706 else
707 main_loop(&mode, confname);
709 if (mode.device)
710 xfree(mode.device);
711 if (confname)
712 xfree(confname);
714 return 0;