ring: remove macro with ptr dereference
[netsniff-ng.git] / src / trafgen.c
blobb334a4672306b897e4418e71a2a5789de03dcdb0
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) && likely(num > 0)) {
417 hdr = tx_ring.frames[it].iov_base;
419 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
420 * sizeof(struct sockaddr_ll); */
421 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
423 hdr->tp_h.tp_snaplen = packets[i].len;
424 hdr->tp_h.tp_len = packets[i].len;
426 apply_counter(i);
427 apply_randomizer(i);
429 fmemcpy(out, packets[i].payload, packets[i].len);
431 ctx->tx_bytes += packets[i].len;
432 ctx->tx_packets++;
434 if (!ctx->rand) {
435 i++;
436 if (i >= plen)
437 i = 0;
438 } else
439 i = rand() % plen;
441 kernel_may_pull_from_tx(&hdr->tp_h);
443 it++;
444 if (it >= tx_ring.layout.tp_frame_nr)
445 it = 0;
447 if (ctx->num > 0)
448 num--;
450 if (unlikely(sigint == 1))
451 break;
455 bug_on(gettimeofday(&end, NULL));
456 diff = tv_subtract(end, start);
458 destroy_tx_ring(sock, &tx_ring);
460 if (ctx->rfraw)
461 leave_rfmon_mac80211(ctx->device_trans, ctx->device);
463 fflush(stdout);
464 printf("\n");
465 printf("\r%12lu frames outgoing\n", ctx->tx_packets);
466 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
467 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
470 static void main_loop(struct ctx *ctx, char *confname, bool slow)
472 compile_packets(confname, ctx->verbose);
473 xmit_precheck(ctx);
475 sock = pf_socket();
477 if (slow)
478 xmit_slowpath_or_die(ctx);
479 else
480 xmit_fastpath_or_die(ctx);
482 close(sock);
484 cleanup_packets();
487 int main(int argc, char **argv)
489 int c, opt_index, i, j, vals[4] = {0};
490 char *confname = NULL, *ptr;
491 bool prio_high = false, setsockmem = true, slow = false;
492 struct ctx ctx;
494 srand(time(NULL));
496 fmemset(&ctx, 0, sizeof(ctx));
497 ctx.cpu = -1;
499 while ((c = getopt_long(argc, argv, short_options, long_options,
500 &opt_index)) != EOF) {
501 switch (c) {
502 case 'h':
503 help();
504 break;
505 case 'v':
506 version();
507 break;
508 case 'V':
509 ctx.verbose = 1;
510 break;
511 case 'd':
512 case 'o':
513 ctx.device = xstrndup(optarg, IFNAMSIZ);
514 break;
515 case 'r':
516 ctx.rand = 1;
517 break;
518 case 'R':
519 ctx.rfraw = 1;
520 break;
521 case 'J':
522 ctx.jumbo_support = 1;
523 break;
524 case 'c':
525 case 'i':
526 confname = xstrdup(optarg);
527 break;
528 case 'k':
529 ctx.kpull = atol(optarg);
530 break;
531 case 'n':
532 ctx.num = atol(optarg);
533 break;
534 case 't':
535 slow = true;
536 ctx.gap = atol(optarg);
537 break;
538 case 'A':
539 setsockmem = false;
540 break;
541 case 'S':
542 ptr = optarg;
543 ctx.reserve_size = 0;
545 for (j = i = strlen(optarg); i > 0; --i) {
546 if (!isdigit(optarg[j - i]))
547 break;
548 ptr++;
551 if (!strncmp(ptr, "KB", strlen("KB")))
552 ctx.reserve_size = 1 << 10;
553 else if (!strncmp(ptr, "MB", strlen("MB")))
554 ctx.reserve_size = 1 << 20;
555 else if (!strncmp(ptr, "GB", strlen("GB")))
556 ctx.reserve_size = 1 << 30;
557 else
558 panic("Syntax error in ring size param!\n");
559 *ptr = 0;
561 ctx.reserve_size *= strtol(optarg, NULL, 0);
562 break;
563 case 'b':
564 set_cpu_affinity(optarg, 0);
565 /* Take the first CPU for rebinding the IRQ */
566 if (ctx.cpu != -2)
567 ctx.cpu = strtol(optarg, NULL, 0);
568 break;
569 case 'B':
570 set_cpu_affinity(optarg, 1);
571 break;
572 case 'H':
573 prio_high = true;
574 break;
575 case 'Q':
576 ctx.cpu = -2;
577 break;
578 case '?':
579 switch (optopt) {
580 case 'd':
581 case 'c':
582 case 'n':
583 case 'S':
584 case 'b':
585 case 'o':
586 case 'i':
587 case 'k':
588 case 'B':
589 case 't':
590 panic("Option -%c requires an argument!\n",
591 optopt);
592 default:
593 if (isprint(optopt))
594 whine("Unknown option character "
595 "`0x%X\'!\n", optopt);
596 die();
598 default:
599 break;
603 if (argc < 5)
604 help();
605 if (ctx.device == NULL)
606 panic("No networking device given!\n");
607 if (confname == NULL)
608 panic("No configuration file given!\n");
609 if (device_mtu(ctx.device) == 0)
610 panic("This is no networking device!\n");
611 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
612 panic("Networking device not running!\n");
614 register_signal(SIGINT, signal_handler);
615 register_signal(SIGHUP, signal_handler);
616 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
618 header();
620 if (prio_high) {
621 set_proc_prio(get_default_proc_prio());
622 set_sched_status(get_default_sched_policy(), get_default_sched_prio());
625 if (setsockmem)
626 set_system_socket_memory(vals);
628 main_loop(&ctx, confname, slow);
630 if (setsockmem)
631 reset_system_socket_memory(vals);
633 free(ctx.device);
634 free(ctx.device_trans);
635 free(confname);
637 return 0;