docs: AUTHORS: add Peter Stuge for his commit
[netsniff-ng.git] / trafgen.c
blob02aa2dfc826fad1698fa083fe7754458282512ca
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)
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;
517 if (ctx->smoke_test)
518 icmp_sock = xmit_smoke_setup(ctx);
520 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
522 bug_on(gettimeofday(&start, NULL));
524 while (likely(sigint == 0) && likely(num > 0)) {
525 pktd = &packet_dyn[i];
526 if (pktd->clen + pktd->rlen + pktd->slen) {
527 apply_counter(i);
528 apply_randomizer(i);
529 apply_csum16(i);
531 retry:
532 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
533 (struct sockaddr *) &saddr, sizeof(saddr));
534 if (unlikely(ret < 0)) {
535 if (errno == ENOBUFS) {
536 sched_yield();
537 goto retry;
540 panic("Sendto error: %s!\n", strerror(errno));
543 tx_bytes += packets[i].len;
544 tx_packets++;
546 if (ctx->smoke_test) {
547 ret = xmit_smoke_probe(icmp_sock, ctx);
548 if (unlikely(ret < 0)) {
549 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
550 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
551 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
552 i, seed);
554 dump_trafgen_snippet(packets[i].payload, packets[i].len);
555 break;
559 if (!ctx->rand) {
560 i++;
561 if (i >= plen)
562 i = 0;
563 } else
564 i = rand() % plen;
566 if (ctx->num > 0)
567 num--;
569 if (ctx->gap > 0)
570 usleep(ctx->gap);
573 bug_on(gettimeofday(&end, NULL));
574 timersub(&end, &start, &diff);
576 if (ctx->smoke_test)
577 close(icmp_sock);
579 stats[cpu].tx_packets = tx_packets;
580 stats[cpu].tx_bytes = tx_bytes;
581 stats[cpu].tv_sec = diff.tv_sec;
582 stats[cpu].tv_usec = diff.tv_usec;
584 stats[cpu].state |= CPU_STATS_STATE_RES;
587 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
589 int ifindex = device_ifindex(ctx->device);
590 uint8_t *out = NULL;
591 unsigned int it = 0;
592 unsigned long num = 1, i = 0, size;
593 struct ring tx_ring;
594 struct frame_map *hdr;
595 struct timeval start, end, diff;
596 struct packet_dyn *pktd;
597 unsigned long long tx_bytes = 0, tx_packets = 0;
599 fmemset(&tx_ring, 0, sizeof(tx_ring));
601 size = ring_size(ctx->device, ctx->reserve_size);
603 set_sock_prio(sock, 512);
604 set_packet_loss_discard(sock);
606 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
607 create_tx_ring(sock, &tx_ring, ctx->verbose);
608 mmap_tx_ring(sock, &tx_ring);
609 alloc_tx_ring_frames(&tx_ring);
610 bind_tx_ring(sock, &tx_ring, ifindex);
612 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
614 if (ctx->kpull)
615 interval = ctx->kpull;
616 if (ctx->num > 0)
617 num = ctx->num;
619 set_itimer_interval_value(&itimer, 0, interval);
620 setitimer(ITIMER_REAL, &itimer, NULL);
622 bug_on(gettimeofday(&start, NULL));
624 while (likely(sigint == 0) && likely(num > 0)) {
625 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
626 hdr = tx_ring.frames[it].iov_base;
627 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
629 hdr->tp_h.tp_snaplen = packets[i].len;
630 hdr->tp_h.tp_len = packets[i].len;
632 pktd = &packet_dyn[i];
633 if (pktd->clen + pktd->rlen + pktd->slen) {
634 apply_counter(i);
635 apply_randomizer(i);
636 apply_csum16(i);
639 fmemcpy(out, packets[i].payload, packets[i].len);
641 tx_bytes += packets[i].len;
642 tx_packets++;
644 if (!ctx->rand) {
645 i++;
646 if (i >= plen)
647 i = 0;
648 } else
649 i = rand() % plen;
651 kernel_may_pull_from_tx(&hdr->tp_h);
653 it++;
654 if (it >= tx_ring.layout.tp_frame_nr)
655 it = 0;
657 if (ctx->num > 0)
658 num--;
660 if (unlikely(sigint == 1))
661 break;
665 bug_on(gettimeofday(&end, NULL));
666 timersub(&end, &start, &diff);
668 destroy_tx_ring(sock, &tx_ring);
670 stats[cpu].tx_packets = tx_packets;
671 stats[cpu].tx_bytes = tx_bytes;
672 stats[cpu].tv_sec = diff.tv_sec;
673 stats[cpu].tv_usec = diff.tv_usec;
675 stats[cpu].state |= CPU_STATS_STATE_RES;
678 static inline void __set_state(int cpu, sig_atomic_t s)
680 stats[cpu].state = s;
683 static inline sig_atomic_t __get_state(int cpu)
685 return stats[cpu].state;
688 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
690 int i;
691 unsigned long total;
693 for (i = 0, total = plen; i < ctx->cpus; i++) {
694 if (i == cpu)
695 continue;
697 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
698 sigint == 0)
699 sched_yield();
701 total += stats[i].cf_packets;
704 return total;
707 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
709 int i, cpu_sel;
710 unsigned long total;
711 long long delta_correction = 0;
713 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
714 if (i == cpu)
715 continue;
717 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
718 sigint == 0)
719 sched_yield();
721 total += stats[i].cd_packets;
724 if (total > orig)
725 delta_correction = -1 * ((long long) total - orig);
726 if (total < orig)
727 delta_correction = +1 * ((long long) orig - total);
729 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
730 if (stats[i].cd_packets > 0) {
731 if ((long long) stats[i].cd_packets +
732 delta_correction > 0) {
733 cpu_sel = i;
734 break;
739 if (cpu == cpu_sel)
740 ctx->num += delta_correction;
743 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
744 sig_atomic_t s)
746 stats[cpu].cf_packets = p;
747 stats[cpu].cf_bytes = b;
748 stats[cpu].state = s;
751 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
753 stats[cpu].cd_packets = p;
754 stats[cpu].state = s;
757 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
759 int i;
760 unsigned long plen_total, orig = ctx->num;
761 size_t mtu, total_len = 0;
763 bug_on(plen != dlen);
765 for (i = 0; i < plen; ++i)
766 total_len += packets[i].len;
768 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
769 plen_total = __wait_and_sum_others(ctx, cpu);
771 if (orig > 0) {
772 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
774 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
775 CPU_STATS_STATE_CFG);
776 __correct_global_delta(ctx, cpu, orig);
779 if (plen == 0) {
780 __set_state(cpu, CPU_STATS_STATE_RES);
781 return -1;
784 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
785 if (packets[i].len > mtu + 14)
786 panic("Device MTU < than packet%d's size!\n", i);
787 if (packets[i].len <= 14)
788 panic("Packet%d's size too short!\n", i);
791 return 0;
794 static void main_loop(struct ctx *ctx, char *confname, bool slow,
795 int cpu, bool invoke_cpp)
797 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
798 if (xmit_packet_precheck(ctx, cpu) < 0)
799 return;
801 if (cpu == 0) {
802 int i;
803 size_t total_len = 0, total_pkts = 0;
805 for (i = 0; i < ctx->cpus; ++i) {
806 total_len += stats[i].cf_bytes;
807 total_pkts += stats[i].cf_packets;
810 printf("%6zu packets to schedule\n", total_pkts);
811 printf("%6zu bytes in total\n", total_len);
812 printf("Running! Hang up with ^C!\n\n");
813 fflush(stdout);
816 sock = pf_socket();
818 if (slow)
819 xmit_slowpath_or_die(ctx, cpu);
820 else
821 xmit_fastpath_or_die(ctx, cpu);
823 close(sock);
825 cleanup_packets();
828 static unsigned int generate_srand_seed(void)
830 int fd;
831 unsigned int seed;
833 fd = open("/dev/urandom", O_RDONLY);
834 if (fd < 0)
835 return time(0);
837 read_or_die(fd, &seed, sizeof(seed));
839 close(fd);
840 return seed;
843 int main(int argc, char **argv)
845 bool slow = false, invoke_cpp = false, reseed = true;
846 int c, opt_index, i, j, vals[4] = {0}, irq;
847 char *confname = NULL, *ptr;
848 unsigned long cpus_tmp;
849 unsigned long long tx_packets, tx_bytes;
850 struct ctx ctx;
852 fmemset(&ctx, 0, sizeof(ctx));
853 ctx.cpus = get_number_cpus_online();
854 ctx.uid = getuid();
855 ctx.gid = getgid();
857 while ((c = getopt_long(argc, argv, short_options, long_options,
858 &opt_index)) != EOF) {
859 switch (c) {
860 case 'h':
861 help();
862 break;
863 case 'v':
864 version();
865 break;
866 case 'e':
867 example();
868 break;
869 case 'p':
870 invoke_cpp = true;
871 break;
872 case 'V':
873 ctx.verbose = true;
874 break;
875 case 'P':
876 cpus_tmp = strtoul(optarg, NULL, 0);
877 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
878 ctx.cpus = cpus_tmp;
879 break;
880 case 'd':
881 case 'o':
882 ctx.device = xstrndup(optarg, IFNAMSIZ);
883 break;
884 case 'r':
885 ctx.rand = true;
886 break;
887 case 's':
888 slow = true;
889 ctx.cpus = 1;
890 ctx.smoke_test = true;
891 ctx.rhost = xstrdup(optarg);
892 break;
893 case 'R':
894 ctx.rfraw = true;
895 break;
896 case 'J':
897 ctx.jumbo_support = true;
898 break;
899 case 'c':
900 case 'i':
901 confname = xstrdup(optarg);
902 if (!strncmp("-", confname, strlen("-")))
903 ctx.cpus = 1;
904 break;
905 case 'u':
906 ctx.uid = strtoul(optarg, NULL, 0);
907 ctx.enforce = true;
908 break;
909 case 'g':
910 ctx.gid = strtoul(optarg, NULL, 0);
911 ctx.enforce = true;
912 break;
913 case 'k':
914 ctx.kpull = strtoul(optarg, NULL, 0);
915 break;
916 case 'E':
917 seed = strtoul(optarg, NULL, 0);
918 reseed = false;
919 break;
920 case 'n':
921 ctx.num = strtoul(optarg, NULL, 0);
922 break;
923 case 't':
924 slow = true;
925 ctx.gap = strtoul(optarg, NULL, 0);
926 if (ctx.gap > 0)
927 /* Fall back to single core to not
928 * mess up correct timing. We are slow
929 * anyway!
931 ctx.cpus = 1;
932 break;
933 case 'S':
934 ptr = optarg;
935 ctx.reserve_size = 0;
937 for (j = i = strlen(optarg); i > 0; --i) {
938 if (!isdigit(optarg[j - i]))
939 break;
940 ptr++;
943 if (!strncmp(ptr, "KiB", strlen("KiB")))
944 ctx.reserve_size = 1 << 10;
945 else if (!strncmp(ptr, "MiB", strlen("MiB")))
946 ctx.reserve_size = 1 << 20;
947 else if (!strncmp(ptr, "GiB", strlen("GiB")))
948 ctx.reserve_size = 1 << 30;
949 else
950 panic("Syntax error in ring size param!\n");
951 *ptr = 0;
953 ctx.reserve_size *= strtol(optarg, NULL, 0);
954 break;
955 case '?':
956 switch (optopt) {
957 case 'd':
958 case 'c':
959 case 'n':
960 case 'S':
961 case 's':
962 case 'P':
963 case 'o':
964 case 'E':
965 case 'i':
966 case 'k':
967 case 'u':
968 case 'g':
969 case 't':
970 panic("Option -%c requires an argument!\n",
971 optopt);
972 default:
973 if (isprint(optopt))
974 printf("Unknown option character `0x%X\'!\n", optopt);
975 die();
977 default:
978 break;
982 if (argc < 5)
983 help();
984 if (ctx.device == NULL)
985 panic("No networking device given!\n");
986 if (confname == NULL)
987 panic("No configuration file given!\n");
988 if (device_mtu(ctx.device) == 0)
989 panic("This is no networking device!\n");
990 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
991 panic("Networking device not running!\n");
993 register_signal(SIGINT, signal_handler);
994 register_signal(SIGHUP, signal_handler);
995 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
997 set_system_socket_memory(vals, array_size(vals));
998 xlockme();
1000 if (ctx.rfraw) {
1001 ctx.device_trans = xstrdup(ctx.device);
1002 xfree(ctx.device);
1004 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1005 sleep(0);
1008 irq = device_irq_number(ctx.device);
1009 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1011 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1012 ctx.cpus = 1;
1014 stats = setup_shared_var(ctx.cpus);
1016 for (i = 0; i < ctx.cpus; i++) {
1017 pid_t pid = fork();
1019 switch (pid) {
1020 case 0:
1021 if (reseed)
1022 seed = generate_srand_seed();
1023 srand(seed);
1025 cpu_affinity(i);
1026 main_loop(&ctx, confname, slow, i, invoke_cpp);
1028 goto thread_out;
1029 case -1:
1030 panic("Cannot fork processes!\n");
1034 for (i = 0; i < ctx.cpus; i++) {
1035 int status;
1037 wait(&status);
1038 if (WEXITSTATUS(status) == EXIT_FAILURE)
1039 die();
1042 if (ctx.rfraw)
1043 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1045 reset_system_socket_memory(vals, array_size(vals));
1047 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1048 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1049 sched_yield();
1051 tx_packets += stats[i].tx_packets;
1052 tx_bytes += stats[i].tx_bytes;
1055 fflush(stdout);
1056 printf("\n");
1057 printf("\r%12llu packets outgoing\n", tx_packets);
1058 printf("\r%12llu bytes outgoing\n", tx_bytes);
1059 for (i = 0; i < ctx.cpus; i++) {
1060 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1061 stats[i].tv_sec, stats[i].tv_usec, i,
1062 stats[i].tx_packets);
1065 thread_out:
1066 xunlockme();
1067 destroy_shared_var(stats, ctx.cpus);
1069 free(ctx.device);
1070 free(ctx.device_trans);
1071 free(ctx.rhost);
1072 free(confname);
1074 return 0;