trafgen: parser: do not enforce whitesapce
[netsniff-ng.git] / trafgen.c
blobdc0c54b60caa6bb264e08952239ef68988a13e4b
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 <sys/socket.h>
14 #include <sys/types.h>
15 #include <sys/fsuid.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/wait.h>
19 #include <sys/mman.h>
20 #include <net/ethernet.h>
21 #include <netinet/in.h>
22 #include <netinet/ip.h>
23 #include <linux/icmp.h>
24 #include <arpa/inet.h>
25 #include <signal.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <fcntl.h>
29 #include <time.h>
30 #include <poll.h>
31 #include <netdb.h>
32 #include <math.h>
33 #include <unistd.h>
35 #include "xmalloc.h"
36 #include "die.h"
37 #include "mac80211.h"
38 #include "xutils.h"
39 #include "xio.h"
40 #include "built_in.h"
41 #include "trafgen_conf.h"
42 #include "tprintf.h"
43 #include "ring_tx.h"
44 #include "csum.h"
46 struct ctx {
47 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
48 unsigned long kpull, num, gap, reserve_size, cpus;
49 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
50 struct sockaddr_in dest;
53 struct cpu_stats {
54 unsigned long tv_sec, tv_usec;
55 unsigned long long tx_packets, tx_bytes;
56 unsigned long long cf_packets, cf_bytes;
57 unsigned long long cd_packets;
58 sig_atomic_t state;
61 sig_atomic_t sigint = 0;
63 struct packet *packets = NULL;
64 size_t plen = 0;
66 struct packet_dyn *packet_dyn = NULL;
67 size_t dlen = 0;
69 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
70 static const struct option long_options[] = {
71 {"dev", required_argument, NULL, 'd'},
72 {"out", required_argument, NULL, 'o'},
73 {"in", required_argument, NULL, 'i'},
74 {"conf", required_argument, NULL, 'c'},
75 {"num", required_argument, NULL, 'n'},
76 {"gap", required_argument, NULL, 't'},
77 {"cpus", required_argument, NULL, 'P'},
78 {"ring-size", required_argument, NULL, 'S'},
79 {"kernel-pull", required_argument, NULL, 'k'},
80 {"smoke-test", required_argument, NULL, 's'},
81 {"seed", required_argument, NULL, 'E'},
82 {"user", required_argument, NULL, 'u'},
83 {"group", required_argument, NULL, 'g'},
84 {"jumbo-support", no_argument, NULL, 'J'},
85 {"cpp", no_argument, NULL, 'p'},
86 {"rfraw", no_argument, NULL, 'R'},
87 {"rand", no_argument, NULL, 'r'},
88 {"verbose", no_argument, NULL, 'V'},
89 {"version", no_argument, NULL, 'v'},
90 {"example", no_argument, NULL, 'e'},
91 {"help", no_argument, NULL, 'h'},
92 {NULL, 0, NULL, 0}
95 static int sock;
97 static struct itimerval itimer;
99 static unsigned long interval = TX_KERNEL_PULL_INT;
101 static struct cpu_stats *stats;
103 unsigned int seed;
105 #define CPU_STATS_STATE_CFG 1
106 #define CPU_STATS_STATE_CHK 2
107 #define CPU_STATS_STATE_RES 4
109 #ifndef ICMP_FILTER
110 # define ICMP_FILTER 1
112 struct icmp_filter {
113 __u32 data;
115 #endif
117 static void signal_handler(int number)
119 switch (number) {
120 case SIGINT:
121 sigint = 1;
122 case SIGHUP:
123 default:
124 break;
128 static void timer_elapsed(int number)
130 int ret;
132 set_itimer_interval_value(&itimer, 0, interval);
134 ret = pull_and_flush_tx_ring(sock);
135 if (unlikely(ret < 0)) {
136 /* We could hit EBADF if the socket has been closed before
137 * the timer was triggered.
139 if (errno != EBADF && errno != ENOBUFS)
140 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
143 setitimer(ITIMER_REAL, &itimer, NULL);
146 static void help(void)
148 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
149 puts("http://www.netsniff-ng.org\n\n"
150 "Usage: trafgen [options]\n"
151 "Options:\n"
152 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
153 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
154 " -p|--cpp Run packet config through C preprocessor\n"
155 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
156 " -R|--rfraw Inject raw 802.11 frames\n"
157 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
158 " -n|--num <uint> Number of packets until exit (def: 0)\n"
159 " -r|--rand Randomize packet selection (def: round robin)\n"
160 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
161 " -t|--gap <uint> Interpacket gap in us (approx)\n"
162 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
163 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
164 " -E|--seed <uint> Manually set srand(3) seed\n"
165 " -u|--user <userid> Drop privileges and change to userid\n"
166 " -g|--group <groupid> Drop privileges and change to groupid\n"
167 " -V|--verbose Be more verbose\n"
168 " -v|--version Show version\n"
169 " -e|--example Show built-in packet config example\n"
170 " -h|--help Guess what?!\n\n"
171 "Examples:\n"
172 " See trafgen.txf for configuration file examples.\n"
173 " trafgen --dev eth0 --conf trafgen.cfg\n"
174 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
175 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
176 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
177 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
178 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
179 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
180 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
181 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
182 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
183 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
184 "Note:\n"
185 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
186 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
187 " we assume the kernel crashed, thus we print the packet and quit.\n"
188 " In case you find a ping-of-death, please mention trafgen in your\n"
189 " commit message of the fix!\n\n"
190 " For introducing bit errors, delays with random variation and more,\n"
191 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
192 " For generating different package distributions, you can use scripting\n"
193 " to generate a trafgen config file with packet ratios as:\n\n"
194 " IMIX 64:7, 570:4, 1518:1\n"
195 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
196 " Cisco 64:7, 594:4, 1518:1\n"
197 " RPR Trimodal 64:60, 512:20, 1518:20\n"
198 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
199 "Please report bugs to <bugs@netsniff-ng.org>\n"
200 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
201 "Swiss federal institute of technology (ETH Zurich)\n"
202 "License: GNU GPL version 2.0\n"
203 "This is free software: you are free to change and redistribute it.\n"
204 "There is NO WARRANTY, to the extent permitted by law.\n");
205 die();
208 static void example(void)
210 const char *e =
211 "/* Note: dynamic elements make trafgen slower! */\n"
212 "#include <stddef.h>\n\n"
213 "{\n"
214 " /* MAC Destination */\n"
215 " fill(0xff, ETH_ALEN),\n"
216 " /* MAC Source */\n"
217 " 0x00, 0x02, 0xb3, drnd(3),\n"
218 " /* IPv4 Protocol */\n"
219 " c16(ETH_P_IP),\n"
220 " /* IPv4 Version, IHL, TOS */\n"
221 " 0b01000101, 0,\n"
222 " /* IPv4 Total Len */\n"
223 " c16(58),\n"
224 " /* IPv4 Ident */\n"
225 " drnd(2),\n"
226 " /* IPv4 Flags, Frag Off */\n"
227 " 0b01000000, 0,\n"
228 " /* IPv4 TTL */\n"
229 " 64,\n"
230 " /* Proto TCP */\n"
231 " 0x06,\n"
232 " /* IPv4 Checksum (IP header from, to) */\n"
233 " csumip(14, 33),\n"
234 " /* Source IP */\n"
235 " drnd(4),\n"
236 " /* Dest IP */\n"
237 " drnd(4),\n"
238 " /* TCP Source Port */\n"
239 " drnd(2),\n"
240 " /* TCP Dest Port */\n"
241 " c16(80),\n"
242 " /* TCP Sequence Number */\n"
243 " drnd(4),\n"
244 " /* TCP Ackn. Number */\n"
245 " c32(0),\n"
246 " /* TCP Header length + TCP SYN/ECN Flag */\n"
247 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
248 " /* Window Size */\n"
249 " c16(16),\n"
250 " /* TCP Checksum (offset IP, offset TCP) */\n"
251 " csumtcp(14, 34),\n"
252 " /* TCP Options */\n"
253 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
254 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
255 " /* Data blob */\n"
256 " \"gotcha!\",\n"
257 "}";
258 puts(e);
259 die();
262 static void version(void)
264 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
265 puts("http://www.netsniff-ng.org\n\n"
266 "Please report bugs to <bugs@netsniff-ng.org>\n"
267 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
268 "Swiss federal institute of technology (ETH Zurich)\n"
269 "License: GNU GPL version 2.0\n"
270 "This is free software: you are free to change and redistribute it.\n"
271 "There is NO WARRANTY, to the extent permitted by law.\n");
272 die();
275 static void apply_counter(int counter_id)
277 int j, i = counter_id;
278 size_t counter_max = packet_dyn[i].clen;
280 for (j = 0; j < counter_max; ++j) {
281 uint8_t val;
282 struct counter *counter = &packet_dyn[i].cnt[j];
284 val = counter->val - counter->min;
286 switch (counter->type) {
287 case TYPE_INC:
288 val = (val + counter->inc) % (counter->max - counter->min + 1);
289 break;
290 case TYPE_DEC:
291 val = (val - counter->inc) % (counter->min - counter->max + 1);
292 break;
293 default:
294 bug();
297 counter->val = val + counter->min;
298 packets[i].payload[counter->off] = val;
302 static void apply_randomizer(int rand_id)
304 int j, i = rand_id;
305 size_t rand_max = packet_dyn[i].rlen;
307 for (j = 0; j < rand_max; ++j) {
308 uint8_t val = (uint8_t) rand();
309 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
311 packets[i].payload[randomizer->off] = val;
315 static void apply_csum16(int csum_id)
317 int j, i = csum_id;
318 size_t csum_max = packet_dyn[i].slen;
320 for (j = 0; j < csum_max; ++j) {
321 uint16_t sum = 0;
322 struct csum16 *csum = &packet_dyn[i].csum[j];
324 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
326 switch (csum->which) {
327 case CSUM_IP:
328 if (csum->to >= packets[i].len)
329 csum->to = packets[i].len - 1;
330 sum = calc_csum(packets[i].payload + csum->from,
331 csum->to - csum->from + 1, 0);
332 break;
333 case CSUM_UDP:
334 sum = p4_csum((void *) packets[i].payload + csum->from,
335 packets[i].payload + csum->to,
336 (packets[i].len - csum->to),
337 IPPROTO_UDP);
338 break;
339 case CSUM_TCP:
340 sum = p4_csum((void *) packets[i].payload + csum->from,
341 packets[i].payload + csum->to,
342 (packets[i].len - csum->to),
343 IPPROTO_TCP);
344 break;
347 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
351 static struct cpu_stats *setup_shared_var(unsigned long cpus)
353 int fd;
354 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
355 struct cpu_stats *buff;
357 fmemset(zbuff, 0, sizeof(zbuff));
358 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
360 fd = creat(file, S_IRUSR | S_IWUSR);
361 bug_on(fd < 0);
362 close(fd);
364 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
365 S_IRUSR | S_IWUSR);
366 write_or_die(fd, zbuff, sizeof(zbuff));
368 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
369 MAP_SHARED, fd, 0);
370 if (buff == (void *) -1)
371 panic("Cannot setup shared variable!\n");
373 close(fd);
374 unlink(file);
376 memset(buff, 0, sizeof(zbuff));
378 return buff;
381 static void destroy_shared_var(void *buff, unsigned long cpus)
383 munmap(buff, cpus * sizeof(struct cpu_stats));
386 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
388 int i;
390 printf("{");
391 for (i = 0; i < len; ++i) {
392 if (i % 15 == 0)
393 printf("\n ");
394 printf("0x%02x, ", payload[i]);
396 printf("\n}\n");
397 fflush(stdout);
400 static int xmit_smoke_setup(struct ctx *ctx)
402 int icmp_sock, ret, ttl = 64;
403 struct icmp_filter filter;
405 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
406 if (icmp_sock < 0)
407 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
409 filter.data = ~(1 << ICMP_ECHOREPLY);
411 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
412 if (ret < 0)
413 panic("Cannot install filter!\n");
415 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
416 if (ret < 0)
417 panic("Cannot set TTL!\n");
419 memset(&ctx->dest, 0, sizeof(ctx->dest));
420 ctx->dest.sin_family = AF_INET;
421 ctx->dest.sin_port = 0;
423 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
424 if (ret < 0)
425 panic("Cannot resolv address!\n");
427 return icmp_sock;
430 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
432 int ret, i, j = 0, probes = 100;
433 short ident, cnt = 1, idstore[probes];
434 uint8_t outpack[512], *data;
435 struct icmphdr *icmp;
436 struct iphdr *ip;
437 size_t len = sizeof(*icmp) + 56;
438 struct sockaddr_in from;
439 socklen_t from_len;
440 struct pollfd fds = {
441 .fd = icmp_sock,
442 .events = POLLIN,
445 fmemset(idstore, 0, sizeof(idstore));
446 while (probes-- > 0) {
447 while ((ident = htons((short) rand())) == 0)
448 sleep(0);
449 idstore[j++] = ident;
451 memset(outpack, 0, sizeof(outpack));
452 icmp = (void *) outpack;
453 icmp->type = ICMP_ECHO;
454 icmp->code = 0;
455 icmp->checksum = 0;
456 icmp->un.echo.id = ident;
457 icmp->un.echo.sequence = htons(cnt++);
459 data = ((uint8_t *) outpack + sizeof(*icmp));
460 for (i = 0; i < 56; ++i)
461 data[i] = (uint8_t) rand();
463 icmp->checksum = csum((unsigned short *) outpack,
464 len / sizeof(unsigned short));
466 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
467 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
468 if (unlikely(ret != len))
469 panic("Cannot send out probe: %s!\n", strerror(errno));
471 ret = poll(&fds, 1, 50);
472 if (ret < 0)
473 panic("Poll failed!\n");
475 if (fds.revents & POLLIN) {
476 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
477 (struct sockaddr *) &from, &from_len);
478 if (unlikely(ret <= 0))
479 panic("Probe receive failed!\n");
480 if (unlikely(from_len != sizeof(ctx->dest)))
481 continue;
482 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
483 continue;
484 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
485 continue;
486 ip = (void *) outpack;
487 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
488 continue;
489 icmp = (void *) outpack + ip->ihl * 4;
490 for (i = 0; i < array_size(idstore); ++i) {
491 if (unlikely(icmp->un.echo.id != idstore[i]))
492 continue;
493 return 0;
498 return -1;
501 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
503 int ret, icmp_sock = -1;
504 unsigned long num = 1, i = 0;
505 struct timeval start, end, diff;
506 unsigned long long tx_bytes = 0, tx_packets = 0;
507 struct packet_dyn *pktd;
508 struct sockaddr_ll saddr = {
509 .sll_family = PF_PACKET,
510 .sll_halen = ETH_ALEN,
511 .sll_ifindex = device_ifindex(ctx->device),
514 if (ctx->num > 0)
515 num = ctx->num;
516 if (ctx->num == 0 && orig_num > 0)
517 num = 0;
519 if (ctx->smoke_test)
520 icmp_sock = xmit_smoke_setup(ctx);
522 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
524 bug_on(gettimeofday(&start, NULL));
526 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
527 pktd = &packet_dyn[i];
528 if (pktd->clen + pktd->rlen + pktd->slen) {
529 apply_counter(i);
530 apply_randomizer(i);
531 apply_csum16(i);
533 retry:
534 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
535 (struct sockaddr *) &saddr, sizeof(saddr));
536 if (unlikely(ret < 0)) {
537 if (errno == ENOBUFS) {
538 sched_yield();
539 goto retry;
542 panic("Sendto error: %s!\n", strerror(errno));
545 tx_bytes += packets[i].len;
546 tx_packets++;
548 if (ctx->smoke_test) {
549 ret = xmit_smoke_probe(icmp_sock, ctx);
550 if (unlikely(ret < 0)) {
551 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
552 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
553 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
554 i, seed);
556 dump_trafgen_snippet(packets[i].payload, packets[i].len);
557 break;
561 if (!ctx->rand) {
562 i++;
563 if (i >= plen)
564 i = 0;
565 } else
566 i = rand() % plen;
568 if (ctx->num > 0)
569 num--;
571 if (ctx->gap > 0)
572 usleep(ctx->gap);
575 bug_on(gettimeofday(&end, NULL));
576 timersub(&end, &start, &diff);
578 if (ctx->smoke_test)
579 close(icmp_sock);
581 stats[cpu].tx_packets = tx_packets;
582 stats[cpu].tx_bytes = tx_bytes;
583 stats[cpu].tv_sec = diff.tv_sec;
584 stats[cpu].tv_usec = diff.tv_usec;
586 stats[cpu].state |= CPU_STATS_STATE_RES;
589 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
591 int ifindex = device_ifindex(ctx->device);
592 uint8_t *out = NULL;
593 unsigned int it = 0;
594 unsigned long num = 1, i = 0, size;
595 struct ring tx_ring;
596 struct frame_map *hdr;
597 struct timeval start, end, diff;
598 struct packet_dyn *pktd;
599 unsigned long long tx_bytes = 0, tx_packets = 0;
601 fmemset(&tx_ring, 0, sizeof(tx_ring));
603 size = ring_size(ctx->device, ctx->reserve_size);
605 set_sock_prio(sock, 512);
606 set_packet_loss_discard(sock);
608 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
609 create_tx_ring(sock, &tx_ring, ctx->verbose);
610 mmap_tx_ring(sock, &tx_ring);
611 alloc_tx_ring_frames(&tx_ring);
612 bind_tx_ring(sock, &tx_ring, ifindex);
614 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
616 if (ctx->kpull)
617 interval = ctx->kpull;
618 if (ctx->num > 0)
619 num = ctx->num;
620 if (ctx->num == 0 && orig_num > 0)
621 num = 0;
623 set_itimer_interval_value(&itimer, 0, interval);
624 setitimer(ITIMER_REAL, &itimer, NULL);
626 bug_on(gettimeofday(&start, NULL));
628 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
629 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
630 hdr = tx_ring.frames[it].iov_base;
631 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
633 hdr->tp_h.tp_snaplen = packets[i].len;
634 hdr->tp_h.tp_len = packets[i].len;
636 pktd = &packet_dyn[i];
637 if (pktd->clen + pktd->rlen + pktd->slen) {
638 apply_counter(i);
639 apply_randomizer(i);
640 apply_csum16(i);
643 fmemcpy(out, packets[i].payload, packets[i].len);
645 tx_bytes += packets[i].len;
646 tx_packets++;
648 if (!ctx->rand) {
649 i++;
650 if (i >= plen)
651 i = 0;
652 } else
653 i = rand() % plen;
655 kernel_may_pull_from_tx(&hdr->tp_h);
657 it++;
658 if (it >= tx_ring.layout.tp_frame_nr)
659 it = 0;
661 if (ctx->num > 0)
662 num--;
664 if (unlikely(sigint == 1))
665 break;
669 bug_on(gettimeofday(&end, NULL));
670 timersub(&end, &start, &diff);
672 destroy_tx_ring(sock, &tx_ring);
674 stats[cpu].tx_packets = tx_packets;
675 stats[cpu].tx_bytes = tx_bytes;
676 stats[cpu].tv_sec = diff.tv_sec;
677 stats[cpu].tv_usec = diff.tv_usec;
679 stats[cpu].state |= CPU_STATS_STATE_RES;
682 static inline void __set_state(int cpu, sig_atomic_t s)
684 stats[cpu].state = s;
687 static inline sig_atomic_t __get_state(int cpu)
689 return stats[cpu].state;
692 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
694 int i;
695 unsigned long total;
697 for (i = 0, total = plen; i < ctx->cpus; i++) {
698 if (i == cpu)
699 continue;
701 while ((__get_state(i) &
702 (CPU_STATS_STATE_CFG |
703 CPU_STATS_STATE_RES)) == 0 &&
704 sigint == 0)
705 sched_yield();
707 total += stats[i].cf_packets;
710 return total;
713 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
715 int i, cpu_sel;
716 unsigned long total;
717 long long delta_correction = 0;
719 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
720 if (i == cpu)
721 continue;
723 while ((__get_state(i) &
724 (CPU_STATS_STATE_CHK |
725 CPU_STATS_STATE_RES)) == 0 &&
726 sigint == 0)
727 sched_yield();
729 total += stats[i].cd_packets;
732 if (total > orig)
733 delta_correction = -1 * ((long long) total - orig);
734 if (total < orig)
735 delta_correction = +1 * ((long long) orig - total);
737 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
738 if (stats[i].cd_packets > 0) {
739 if ((long long) stats[i].cd_packets +
740 delta_correction > 0) {
741 cpu_sel = i;
742 break;
747 if (cpu == cpu_sel)
748 ctx->num += delta_correction;
751 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
752 sig_atomic_t s)
754 stats[cpu].cf_packets = p;
755 stats[cpu].cf_bytes = b;
756 stats[cpu].state = s;
759 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
761 stats[cpu].cd_packets = p;
762 stats[cpu].state = s;
765 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
767 int i;
768 unsigned long plen_total, orig = ctx->num;
769 size_t mtu, total_len = 0;
771 bug_on(plen != dlen);
773 for (i = 0; i < plen; ++i)
774 total_len += packets[i].len;
776 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
777 plen_total = __wait_and_sum_others(ctx, cpu);
779 if (orig > 0) {
780 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
782 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
783 CPU_STATS_STATE_CFG);
784 __correct_global_delta(ctx, cpu, orig);
787 if (plen == 0) {
788 __set_state(cpu, CPU_STATS_STATE_RES);
789 return 0;
792 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
793 if (packets[i].len > mtu + 14)
794 panic("Device MTU < than packet%d's size!\n", i);
795 if (packets[i].len <= 14)
796 panic("Packet%d's size too short!\n", i);
799 return 0;
802 static void main_loop(struct ctx *ctx, char *confname, bool slow,
803 int cpu, bool invoke_cpp, unsigned long orig_num)
805 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
806 if (xmit_packet_precheck(ctx, cpu) < 0)
807 return;
809 if (cpu == 0) {
810 int i;
811 size_t total_len = 0, total_pkts = 0;
813 for (i = 0; i < ctx->cpus; ++i) {
814 total_len += stats[i].cf_bytes;
815 total_pkts += stats[i].cf_packets;
818 printf("%6zu packets to schedule\n", total_pkts);
819 printf("%6zu bytes in total\n", total_len);
820 printf("Running! Hang up with ^C!\n\n");
821 fflush(stdout);
824 sock = pf_socket();
826 if (slow)
827 xmit_slowpath_or_die(ctx, cpu, orig_num);
828 else
829 xmit_fastpath_or_die(ctx, cpu, orig_num);
831 close(sock);
833 cleanup_packets();
836 static unsigned int generate_srand_seed(void)
838 int fd;
839 unsigned int seed;
841 fd = open("/dev/urandom", O_RDONLY);
842 if (fd < 0)
843 return time(0);
845 read_or_die(fd, &seed, sizeof(seed));
847 close(fd);
848 return seed;
851 int main(int argc, char **argv)
853 bool slow = false, invoke_cpp = false, reseed = true;
854 int c, opt_index, i, j, vals[4] = {0}, irq;
855 char *confname = NULL, *ptr;
856 unsigned long cpus_tmp, orig_num = 0;
857 unsigned long long tx_packets, tx_bytes;
858 struct ctx ctx;
860 fmemset(&ctx, 0, sizeof(ctx));
861 ctx.cpus = get_number_cpus_online();
862 ctx.uid = getuid();
863 ctx.gid = getgid();
865 while ((c = getopt_long(argc, argv, short_options, long_options,
866 &opt_index)) != EOF) {
867 switch (c) {
868 case 'h':
869 help();
870 break;
871 case 'v':
872 version();
873 break;
874 case 'e':
875 example();
876 break;
877 case 'p':
878 invoke_cpp = true;
879 break;
880 case 'V':
881 ctx.verbose = true;
882 break;
883 case 'P':
884 cpus_tmp = strtoul(optarg, NULL, 0);
885 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
886 ctx.cpus = cpus_tmp;
887 break;
888 case 'd':
889 case 'o':
890 ctx.device = xstrndup(optarg, IFNAMSIZ);
891 break;
892 case 'r':
893 ctx.rand = true;
894 break;
895 case 's':
896 slow = true;
897 ctx.cpus = 1;
898 ctx.smoke_test = true;
899 ctx.rhost = xstrdup(optarg);
900 break;
901 case 'R':
902 ctx.rfraw = true;
903 break;
904 case 'J':
905 ctx.jumbo_support = true;
906 break;
907 case 'c':
908 case 'i':
909 confname = xstrdup(optarg);
910 if (!strncmp("-", confname, strlen("-")))
911 ctx.cpus = 1;
912 break;
913 case 'u':
914 ctx.uid = strtoul(optarg, NULL, 0);
915 ctx.enforce = true;
916 break;
917 case 'g':
918 ctx.gid = strtoul(optarg, NULL, 0);
919 ctx.enforce = true;
920 break;
921 case 'k':
922 ctx.kpull = strtoul(optarg, NULL, 0);
923 break;
924 case 'E':
925 seed = strtoul(optarg, NULL, 0);
926 reseed = false;
927 break;
928 case 'n':
929 orig_num = strtoul(optarg, NULL, 0);
930 ctx.num = orig_num;
931 break;
932 case 't':
933 slow = true;
934 ctx.gap = strtoul(optarg, NULL, 0);
935 if (ctx.gap > 0)
936 /* Fall back to single core to not
937 * mess up correct timing. We are slow
938 * anyway!
940 ctx.cpus = 1;
941 break;
942 case 'S':
943 ptr = optarg;
944 ctx.reserve_size = 0;
946 for (j = i = strlen(optarg); i > 0; --i) {
947 if (!isdigit(optarg[j - i]))
948 break;
949 ptr++;
952 if (!strncmp(ptr, "KiB", strlen("KiB")))
953 ctx.reserve_size = 1 << 10;
954 else if (!strncmp(ptr, "MiB", strlen("MiB")))
955 ctx.reserve_size = 1 << 20;
956 else if (!strncmp(ptr, "GiB", strlen("GiB")))
957 ctx.reserve_size = 1 << 30;
958 else
959 panic("Syntax error in ring size param!\n");
960 *ptr = 0;
962 ctx.reserve_size *= strtol(optarg, NULL, 0);
963 break;
964 case '?':
965 switch (optopt) {
966 case 'd':
967 case 'c':
968 case 'n':
969 case 'S':
970 case 's':
971 case 'P':
972 case 'o':
973 case 'E':
974 case 'i':
975 case 'k':
976 case 'u':
977 case 'g':
978 case 't':
979 panic("Option -%c requires an argument!\n",
980 optopt);
981 default:
982 if (isprint(optopt))
983 printf("Unknown option character `0x%X\'!\n", optopt);
984 die();
986 default:
987 break;
991 if (argc < 5)
992 help();
993 if (ctx.device == NULL)
994 panic("No networking device given!\n");
995 if (confname == NULL)
996 panic("No configuration file given!\n");
997 if (device_mtu(ctx.device) == 0)
998 panic("This is no networking device!\n");
999 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1000 panic("Networking device not running!\n");
1002 register_signal(SIGINT, signal_handler);
1003 register_signal(SIGHUP, signal_handler);
1004 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1006 set_system_socket_memory(vals, array_size(vals));
1007 xlockme();
1009 if (ctx.rfraw) {
1010 ctx.device_trans = xstrdup(ctx.device);
1011 xfree(ctx.device);
1013 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1014 sleep(0);
1017 irq = device_irq_number(ctx.device);
1018 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1020 stats = setup_shared_var(ctx.cpus);
1022 for (i = 0; i < ctx.cpus; i++) {
1023 pid_t pid = fork();
1025 switch (pid) {
1026 case 0:
1027 if (reseed)
1028 seed = generate_srand_seed();
1029 srand(seed);
1031 cpu_affinity(i);
1032 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1034 goto thread_out;
1035 case -1:
1036 panic("Cannot fork processes!\n");
1040 for (i = 0; i < ctx.cpus; i++) {
1041 int status;
1043 wait(&status);
1044 if (WEXITSTATUS(status) == EXIT_FAILURE)
1045 die();
1048 if (ctx.rfraw)
1049 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1051 reset_system_socket_memory(vals, array_size(vals));
1053 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1054 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1055 sched_yield();
1057 tx_packets += stats[i].tx_packets;
1058 tx_bytes += stats[i].tx_bytes;
1061 fflush(stdout);
1062 printf("\n");
1063 printf("\r%12llu packets outgoing\n", tx_packets);
1064 printf("\r%12llu bytes outgoing\n", tx_bytes);
1065 for (i = 0; i < ctx.cpus; i++) {
1066 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1067 stats[i].tv_sec, stats[i].tv_usec, i,
1068 stats[i].tx_packets);
1071 thread_out:
1072 xunlockme();
1073 destroy_shared_var(stats, ctx.cpus);
1075 free(ctx.device);
1076 free(ctx.device_trans);
1077 free(ctx.rhost);
1078 free(confname);
1080 return 0;