netsniff-ng: Move variable definition
[netsniff-ng.git] / trafgen.c
blob52d980463cfdeed6fe8824b460eb3925856242a8
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/stat.h>
18 #include <sys/time.h>
19 #include <sys/wait.h>
20 #include <sys/mman.h>
21 #include <net/ethernet.h>
22 #include <netinet/in.h>
23 #include <netinet/ip.h>
24 #include <linux/icmp.h>
25 #include <linux/if.h>
26 #include <arpa/inet.h>
27 #include <signal.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <poll.h>
33 #include <netdb.h>
34 #include <math.h>
35 #include <unistd.h>
37 #include "xmalloc.h"
38 #include "die.h"
39 #include "str.h"
40 #include "sig.h"
41 #include "sock.h"
42 #include "cpus.h"
43 #include "lockme.h"
44 #include "privs.h"
45 #include "proc.h"
46 #include "mac80211.h"
47 #include "ioops.h"
48 #include "irq.h"
49 #include "config.h"
50 #include "built_in.h"
51 #include "trafgen_conf.h"
52 #include "tprintf.h"
53 #include "timer.h"
54 #include "ring_tx.h"
55 #include "csum.h"
57 struct ctx {
58 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
59 size_t reserve_size;
60 unsigned long num;
61 unsigned int cpus;
62 uid_t uid; gid_t gid;
63 char *device, *device_trans, *rhost;
64 struct timespec gap;
65 struct sockaddr_in dest;
68 struct cpu_stats {
69 unsigned long tv_sec, tv_usec;
70 unsigned long long tx_packets, tx_bytes;
71 unsigned long long cf_packets, cf_bytes;
72 unsigned long long cd_packets;
73 sig_atomic_t state;
76 static sig_atomic_t sigint = 0;
78 struct packet *packets = NULL;
79 size_t plen = 0;
81 struct packet_dyn *packet_dyn = NULL;
82 size_t dlen = 0;
84 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
85 static const struct option long_options[] = {
86 {"dev", required_argument, NULL, 'd'},
87 {"out", required_argument, NULL, 'o'},
88 {"in", required_argument, NULL, 'i'},
89 {"conf", required_argument, NULL, 'c'},
90 {"num", required_argument, NULL, 'n'},
91 {"gap", required_argument, NULL, 't'},
92 {"cpus", required_argument, NULL, 'P'},
93 {"ring-size", required_argument, NULL, 'S'},
94 {"kernel-pull", required_argument, NULL, 'k'},
95 {"smoke-test", required_argument, NULL, 's'},
96 {"seed", required_argument, NULL, 'E'},
97 {"user", required_argument, NULL, 'u'},
98 {"group", required_argument, NULL, 'g'},
99 {"prio-high", no_argument, NULL, 'H'},
100 {"notouch-irq", no_argument, NULL, 'Q'},
101 {"no-sock-mem", no_argument, NULL, 'A'},
102 {"qdisc-path", no_argument, NULL, 'q'},
103 {"jumbo-support", no_argument, NULL, 'J'},
104 {"no-cpu-stats", no_argument, NULL, 'C'},
105 {"cpp", no_argument, NULL, 'p'},
106 {"rfraw", no_argument, NULL, 'R'},
107 {"rand", no_argument, NULL, 'r'},
108 {"verbose", no_argument, NULL, 'V'},
109 {"version", no_argument, NULL, 'v'},
110 {"example", no_argument, NULL, 'e'},
111 {"help", no_argument, NULL, 'h'},
112 {NULL, 0, NULL, 0}
115 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
116 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
117 "Swiss federal institute of technology (ETH Zurich)\n"
118 "License: GNU GPL version 2.0\n"
119 "This is free software: you are free to change and redistribute it.\n"
120 "There is NO WARRANTY, to the extent permitted by law.\n";
122 static int sock;
123 static struct cpu_stats *stats;
124 static unsigned int seed;
126 #define CPU_STATS_STATE_CFG 1
127 #define CPU_STATS_STATE_CHK 2
128 #define CPU_STATS_STATE_RES 4
130 #ifndef ICMP_FILTER
131 # define ICMP_FILTER 1
133 struct icmp_filter {
134 __u32 data;
136 #endif
138 #define SMOKE_N_PROBES 100
140 static void signal_handler(int number)
142 switch (number) {
143 case SIGINT:
144 case SIGQUIT:
145 case SIGTERM:
146 sigint = 1;
147 case SIGHUP:
148 default:
149 break;
153 static void __noreturn help(void)
155 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
156 puts("http://www.netsniff-ng.org\n\n"
157 "Usage: trafgen [options]\n"
158 "Options:\n"
159 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
160 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
161 " -p|--cpp Run packet config through C preprocessor\n"
162 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
163 " -R|--rfraw Inject raw 802.11 frames\n"
164 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
165 " -n|--num <uint> Number of packets until exit (def: 0)\n"
166 " -r|--rand Randomize packet selection (def: round robin)\n"
167 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
168 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
169 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
170 " -E|--seed <uint> Manually set srand(3) seed\n"
171 " -u|--user <userid> Drop privileges and change to userid\n"
172 " -g|--group <groupid> Drop privileges and change to groupid\n"
173 " -H|--prio-high Make this high priority process\n"
174 " -A|--no-sock-mem Don't tune core socket memory\n"
175 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
176 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
177 " -V|--verbose Be more verbose\n"
178 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
179 " -v|--version Show version and exit\n"
180 " -e|--example Show built-in packet config example\n"
181 " -h|--help Guess what?!\n\n"
182 "Examples:\n"
183 " See trafgen.txf for configuration file examples.\n"
184 " trafgen --dev eth0 --conf trafgen.cfg\n"
185 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
186 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
187 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
188 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
189 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
190 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
191 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
192 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
193 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
194 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
195 "Note:\n"
196 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
197 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
198 " we assume the kernel crashed, thus we print the packet and quit.\n"
199 " In case you find a ping-of-death, please mention trafgen in your\n"
200 " commit message of the fix!\n\n"
201 " For introducing bit errors, delays with random variation and more,\n"
202 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
203 " For generating different package distributions, you can use scripting\n"
204 " to generate a trafgen config file with packet ratios as:\n\n"
205 " IMIX 64:7, 570:4, 1518:1\n"
206 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
207 " Cisco 64:7, 594:4, 1518:1\n"
208 " RPR Trimodal 64:60, 512:20, 1518:20\n"
209 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n");
210 puts(copyright);
211 die();
214 static void __noreturn example(void)
216 const char *e =
217 "/* Note: dynamic elements make trafgen slower! */\n"
218 "#include <stddef.h>\n\n"
219 "{\n"
220 " /* MAC Destination */\n"
221 " fill(0xff, ETH_ALEN),\n"
222 " /* MAC Source */\n"
223 " 0x00, 0x02, 0xb3, drnd(3),\n"
224 " /* IPv4 Protocol */\n"
225 " c16(ETH_P_IP),\n"
226 " /* IPv4 Version, IHL, TOS */\n"
227 " 0b01000101, 0,\n"
228 " /* IPv4 Total Len */\n"
229 " c16(59),\n"
230 " /* IPv4 Ident */\n"
231 " drnd(2),\n"
232 " /* IPv4 Flags, Frag Off */\n"
233 " 0b01000000, 0,\n"
234 " /* IPv4 TTL */\n"
235 " 64,\n"
236 " /* Proto TCP */\n"
237 " 0x06,\n"
238 " /* IPv4 Checksum (IP header from, to) */\n"
239 " csumip(14, 33),\n"
240 " /* Source IP */\n"
241 " drnd(4),\n"
242 " /* Dest IP */\n"
243 " drnd(4),\n"
244 " /* TCP Source Port */\n"
245 " drnd(2),\n"
246 " /* TCP Dest Port */\n"
247 " c16(80),\n"
248 " /* TCP Sequence Number */\n"
249 " drnd(4),\n"
250 " /* TCP Ackn. Number */\n"
251 " c32(0),\n"
252 " /* TCP Header length + TCP SYN/ECN Flag */\n"
253 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
254 " /* Window Size */\n"
255 " c16(16),\n"
256 " /* TCP Checksum (offset IP, offset TCP) */\n"
257 " csumtcp(14, 34),\n"
258 " /* TCP Options */\n"
259 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
260 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
261 " /* Data blob */\n"
262 " \"gotcha!\",\n"
263 "}";
264 puts(e);
265 die();
268 static void __noreturn version(void)
270 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
271 puts("multithreaded zero-copy network packet generator\n"
272 "http://www.netsniff-ng.org\n\n");
273 puts(copyright);
274 die();
277 static void apply_counter(int id)
279 size_t j, counter_max = packet_dyn[id].clen;
281 for (j = 0; j < counter_max; ++j) {
282 uint8_t val;
283 struct counter *counter = &packet_dyn[id].cnt[j];
285 val = counter->val - counter->min;
287 switch (counter->type) {
288 case TYPE_INC:
289 val = (val + counter->inc) % (counter->max - counter->min + 1);
290 break;
291 case TYPE_DEC:
292 val = (val - counter->inc) % (counter->min - counter->max + 1);
293 break;
294 default:
295 bug();
298 counter->val = val + counter->min;
299 packets[id].payload[counter->off] = val;
303 static void apply_randomizer(int id)
305 size_t j, rand_max = packet_dyn[id].rlen;
307 for (j = 0; j < rand_max; ++j) {
308 uint8_t val = (uint8_t) rand();
309 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
311 packets[id].payload[randomizer->off] = val;
315 static void apply_csum16(int id)
317 size_t j, csum_max = packet_dyn[id].slen;
319 for (j = 0; j < csum_max; ++j) {
320 uint16_t sum = 0;
321 struct csum16 *csum = &packet_dyn[id].csum[j];
323 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
324 if (unlikely((size_t) csum->to >= packets[id].len))
325 csum->to = packets[id].len - 1;
327 switch (csum->which) {
328 case CSUM_IP:
329 sum = calc_csum(packets[id].payload + csum->from,
330 csum->to - csum->from + 1, 0);
331 break;
332 case CSUM_UDP:
333 sum = p4_csum((void *) packets[id].payload + csum->from,
334 packets[id].payload + csum->to,
335 (packets[id].len - csum->to),
336 IPPROTO_UDP);
337 break;
338 case CSUM_TCP:
339 sum = p4_csum((void *) packets[id].payload + csum->from,
340 packets[id].payload + csum->to,
341 (packets[id].len - csum->to),
342 IPPROTO_TCP);
343 break;
344 default:
345 bug();
346 break;
349 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
353 static struct cpu_stats *setup_shared_var(unsigned int cpus)
355 int fd;
356 size_t len = cpus * sizeof(struct cpu_stats);
357 char *zbuff, file[256];
358 struct cpu_stats *buff;
360 zbuff = xzmalloc(len);
361 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
363 fd = creat(file, S_IRUSR | S_IWUSR);
364 bug_on(fd < 0);
365 close(fd);
367 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
368 S_IRUSR | S_IWUSR);
369 write_or_die(fd, zbuff, len);
370 xfree(zbuff);
372 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
373 MAP_SHARED, fd, 0);
374 if (buff == MAP_FAILED)
375 panic("Cannot setup shared variable!\n");
377 close(fd);
378 unlink(file);
380 memset(buff, 0, len);
381 return buff;
384 static void destroy_shared_var(void *buff, unsigned int cpus)
386 munmap(buff, cpus * sizeof(struct cpu_stats));
389 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
391 size_t i;
393 printf("{");
394 for (i = 0; i < len; ++i) {
395 if (i % 15 == 0)
396 printf("\n ");
397 printf("0x%02x, ", payload[i]);
399 printf("\n}\n");
400 fflush(stdout);
403 static int xmit_smoke_setup(struct ctx *ctx)
405 int icmp_sock, ret, ttl = 64;
406 struct icmp_filter filter;
408 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
409 if (icmp_sock < 0)
410 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
412 filter.data = ~(1 << ICMP_ECHOREPLY);
414 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
415 if (ret < 0)
416 panic("Cannot install filter!\n");
418 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
419 if (ret < 0)
420 panic("Cannot set TTL!\n");
422 memset(&ctx->dest, 0, sizeof(ctx->dest));
423 ctx->dest.sin_family = AF_INET;
424 ctx->dest.sin_port = 0;
426 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
427 if (ret < 0)
428 panic("Cannot resolv address!\n");
430 return icmp_sock;
433 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
435 int ret;
436 unsigned int i, j;
437 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
438 uint8_t outpack[512], *data;
439 struct icmphdr *icmp;
440 struct iphdr *ip;
441 size_t len = sizeof(*icmp) + 56;
442 struct sockaddr_in from;
443 socklen_t from_len;
444 struct pollfd fds = {
445 .fd = icmp_sock,
446 .events = POLLIN,
449 fmemset(idstore, 0, sizeof(idstore));
450 for (j = 0; j < SMOKE_N_PROBES; j++) {
451 while ((ident = htons((short) rand())) == 0)
452 sleep(0);
453 idstore[j] = ident;
455 memset(outpack, 0, sizeof(outpack));
456 icmp = (void *) outpack;
457 icmp->type = ICMP_ECHO;
458 icmp->un.echo.id = ident;
459 icmp->un.echo.sequence = htons(cnt++);
461 data = ((uint8_t *) outpack + sizeof(*icmp));
462 for (i = 0; i < 56; ++i)
463 data[i] = (uint8_t) rand();
465 icmp->checksum = csum((unsigned short *) outpack,
466 len / sizeof(unsigned short));
468 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
469 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
470 if (unlikely(ret != (int) len))
471 panic("Cannot send out probe: %s!\n", strerror(errno));
473 ret = poll(&fds, 1, 50);
474 if (ret < 0)
475 panic("Poll failed!\n");
477 if (fds.revents & POLLIN) {
478 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
479 (struct sockaddr *) &from, &from_len);
480 if (unlikely(ret <= 0))
481 panic("Probe receive failed!\n");
482 if (unlikely(from_len != sizeof(ctx->dest)))
483 continue;
484 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
485 continue;
486 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
487 continue;
488 ip = (void *) outpack;
489 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
490 continue;
491 icmp = (void *) outpack + ip->ihl * 4;
492 for (i = 0; i < array_size(idstore); ++i) {
493 if (unlikely(icmp->un.echo.id != idstore[i]))
494 continue;
495 return 0;
500 return -1;
503 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
505 int ret, icmp_sock = -1;
506 unsigned long num = 1, i = 0;
507 struct timeval start, end, diff;
508 unsigned long long tx_bytes = 0, tx_packets = 0;
509 struct packet_dyn *pktd;
510 struct sockaddr_ll saddr = {
511 .sll_family = PF_PACKET,
512 .sll_halen = ETH_ALEN,
513 .sll_ifindex = device_ifindex(ctx->device),
516 if (ctx->num > 0)
517 num = ctx->num;
518 if (ctx->num == 0 && orig_num > 0)
519 num = 0;
521 if (ctx->smoke_test)
522 icmp_sock = xmit_smoke_setup(ctx);
524 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
526 bug_on(gettimeofday(&start, NULL));
528 while (likely(sigint == 0 && num > 0 && plen > 0)) {
529 pktd = &packet_dyn[i];
530 if (pktd->clen + pktd->rlen + pktd->slen) {
531 apply_counter(i);
532 apply_randomizer(i);
533 apply_csum16(i);
535 retry:
536 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
537 (struct sockaddr *) &saddr, sizeof(saddr));
538 if (unlikely(ret < 0)) {
539 if (errno == ENOBUFS) {
540 sched_yield();
541 goto retry;
543 if (ctx->smoke_test)
544 panic("Sendto error: %s!\n", strerror(errno));
547 tx_bytes += packets[i].len;
548 tx_packets++;
550 if (ctx->smoke_test) {
551 ret = xmit_smoke_probe(icmp_sock, ctx);
552 if (unlikely(ret < 0)) {
553 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
554 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
555 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
556 i, seed);
558 dump_trafgen_snippet(packets[i].payload, packets[i].len);
559 break;
563 if (!ctx->rand) {
564 i++;
565 if (i >= plen)
566 i = 0;
567 } else
568 i = rand() % plen;
570 if (ctx->num > 0)
571 num--;
573 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
574 nanosleep(&ctx->gap, NULL);
577 bug_on(gettimeofday(&end, NULL));
578 timersub(&end, &start, &diff);
580 if (ctx->smoke_test)
581 close(icmp_sock);
583 stats[cpu].tx_packets = tx_packets;
584 stats[cpu].tx_bytes = tx_bytes;
585 stats[cpu].tv_sec = diff.tv_sec;
586 stats[cpu].tv_usec = diff.tv_usec;
588 stats[cpu].state |= CPU_STATS_STATE_RES;
591 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
593 int ifindex = device_ifindex(ctx->device);
594 uint8_t *out = NULL;
595 unsigned int it = 0;
596 unsigned long num = 1, i = 0;
597 size_t size = ring_size(ctx->device, ctx->reserve_size);
598 struct ring tx_ring;
599 struct frame_map *hdr;
600 struct timeval start, end, diff;
601 struct packet_dyn *pktd;
602 unsigned long long tx_bytes = 0, tx_packets = 0;
604 set_sock_prio(sock, 512);
606 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
608 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
610 if (ctx->num > 0)
611 num = ctx->num;
612 if (ctx->num == 0 && orig_num > 0)
613 num = 0;
615 bug_on(gettimeofday(&start, NULL));
617 while (likely(sigint == 0 && num > 0 && plen > 0)) {
618 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
619 int ret = pull_and_flush_tx_ring(sock);
620 if (unlikely(ret < 0)) {
621 /* We could hit EBADF if the socket has been closed before
622 * the timer was triggered.
624 if (errno != EBADF && errno != ENOBUFS)
625 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
628 continue;
631 hdr = tx_ring.frames[it].iov_base;
632 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
634 hdr->tp_h.tp_snaplen = packets[i].len;
635 hdr->tp_h.tp_len = packets[i].len;
637 pktd = &packet_dyn[i];
638 if (pktd->clen + pktd->rlen + pktd->slen) {
639 apply_counter(i);
640 apply_randomizer(i);
641 apply_csum16(i);
644 fmemcpy(out, packets[i].payload, packets[i].len);
646 tx_bytes += packets[i].len;
647 tx_packets++;
649 if (!ctx->rand) {
650 i++;
651 if (i >= plen)
652 i = 0;
653 } else
654 i = rand() % plen;
656 kernel_may_pull_from_tx(&hdr->tp_h);
658 it++;
659 if (it >= tx_ring.layout.tp_frame_nr)
660 it = 0;
662 if (ctx->num > 0)
663 num--;
666 bug_on(gettimeofday(&end, NULL));
667 timersub(&end, &start, &diff);
669 pull_and_flush_tx_ring_wait(sock);
670 destroy_tx_ring(sock, &tx_ring);
672 stats[cpu].tx_packets = tx_packets;
673 stats[cpu].tx_bytes = tx_bytes;
674 stats[cpu].tv_sec = diff.tv_sec;
675 stats[cpu].tv_usec = diff.tv_usec;
677 stats[cpu].state |= CPU_STATS_STATE_RES;
680 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
682 stats[cpu].state = s;
685 static inline sig_atomic_t __get_state(unsigned int cpu)
687 return stats[cpu].state;
690 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
692 unsigned int i;
693 unsigned long total;
695 for (i = 0, total = plen; i < ctx->cpus; i++) {
696 if (i == cpu)
697 continue;
699 while ((__get_state(i) &
700 (CPU_STATS_STATE_CFG |
701 CPU_STATS_STATE_RES)) == 0 &&
702 sigint == 0)
703 sched_yield();
705 total += stats[i].cf_packets;
708 return total;
711 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
713 unsigned int i;
714 unsigned long total;
715 int cpu_sel;
716 long long delta_correction = 0;
718 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
719 if (i == cpu)
720 continue;
722 while ((__get_state(i) &
723 (CPU_STATS_STATE_CHK |
724 CPU_STATS_STATE_RES)) == 0 &&
725 sigint == 0)
726 sched_yield();
728 total += stats[i].cd_packets;
731 if (total > orig)
732 delta_correction = -1 * ((long long) total - orig);
733 if (total < orig)
734 delta_correction = +1 * ((long long) orig - total);
736 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
737 if (stats[i].cd_packets > 0) {
738 if ((long long) stats[i].cd_packets +
739 delta_correction >= 0) {
740 cpu_sel = i;
741 break;
746 if ((int) cpu == cpu_sel)
747 ctx->num += delta_correction;
750 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
751 sig_atomic_t s)
753 stats[cpu].cf_packets = p;
754 stats[cpu].cf_bytes = b;
755 stats[cpu].state = s;
758 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
760 stats[cpu].cd_packets = p;
761 stats[cpu].state = s;
764 static int xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
766 unsigned int i;
767 unsigned long plen_total, orig = ctx->num;
768 size_t mtu, total_len = 0;
770 bug_on(plen != dlen);
772 for (i = 0; i < plen; ++i)
773 total_len += packets[i].len;
775 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
776 plen_total = __wait_and_sum_others(ctx, cpu);
778 if (orig > 0) {
779 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
781 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
782 CPU_STATS_STATE_CFG);
783 __correct_global_delta(ctx, cpu, orig);
786 if (plen == 0) {
787 __set_state(cpu, CPU_STATS_STATE_RES);
788 return 0;
791 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
792 if (packets[i].len > mtu + 14)
793 panic("Device MTU < than packet%d's size!\n", i);
794 if (packets[i].len <= 14)
795 panic("Packet%d's size too short!\n", i);
798 return 0;
801 static void main_loop(struct ctx *ctx, char *confname, bool slow,
802 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
804 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
805 if (xmit_packet_precheck(ctx, cpu) < 0)
806 return;
808 if (cpu == 0) {
809 unsigned int i;
810 size_t total_len = 0, total_pkts = 0;
812 for (i = 0; i < ctx->cpus; ++i) {
813 total_len += stats[i].cf_bytes;
814 total_pkts += stats[i].cf_packets;
817 printf("%6zu packets to schedule\n", total_pkts);
818 printf("%6zu bytes in total\n", total_len);
819 printf("Running! Hang up with ^C!\n\n");
820 fflush(stdout);
823 sock = pf_tx_socket();
825 if (ctx->qdisc_path == false)
826 set_sock_qdisc_bypass(sock, ctx->verbose);
828 if (slow)
829 xmit_slowpath_or_die(ctx, cpu, orig_num);
830 else
831 xmit_fastpath_or_die(ctx, cpu, orig_num);
833 close(sock);
835 cleanup_packets();
838 static unsigned int generate_srand_seed(void)
840 int fd;
841 unsigned int _seed;
843 fd = open("/dev/urandom", O_RDONLY);
844 if (fd < 0)
845 return time(NULL);
847 read_or_die(fd, &_seed, sizeof(_seed));
849 close(fd);
850 return _seed;
853 int main(int argc, char **argv)
855 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
856 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
857 int c, opt_index, vals[4] = {0}, irq;
858 uint64_t gap = 0;
859 unsigned int i, j;
860 char *confname = NULL, *ptr;
861 unsigned long cpus_tmp, orig_num = 0;
862 unsigned long long tx_packets, tx_bytes;
863 struct ctx ctx;
865 fmemset(&ctx, 0, sizeof(ctx));
866 ctx.cpus = get_number_cpus_online();
867 ctx.uid = getuid();
868 ctx.gid = getgid();
869 ctx.qdisc_path = false;
871 /* Keep an initial small default size to reduce cache-misses. */
872 ctx.reserve_size = 512 * (1 << 10);
874 while ((c = getopt_long(argc, argv, short_options, long_options,
875 &opt_index)) != EOF) {
876 switch (c) {
877 case 'h':
878 help();
879 break;
880 case 'v':
881 version();
882 break;
883 case 'C':
884 cpustats = false;
885 break;
886 case 'e':
887 example();
888 break;
889 case 'p':
890 invoke_cpp = true;
891 break;
892 case 'V':
893 ctx.verbose = true;
894 break;
895 case 'P':
896 cpus_tmp = strtoul(optarg, NULL, 0);
897 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
898 ctx.cpus = cpus_tmp;
899 break;
900 case 'd':
901 case 'o':
902 ctx.device = xstrndup(optarg, IFNAMSIZ);
903 break;
904 case 'H':
905 prio_high = true;
906 break;
907 case 'A':
908 set_sock_mem = false;
909 break;
910 case 'Q':
911 set_irq_aff = false;
912 break;
913 case 'q':
914 ctx.qdisc_path = true;
915 break;
916 case 'r':
917 ctx.rand = true;
918 break;
919 case 's':
920 slow = true;
921 ctx.cpus = 1;
922 ctx.smoke_test = true;
923 ctx.rhost = xstrdup(optarg);
924 break;
925 case 'R':
926 ctx.rfraw = true;
927 break;
928 case 'J':
929 ctx.jumbo_support = true;
930 break;
931 case 'c':
932 case 'i':
933 confname = xstrdup(optarg);
934 if (!strncmp("-", confname, strlen("-")))
935 ctx.cpus = 1;
936 break;
937 case 'u':
938 ctx.uid = strtoul(optarg, NULL, 0);
939 ctx.enforce = true;
940 break;
941 case 'g':
942 ctx.gid = strtoul(optarg, NULL, 0);
943 ctx.enforce = true;
944 break;
945 case 'k':
946 printf("Option -k/--kernel-pull is no longer used and "
947 "will be removed in a future release!\n");
948 break;
949 case 'E':
950 seed = strtoul(optarg, NULL, 0);
951 reseed = false;
952 break;
953 case 'n':
954 orig_num = strtoul(optarg, NULL, 0);
955 ctx.num = orig_num;
956 break;
957 case 't':
958 slow = true;
959 ptr = optarg;
960 gap = strtoul(optarg, NULL, 0);
962 for (j = i = strlen(optarg); i > 0; --i) {
963 if (!isdigit(optarg[j - i]))
964 break;
965 ptr++;
968 if (!strncmp(ptr, "ns", strlen("ns"))) {
969 ctx.gap.tv_sec = gap / 1000000000;
970 ctx.gap.tv_nsec = gap % 1000000000;
971 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
972 /* Default to microseconds for backwards
973 * compatibility if no postfix is given.
975 ctx.gap.tv_sec = gap / 1000000;
976 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
977 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
978 ctx.gap.tv_sec = gap / 1000;
979 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
980 } else if (!strncmp(ptr, "s", strlen("s"))) {
981 ctx.gap.tv_sec = gap;
982 ctx.gap.tv_nsec = 0;
983 } else
984 panic("Syntax error in time param!\n");
986 if (gap > 0)
987 /* Fall back to single core to not mess up
988 * correct timing. We are slow anyway!
990 ctx.cpus = 1;
991 break;
992 case 'S':
993 ptr = optarg;
995 for (j = i = strlen(optarg); i > 0; --i) {
996 if (!isdigit(optarg[j - i]))
997 break;
998 ptr++;
1001 if (!strncmp(ptr, "KiB", strlen("KiB")))
1002 ctx.reserve_size = 1 << 10;
1003 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1004 ctx.reserve_size = 1 << 20;
1005 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1006 ctx.reserve_size = 1 << 30;
1007 else
1008 panic("Syntax error in ring size param!\n");
1010 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1011 break;
1012 case '?':
1013 switch (optopt) {
1014 case 'd':
1015 case 'c':
1016 case 'n':
1017 case 'S':
1018 case 's':
1019 case 'P':
1020 case 'o':
1021 case 'E':
1022 case 'i':
1023 case 'k':
1024 case 'u':
1025 case 'g':
1026 case 't':
1027 panic("Option -%c requires an argument!\n",
1028 optopt);
1029 default:
1030 if (isprint(optopt))
1031 printf("Unknown option character `0x%X\'!\n", optopt);
1032 die();
1034 default:
1035 break;
1039 if (argc < 5)
1040 help();
1041 if (ctx.device == NULL)
1042 panic("No networking device given!\n");
1043 if (confname == NULL)
1044 panic("No configuration file given!\n");
1045 if (device_mtu(ctx.device) == 0)
1046 panic("This is no networking device!\n");
1048 register_signal(SIGINT, signal_handler);
1049 register_signal(SIGQUIT, signal_handler);
1050 register_signal(SIGTERM, signal_handler);
1051 register_signal(SIGHUP, signal_handler);
1053 if (prio_high) {
1054 set_proc_prio(-20);
1055 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1058 if (set_sock_mem)
1059 set_system_socket_memory(vals, array_size(vals));
1060 xlockme();
1062 if (ctx.rfraw) {
1063 ctx.device_trans = xstrdup(ctx.device);
1064 xfree(ctx.device);
1066 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1067 sleep(0);
1070 irq = device_irq_number(ctx.device);
1071 if (set_irq_aff)
1072 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1074 stats = setup_shared_var(ctx.cpus);
1076 for (i = 0; i < ctx.cpus; i++) {
1077 pid_t pid = fork();
1079 switch (pid) {
1080 case 0:
1081 if (reseed)
1082 seed = generate_srand_seed();
1083 srand(seed);
1085 cpu_affinity(i);
1086 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1088 goto thread_out;
1089 case -1:
1090 panic("Cannot fork processes!\n");
1094 for (i = 0; i < ctx.cpus; i++) {
1095 int status;
1097 wait(&status);
1098 if (WEXITSTATUS(status) == EXIT_FAILURE)
1099 die();
1102 if (ctx.rfraw)
1103 leave_rfmon_mac80211(ctx.device);
1105 if (set_sock_mem)
1106 reset_system_socket_memory(vals, array_size(vals));
1108 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1109 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1110 sched_yield();
1112 tx_packets += stats[i].tx_packets;
1113 tx_bytes += stats[i].tx_bytes;
1116 fflush(stdout);
1117 printf("\n");
1118 printf("\r%12llu packets outgoing\n", tx_packets);
1119 printf("\r%12llu bytes outgoing\n", tx_bytes);
1120 for (i = 0; cpustats && i < ctx.cpus; i++) {
1121 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1122 stats[i].tv_sec, stats[i].tv_usec, i,
1123 stats[i].tx_packets);
1126 thread_out:
1127 xunlockme();
1128 destroy_shared_var(stats, ctx.cpus);
1129 if (set_irq_aff)
1130 device_restore_irq_affinity_list();
1132 free(ctx.device);
1133 free(ctx.device_trans);
1134 free(ctx.rhost);
1135 free(confname);
1137 return 0;