Corrected spinning loop potential in getrandombytes
[netsniff-ng.git] / trafgen.c
blob0fdc397e133e9f494a5e650c786d5c0675db56bf
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.
7 * Who can now hold the fords when the King of the Nine Riders comes? And
8 * other armies will come. I am too late. All is lost. I tarried on the
9 * way. All is lost. Even if my errand is performed, no one will ever
10 * know. There will be no one I can tell. It will be in vain.
12 * -- The Lord of the Rings, Frodo thinking,
13 * Chapter 'The Stairs of Cirith Ungol'.
16 #include <stdio.h>
17 #include <string.h>
18 #include <getopt.h>
19 #include <ctype.h>
20 #include <stdbool.h>
21 #include <sys/socket.h>
22 #include <sys/types.h>
23 #include <sys/fsuid.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/wait.h>
27 #include <sys/mman.h>
28 #include <net/ethernet.h>
29 #include <netinet/in.h>
30 #include <netinet/ip.h>
31 #include <linux/icmp.h>
32 #include <arpa/inet.h>
33 #include <signal.h>
34 #include <stdint.h>
35 #include <stdlib.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <poll.h>
39 #include <netdb.h>
40 #include <math.h>
41 #include <unistd.h>
43 #include "xmalloc.h"
44 #include "die.h"
45 #include "mac80211.h"
46 #include "xutils.h"
47 #include "xio.h"
48 #include "built_in.h"
49 #include "trafgen_conf.h"
50 #include "tprintf.h"
51 #include "ring_tx.h"
52 #include "csum.h"
54 struct ctx {
55 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
56 unsigned long kpull, num, gap, reserve_size, cpus;
57 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
58 struct sockaddr_in dest;
61 struct cpu_stats {
62 unsigned long tv_sec, tv_usec;
63 unsigned long long tx_packets, tx_bytes;
64 unsigned long long cf_packets, cf_bytes;
65 unsigned long long cd_packets;
66 sig_atomic_t state;
69 sig_atomic_t sigint = 0;
71 struct packet *packets = NULL;
72 size_t plen = 0;
74 struct packet_dyn *packet_dyn = NULL;
75 size_t dlen = 0;
77 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
78 static const struct option long_options[] = {
79 {"dev", required_argument, NULL, 'd'},
80 {"out", required_argument, NULL, 'o'},
81 {"in", required_argument, NULL, 'i'},
82 {"conf", required_argument, NULL, 'c'},
83 {"num", required_argument, NULL, 'n'},
84 {"gap", required_argument, NULL, 't'},
85 {"cpus", required_argument, NULL, 'P'},
86 {"ring-size", required_argument, NULL, 'S'},
87 {"kernel-pull", required_argument, NULL, 'k'},
88 {"smoke-test", required_argument, NULL, 's'},
89 {"seed", required_argument, NULL, 'E'},
90 {"user", required_argument, NULL, 'u'},
91 {"group", required_argument, NULL, 'g'},
92 {"jumbo-support", no_argument, NULL, 'J'},
93 {"cpp", no_argument, NULL, 'p'},
94 {"rfraw", no_argument, NULL, 'R'},
95 {"rand", no_argument, NULL, 'r'},
96 {"verbose", no_argument, NULL, 'V'},
97 {"version", no_argument, NULL, 'v'},
98 {"example", no_argument, NULL, 'e'},
99 {"help", no_argument, NULL, 'h'},
100 {NULL, 0, NULL, 0}
103 static int sock;
105 static struct itimerval itimer;
107 static unsigned long interval = TX_KERNEL_PULL_INT;
109 static struct cpu_stats *stats;
111 unsigned int seed;
113 #define CPU_STATS_STATE_CFG 1
114 #define CPU_STATS_STATE_CHK 2
115 #define CPU_STATS_STATE_RES 4
117 #ifndef ICMP_FILTER
118 # define ICMP_FILTER 1
120 struct icmp_filter {
121 __u32 data;
123 #endif
125 static void signal_handler(int number)
127 switch (number) {
128 case SIGINT:
129 sigint = 1;
130 case SIGHUP:
131 default:
132 break;
136 static void timer_elapsed(int number)
138 set_itimer_interval_value(&itimer, 0, interval);
139 pull_and_flush_tx_ring(sock);
140 setitimer(ITIMER_REAL, &itimer, NULL);
143 static void help(void)
145 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
146 puts("http://www.netsniff-ng.org\n\n"
147 "Usage: trafgen [options]\n"
148 "Options:\n"
149 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
150 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
151 " -p|--cpp Run packet config through C preprocessor\n"
152 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
153 " -R|--rfraw Inject raw 802.11 frames\n"
154 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
155 " -n|--num <uint> Number of packets until exit (def: 0)\n"
156 " -r|--rand Randomize packet selection (def: round robin)\n"
157 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
158 " -t|--gap <uint> Interpacket gap in us (approx)\n"
159 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
160 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
161 " -E|--seed <uint> Manually set srand(3) seed\n"
162 " -u|--user <userid> Drop privileges and change to userid\n"
163 " -g|--group <groupid> Drop privileges and change to groupid\n"
164 " -V|--verbose Be more verbose\n"
165 " -v|--version Show version\n"
166 " -e|--example Show built-in packet config example\n"
167 " -h|--help Guess what?!\n\n"
168 "Examples:\n"
169 " See trafgen.txf for configuration file examples.\n"
170 " trafgen --dev eth0 --conf trafgen.cfg\n"
171 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
172 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
173 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
174 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
175 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
176 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
177 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
178 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
179 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
180 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
181 "Note:\n"
182 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
183 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
184 " we assume the kernel crashed, thus we print the packet and quit.\n"
185 " In case you find a ping-of-death, please mention trafgen in your\n"
186 " commit message of the fix!\n\n"
187 " For introducing bit errors, delays with random variation and more,\n"
188 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
189 " For generating different package distributions, you can use scripting\n"
190 " to generate a trafgen config file with packet ratios as:\n\n"
191 " IMIX 64:7, 570:4, 1518:1\n"
192 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
193 " Cisco 64:7, 594:4, 1518:1\n"
194 " RPR Trimodal 64:60, 512:20, 1518:20\n"
195 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
196 "Please report bugs to <bugs@netsniff-ng.org>\n"
197 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
198 "Swiss federal institute of technology (ETH Zurich)\n"
199 "License: GNU GPL version 2.0\n"
200 "This is free software: you are free to change and redistribute it.\n"
201 "There is NO WARRANTY, to the extent permitted by law.\n");
202 die();
205 static void example(void)
207 const char *e =
208 "/* Note: dynamic elements make trafgen slower! */\n"
209 "#include <stddef.h>\n\n"
210 "{\n"
211 " /* MAC Destination */\n"
212 " fill(0xff, ETH_ALEN),\n"
213 " /* MAC Source */\n"
214 " 0x00, 0x02, 0xb3, drnd(3),\n"
215 " /* IPv4 Protocol */\n"
216 " c16(ETH_P_IP),\n"
217 " /* IPv4 Version, IHL, TOS */\n"
218 " 0b01000101, 0,\n"
219 " /* IPv4 Total Len */\n"
220 " c16(59),\n"
221 " /* IPv4 Ident */\n"
222 " drnd(2),\n"
223 " /* IPv4 Flags, Frag Off */\n"
224 " 0b01000000, 0,\n"
225 " /* IPv4 TTL */\n"
226 " 64,\n"
227 " /* Proto TCP */\n"
228 " 0x06,\n"
229 " /* IPv4 Checksum (IP header from, to) */\n"
230 " csumip(14, 33),\n"
231 " /* Source IP */\n"
232 " drnd(4),\n"
233 " /* Dest IP */\n"
234 " drnd(4),\n"
235 " /* TCP Source Port */\n"
236 " drnd(2),\n"
237 " /* TCP Dest Port */\n"
238 " c16(80),\n"
239 " /* TCP Sequence Number */\n"
240 " drnd(4),\n"
241 " /* TCP Ackn. Number */\n"
242 " c32(0),\n"
243 " /* TCP Header length + TCP SYN/ECN Flag */\n"
244 " c16((0x8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
245 " /* Window Size */\n"
246 " c16(16),\n"
247 " /* TCP Checksum (offset IP, offset TCP) */\n"
248 " csumtcp(14, 34),\n"
249 " /* TCP Options */\n"
250 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
251 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
252 " /* Data blob */\n"
253 " \"gotcha!\",\n"
254 "}";
255 puts(e);
256 die();
259 static void version(void)
261 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
262 puts("http://www.netsniff-ng.org\n\n"
263 "Please report bugs to <bugs@netsniff-ng.org>\n"
264 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
265 "Swiss federal institute of technology (ETH Zurich)\n"
266 "License: GNU GPL version 2.0\n"
267 "This is free software: you are free to change and redistribute it.\n"
268 "There is NO WARRANTY, to the extent permitted by law.\n");
269 die();
272 static void apply_counter(int counter_id)
274 int j, i = counter_id;
275 size_t counter_max = packet_dyn[i].clen;
277 for (j = 0; j < counter_max; ++j) {
278 uint8_t val;
279 struct counter *counter = &packet_dyn[i].cnt[j];
281 val = counter->val - counter->min;
283 switch (counter->type) {
284 case TYPE_INC:
285 val = (val + counter->inc) % (counter->max - counter->min + 1);
286 break;
287 case TYPE_DEC:
288 val = (val - counter->inc) % (counter->min - counter->max + 1);
289 break;
290 default:
291 bug();
294 counter->val = val + counter->min;
295 packets[i].payload[counter->off] = val;
299 static void apply_randomizer(int rand_id)
301 int j, i = rand_id;
302 size_t rand_max = packet_dyn[i].rlen;
304 for (j = 0; j < rand_max; ++j) {
305 uint8_t val = (uint8_t) rand();
306 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
308 packets[i].payload[randomizer->off] = val;
312 static void apply_csum16(int csum_id)
314 int j, i = csum_id;
315 size_t csum_max = packet_dyn[i].slen;
317 for (j = 0; j < csum_max; ++j) {
318 uint16_t sum = 0;
319 struct csum16 *csum = &packet_dyn[i].csum[j];
321 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
323 switch (csum->which) {
324 case CSUM_IP:
325 if (csum->to >= packets[i].len)
326 csum->to = packets[i].len - 1;
327 sum = calc_csum(packets[i].payload + csum->from,
328 csum->to - csum->from + 1, 0);
329 break;
330 case CSUM_UDP:
331 sum = p4_csum((void *) packets[i].payload + csum->from,
332 packets[i].payload + csum->to,
333 (packets[i].len - csum->to),
334 IPPROTO_UDP);
335 break;
336 case CSUM_TCP:
337 sum = p4_csum((void *) packets[i].payload + csum->from,
338 packets[i].payload + csum->to,
339 (packets[i].len - csum->to),
340 IPPROTO_TCP);
341 break;
344 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
348 static struct cpu_stats *setup_shared_var(unsigned long cpus)
350 int fd;
351 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
352 struct cpu_stats *buff;
354 fmemset(zbuff, 0, sizeof(zbuff));
355 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
357 fd = creat(file, S_IRUSR | S_IWUSR);
358 bug_on(fd < 0);
359 close(fd);
361 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
362 S_IRUSR | S_IWUSR);
363 write_or_die(fd, zbuff, sizeof(zbuff));
365 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
366 MAP_SHARED, fd, 0);
367 if (buff == (void *) -1)
368 panic("Cannot setup shared variable!\n");
370 close(fd);
371 unlink(file);
373 memset(buff, 0, sizeof(zbuff));
375 return buff;
378 static void destroy_shared_var(void *buff, unsigned long cpus)
380 munmap(buff, cpus * sizeof(struct cpu_stats));
383 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
385 int i;
387 printf("{");
388 for (i = 0; i < len; ++i) {
389 if (i % 15 == 0)
390 printf("\n ");
391 printf("0x%02x, ", payload[i]);
393 printf("\n}\n");
394 fflush(stdout);
397 static int xmit_smoke_setup(struct ctx *ctx)
399 int icmp_sock, ret, ttl = 64;
400 struct icmp_filter filter;
402 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
403 if (icmp_sock < 0)
404 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
406 filter.data = ~(1 << ICMP_ECHOREPLY);
408 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
409 if (ret < 0)
410 panic("Cannot install filter!\n");
412 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
413 if (ret < 0)
414 panic("Cannot set TTL!\n");
416 memset(&ctx->dest, 0, sizeof(ctx->dest));
417 ctx->dest.sin_family = AF_INET;
418 ctx->dest.sin_port = 0;
420 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
421 if (ret < 0)
422 panic("Cannot resolv address!\n");
424 return icmp_sock;
427 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
429 int ret, i, j = 0, probes = 100;
430 short ident, cnt = 1, idstore[probes];
431 uint8_t outpack[512], *data;
432 struct icmphdr *icmp;
433 struct iphdr *ip;
434 size_t len = sizeof(*icmp) + 56;
435 struct sockaddr_in from;
436 socklen_t from_len;
437 struct pollfd fds = {
438 .fd = icmp_sock,
439 .events = POLLIN,
442 fmemset(idstore, 0, sizeof(idstore));
443 while (probes-- > 0) {
444 while ((ident = htons((short) rand())) == 0)
445 sleep(0);
446 idstore[j++] = ident;
448 memset(outpack, 0, sizeof(outpack));
449 icmp = (void *) outpack;
450 icmp->type = ICMP_ECHO;
451 icmp->code = 0;
452 icmp->checksum = 0;
453 icmp->un.echo.id = ident;
454 icmp->un.echo.sequence = htons(cnt++);
456 data = ((uint8_t *) outpack + sizeof(*icmp));
457 for (i = 0; i < 56; ++i)
458 data[i] = (uint8_t) rand();
460 icmp->checksum = csum((unsigned short *) outpack,
461 len / sizeof(unsigned short));
463 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
464 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
465 if (unlikely(ret != len))
466 panic("Cannot send out probe: %s!\n", strerror(errno));
468 ret = poll(&fds, 1, 50);
469 if (ret < 0)
470 panic("Poll failed!\n");
472 if (fds.revents & POLLIN) {
473 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
474 (struct sockaddr *) &from, &from_len);
475 if (unlikely(ret <= 0))
476 panic("Probe receive failed!\n");
477 if (unlikely(from_len != sizeof(ctx->dest)))
478 continue;
479 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
480 continue;
481 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
482 continue;
483 ip = (void *) outpack;
484 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
485 continue;
486 icmp = (void *) outpack + ip->ihl * 4;
487 for (i = 0; i < array_size(idstore); ++i) {
488 if (unlikely(icmp->un.echo.id != idstore[i]))
489 continue;
490 return 0;
495 return -1;
498 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
500 int ret, icmp_sock = -1;
501 unsigned long num = 1, i = 0;
502 struct timeval start, end, diff;
503 unsigned long long tx_bytes = 0, tx_packets = 0;
504 struct packet_dyn *pktd;
505 struct sockaddr_ll saddr = {
506 .sll_family = PF_PACKET,
507 .sll_halen = ETH_ALEN,
508 .sll_ifindex = device_ifindex(ctx->device),
511 if (ctx->num > 0)
512 num = ctx->num;
514 if (ctx->smoke_test)
515 icmp_sock = xmit_smoke_setup(ctx);
517 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
519 bug_on(gettimeofday(&start, NULL));
521 while (likely(sigint == 0) && likely(num > 0)) {
522 pktd = &packet_dyn[i];
523 if (pktd->clen + pktd->rlen + pktd->slen) {
524 apply_counter(i);
525 apply_randomizer(i);
526 apply_csum16(i);
528 retry:
529 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
530 (struct sockaddr *) &saddr, sizeof(saddr));
531 if (unlikely(ret < 0)) {
532 if (errno == ENOBUFS) {
533 sched_yield();
534 goto retry;
537 panic("Sendto error: %s!\n", strerror(errno));
540 tx_bytes += packets[i].len;
541 tx_packets++;
543 if (ctx->smoke_test) {
544 ret = xmit_smoke_probe(icmp_sock, ctx);
545 if (unlikely(ret < 0)) {
546 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
547 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
548 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
549 i, seed);
551 dump_trafgen_snippet(packets[i].payload, packets[i].len);
552 break;
556 if (!ctx->rand) {
557 i++;
558 if (i >= plen)
559 i = 0;
560 } else
561 i = rand() % plen;
563 if (ctx->num > 0)
564 num--;
566 if (ctx->gap > 0)
567 usleep(ctx->gap);
570 bug_on(gettimeofday(&end, NULL));
571 timersub(&end, &start, &diff);
573 if (ctx->smoke_test)
574 close(icmp_sock);
576 stats[cpu].tx_packets = tx_packets;
577 stats[cpu].tx_bytes = tx_bytes;
578 stats[cpu].tv_sec = diff.tv_sec;
579 stats[cpu].tv_usec = diff.tv_usec;
581 stats[cpu].state |= CPU_STATS_STATE_RES;
584 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
586 int ifindex = device_ifindex(ctx->device);
587 uint8_t *out = NULL;
588 unsigned int it = 0;
589 unsigned long num = 1, i = 0, size;
590 struct ring tx_ring;
591 struct frame_map *hdr;
592 struct timeval start, end, diff;
593 struct packet_dyn *pktd;
594 unsigned long long tx_bytes = 0, tx_packets = 0;
596 fmemset(&tx_ring, 0, sizeof(tx_ring));
598 size = ring_size(ctx->device, ctx->reserve_size);
600 set_sock_prio(sock, 512);
601 set_packet_loss_discard(sock);
603 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
604 create_tx_ring(sock, &tx_ring, ctx->verbose);
605 mmap_tx_ring(sock, &tx_ring);
606 alloc_tx_ring_frames(&tx_ring);
607 bind_tx_ring(sock, &tx_ring, ifindex);
609 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
611 if (ctx->kpull)
612 interval = ctx->kpull;
613 if (ctx->num > 0)
614 num = ctx->num;
616 set_itimer_interval_value(&itimer, 0, interval);
617 setitimer(ITIMER_REAL, &itimer, NULL);
619 bug_on(gettimeofday(&start, NULL));
621 while (likely(sigint == 0) && likely(num > 0)) {
622 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
623 hdr = tx_ring.frames[it].iov_base;
624 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
626 hdr->tp_h.tp_snaplen = packets[i].len;
627 hdr->tp_h.tp_len = packets[i].len;
629 pktd = &packet_dyn[i];
630 if (pktd->clen + pktd->rlen + pktd->slen) {
631 apply_counter(i);
632 apply_randomizer(i);
633 apply_csum16(i);
636 fmemcpy(out, packets[i].payload, packets[i].len);
638 tx_bytes += packets[i].len;
639 tx_packets++;
641 if (!ctx->rand) {
642 i++;
643 if (i >= plen)
644 i = 0;
645 } else
646 i = rand() % plen;
648 kernel_may_pull_from_tx(&hdr->tp_h);
650 it++;
651 if (it >= tx_ring.layout.tp_frame_nr)
652 it = 0;
654 if (ctx->num > 0)
655 num--;
657 if (unlikely(sigint == 1))
658 break;
662 bug_on(gettimeofday(&end, NULL));
663 timersub(&end, &start, &diff);
665 destroy_tx_ring(sock, &tx_ring);
667 stats[cpu].tx_packets = tx_packets;
668 stats[cpu].tx_bytes = tx_bytes;
669 stats[cpu].tv_sec = diff.tv_sec;
670 stats[cpu].tv_usec = diff.tv_usec;
672 stats[cpu].state |= CPU_STATS_STATE_RES;
675 static inline void __set_state(int cpu, sig_atomic_t s)
677 stats[cpu].state = s;
680 static inline sig_atomic_t __get_state(int cpu)
682 return stats[cpu].state;
685 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
687 int i;
688 unsigned long total;
690 for (i = 0, total = plen; i < ctx->cpus; i++) {
691 if (i == cpu)
692 continue;
694 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
695 sigint == 0)
696 sched_yield();
698 total += stats[i].cf_packets;
701 return total;
704 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
706 int i, cpu_sel;
707 unsigned long total;
708 long long delta_correction = 0;
710 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
711 if (i == cpu)
712 continue;
714 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
715 sigint == 0)
716 sched_yield();
718 total += stats[i].cd_packets;
721 if (total > orig)
722 delta_correction = -1 * ((long long) total - orig);
723 if (total < orig)
724 delta_correction = +1 * ((long long) orig - total);
726 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
727 if (stats[i].cd_packets > 0) {
728 if ((long long) stats[i].cd_packets +
729 delta_correction > 0) {
730 cpu_sel = i;
731 break;
736 if (cpu == cpu_sel)
737 ctx->num += delta_correction;
740 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
741 sig_atomic_t s)
743 stats[cpu].cf_packets = p;
744 stats[cpu].cf_bytes = b;
745 stats[cpu].state = s;
748 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
750 stats[cpu].cd_packets = p;
751 stats[cpu].state = s;
754 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
756 int i;
757 unsigned long plen_total, orig = ctx->num;
758 size_t mtu, total_len = 0;
760 bug_on(plen != dlen);
762 for (i = 0; i < plen; ++i)
763 total_len += packets[i].len;
765 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
766 plen_total = __wait_and_sum_others(ctx, cpu);
768 if (orig > 0) {
769 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
771 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
772 CPU_STATS_STATE_CFG);
773 __correct_global_delta(ctx, cpu, orig);
776 if (plen == 0) {
777 __set_state(cpu, CPU_STATS_STATE_RES);
778 return -1;
781 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
782 if (packets[i].len > mtu + 14)
783 panic("Device MTU < than packet%d's size!\n", i);
784 if (packets[i].len <= 14)
785 panic("Packet%d's size too short!\n", i);
788 return 0;
791 static void main_loop(struct ctx *ctx, char *confname, bool slow,
792 int cpu, bool invoke_cpp)
794 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
795 if (xmit_packet_precheck(ctx, cpu) < 0)
796 return;
798 if (cpu == 0) {
799 int i;
800 size_t total_len = 0, total_pkts = 0;
802 for (i = 0; i < ctx->cpus; ++i) {
803 total_len += stats[i].cf_bytes;
804 total_pkts += stats[i].cf_packets;
807 printf("%6zu packets to schedule\n", total_pkts);
808 printf("%6zu bytes in total\n", total_len);
809 printf("Running! Hang up with ^C!\n\n");
810 fflush(stdout);
813 sock = pf_socket();
815 if (slow)
816 xmit_slowpath_or_die(ctx, cpu);
817 else
818 xmit_fastpath_or_die(ctx, cpu);
820 close(sock);
822 cleanup_packets();
825 static unsigned int generate_srand_seed(void)
827 int fd;
828 unsigned int seed;
830 fd = open("/dev/urandom", O_RDONLY);
831 if (fd < 0)
832 return time(0);
834 read_or_die(fd, &seed, sizeof(seed));
836 close(fd);
837 return seed;
840 int main(int argc, char **argv)
842 bool slow = false, invoke_cpp = false, reseed = true;
843 int c, opt_index, i, j, vals[4] = {0}, irq;
844 char *confname = NULL, *ptr;
845 unsigned long cpus_tmp;
846 unsigned long long tx_packets, tx_bytes;
847 struct ctx ctx;
849 fmemset(&ctx, 0, sizeof(ctx));
850 ctx.cpus = get_number_cpus_online();
851 ctx.uid = getuid();
852 ctx.gid = getgid();
854 while ((c = getopt_long(argc, argv, short_options, long_options,
855 &opt_index)) != EOF) {
856 switch (c) {
857 case 'h':
858 help();
859 break;
860 case 'v':
861 version();
862 break;
863 case 'e':
864 example();
865 break;
866 case 'p':
867 invoke_cpp = true;
868 break;
869 case 'V':
870 ctx.verbose = true;
871 break;
872 case 'P':
873 cpus_tmp = strtoul(optarg, NULL, 0);
874 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
875 ctx.cpus = cpus_tmp;
876 break;
877 case 'd':
878 case 'o':
879 ctx.device = xstrndup(optarg, IFNAMSIZ);
880 break;
881 case 'r':
882 ctx.rand = true;
883 break;
884 case 's':
885 slow = true;
886 ctx.cpus = 1;
887 ctx.smoke_test = true;
888 ctx.rhost = xstrdup(optarg);
889 break;
890 case 'R':
891 ctx.rfraw = true;
892 break;
893 case 'J':
894 ctx.jumbo_support = true;
895 break;
896 case 'c':
897 case 'i':
898 confname = xstrdup(optarg);
899 if (!strncmp("-", confname, strlen("-")))
900 ctx.cpus = 1;
901 break;
902 case 'u':
903 ctx.uid = strtoul(optarg, NULL, 0);
904 ctx.enforce = true;
905 break;
906 case 'g':
907 ctx.gid = strtoul(optarg, NULL, 0);
908 ctx.enforce = true;
909 break;
910 case 'k':
911 ctx.kpull = strtoul(optarg, NULL, 0);
912 break;
913 case 'E':
914 seed = strtoul(optarg, NULL, 0);
915 reseed = false;
916 break;
917 case 'n':
918 ctx.num = strtoul(optarg, NULL, 0);
919 break;
920 case 't':
921 slow = true;
922 ctx.gap = strtoul(optarg, NULL, 0);
923 if (ctx.gap > 0)
924 /* Fall back to single core to not
925 * mess up correct timing. We are slow
926 * anyway!
928 ctx.cpus = 1;
929 break;
930 case 'S':
931 ptr = optarg;
932 ctx.reserve_size = 0;
934 for (j = i = strlen(optarg); i > 0; --i) {
935 if (!isdigit(optarg[j - i]))
936 break;
937 ptr++;
940 if (!strncmp(ptr, "KiB", strlen("KiB")))
941 ctx.reserve_size = 1 << 10;
942 else if (!strncmp(ptr, "MiB", strlen("MiB")))
943 ctx.reserve_size = 1 << 20;
944 else if (!strncmp(ptr, "GiB", strlen("GiB")))
945 ctx.reserve_size = 1 << 30;
946 else
947 panic("Syntax error in ring size param!\n");
948 *ptr = 0;
950 ctx.reserve_size *= strtol(optarg, NULL, 0);
951 break;
952 case '?':
953 switch (optopt) {
954 case 'd':
955 case 'c':
956 case 'n':
957 case 'S':
958 case 's':
959 case 'P':
960 case 'o':
961 case 'E':
962 case 'i':
963 case 'k':
964 case 'u':
965 case 'g':
966 case 't':
967 panic("Option -%c requires an argument!\n",
968 optopt);
969 default:
970 if (isprint(optopt))
971 printf("Unknown option character `0x%X\'!\n", optopt);
972 die();
974 default:
975 break;
979 if (argc < 5)
980 help();
981 if (ctx.device == NULL)
982 panic("No networking device given!\n");
983 if (confname == NULL)
984 panic("No configuration file given!\n");
985 if (device_mtu(ctx.device) == 0)
986 panic("This is no networking device!\n");
987 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
988 panic("Networking device not running!\n");
990 register_signal(SIGINT, signal_handler);
991 register_signal(SIGHUP, signal_handler);
992 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
994 set_system_socket_memory(vals, array_size(vals));
995 xlockme();
997 if (ctx.rfraw) {
998 ctx.device_trans = xstrdup(ctx.device);
999 xfree(ctx.device);
1001 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1002 sleep(0);
1005 irq = device_irq_number(ctx.device);
1006 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1008 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1009 ctx.cpus = 1;
1011 stats = setup_shared_var(ctx.cpus);
1013 for (i = 0; i < ctx.cpus; i++) {
1014 pid_t pid = fork();
1016 switch (pid) {
1017 case 0:
1018 if (reseed)
1019 seed = generate_srand_seed();
1020 srand(seed);
1022 cpu_affinity(i);
1023 main_loop(&ctx, confname, slow, i, invoke_cpp);
1025 goto thread_out;
1026 case -1:
1027 panic("Cannot fork processes!\n");
1031 for (i = 0; i < ctx.cpus; i++) {
1032 int status;
1034 wait(&status);
1035 if (WEXITSTATUS(status) == EXIT_FAILURE)
1036 die();
1039 if (ctx.rfraw)
1040 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1042 reset_system_socket_memory(vals, array_size(vals));
1044 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1045 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1046 sched_yield();
1048 tx_packets += stats[i].tx_packets;
1049 tx_bytes += stats[i].tx_bytes;
1052 fflush(stdout);
1053 printf("\n");
1054 printf("\r%12llu packets outgoing\n", tx_packets);
1055 printf("\r%12llu bytes outgoing\n", tx_bytes);
1056 for (i = 0; i < ctx.cpus; i++) {
1057 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1058 stats[i].tv_sec, stats[i].tv_usec, i,
1059 stats[i].tx_packets);
1062 thread_out:
1063 xunlockme();
1064 destroy_shared_var(stats, ctx.cpus);
1066 free(ctx.device);
1067 free(ctx.device_trans);
1068 free(ctx.rhost);
1069 free(confname);
1071 return 0;