trafgen: Added option to pass macro/define for C preprocessor
[netsniff-ng.git] / trafgen.c
blobdf2ecf4c27cd9c85f17c0cebdab86ab86d3cb1a0
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;
67 char *packet_str;
70 struct cpu_stats {
71 unsigned long tv_sec, tv_usec;
72 unsigned long long tx_packets, tx_bytes;
73 unsigned long long cf_packets, cf_bytes;
74 unsigned long long cd_packets;
75 sig_atomic_t state;
78 static sig_atomic_t sigint = 0;
80 struct packet *packets = NULL;
81 size_t plen = 0;
83 struct packet_dyn *packet_dyn = NULL;
84 size_t dlen = 0;
86 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQqD:";
87 static const struct option long_options[] = {
88 {"dev", required_argument, NULL, 'd'},
89 {"out", required_argument, NULL, 'o'},
90 {"in", required_argument, NULL, 'i'},
91 {"conf", required_argument, NULL, 'c'},
92 {"num", required_argument, NULL, 'n'},
93 {"gap", required_argument, NULL, 't'},
94 {"cpus", required_argument, NULL, 'P'},
95 {"ring-size", required_argument, NULL, 'S'},
96 {"kernel-pull", required_argument, NULL, 'k'},
97 {"smoke-test", required_argument, NULL, 's'},
98 {"seed", required_argument, NULL, 'E'},
99 {"user", required_argument, NULL, 'u'},
100 {"group", required_argument, NULL, 'g'},
101 {"prio-high", no_argument, NULL, 'H'},
102 {"notouch-irq", no_argument, NULL, 'Q'},
103 {"no-sock-mem", no_argument, NULL, 'A'},
104 {"qdisc-path", no_argument, NULL, 'q'},
105 {"jumbo-support", no_argument, NULL, 'J'},
106 {"no-cpu-stats", no_argument, NULL, 'C'},
107 {"cpp", no_argument, NULL, 'p'},
108 {"define", required_argument, NULL, 'D'},
109 {"rfraw", no_argument, NULL, 'R'},
110 {"rand", no_argument, NULL, 'r'},
111 {"verbose", no_argument, NULL, 'V'},
112 {"version", no_argument, NULL, 'v'},
113 {"example", no_argument, NULL, 'e'},
114 {"help", no_argument, NULL, 'h'},
115 {NULL, 0, NULL, 0}
118 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
119 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
120 "Swiss federal institute of technology (ETH Zurich)\n"
121 "License: GNU GPL version 2.0\n"
122 "This is free software: you are free to change and redistribute it.\n"
123 "There is NO WARRANTY, to the extent permitted by law.";
125 static int sock;
126 static struct cpu_stats *stats;
127 static unsigned int seed;
129 #define CPU_STATS_STATE_CFG 1
130 #define CPU_STATS_STATE_CHK 2
131 #define CPU_STATS_STATE_RES 4
133 #ifndef ICMP_FILTER
134 # define ICMP_FILTER 1
136 struct icmp_filter {
137 __u32 data;
139 #endif
141 #define SMOKE_N_PROBES 100
143 #define PKT_MIN_LEN 14
145 static void signal_handler(int number)
147 switch (number) {
148 case SIGINT:
149 case SIGQUIT:
150 case SIGTERM:
151 sigint = 1;
152 case SIGHUP:
153 default:
154 break;
158 static void __noreturn help(void)
160 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
161 puts("http://www.netsniff-ng.org\n\n"
162 "Usage: trafgen [options] [packet]\n"
163 "Options:\n"
164 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
165 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
166 " -p|--cpp Run packet config through C preprocessor\n"
167 " -D|--define Add macro/define for C preprocessor\n"
168 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
169 " -R|--rfraw Inject raw 802.11 frames\n"
170 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
171 " -n|--num <uint> Number of packets until exit (def: 0)\n"
172 " -r|--rand Randomize packet selection (def: round robin)\n"
173 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
174 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
175 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
176 " -E|--seed <uint> Manually set srand(3) seed\n"
177 " -u|--user <userid> Drop privileges and change to userid\n"
178 " -g|--group <groupid> Drop privileges and change to groupid\n"
179 " -H|--prio-high Make this high priority process\n"
180 " -A|--no-sock-mem Don't tune core socket memory\n"
181 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
182 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
183 " -V|--verbose Be more verbose\n"
184 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
185 " -v|--version Show version and exit\n"
186 " -e|--example Show built-in packet config example\n"
187 " -h|--help Guess what?!\n\n"
188 "Examples:\n"
189 " trafgen --dev eth0 --conf trafgen.cfg\n"
190 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
191 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
192 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
193 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
194 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
195 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
196 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
197 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
198 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
199 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
200 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
201 "Generate config files from existing pcap using netsniff-ng:\n"
202 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
203 "Note:\n"
204 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
205 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
206 " we assume the kernel crashed, thus we print the packet and quit.\n"
207 " In case you find a ping-of-death, please mention trafgen in your\n"
208 " commit message of the fix!\n\n"
209 " For introducing bit errors, delays with random variation and more,\n"
210 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
211 " For generating different package distributions, you can use scripting\n"
212 " to generate a trafgen config file with packet ratios as:\n\n"
213 " IMIX 64:7, 570:4, 1518:1\n"
214 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
215 " Cisco 64:7, 594:4, 1518:1\n"
216 " RPR Trimodal 64:60, 512:20, 1518:20\n"
217 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
218 puts(copyright);
219 die();
222 static void __noreturn example(void)
224 const char *e =
225 "/* Note: dynamic elements make trafgen slower! */\n"
226 "#include <stddef.h>\n\n"
227 "{\n"
228 " /* MAC Destination */\n"
229 " fill(0xff, ETH_ALEN),\n"
230 " /* MAC Source */\n"
231 " 0x00, 0x02, 0xb3, drnd(3),\n"
232 " /* IPv4 Protocol */\n"
233 " c16(ETH_P_IP),\n"
234 " /* IPv4 Version, IHL, TOS */\n"
235 " 0b01000101, 0,\n"
236 " /* IPv4 Total Len */\n"
237 " c16(59),\n"
238 " /* IPv4 Ident */\n"
239 " drnd(2),\n"
240 " /* IPv4 Flags, Frag Off */\n"
241 " 0b01000000, 0,\n"
242 " /* IPv4 TTL */\n"
243 " 64,\n"
244 " /* Proto TCP */\n"
245 " 0x06,\n"
246 " /* IPv4 Checksum (IP header from, to) */\n"
247 " csumip(14, 33),\n"
248 " /* Source IP */\n"
249 " drnd(4),\n"
250 " /* Dest IP */\n"
251 " drnd(4),\n"
252 " /* TCP Source Port */\n"
253 " drnd(2),\n"
254 " /* TCP Dest Port */\n"
255 " c16(80),\n"
256 " /* TCP Sequence Number */\n"
257 " drnd(4),\n"
258 " /* TCP Ackn. Number */\n"
259 " c32(0),\n"
260 " /* TCP Header length + TCP SYN/ECN Flag */\n"
261 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
262 " /* Window Size */\n"
263 " c16(16),\n"
264 " /* TCP Checksum (offset IP, offset TCP) */\n"
265 " csumtcp(14, 34),\n"
266 " /* TCP Options */\n"
267 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
268 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
269 " /* Data blob */\n"
270 " \"gotcha!\",\n"
271 "}";
272 puts(e);
273 die();
276 static void __noreturn version(void)
278 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
279 puts("multithreaded zero-copy network packet generator\n"
280 "http://www.netsniff-ng.org\n");
281 puts(copyright);
282 die();
285 static void apply_counter(int id)
287 size_t j, counter_max = packet_dyn[id].clen;
289 for (j = 0; j < counter_max; ++j) {
290 uint8_t val;
291 struct counter *counter = &packet_dyn[id].cnt[j];
293 val = counter->val - counter->min;
295 switch (counter->type) {
296 case TYPE_INC:
297 val = (val + counter->inc) % (counter->max - counter->min + 1);
298 break;
299 case TYPE_DEC:
300 val = (val - counter->inc) % (counter->min - counter->max + 1);
301 break;
302 default:
303 bug();
306 counter->val = val + counter->min;
307 packets[id].payload[counter->off] = val;
311 static void apply_randomizer(int id)
313 size_t j, rand_max = packet_dyn[id].rlen;
315 for (j = 0; j < rand_max; ++j) {
316 uint8_t val = (uint8_t) rand();
317 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
319 packets[id].payload[randomizer->off] = val;
323 static void apply_csum16(int id)
325 size_t j, csum_max = packet_dyn[id].slen;
327 for (j = 0; j < csum_max; ++j) {
328 uint16_t sum = 0;
329 struct csum16 *csum = &packet_dyn[id].csum[j];
331 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
332 if (unlikely((size_t) csum->to >= packets[id].len))
333 csum->to = packets[id].len - 1;
335 switch (csum->which) {
336 case CSUM_IP:
337 sum = calc_csum(packets[id].payload + csum->from,
338 csum->to - csum->from + 1);
339 break;
340 case CSUM_UDP:
341 sum = p4_csum((void *) packets[id].payload + csum->from,
342 packets[id].payload + csum->to,
343 (packets[id].len - csum->to),
344 IPPROTO_UDP);
345 break;
346 case CSUM_TCP:
347 sum = p4_csum((void *) packets[id].payload + csum->from,
348 packets[id].payload + csum->to,
349 (packets[id].len - csum->to),
350 IPPROTO_TCP);
351 break;
352 case CSUM_UDP6:
353 sum = p6_csum((void *) packets[id].payload + csum->from,
354 packets[id].payload + csum->to,
355 (packets[id].len - csum->to),
356 IPPROTO_UDP);
357 break;
358 case CSUM_TCP6:
359 sum = p6_csum((void *) packets[id].payload + csum->from,
360 packets[id].payload + csum->to,
361 (packets[id].len - csum->to),
362 IPPROTO_TCP);
363 break;
364 default:
365 bug();
366 break;
369 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
373 static void preprocess_packets(void)
375 size_t i;
377 for (i = 0; i < plen; i++) {
378 struct packet_dyn *pktd = &packet_dyn[i];
380 if (packet_dyn_has_only_csums(pktd)) {
381 apply_csum16(i);
382 pktd->slen = 0;
383 xfree(pktd->csum);
388 static struct cpu_stats *setup_shared_var(unsigned int cpus)
390 int fd;
391 size_t len = cpus * sizeof(struct cpu_stats);
392 char *zbuff, file[256];
393 struct cpu_stats *buff;
395 zbuff = xzmalloc(len);
396 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
398 fd = creat(file, S_IRUSR | S_IWUSR);
399 bug_on(fd < 0);
400 close(fd);
402 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
403 S_IRUSR | S_IWUSR);
404 write_or_die(fd, zbuff, len);
405 xfree(zbuff);
407 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
408 MAP_SHARED, fd, 0);
409 if (buff == MAP_FAILED)
410 panic("Cannot setup shared variable!\n");
412 close(fd);
413 unlink(file);
415 memset(buff, 0, len);
416 return buff;
419 static void destroy_shared_var(void *buff, unsigned int cpus)
421 munmap(buff, cpus * sizeof(struct cpu_stats));
424 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
426 size_t i;
428 printf("{");
429 for (i = 0; i < len; ++i) {
430 if (i % 15 == 0)
431 printf("\n ");
432 printf("0x%02x, ", payload[i]);
434 printf("\n}\n");
435 fflush(stdout);
438 static int xmit_smoke_setup(struct ctx *ctx)
440 int icmp_sock, ret, ttl = 64;
441 struct icmp_filter filter;
443 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
444 if (icmp_sock < 0)
445 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
447 filter.data = ~(1 << ICMP_ECHOREPLY);
449 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
450 if (ret < 0)
451 panic("Cannot install filter!\n");
453 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
454 if (ret < 0)
455 panic("Cannot set TTL!\n");
457 memset(&ctx->dest, 0, sizeof(ctx->dest));
458 ctx->dest.sin_family = AF_INET;
459 ctx->dest.sin_port = 0;
461 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
462 if (ret < 0)
463 panic("Cannot resolve address!\n");
465 return icmp_sock;
468 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
470 int ret;
471 unsigned int i, j;
472 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
473 uint8_t outpack[512], *data;
474 struct icmphdr *icmp;
475 struct iphdr *ip;
476 size_t len = sizeof(*icmp) + 56;
477 struct sockaddr_in from;
478 socklen_t from_len;
479 struct pollfd fds = {
480 .fd = icmp_sock,
481 .events = POLLIN,
484 fmemset(idstore, 0, sizeof(idstore));
485 for (j = 0; j < SMOKE_N_PROBES; j++) {
486 while ((ident = htons((short) rand())) == 0)
487 sleep(0);
488 idstore[j] = ident;
490 memset(outpack, 0, sizeof(outpack));
491 icmp = (void *) outpack;
492 icmp->type = ICMP_ECHO;
493 icmp->un.echo.id = ident;
494 icmp->un.echo.sequence = htons(cnt++);
496 data = ((uint8_t *) outpack + sizeof(*icmp));
497 for (i = 0; i < 56; ++i)
498 data[i] = (uint8_t) rand();
500 icmp->checksum = csum((unsigned short *) outpack,
501 len / sizeof(unsigned short));
503 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
504 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
505 if (unlikely(ret != (int) len))
506 panic("Cannot send out probe: %s!\n", strerror(errno));
508 ret = poll(&fds, 1, 50);
509 if (ret < 0)
510 panic("Poll failed!\n");
512 if (fds.revents & POLLIN) {
513 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
514 (struct sockaddr *) &from, &from_len);
515 if (unlikely(ret <= 0))
516 panic("Probe receive failed!\n");
517 if (unlikely(from_len != sizeof(ctx->dest)))
518 continue;
519 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
520 continue;
521 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
522 continue;
523 ip = (void *) outpack;
524 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
525 continue;
526 icmp = (void *) outpack + ip->ihl * 4;
527 for (i = 0; i < array_size(idstore); ++i) {
528 if (unlikely(icmp->un.echo.id != idstore[i]))
529 continue;
530 return 0;
535 return -1;
538 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
540 int ret, icmp_sock = -1;
541 unsigned long num = 1, i = 0;
542 struct timeval start, end, diff;
543 unsigned long long tx_bytes = 0, tx_packets = 0;
544 struct packet_dyn *pktd;
545 struct sockaddr_ll saddr = {
546 .sll_family = PF_PACKET,
547 .sll_halen = ETH_ALEN,
548 .sll_ifindex = device_ifindex(ctx->device),
551 if (ctx->num > 0)
552 num = ctx->num;
553 if (ctx->num == 0 && orig_num > 0)
554 num = 0;
556 if (ctx->smoke_test)
557 icmp_sock = xmit_smoke_setup(ctx);
559 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
561 bug_on(gettimeofday(&start, NULL));
563 while (likely(sigint == 0 && num > 0 && plen > 0)) {
564 pktd = &packet_dyn[i];
565 if (packet_dyn_has_elems(pktd)) {
566 apply_counter(i);
567 apply_randomizer(i);
568 apply_csum16(i);
570 retry:
571 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
572 (struct sockaddr *) &saddr, sizeof(saddr));
573 if (unlikely(ret < 0)) {
574 if (errno == ENOBUFS) {
575 sched_yield();
576 goto retry;
578 if (ctx->smoke_test)
579 panic("Sendto error: %s!\n", strerror(errno));
582 tx_bytes += packets[i].len;
583 tx_packets++;
585 if (ctx->smoke_test) {
586 ret = xmit_smoke_probe(icmp_sock, ctx);
587 if (unlikely(ret < 0)) {
588 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
589 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
590 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
591 i, seed);
593 dump_trafgen_snippet(packets[i].payload, packets[i].len);
594 break;
598 if (!ctx->rand) {
599 i++;
600 if (i >= plen)
601 i = 0;
602 } else
603 i = rand() % plen;
605 if (ctx->num > 0)
606 num--;
608 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
609 nanosleep(&ctx->gap, NULL);
612 bug_on(gettimeofday(&end, NULL));
613 timersub(&end, &start, &diff);
615 if (ctx->smoke_test)
616 close(icmp_sock);
618 stats[cpu].tx_packets = tx_packets;
619 stats[cpu].tx_bytes = tx_bytes;
620 stats[cpu].tv_sec = diff.tv_sec;
621 stats[cpu].tv_usec = diff.tv_usec;
623 stats[cpu].state |= CPU_STATS_STATE_RES;
626 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
628 int ifindex = device_ifindex(ctx->device);
629 uint8_t *out = NULL;
630 unsigned int it = 0;
631 unsigned long num = 1, i = 0;
632 size_t size = ring_size(ctx->device, ctx->reserve_size);
633 struct ring tx_ring;
634 struct frame_map *hdr;
635 struct timeval start, end, diff;
636 struct packet_dyn *pktd;
637 unsigned long long tx_bytes = 0, tx_packets = 0;
639 set_sock_prio(sock, 512);
641 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
643 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
645 if (ctx->num > 0)
646 num = ctx->num;
647 if (ctx->num == 0 && orig_num > 0)
648 num = 0;
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, char **cpp_argv,
829 unsigned long orig_num)
831 if (ctx->packet_str)
832 compile_packets_str(ctx->packet_str, ctx->verbose, cpu);
833 else
834 compile_packets(confname, ctx->verbose, cpu, invoke_cpp, cpp_argv);
836 preprocess_packets();
838 xmit_packet_precheck(ctx, cpu);
840 if (cpu == 0) {
841 unsigned int i;
842 size_t total_len = 0, total_pkts = 0;
844 for (i = 0; i < ctx->cpus; ++i) {
845 total_len += stats[i].cf_bytes;
846 total_pkts += stats[i].cf_packets;
849 printf("%6zu packets to schedule\n", total_pkts);
850 printf("%6zu bytes in total\n", total_len);
851 printf("Running! Hang up with ^C!\n\n");
852 fflush(stdout);
855 sock = pf_socket();
857 if (ctx->qdisc_path == false)
858 set_sock_qdisc_bypass(sock, ctx->verbose);
860 if (slow)
861 xmit_slowpath_or_die(ctx, cpu, orig_num);
862 else
863 xmit_fastpath_or_die(ctx, cpu, orig_num);
865 close(sock);
867 cleanup_packets();
870 static unsigned int generate_srand_seed(void)
872 int fd;
873 unsigned int _seed;
875 fd = open("/dev/urandom", O_RDONLY);
876 if (fd < 0)
877 return time(NULL);
879 read_or_die(fd, &_seed, sizeof(_seed));
881 close(fd);
882 return _seed;
885 static void on_panic_del_rfmon(void *arg)
887 leave_rfmon_mac80211(arg);
890 int main(int argc, char **argv)
892 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
893 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
894 int c, opt_index, vals[4] = {0}, irq;
895 uint64_t gap = 0;
896 unsigned int i, j;
897 char *confname = NULL, *ptr;
898 unsigned long cpus_tmp, orig_num = 0;
899 unsigned long long tx_packets, tx_bytes;
900 struct ctx ctx;
901 int min_opts = 5;
902 char **cpp_argv = NULL;
903 size_t cpp_argc = 0;
905 fmemset(&ctx, 0, sizeof(ctx));
906 ctx.cpus = get_number_cpus_online();
907 ctx.uid = getuid();
908 ctx.gid = getgid();
909 ctx.qdisc_path = false;
911 /* Keep an initial small default size to reduce cache-misses. */
912 ctx.reserve_size = 512 * (1 << 10);
914 while ((c = getopt_long(argc, argv, short_options, long_options,
915 &opt_index)) != EOF) {
916 switch (c) {
917 case 'h':
918 help();
919 break;
920 case 'v':
921 version();
922 break;
923 case 'C':
924 cpustats = false;
925 break;
926 case 'e':
927 example();
928 break;
929 case 'p':
930 invoke_cpp = true;
931 break;
932 case 'D':
933 cpp_argv = argv_insert(cpp_argv, &cpp_argc, "-D");
934 cpp_argv = argv_insert(cpp_argv, &cpp_argc, optarg);
935 break;
936 case 'V':
937 ctx.verbose = true;
938 break;
939 case 'P':
940 cpus_tmp = strtoul(optarg, NULL, 0);
941 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
942 ctx.cpus = cpus_tmp;
943 break;
944 case 'd':
945 case 'o':
946 ctx.device = xstrndup(optarg, IFNAMSIZ);
947 break;
948 case 'H':
949 prio_high = true;
950 break;
951 case 'A':
952 set_sock_mem = false;
953 break;
954 case 'Q':
955 set_irq_aff = false;
956 break;
957 case 'q':
958 ctx.qdisc_path = true;
959 break;
960 case 'r':
961 ctx.rand = true;
962 break;
963 case 's':
964 slow = true;
965 ctx.cpus = 1;
966 ctx.smoke_test = true;
967 ctx.rhost = xstrdup(optarg);
968 break;
969 case 'R':
970 ctx.rfraw = true;
971 break;
972 case 'J':
973 ctx.jumbo_support = true;
974 break;
975 case 'c':
976 case 'i':
977 confname = xstrdup(optarg);
978 if (!strncmp("-", confname, strlen("-")))
979 ctx.cpus = 1;
980 break;
981 case 'u':
982 ctx.uid = strtoul(optarg, NULL, 0);
983 ctx.enforce = true;
984 break;
985 case 'g':
986 ctx.gid = strtoul(optarg, NULL, 0);
987 ctx.enforce = true;
988 break;
989 case 'k':
990 printf("Option -k/--kernel-pull is no longer used and "
991 "will be removed in a future release!\n");
992 break;
993 case 'E':
994 seed = strtoul(optarg, NULL, 0);
995 reseed = false;
996 break;
997 case 'n':
998 orig_num = strtoul(optarg, NULL, 0);
999 ctx.num = orig_num;
1000 break;
1001 case 't':
1002 slow = true;
1003 ptr = optarg;
1004 prctl(PR_SET_TIMERSLACK, 1UL);
1005 gap = strtoul(optarg, NULL, 0);
1007 for (j = i = strlen(optarg); i > 0; --i) {
1008 if (!isdigit(optarg[j - i]))
1009 break;
1010 ptr++;
1013 if (!strncmp(ptr, "ns", strlen("ns"))) {
1014 ctx.gap.tv_sec = gap / 1000000000;
1015 ctx.gap.tv_nsec = gap % 1000000000;
1016 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1017 /* Default to microseconds for backwards
1018 * compatibility if no postfix is given.
1020 ctx.gap.tv_sec = gap / 1000000;
1021 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
1022 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1023 ctx.gap.tv_sec = gap / 1000;
1024 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1025 } else if (!strncmp(ptr, "s", strlen("s"))) {
1026 ctx.gap.tv_sec = gap;
1027 ctx.gap.tv_nsec = 0;
1028 } else
1029 panic("Syntax error in time param!\n");
1031 if (gap > 0)
1032 /* Fall back to single core to not mess up
1033 * correct timing. We are slow anyway!
1035 ctx.cpus = 1;
1036 break;
1037 case 'S':
1038 ptr = optarg;
1040 for (j = i = strlen(optarg); i > 0; --i) {
1041 if (!isdigit(optarg[j - i]))
1042 break;
1043 ptr++;
1046 if (!strncmp(ptr, "KiB", strlen("KiB")))
1047 ctx.reserve_size = 1 << 10;
1048 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1049 ctx.reserve_size = 1 << 20;
1050 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1051 ctx.reserve_size = 1 << 30;
1052 else
1053 panic("Syntax error in ring size param!\n");
1055 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1056 break;
1057 case '?':
1058 switch (optopt) {
1059 case 'd':
1060 case 'c':
1061 case 'n':
1062 case 'S':
1063 case 's':
1064 case 'P':
1065 case 'o':
1066 case 'E':
1067 case 'i':
1068 case 'k':
1069 case 'u':
1070 case 'g':
1071 case 't':
1072 panic("Option -%c requires an argument!\n",
1073 optopt);
1074 default:
1075 if (isprint(optopt))
1076 printf("Unknown option character `0x%X\'!\n", optopt);
1077 die();
1079 default:
1080 break;
1084 if (argc >= optind) {
1085 min_opts = 4;
1086 ctx.packet_str = argv2str(optind, argc, argv);
1089 if (argc < min_opts)
1090 help();
1091 if (ctx.device == NULL)
1092 panic("No networking device given!\n");
1093 if (confname == NULL && !ctx.packet_str)
1094 panic("No configuration file or packet string given!\n");
1095 if (device_mtu(ctx.device) == 0)
1096 panic("This is no networking device!\n");
1098 register_signal(SIGINT, signal_handler);
1099 register_signal(SIGQUIT, signal_handler);
1100 register_signal(SIGTERM, signal_handler);
1101 register_signal(SIGHUP, signal_handler);
1103 if (prio_high) {
1104 set_proc_prio(-20);
1105 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1108 if (set_sock_mem)
1109 set_system_socket_memory(vals, array_size(vals));
1110 xlockme();
1112 if (ctx.rfraw) {
1113 ctx.device_trans = xstrdup(ctx.device);
1114 xfree(ctx.device);
1116 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1117 panic_handler_add(on_panic_del_rfmon, ctx.device);
1118 sleep(0);
1122 * If number of packets is smaller than number of CPUs use only as
1123 * many CPUs as there are packets. Otherwise we end up sending more
1124 * packets than intended or none at all.
1126 if (ctx.num)
1127 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1129 irq = device_irq_number(ctx.device);
1130 if (set_irq_aff)
1131 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1133 stats = setup_shared_var(ctx.cpus);
1135 for (i = 0; i < ctx.cpus; i++) {
1136 pid_t pid = fork();
1138 switch (pid) {
1139 case 0:
1140 if (reseed)
1141 seed = generate_srand_seed();
1142 srand(seed);
1144 cpu_affinity(i);
1145 main_loop(&ctx, confname, slow, i, invoke_cpp,
1146 cpp_argv, orig_num);
1148 goto thread_out;
1149 case -1:
1150 panic("Cannot fork processes!\n");
1154 for (i = 0; i < ctx.cpus; i++) {
1155 int status;
1157 wait(&status);
1158 if (WEXITSTATUS(status) == EXIT_FAILURE)
1159 die();
1162 if (ctx.rfraw)
1163 leave_rfmon_mac80211(ctx.device);
1165 if (set_sock_mem)
1166 reset_system_socket_memory(vals, array_size(vals));
1168 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1169 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1170 sched_yield();
1172 tx_packets += stats[i].tx_packets;
1173 tx_bytes += stats[i].tx_bytes;
1176 fflush(stdout);
1177 printf("\n");
1178 printf("\r%12llu packets outgoing\n", tx_packets);
1179 printf("\r%12llu bytes outgoing\n", tx_bytes);
1180 for (i = 0; cpustats && i < ctx.cpus; i++) {
1181 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1182 stats[i].tv_sec, stats[i].tv_usec, i,
1183 stats[i].tx_packets);
1186 thread_out:
1187 xunlockme();
1188 destroy_shared_var(stats, ctx.cpus);
1189 if (set_irq_aff)
1190 device_restore_irq_affinity_list();
1192 argv_free(cpp_argv);
1193 free(ctx.device);
1194 free(ctx.device_trans);
1195 free(ctx.rhost);
1196 free(confname);
1197 free(ctx.packet_str);
1199 return 0;