trafgen: remove pointer fiddling, improve code
[netsniff-ng-old.git] / src / trafgen.c
blob123e0ffc6b2f9018e5de713a5543c3798c39957c
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 __import int main_loop_interactive(struct mode *mode, char *confname);
205 __import int compile_packets(char *file, int verbose);
207 static int sock;
208 static struct itimerval itimer;
209 static unsigned long interval = TX_KERNEL_PULL_INT;
211 __export sig_atomic_t sigint = 0;
213 __export struct packet *packets = NULL;
214 __export unsigned int packets_len = 0;
215 __export struct packet_dynamics *packet_dyns = NULL;
216 __export unsigned int packet_dyn_len = 0;
218 static const char *short_options = "d:c:n:t:vJhS:HQb:B:rk:xi:o:V";
220 static struct option long_options[] = {
221 {"dev", required_argument, 0, 'd'},
222 {"out", required_argument, 0, 'o'},
223 {"in", required_argument, 0, 'i'},
224 {"conf", required_argument, 0, 'c'},
225 {"num", required_argument, 0, 'n'},
226 {"gap", required_argument, 0, 't'},
227 {"ring-size", required_argument, 0, 'S'},
228 {"bind-cpu", required_argument, 0, 'b'},
229 {"unbind-cpu", required_argument, 0, 'B'},
230 {"kernel-pull", required_argument, 0, 'k'},
231 {"jumbo-support", no_argument, 0, 'J'},
232 {"interactive", no_argument, 0, 'x'},
233 {"rand", no_argument, 0, 'r'},
234 {"prio-high", no_argument, 0, 'H'},
235 {"notouch-irq", no_argument, 0, 'Q'},
236 {"verbose", no_argument, 0, 'V'},
237 {"version", no_argument, 0, 'v'},
238 {"help", no_argument, 0, 'h'},
239 {0, 0, 0, 0}
242 static void signal_handler(int number)
244 switch (number) {
245 case SIGINT:
246 sigint = 1;
247 break;
248 case SIGHUP:
249 default:
250 break;
254 static void timer_elapsed(int number)
256 itimer.it_interval.tv_sec = 0;
257 itimer.it_interval.tv_usec = interval;
258 itimer.it_value.tv_sec = 0;
259 itimer.it_value.tv_usec = interval;
261 pull_and_flush_tx_ring(sock);
262 setitimer(ITIMER_REAL, &itimer, NULL);
265 static void header(void)
267 printf("%s%s%s\n", colorize_start(bold), "trafgen "
268 VERSION_STRING, colorize_end());
271 static void help(void)
273 printf("\ntrafgen %s, high-perf zero-copy network packet generator\n",
274 VERSION_STRING);
275 printf("http://www.netsniff-ng.org\n\n");
276 printf("Usage: trafgen [options]\n");
277 printf("Options:\n");
278 printf(" -o|-d|--out|--dev <netdev|pcap> Networking Device i.e., eth0 or pcap\n");
279 printf(" -i|-c|--in|--conf <cfg-file> Packet configuration file\n");
280 printf(" -x|--interactive Start trafgen in interactive server mode\n");
281 printf(" -J|--jumbo-support Support for 64KB Super Jumbo Frames\n");
282 printf(" Default TX slot: 2048Byte\n");
283 printf(" -n|--num <uint> Number of packets until exit\n");
284 printf(" `-- 0 Loop until interrupt (default)\n");
285 printf(" `- n Send n packets and done\n");
286 printf(" -r|--rand Randomize packet selection process\n");
287 printf(" Instead of a round robin selection\n");
288 printf(" -t|--gap <uint> Interpacket gap in us (approx)\n");
289 printf(" -S|--ring-size <size> Manually set ring size to <size>:\n");
290 printf(" mmap space in KB/MB/GB, e.g. \'10MB\'\n");
291 printf(" -k|--kernel-pull <uint> Kernel pull from user interval in us\n");
292 printf(" Default is 10us where the TX_RING\n");
293 printf(" is populated with payload from uspace\n");
294 printf(" -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n");
295 printf(" -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n");
296 printf(" -H|--prio-high Make this high priority process\n");
297 printf(" -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n");
298 printf(" -v|--version Show version\n");
299 printf(" -h|--help Guess what?!\n");
300 printf("\n");
301 printf("Examples:\n");
302 printf(" See trafgen.txf for configuration file examples.\n");
303 printf(" trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0\n");
304 printf(" trafgen --out eth0 --in trafgen.txf --bind-cpu 0\n");
305 printf(" trafgen --out test.pcap --in trafgen.txf --bind-cpu 0\n");
306 printf(" trafgen --dev eth0 --conf trafgen.txf --rand --gap 1000\n");
307 printf(" trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 10 --rand\n");
308 printf(" trafgen --interactive\n");
309 printf(" trafgen --interactive --dev mgmt0 (only start server on mgmt0)\n");
310 printf(" trafgen --interactive --conf trafgen-cli.batch\n");
311 printf("\n");
312 printf("Note:\n");
313 printf(" This tool is targeted for network developers! You should\n");
314 printf(" be aware of what you are doing and what these options above\n");
315 printf(" mean! Only use this tool in an isolated LAN that you own!\n");
316 printf("\n");
317 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
318 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
319 printf("Swiss federal institute of technology (ETH Zurich)\n");
320 printf("License: GNU GPL version 2\n");
321 printf("This is free software: you are free to change and redistribute it.\n");
322 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
323 die();
326 static void version(void)
328 printf("\ntrafgen %s, high-perf zero-copy network packet generator\n",
329 VERSION_STRING);
330 printf("http://www.netsniff-ng.org\n\n");
331 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
332 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
333 printf("Swiss federal institute of technology (ETH Zurich)\n");
334 printf("License: GNU GPL version 2\n");
335 printf("This is free software: you are free to change and redistribute it.\n");
336 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
337 die();
340 static inline void apply_counter(int i)
342 int j;
344 for (j = 0; j < packet_dyns[i].counter_len; ++j) {
345 uint8_t val;
346 struct counter *counter = &packet_dyns[i].counter[j];
348 val = counter->val;
349 val -= counter->min;
351 if (counter->type == TYPE_INC)
352 val = (val + counter->inc) %
353 (counter->max - counter->min + 1);
354 else
355 val = (val - counter->inc) %
356 (counter->min - counter->max + 1);
358 val += counter->min;
359 counter->val = val;
361 packets[i].payload[counter->off] = val;
365 static inline void apply_randomizer(int i)
367 int j;
369 for (j = 0; j < packet_dyns[i].randomizer_len; ++j) {
370 uint8_t val = (uint8_t) mt_rand_int32();
371 struct randomizer *randomizer = &packet_dyns[i].randomizer[j];
373 randomizer->val = val;
374 packets[i].payload[randomizer->off] = val;
378 static void tx_precheck(struct mode *mode)
380 int i, mtu;
382 if (!mode)
383 panic("Panic over invalid args for TX trigger!\n");
384 if (packets_len == 0 || packets_len != packet_dyn_len)
385 panic("Panic over invalid args for TX trigger!\n");
386 if (!device_up_and_running(mode->device))
387 panic("Device not up and running!\n");
389 mtu = device_mtu(mode->device);
391 for (i = 0; i < packets_len; ++i) {
392 if (packets[i].len > mtu + 14)
393 panic("Device MTU < than your packet size!\n");
394 if (packets[i].len <= 14)
395 panic("Device packet size too short!\n");
399 static void tx_slowpath_or_die(struct mode *mode)
401 int ifindex, ret;
402 unsigned int i;
403 struct sockaddr_ll s_addr;
404 unsigned long num = 1;
406 tx_precheck(mode);
408 sock = pf_socket();
410 ifindex = device_ifindex(mode->device);
412 if (mode->num > 0)
413 num = mode->num;
414 if (mode->rand)
415 printf("Note: randomizes output makes trafgen slower!\n");
417 printf("MD: TX slowpath %s %luus\n\n", mode->rand ? "RND" : "RR", mode->gap);
418 printf("Running! Hang up with ^C!\n\n");
420 fmemset(&s_addr, 0, sizeof(s_addr));
421 s_addr.sll_family = PF_PACKET;
422 s_addr.sll_halen = ETH_ALEN;
423 s_addr.sll_ifindex = ifindex;
425 i = 0;
427 while (likely(sigint == 0) && likely(num > 0)) {
428 apply_counter(i);
429 apply_randomizer(i);
431 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
432 (struct sockaddr *) &s_addr, sizeof(s_addr));
433 if (ret < 0)
434 whine("sendto error!\n");
436 mode->stats.tx_bytes += packets[i].len;
437 mode->stats.tx_packets++;
439 if (mode->rand) {
440 i = mt_rand_int32() % packets_len;
441 } else {
442 i++;
443 atomic_cmp_swp(&i, packets_len, 0);
446 if (mode->num > 0)
447 num--;
449 usleep(mode->gap);
452 close(sock);
454 fflush(stdout);
455 printf("\n");
456 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
457 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
460 static void tx_fastpath_or_die(struct mode *mode)
462 int irq, ifindex;
463 unsigned int i, size, it = 0;
464 unsigned long num = 1;
465 uint8_t *out = NULL;
466 struct ring tx_ring;
467 struct frame_map *hdr;
469 tx_precheck(mode);
471 sock = pf_socket();
473 fmemset(&tx_ring, 0, sizeof(tx_ring));
474 ifindex = device_ifindex(mode->device);
475 size = ring_size(mode->device, mode->reserve_size);
477 set_packet_loss_discard(sock);
478 setup_tx_ring_layout(sock, &tx_ring, size, mode->jumbo_support);
479 create_tx_ring(sock, &tx_ring);
480 mmap_tx_ring(sock, &tx_ring);
481 alloc_tx_ring_frames(&tx_ring);
482 bind_tx_ring(sock, &tx_ring, ifindex);
484 if (mode->cpu >= 0 && ifindex > 0) {
485 irq = device_irq_number(mode->device);
486 device_bind_irq_to_cpu(mode->cpu, irq);
487 printf("IRQ: %s:%d > CPU%d\n", mode->device, irq,
488 mode->cpu);
491 if (mode->kpull)
492 interval = mode->kpull;
493 if (mode->num > 0)
494 num = mode->num;
495 if (mode->rand)
496 printf("Note: randomizes output makes trafgen slower!\n");
498 printf("MD: TX fastpath %s %luus\n\n", mode->rand ? "RND" : "RR", interval);
499 printf("Running! Hang up with ^C!\n\n");
501 itimer.it_interval.tv_sec = 0;
502 itimer.it_interval.tv_usec = interval;
503 itimer.it_value.tv_sec = 0;
504 itimer.it_value.tv_usec = interval;
505 setitimer(ITIMER_REAL, &itimer, NULL);
507 i = 0;
509 while (likely(sigint == 0) && likely(num > 0)) {
510 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) &&
511 likely(num > 0)) {
512 hdr = tx_ring.frames[it].iov_base;
514 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
515 * sizeof(struct sockaddr_ll); */
516 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
517 sizeof(struct sockaddr_ll);
519 hdr->tp_h.tp_snaplen = packets[i].len;
520 hdr->tp_h.tp_len = packets[i].len;
522 apply_counter(i);
523 apply_randomizer(i);
525 fmemcpy(out, packets[i].payload, packets[i].len);
527 mode->stats.tx_bytes += packets[i].len;
528 mode->stats.tx_packets++;
530 if (mode->rand) {
531 i = mt_rand_int32() % packets_len;
532 } else {
533 i++;
534 atomic_cmp_swp(&i, packets_len, 0);
537 kernel_may_pull_from_tx(&hdr->tp_h);
538 next_slot_prewr(&it, &tx_ring);
540 if (mode->num > 0)
541 num--;
542 if (unlikely(sigint == 1))
543 break;
547 destroy_tx_ring(sock, &tx_ring);
548 close(sock);
550 fflush(stdout);
551 printf("\n");
552 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
553 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
556 static void cleanup_packets(void)
558 int i;
560 for (i = 0; i < packets_len; ++i) {
561 if (packets[i].len > 0)
562 xfree(packets[i].payload);
565 if (packets_len > 0)
566 xfree(packets);
568 for (i = 0; i < packet_dyn_len; ++i) {
569 if (packet_dyns[i].counter_len > 0)
570 xfree(packet_dyns[i].counter);
572 if (packet_dyns[i].randomizer_len > 0)
573 xfree(packet_dyns[i].randomizer);
576 if (packet_dyn_len > 0)
577 xfree(packet_dyns);
580 static void main_loop(struct mode *mode, char *confname)
582 compile_packets(confname, mode->verbose);
584 if (mode->gap > 0)
585 tx_slowpath_or_die(mode);
586 else
587 tx_fastpath_or_die(mode);
589 cleanup_packets();
592 int main(int argc, char **argv)
594 int c, opt_index, i, j, interactive = 0;
595 char *confname = NULL, *ptr;
596 bool prio_high = false;
597 struct mode mode;
599 check_for_root_maybe_die();
601 fmemset(&mode, 0, sizeof(mode));
602 mode.cpu = CPU_UNKNOWN;
603 mode.gap = 0;
604 mode.num = 0;
606 while ((c = getopt_long(argc, argv, short_options, long_options,
607 &opt_index)) != EOF) {
608 switch (c) {
609 case 'h':
610 help();
611 break;
612 case 'v':
613 version();
614 break;
615 case 'V':
616 mode.verbose = 1;
617 break;
618 case 'd':
619 case 'o':
620 mode.device = xstrndup(optarg, IFNAMSIZ);
621 break;
622 case 'x':
623 interactive = 1;
624 break;
625 case 'r':
626 mode.rand = 1;
627 break;
628 case 'J':
629 mode.jumbo_support = 1;
630 break;
631 case 'c':
632 case 'i':
633 confname = xstrdup(optarg);
634 break;
635 case 'k':
636 mode.kpull = atol(optarg);
637 break;
638 case 'n':
639 mode.num = atol(optarg);
640 break;
641 case 't':
642 mode.gap = atol(optarg);
643 break;
644 case 'S':
645 ptr = optarg;
646 mode.reserve_size = 0;
648 for (j = i = strlen(optarg); i > 0; --i) {
649 if (!isdigit(optarg[j - i]))
650 break;
651 ptr++;
654 if (!strncmp(ptr, "KB", strlen("KB")))
655 mode.reserve_size = 1 << 10;
656 else if (!strncmp(ptr, "MB", strlen("MB")))
657 mode.reserve_size = 1 << 20;
658 else if (!strncmp(ptr, "GB", strlen("GB")))
659 mode.reserve_size = 1 << 30;
660 else
661 panic("Syntax error in ring size param!\n");
662 *ptr = 0;
664 mode.reserve_size *= atoi(optarg);
665 break;
666 case 'b':
667 set_cpu_affinity(optarg, 0);
668 /* Take the first CPU for rebinding the IRQ */
669 if (mode.cpu != CPU_NOTOUCH)
670 mode.cpu = atoi(optarg);
671 break;
672 case 'B':
673 set_cpu_affinity(optarg, 1);
674 break;
675 case 'H':
676 prio_high = true;
677 break;
678 case 'Q':
679 mode.cpu = CPU_NOTOUCH;
680 break;
681 case '?':
682 switch (optopt) {
683 case 'd':
684 case 'c':
685 case 'n':
686 case 'S':
687 case 'b':
688 case 'o':
689 case 'i':
690 case 'k':
691 case 'B':
692 case 't':
693 panic("Option -%c requires an argument!\n",
694 optopt);
695 default:
696 if (isprint(optopt))
697 whine("Unknown option character "
698 "`0x%X\'!\n", optopt);
699 die();
701 default:
702 break;
706 if (!interactive && argc < 5)
707 help();
708 if (interactive && argc < 2)
709 help();
710 if (!interactive && mode.device == NULL)
711 panic("No networking device given!\n");
712 if (!interactive && confname == NULL)
713 panic("No configuration file given!\n");
714 if (!interactive && device_mtu(mode.device) == 0)
715 panic("This is no networking device!\n");
716 if (!interactive && device_up_and_running(mode.device) == 0)
717 panic("Networking device not running!\n");
719 register_signal(SIGINT, signal_handler);
720 register_signal(SIGHUP, signal_handler);
721 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
723 header();
725 if (prio_high == true) {
726 set_proc_prio(get_default_proc_prio());
727 set_sched_status(get_default_sched_policy(),
728 get_default_sched_prio());
731 if (interactive)
732 main_loop_interactive(&mode, confname);
733 else
734 main_loop(&mode, confname);
736 if (mode.device)
737 xfree(mode.device);
738 if (confname)
739 xfree(confname);
741 return 0;