flowtop: Add runtime command to show help window
[netsniff-ng.git] / trafgen.c
blob1da1897f6535091c822085e861d8341db582f98d
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
4 * Swiss federal institute of technology (ETH Zurich)
5 * Subject to the GPL, version 2.
6 */
8 #include <stdio.h>
9 #include <string.h>
10 #include <getopt.h>
11 #include <ctype.h>
12 #include <stdbool.h>
13 #include <sched.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
16 #include <sys/fsuid.h>
17 #include <sys/prctl.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <sys/mman.h>
22 #include <net/ethernet.h>
23 #include <netinet/in.h>
24 #include <netinet/ip.h>
25 #include <linux/icmp.h>
26 #include <linux/if.h>
27 #include <arpa/inet.h>
28 #include <signal.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <poll.h>
34 #include <netdb.h>
35 #include <math.h>
36 #include <unistd.h>
38 #include "xmalloc.h"
39 #include "die.h"
40 #include "str.h"
41 #include "sig.h"
42 #include "sock.h"
43 #include "cpus.h"
44 #include "lockme.h"
45 #include "privs.h"
46 #include "proc.h"
47 #include "mac80211.h"
48 #include "ioops.h"
49 #include "irq.h"
50 #include "config.h"
51 #include "built_in.h"
52 #include "trafgen_conf.h"
53 #include "tprintf.h"
54 #include "timer.h"
55 #include "ring_tx.h"
56 #include "csum.h"
58 struct ctx {
59 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
60 size_t reserve_size;
61 unsigned long num;
62 unsigned int cpus;
63 uid_t uid; gid_t gid;
64 char *device, *device_trans, *rhost;
65 struct timespec gap;
66 struct sockaddr_in dest;
69 struct cpu_stats {
70 unsigned long tv_sec, tv_usec;
71 unsigned long long tx_packets, tx_bytes;
72 unsigned long long cf_packets, cf_bytes;
73 unsigned long long cd_packets;
74 sig_atomic_t state;
77 static sig_atomic_t sigint = 0;
79 struct packet *packets = NULL;
80 size_t plen = 0;
82 struct packet_dyn *packet_dyn = NULL;
83 size_t dlen = 0;
85 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
86 static const struct option long_options[] = {
87 {"dev", required_argument, NULL, 'd'},
88 {"out", required_argument, NULL, 'o'},
89 {"in", required_argument, NULL, 'i'},
90 {"conf", required_argument, NULL, 'c'},
91 {"num", required_argument, NULL, 'n'},
92 {"gap", required_argument, NULL, 't'},
93 {"cpus", required_argument, NULL, 'P'},
94 {"ring-size", required_argument, NULL, 'S'},
95 {"kernel-pull", required_argument, NULL, 'k'},
96 {"smoke-test", required_argument, NULL, 's'},
97 {"seed", required_argument, NULL, 'E'},
98 {"user", required_argument, NULL, 'u'},
99 {"group", required_argument, NULL, 'g'},
100 {"prio-high", no_argument, NULL, 'H'},
101 {"notouch-irq", no_argument, NULL, 'Q'},
102 {"no-sock-mem", no_argument, NULL, 'A'},
103 {"qdisc-path", no_argument, NULL, 'q'},
104 {"jumbo-support", no_argument, NULL, 'J'},
105 {"no-cpu-stats", no_argument, NULL, 'C'},
106 {"cpp", no_argument, NULL, 'p'},
107 {"rfraw", no_argument, NULL, 'R'},
108 {"rand", no_argument, NULL, 'r'},
109 {"verbose", no_argument, NULL, 'V'},
110 {"version", no_argument, NULL, 'v'},
111 {"example", no_argument, NULL, 'e'},
112 {"help", no_argument, NULL, 'h'},
113 {NULL, 0, NULL, 0}
116 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
117 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
118 "Swiss federal institute of technology (ETH Zurich)\n"
119 "License: GNU GPL version 2.0\n"
120 "This is free software: you are free to change and redistribute it.\n"
121 "There is NO WARRANTY, to the extent permitted by law.";
123 static int sock;
124 static struct cpu_stats *stats;
125 static unsigned int seed;
127 #define CPU_STATS_STATE_CFG 1
128 #define CPU_STATS_STATE_CHK 2
129 #define CPU_STATS_STATE_RES 4
131 #ifndef ICMP_FILTER
132 # define ICMP_FILTER 1
134 struct icmp_filter {
135 __u32 data;
137 #endif
139 #define SMOKE_N_PROBES 100
141 #define PKT_MIN_LEN 14
143 static void signal_handler(int number)
145 switch (number) {
146 case SIGINT:
147 case SIGQUIT:
148 case SIGTERM:
149 sigint = 1;
150 case SIGHUP:
151 default:
152 break;
156 static void __noreturn help(void)
158 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
159 puts("http://www.netsniff-ng.org\n\n"
160 "Usage: trafgen [options]\n"
161 "Options:\n"
162 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
163 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
164 " -p|--cpp Run packet config through C preprocessor\n"
165 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
166 " -R|--rfraw Inject raw 802.11 frames\n"
167 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
168 " -n|--num <uint> Number of packets until exit (def: 0)\n"
169 " -r|--rand Randomize packet selection (def: round robin)\n"
170 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
171 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
172 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
173 " -E|--seed <uint> Manually set srand(3) seed\n"
174 " -u|--user <userid> Drop privileges and change to userid\n"
175 " -g|--group <groupid> Drop privileges and change to groupid\n"
176 " -H|--prio-high Make this high priority process\n"
177 " -A|--no-sock-mem Don't tune core socket memory\n"
178 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
179 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
180 " -V|--verbose Be more verbose\n"
181 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
182 " -v|--version Show version and exit\n"
183 " -e|--example Show built-in packet config example\n"
184 " -h|--help Guess what?!\n\n"
185 "Examples:\n"
186 " trafgen --dev eth0 --conf trafgen.cfg\n"
187 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
188 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
189 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
190 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
191 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
192 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
193 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
194 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
195 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
196 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
197 "Generate config files from existing pcap using netsniff-ng:\n"
198 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
199 "Note:\n"
200 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
201 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
202 " we assume the kernel crashed, thus we print the packet and quit.\n"
203 " In case you find a ping-of-death, please mention trafgen in your\n"
204 " commit message of the fix!\n\n"
205 " For introducing bit errors, delays with random variation and more,\n"
206 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
207 " For generating different package distributions, you can use scripting\n"
208 " to generate a trafgen config file with packet ratios as:\n\n"
209 " IMIX 64:7, 570:4, 1518:1\n"
210 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
211 " Cisco 64:7, 594:4, 1518:1\n"
212 " RPR Trimodal 64:60, 512:20, 1518:20\n"
213 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
214 puts(copyright);
215 die();
218 static void __noreturn example(void)
220 const char *e =
221 "/* Note: dynamic elements make trafgen slower! */\n"
222 "#include <stddef.h>\n\n"
223 "{\n"
224 " /* MAC Destination */\n"
225 " fill(0xff, ETH_ALEN),\n"
226 " /* MAC Source */\n"
227 " 0x00, 0x02, 0xb3, drnd(3),\n"
228 " /* IPv4 Protocol */\n"
229 " c16(ETH_P_IP),\n"
230 " /* IPv4 Version, IHL, TOS */\n"
231 " 0b01000101, 0,\n"
232 " /* IPv4 Total Len */\n"
233 " c16(59),\n"
234 " /* IPv4 Ident */\n"
235 " drnd(2),\n"
236 " /* IPv4 Flags, Frag Off */\n"
237 " 0b01000000, 0,\n"
238 " /* IPv4 TTL */\n"
239 " 64,\n"
240 " /* Proto TCP */\n"
241 " 0x06,\n"
242 " /* IPv4 Checksum (IP header from, to) */\n"
243 " csumip(14, 33),\n"
244 " /* Source IP */\n"
245 " drnd(4),\n"
246 " /* Dest IP */\n"
247 " drnd(4),\n"
248 " /* TCP Source Port */\n"
249 " drnd(2),\n"
250 " /* TCP Dest Port */\n"
251 " c16(80),\n"
252 " /* TCP Sequence Number */\n"
253 " drnd(4),\n"
254 " /* TCP Ackn. Number */\n"
255 " c32(0),\n"
256 " /* TCP Header length + TCP SYN/ECN Flag */\n"
257 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
258 " /* Window Size */\n"
259 " c16(16),\n"
260 " /* TCP Checksum (offset IP, offset TCP) */\n"
261 " csumtcp(14, 34),\n"
262 " /* TCP Options */\n"
263 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
264 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
265 " /* Data blob */\n"
266 " \"gotcha!\",\n"
267 "}";
268 puts(e);
269 die();
272 static void __noreturn version(void)
274 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
275 puts("multithreaded zero-copy network packet generator\n"
276 "http://www.netsniff-ng.org\n");
277 puts(copyright);
278 die();
281 static void apply_counter(int id)
283 size_t j, counter_max = packet_dyn[id].clen;
285 for (j = 0; j < counter_max; ++j) {
286 uint8_t val;
287 struct counter *counter = &packet_dyn[id].cnt[j];
289 val = counter->val - counter->min;
291 switch (counter->type) {
292 case TYPE_INC:
293 val = (val + counter->inc) % (counter->max - counter->min + 1);
294 break;
295 case TYPE_DEC:
296 val = (val - counter->inc) % (counter->min - counter->max + 1);
297 break;
298 default:
299 bug();
302 counter->val = val + counter->min;
303 packets[id].payload[counter->off] = val;
307 static void apply_randomizer(int id)
309 size_t j, rand_max = packet_dyn[id].rlen;
311 for (j = 0; j < rand_max; ++j) {
312 uint8_t val = (uint8_t) rand();
313 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
315 packets[id].payload[randomizer->off] = val;
319 static void apply_csum16(int id)
321 size_t j, csum_max = packet_dyn[id].slen;
323 for (j = 0; j < csum_max; ++j) {
324 uint16_t sum = 0;
325 struct csum16 *csum = &packet_dyn[id].csum[j];
327 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
328 if (unlikely((size_t) csum->to >= packets[id].len))
329 csum->to = packets[id].len - 1;
331 switch (csum->which) {
332 case CSUM_IP:
333 sum = calc_csum(packets[id].payload + csum->from,
334 csum->to - csum->from + 1, 0);
335 break;
336 case CSUM_UDP:
337 sum = p4_csum((void *) packets[id].payload + csum->from,
338 packets[id].payload + csum->to,
339 (packets[id].len - csum->to),
340 IPPROTO_UDP);
341 break;
342 case CSUM_TCP:
343 sum = p4_csum((void *) packets[id].payload + csum->from,
344 packets[id].payload + csum->to,
345 (packets[id].len - csum->to),
346 IPPROTO_TCP);
347 break;
348 case CSUM_UDP6:
349 sum = p6_csum((void *) packets[id].payload + csum->from,
350 packets[id].payload + csum->to,
351 (packets[id].len - csum->to),
352 IPPROTO_UDP);
353 break;
354 case CSUM_TCP6:
355 sum = p6_csum((void *) packets[id].payload + csum->from,
356 packets[id].payload + csum->to,
357 (packets[id].len - csum->to),
358 IPPROTO_TCP);
359 break;
360 default:
361 bug();
362 break;
365 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
369 static void preprocess_packets(void)
371 size_t i;
373 for (i = 0; i < plen; i++) {
374 struct packet_dyn *pktd = &packet_dyn[i];
376 if (packet_dyn_has_only_csums(pktd)) {
377 apply_csum16(i);
378 pktd->slen = 0;
379 xfree(pktd->csum);
384 static struct cpu_stats *setup_shared_var(unsigned int cpus)
386 int fd;
387 size_t len = cpus * sizeof(struct cpu_stats);
388 char *zbuff, file[256];
389 struct cpu_stats *buff;
391 zbuff = xzmalloc(len);
392 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
394 fd = creat(file, S_IRUSR | S_IWUSR);
395 bug_on(fd < 0);
396 close(fd);
398 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
399 S_IRUSR | S_IWUSR);
400 write_or_die(fd, zbuff, len);
401 xfree(zbuff);
403 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
404 MAP_SHARED, fd, 0);
405 if (buff == MAP_FAILED)
406 panic("Cannot setup shared variable!\n");
408 close(fd);
409 unlink(file);
411 memset(buff, 0, len);
412 return buff;
415 static void destroy_shared_var(void *buff, unsigned int cpus)
417 munmap(buff, cpus * sizeof(struct cpu_stats));
420 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
422 size_t i;
424 printf("{");
425 for (i = 0; i < len; ++i) {
426 if (i % 15 == 0)
427 printf("\n ");
428 printf("0x%02x, ", payload[i]);
430 printf("\n}\n");
431 fflush(stdout);
434 static int xmit_smoke_setup(struct ctx *ctx)
436 int icmp_sock, ret, ttl = 64;
437 struct icmp_filter filter;
439 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
440 if (icmp_sock < 0)
441 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
443 filter.data = ~(1 << ICMP_ECHOREPLY);
445 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
446 if (ret < 0)
447 panic("Cannot install filter!\n");
449 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
450 if (ret < 0)
451 panic("Cannot set TTL!\n");
453 memset(&ctx->dest, 0, sizeof(ctx->dest));
454 ctx->dest.sin_family = AF_INET;
455 ctx->dest.sin_port = 0;
457 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
458 if (ret < 0)
459 panic("Cannot resolve address!\n");
461 return icmp_sock;
464 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
466 int ret;
467 unsigned int i, j;
468 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
469 uint8_t outpack[512], *data;
470 struct icmphdr *icmp;
471 struct iphdr *ip;
472 size_t len = sizeof(*icmp) + 56;
473 struct sockaddr_in from;
474 socklen_t from_len;
475 struct pollfd fds = {
476 .fd = icmp_sock,
477 .events = POLLIN,
480 fmemset(idstore, 0, sizeof(idstore));
481 for (j = 0; j < SMOKE_N_PROBES; j++) {
482 while ((ident = htons((short) rand())) == 0)
483 sleep(0);
484 idstore[j] = ident;
486 memset(outpack, 0, sizeof(outpack));
487 icmp = (void *) outpack;
488 icmp->type = ICMP_ECHO;
489 icmp->un.echo.id = ident;
490 icmp->un.echo.sequence = htons(cnt++);
492 data = ((uint8_t *) outpack + sizeof(*icmp));
493 for (i = 0; i < 56; ++i)
494 data[i] = (uint8_t) rand();
496 icmp->checksum = csum((unsigned short *) outpack,
497 len / sizeof(unsigned short));
499 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
500 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
501 if (unlikely(ret != (int) len))
502 panic("Cannot send out probe: %s!\n", strerror(errno));
504 ret = poll(&fds, 1, 50);
505 if (ret < 0)
506 panic("Poll failed!\n");
508 if (fds.revents & POLLIN) {
509 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
510 (struct sockaddr *) &from, &from_len);
511 if (unlikely(ret <= 0))
512 panic("Probe receive failed!\n");
513 if (unlikely(from_len != sizeof(ctx->dest)))
514 continue;
515 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
516 continue;
517 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
518 continue;
519 ip = (void *) outpack;
520 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
521 continue;
522 icmp = (void *) outpack + ip->ihl * 4;
523 for (i = 0; i < array_size(idstore); ++i) {
524 if (unlikely(icmp->un.echo.id != idstore[i]))
525 continue;
526 return 0;
531 return -1;
534 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
536 int ret, icmp_sock = -1;
537 unsigned long num = 1, i = 0;
538 struct timeval start, end, diff;
539 unsigned long long tx_bytes = 0, tx_packets = 0;
540 struct packet_dyn *pktd;
541 struct sockaddr_ll saddr = {
542 .sll_family = PF_PACKET,
543 .sll_halen = ETH_ALEN,
544 .sll_ifindex = device_ifindex(ctx->device),
547 if (ctx->num > 0)
548 num = ctx->num;
549 if (ctx->num == 0 && orig_num > 0)
550 num = 0;
552 if (ctx->smoke_test)
553 icmp_sock = xmit_smoke_setup(ctx);
555 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
557 preprocess_packets();
559 bug_on(gettimeofday(&start, NULL));
561 while (likely(sigint == 0 && num > 0 && plen > 0)) {
562 pktd = &packet_dyn[i];
563 if (packet_dyn_has_elems(pktd)) {
564 apply_counter(i);
565 apply_randomizer(i);
566 apply_csum16(i);
568 retry:
569 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
570 (struct sockaddr *) &saddr, sizeof(saddr));
571 if (unlikely(ret < 0)) {
572 if (errno == ENOBUFS) {
573 sched_yield();
574 goto retry;
576 if (ctx->smoke_test)
577 panic("Sendto error: %s!\n", strerror(errno));
580 tx_bytes += packets[i].len;
581 tx_packets++;
583 if (ctx->smoke_test) {
584 ret = xmit_smoke_probe(icmp_sock, ctx);
585 if (unlikely(ret < 0)) {
586 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
587 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
588 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
589 i, seed);
591 dump_trafgen_snippet(packets[i].payload, packets[i].len);
592 break;
596 if (!ctx->rand) {
597 i++;
598 if (i >= plen)
599 i = 0;
600 } else
601 i = rand() % plen;
603 if (ctx->num > 0)
604 num--;
606 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
607 nanosleep(&ctx->gap, NULL);
610 bug_on(gettimeofday(&end, NULL));
611 timersub(&end, &start, &diff);
613 if (ctx->smoke_test)
614 close(icmp_sock);
616 stats[cpu].tx_packets = tx_packets;
617 stats[cpu].tx_bytes = tx_bytes;
618 stats[cpu].tv_sec = diff.tv_sec;
619 stats[cpu].tv_usec = diff.tv_usec;
621 stats[cpu].state |= CPU_STATS_STATE_RES;
624 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
626 int ifindex = device_ifindex(ctx->device);
627 uint8_t *out = NULL;
628 unsigned int it = 0;
629 unsigned long num = 1, i = 0;
630 size_t size = ring_size(ctx->device, ctx->reserve_size);
631 struct ring tx_ring;
632 struct frame_map *hdr;
633 struct timeval start, end, diff;
634 struct packet_dyn *pktd;
635 unsigned long long tx_bytes = 0, tx_packets = 0;
637 set_sock_prio(sock, 512);
639 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
641 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
643 if (ctx->num > 0)
644 num = ctx->num;
645 if (ctx->num == 0 && orig_num > 0)
646 num = 0;
648 preprocess_packets();
650 bug_on(gettimeofday(&start, NULL));
652 while (likely(sigint == 0 && num > 0 && plen > 0)) {
653 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
654 int ret = pull_and_flush_tx_ring(sock);
655 if (unlikely(ret < 0)) {
656 /* We could hit EBADF if the socket has been closed before
657 * the timer was triggered.
659 if (errno != EBADF && errno != ENOBUFS)
660 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
663 continue;
666 hdr = tx_ring.frames[it].iov_base;
667 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
669 hdr->tp_h.tp_snaplen = packets[i].len;
670 hdr->tp_h.tp_len = packets[i].len;
672 pktd = &packet_dyn[i];
673 if (packet_dyn_has_elems(pktd)) {
674 apply_counter(i);
675 apply_randomizer(i);
676 apply_csum16(i);
679 fmemcpy(out, packets[i].payload, packets[i].len);
681 tx_bytes += packets[i].len;
682 tx_packets++;
684 if (!ctx->rand) {
685 i++;
686 if (i >= plen)
687 i = 0;
688 } else
689 i = rand() % plen;
691 kernel_may_pull_from_tx(&hdr->tp_h);
693 it++;
694 if (it >= tx_ring.layout.tp_frame_nr)
695 it = 0;
697 if (ctx->num > 0)
698 num--;
701 bug_on(gettimeofday(&end, NULL));
702 timersub(&end, &start, &diff);
704 pull_and_flush_tx_ring_wait(sock);
705 destroy_tx_ring(sock, &tx_ring);
707 stats[cpu].tx_packets = tx_packets;
708 stats[cpu].tx_bytes = tx_bytes;
709 stats[cpu].tv_sec = diff.tv_sec;
710 stats[cpu].tv_usec = diff.tv_usec;
712 stats[cpu].state |= CPU_STATS_STATE_RES;
715 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
717 stats[cpu].state = s;
720 static inline sig_atomic_t __get_state(unsigned int cpu)
722 return stats[cpu].state;
725 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
727 unsigned int i;
728 unsigned long total;
730 for (i = 0, total = plen; i < ctx->cpus; i++) {
731 if (i == cpu)
732 continue;
734 while ((__get_state(i) &
735 (CPU_STATS_STATE_CFG |
736 CPU_STATS_STATE_RES)) == 0 &&
737 sigint == 0)
738 sched_yield();
740 total += stats[i].cf_packets;
743 return total;
746 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
748 unsigned int i;
749 unsigned long total;
750 int cpu_sel;
751 long long delta_correction = 0;
753 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
754 if (i == cpu)
755 continue;
757 while ((__get_state(i) &
758 (CPU_STATS_STATE_CHK |
759 CPU_STATS_STATE_RES)) == 0 &&
760 sigint == 0)
761 sched_yield();
763 total += stats[i].cd_packets;
766 if (total > orig)
767 delta_correction = -1 * ((long long) total - orig);
768 if (total < orig)
769 delta_correction = +1 * ((long long) orig - total);
771 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
772 if (stats[i].cd_packets > 0) {
773 if ((long long) stats[i].cd_packets +
774 delta_correction >= 0) {
775 cpu_sel = i;
776 break;
781 if ((int) cpu == cpu_sel)
782 ctx->num += delta_correction;
785 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
786 sig_atomic_t s)
788 stats[cpu].cf_packets = p;
789 stats[cpu].cf_bytes = b;
790 stats[cpu].state = s;
793 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
795 stats[cpu].cd_packets = p;
796 stats[cpu].state = s;
799 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
801 unsigned long plen_total, orig = ctx->num;
802 size_t total_len = 0;
803 unsigned int i;
805 bug_on(plen != dlen);
807 for (i = 0; i < plen; ++i)
808 total_len += packets[i].len;
810 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
811 plen_total = __wait_and_sum_others(ctx, cpu);
813 if (orig > 0) {
814 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
816 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
817 CPU_STATS_STATE_CFG);
818 __correct_global_delta(ctx, cpu, orig);
821 if (plen == 0) {
822 __set_state(cpu, CPU_STATS_STATE_RES);
823 return;
827 static void main_loop(struct ctx *ctx, char *confname, bool slow,
828 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
830 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
831 xmit_packet_precheck(ctx, cpu);
833 if (cpu == 0) {
834 unsigned int i;
835 size_t total_len = 0, total_pkts = 0;
837 for (i = 0; i < ctx->cpus; ++i) {
838 total_len += stats[i].cf_bytes;
839 total_pkts += stats[i].cf_packets;
842 printf("%6zu packets to schedule\n", total_pkts);
843 printf("%6zu bytes in total\n", total_len);
844 printf("Running! Hang up with ^C!\n\n");
845 fflush(stdout);
848 sock = pf_socket();
850 if (ctx->qdisc_path == false)
851 set_sock_qdisc_bypass(sock, ctx->verbose);
853 if (slow)
854 xmit_slowpath_or_die(ctx, cpu, orig_num);
855 else
856 xmit_fastpath_or_die(ctx, cpu, orig_num);
858 close(sock);
860 cleanup_packets();
863 static unsigned int generate_srand_seed(void)
865 int fd;
866 unsigned int _seed;
868 fd = open("/dev/urandom", O_RDONLY);
869 if (fd < 0)
870 return time(NULL);
872 read_or_die(fd, &_seed, sizeof(_seed));
874 close(fd);
875 return _seed;
878 static void on_panic_del_rfmon(void *arg)
880 leave_rfmon_mac80211(arg);
883 int main(int argc, char **argv)
885 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
886 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
887 int c, opt_index, vals[4] = {0}, irq;
888 uint64_t gap = 0;
889 unsigned int i, j;
890 char *confname = NULL, *ptr;
891 unsigned long cpus_tmp, orig_num = 0;
892 unsigned long long tx_packets, tx_bytes;
893 struct ctx ctx;
895 fmemset(&ctx, 0, sizeof(ctx));
896 ctx.cpus = get_number_cpus_online();
897 ctx.uid = getuid();
898 ctx.gid = getgid();
899 ctx.qdisc_path = false;
901 /* Keep an initial small default size to reduce cache-misses. */
902 ctx.reserve_size = 512 * (1 << 10);
904 while ((c = getopt_long(argc, argv, short_options, long_options,
905 &opt_index)) != EOF) {
906 switch (c) {
907 case 'h':
908 help();
909 break;
910 case 'v':
911 version();
912 break;
913 case 'C':
914 cpustats = false;
915 break;
916 case 'e':
917 example();
918 break;
919 case 'p':
920 invoke_cpp = true;
921 break;
922 case 'V':
923 ctx.verbose = true;
924 break;
925 case 'P':
926 cpus_tmp = strtoul(optarg, NULL, 0);
927 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
928 ctx.cpus = cpus_tmp;
929 break;
930 case 'd':
931 case 'o':
932 ctx.device = xstrndup(optarg, IFNAMSIZ);
933 break;
934 case 'H':
935 prio_high = true;
936 break;
937 case 'A':
938 set_sock_mem = false;
939 break;
940 case 'Q':
941 set_irq_aff = false;
942 break;
943 case 'q':
944 ctx.qdisc_path = true;
945 break;
946 case 'r':
947 ctx.rand = true;
948 break;
949 case 's':
950 slow = true;
951 ctx.cpus = 1;
952 ctx.smoke_test = true;
953 ctx.rhost = xstrdup(optarg);
954 break;
955 case 'R':
956 ctx.rfraw = true;
957 break;
958 case 'J':
959 ctx.jumbo_support = true;
960 break;
961 case 'c':
962 case 'i':
963 confname = xstrdup(optarg);
964 if (!strncmp("-", confname, strlen("-")))
965 ctx.cpus = 1;
966 break;
967 case 'u':
968 ctx.uid = strtoul(optarg, NULL, 0);
969 ctx.enforce = true;
970 break;
971 case 'g':
972 ctx.gid = strtoul(optarg, NULL, 0);
973 ctx.enforce = true;
974 break;
975 case 'k':
976 printf("Option -k/--kernel-pull is no longer used and "
977 "will be removed in a future release!\n");
978 break;
979 case 'E':
980 seed = strtoul(optarg, NULL, 0);
981 reseed = false;
982 break;
983 case 'n':
984 orig_num = strtoul(optarg, NULL, 0);
985 ctx.num = orig_num;
986 break;
987 case 't':
988 slow = true;
989 ptr = optarg;
990 prctl(PR_SET_TIMERSLACK, 1UL);
991 gap = strtoul(optarg, NULL, 0);
993 for (j = i = strlen(optarg); i > 0; --i) {
994 if (!isdigit(optarg[j - i]))
995 break;
996 ptr++;
999 if (!strncmp(ptr, "ns", strlen("ns"))) {
1000 ctx.gap.tv_sec = gap / 1000000000;
1001 ctx.gap.tv_nsec = gap % 1000000000;
1002 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1003 /* Default to microseconds for backwards
1004 * compatibility if no postfix is given.
1006 ctx.gap.tv_sec = gap / 1000000;
1007 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
1008 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1009 ctx.gap.tv_sec = gap / 1000;
1010 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1011 } else if (!strncmp(ptr, "s", strlen("s"))) {
1012 ctx.gap.tv_sec = gap;
1013 ctx.gap.tv_nsec = 0;
1014 } else
1015 panic("Syntax error in time param!\n");
1017 if (gap > 0)
1018 /* Fall back to single core to not mess up
1019 * correct timing. We are slow anyway!
1021 ctx.cpus = 1;
1022 break;
1023 case 'S':
1024 ptr = optarg;
1026 for (j = i = strlen(optarg); i > 0; --i) {
1027 if (!isdigit(optarg[j - i]))
1028 break;
1029 ptr++;
1032 if (!strncmp(ptr, "KiB", strlen("KiB")))
1033 ctx.reserve_size = 1 << 10;
1034 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1035 ctx.reserve_size = 1 << 20;
1036 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1037 ctx.reserve_size = 1 << 30;
1038 else
1039 panic("Syntax error in ring size param!\n");
1041 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1042 break;
1043 case '?':
1044 switch (optopt) {
1045 case 'd':
1046 case 'c':
1047 case 'n':
1048 case 'S':
1049 case 's':
1050 case 'P':
1051 case 'o':
1052 case 'E':
1053 case 'i':
1054 case 'k':
1055 case 'u':
1056 case 'g':
1057 case 't':
1058 panic("Option -%c requires an argument!\n",
1059 optopt);
1060 default:
1061 if (isprint(optopt))
1062 printf("Unknown option character `0x%X\'!\n", optopt);
1063 die();
1065 default:
1066 break;
1070 if (argc < 5)
1071 help();
1072 if (ctx.device == NULL)
1073 panic("No networking device given!\n");
1074 if (confname == NULL)
1075 panic("No configuration file given!\n");
1076 if (device_mtu(ctx.device) == 0)
1077 panic("This is no networking device!\n");
1079 register_signal(SIGINT, signal_handler);
1080 register_signal(SIGQUIT, signal_handler);
1081 register_signal(SIGTERM, signal_handler);
1082 register_signal(SIGHUP, signal_handler);
1084 if (prio_high) {
1085 set_proc_prio(-20);
1086 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1089 if (set_sock_mem)
1090 set_system_socket_memory(vals, array_size(vals));
1091 xlockme();
1093 if (ctx.rfraw) {
1094 ctx.device_trans = xstrdup(ctx.device);
1095 xfree(ctx.device);
1097 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1098 panic_handler_add(on_panic_del_rfmon, ctx.device);
1099 sleep(0);
1103 * If number of packets is smaller than number of CPUs use only as
1104 * many CPUs as there are packets. Otherwise we end up sending more
1105 * packets than intended or none at all.
1107 if (ctx.num)
1108 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1110 irq = device_irq_number(ctx.device);
1111 if (set_irq_aff)
1112 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1114 stats = setup_shared_var(ctx.cpus);
1116 for (i = 0; i < ctx.cpus; i++) {
1117 pid_t pid = fork();
1119 switch (pid) {
1120 case 0:
1121 if (reseed)
1122 seed = generate_srand_seed();
1123 srand(seed);
1125 cpu_affinity(i);
1126 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1128 goto thread_out;
1129 case -1:
1130 panic("Cannot fork processes!\n");
1134 for (i = 0; i < ctx.cpus; i++) {
1135 int status;
1137 wait(&status);
1138 if (WEXITSTATUS(status) == EXIT_FAILURE)
1139 die();
1142 if (ctx.rfraw)
1143 leave_rfmon_mac80211(ctx.device);
1145 if (set_sock_mem)
1146 reset_system_socket_memory(vals, array_size(vals));
1148 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1149 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1150 sched_yield();
1152 tx_packets += stats[i].tx_packets;
1153 tx_bytes += stats[i].tx_bytes;
1156 fflush(stdout);
1157 printf("\n");
1158 printf("\r%12llu packets outgoing\n", tx_packets);
1159 printf("\r%12llu bytes outgoing\n", tx_bytes);
1160 for (i = 0; cpustats && i < ctx.cpus; i++) {
1161 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1162 stats[i].tv_sec, stats[i].tv_usec, i,
1163 stats[i].tx_packets);
1166 thread_out:
1167 xunlockme();
1168 destroy_shared_var(stats, ctx.cpus);
1169 if (set_irq_aff)
1170 device_restore_irq_affinity_list();
1172 free(ctx.device);
1173 free(ctx.device_trans);
1174 free(ctx.rhost);
1175 free(confname);
1177 return 0;