build: minor: do announcement before tagging
[netsniff-ng.git] / trafgen.c
blob03c12c5b1159097a3130c625673f1290ff6ce900
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 set_itimer_interval_value(&itimer, 0, interval);
131 pull_and_flush_tx_ring(sock);
132 setitimer(ITIMER_REAL, &itimer, NULL);
135 static void help(void)
137 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
138 puts("http://www.netsniff-ng.org\n\n"
139 "Usage: trafgen [options]\n"
140 "Options:\n"
141 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
142 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
143 " -p|--cpp Run packet config through C preprocessor\n"
144 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
145 " -R|--rfraw Inject raw 802.11 frames\n"
146 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
147 " -n|--num <uint> Number of packets until exit (def: 0)\n"
148 " -r|--rand Randomize packet selection (def: round robin)\n"
149 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
150 " -t|--gap <uint> Interpacket gap in us (approx)\n"
151 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
152 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
153 " -E|--seed <uint> Manually set srand(3) seed\n"
154 " -u|--user <userid> Drop privileges and change to userid\n"
155 " -g|--group <groupid> Drop privileges and change to groupid\n"
156 " -V|--verbose Be more verbose\n"
157 " -v|--version Show version\n"
158 " -e|--example Show built-in packet config example\n"
159 " -h|--help Guess what?!\n\n"
160 "Examples:\n"
161 " See trafgen.txf for configuration file examples.\n"
162 " trafgen --dev eth0 --conf trafgen.cfg\n"
163 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
164 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
165 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
166 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
167 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
168 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
169 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
170 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
171 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
172 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
173 "Note:\n"
174 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
175 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
176 " we assume the kernel crashed, thus we print the packet and quit.\n"
177 " In case you find a ping-of-death, please mention trafgen in your\n"
178 " commit message of the fix!\n\n"
179 " For introducing bit errors, delays with random variation and more,\n"
180 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
181 " For generating different package distributions, you can use scripting\n"
182 " to generate a trafgen config file with packet ratios as:\n\n"
183 " IMIX 64:7, 570:4, 1518:1\n"
184 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
185 " Cisco 64:7, 594:4, 1518:1\n"
186 " RPR Trimodal 64:60, 512:20, 1518:20\n"
187 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
188 "Please report bugs to <bugs@netsniff-ng.org>\n"
189 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
190 "Swiss federal institute of technology (ETH Zurich)\n"
191 "License: GNU GPL version 2.0\n"
192 "This is free software: you are free to change and redistribute it.\n"
193 "There is NO WARRANTY, to the extent permitted by law.\n");
194 die();
197 static void example(void)
199 const char *e =
200 "/* Note: dynamic elements make trafgen slower! */\n"
201 "#include <stddef.h>\n\n"
202 "{\n"
203 " /* MAC Destination */\n"
204 " fill(0xff, ETH_ALEN),\n"
205 " /* MAC Source */\n"
206 " 0x00, 0x02, 0xb3, drnd(3),\n"
207 " /* IPv4 Protocol */\n"
208 " c16(ETH_P_IP),\n"
209 " /* IPv4 Version, IHL, TOS */\n"
210 " 0b01000101, 0,\n"
211 " /* IPv4 Total Len */\n"
212 " c16(58),\n"
213 " /* IPv4 Ident */\n"
214 " drnd(2),\n"
215 " /* IPv4 Flags, Frag Off */\n"
216 " 0b01000000, 0,\n"
217 " /* IPv4 TTL */\n"
218 " 64,\n"
219 " /* Proto TCP */\n"
220 " 0x06,\n"
221 " /* IPv4 Checksum (IP header from, to) */\n"
222 " csumip(14, 33),\n"
223 " /* Source IP */\n"
224 " drnd(4),\n"
225 " /* Dest IP */\n"
226 " drnd(4),\n"
227 " /* TCP Source Port */\n"
228 " drnd(2),\n"
229 " /* TCP Dest Port */\n"
230 " c16(80),\n"
231 " /* TCP Sequence Number */\n"
232 " drnd(4),\n"
233 " /* TCP Ackn. Number */\n"
234 " c32(0),\n"
235 " /* TCP Header length + TCP SYN/ECN Flag */\n"
236 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
237 " /* Window Size */\n"
238 " c16(16),\n"
239 " /* TCP Checksum (offset IP, offset TCP) */\n"
240 " csumtcp(14, 34),\n"
241 " /* TCP Options */\n"
242 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
243 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
244 " /* Data blob */\n"
245 " \"gotcha!\",\n"
246 "}";
247 puts(e);
248 die();
251 static void version(void)
253 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
254 puts("http://www.netsniff-ng.org\n\n"
255 "Please report bugs to <bugs@netsniff-ng.org>\n"
256 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
257 "Swiss federal institute of technology (ETH Zurich)\n"
258 "License: GNU GPL version 2.0\n"
259 "This is free software: you are free to change and redistribute it.\n"
260 "There is NO WARRANTY, to the extent permitted by law.\n");
261 die();
264 static void apply_counter(int counter_id)
266 int j, i = counter_id;
267 size_t counter_max = packet_dyn[i].clen;
269 for (j = 0; j < counter_max; ++j) {
270 uint8_t val;
271 struct counter *counter = &packet_dyn[i].cnt[j];
273 val = counter->val - counter->min;
275 switch (counter->type) {
276 case TYPE_INC:
277 val = (val + counter->inc) % (counter->max - counter->min + 1);
278 break;
279 case TYPE_DEC:
280 val = (val - counter->inc) % (counter->min - counter->max + 1);
281 break;
282 default:
283 bug();
286 counter->val = val + counter->min;
287 packets[i].payload[counter->off] = val;
291 static void apply_randomizer(int rand_id)
293 int j, i = rand_id;
294 size_t rand_max = packet_dyn[i].rlen;
296 for (j = 0; j < rand_max; ++j) {
297 uint8_t val = (uint8_t) rand();
298 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
300 packets[i].payload[randomizer->off] = val;
304 static void apply_csum16(int csum_id)
306 int j, i = csum_id;
307 size_t csum_max = packet_dyn[i].slen;
309 for (j = 0; j < csum_max; ++j) {
310 uint16_t sum = 0;
311 struct csum16 *csum = &packet_dyn[i].csum[j];
313 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
315 switch (csum->which) {
316 case CSUM_IP:
317 if (csum->to >= packets[i].len)
318 csum->to = packets[i].len - 1;
319 sum = calc_csum(packets[i].payload + csum->from,
320 csum->to - csum->from + 1, 0);
321 break;
322 case CSUM_UDP:
323 sum = p4_csum((void *) packets[i].payload + csum->from,
324 packets[i].payload + csum->to,
325 (packets[i].len - csum->to),
326 IPPROTO_UDP);
327 break;
328 case CSUM_TCP:
329 sum = p4_csum((void *) packets[i].payload + csum->from,
330 packets[i].payload + csum->to,
331 (packets[i].len - csum->to),
332 IPPROTO_TCP);
333 break;
336 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
340 static struct cpu_stats *setup_shared_var(unsigned long cpus)
342 int fd;
343 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
344 struct cpu_stats *buff;
346 fmemset(zbuff, 0, sizeof(zbuff));
347 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
349 fd = creat(file, S_IRUSR | S_IWUSR);
350 bug_on(fd < 0);
351 close(fd);
353 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
354 S_IRUSR | S_IWUSR);
355 write_or_die(fd, zbuff, sizeof(zbuff));
357 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
358 MAP_SHARED, fd, 0);
359 if (buff == (void *) -1)
360 panic("Cannot setup shared variable!\n");
362 close(fd);
363 unlink(file);
365 memset(buff, 0, sizeof(zbuff));
367 return buff;
370 static void destroy_shared_var(void *buff, unsigned long cpus)
372 munmap(buff, cpus * sizeof(struct cpu_stats));
375 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
377 int i;
379 printf("{");
380 for (i = 0; i < len; ++i) {
381 if (i % 15 == 0)
382 printf("\n ");
383 printf("0x%02x, ", payload[i]);
385 printf("\n}\n");
386 fflush(stdout);
389 static int xmit_smoke_setup(struct ctx *ctx)
391 int icmp_sock, ret, ttl = 64;
392 struct icmp_filter filter;
394 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
395 if (icmp_sock < 0)
396 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
398 filter.data = ~(1 << ICMP_ECHOREPLY);
400 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
401 if (ret < 0)
402 panic("Cannot install filter!\n");
404 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
405 if (ret < 0)
406 panic("Cannot set TTL!\n");
408 memset(&ctx->dest, 0, sizeof(ctx->dest));
409 ctx->dest.sin_family = AF_INET;
410 ctx->dest.sin_port = 0;
412 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
413 if (ret < 0)
414 panic("Cannot resolv address!\n");
416 return icmp_sock;
419 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
421 int ret, i, j = 0, probes = 100;
422 short ident, cnt = 1, idstore[probes];
423 uint8_t outpack[512], *data;
424 struct icmphdr *icmp;
425 struct iphdr *ip;
426 size_t len = sizeof(*icmp) + 56;
427 struct sockaddr_in from;
428 socklen_t from_len;
429 struct pollfd fds = {
430 .fd = icmp_sock,
431 .events = POLLIN,
434 fmemset(idstore, 0, sizeof(idstore));
435 while (probes-- > 0) {
436 while ((ident = htons((short) rand())) == 0)
437 sleep(0);
438 idstore[j++] = ident;
440 memset(outpack, 0, sizeof(outpack));
441 icmp = (void *) outpack;
442 icmp->type = ICMP_ECHO;
443 icmp->code = 0;
444 icmp->checksum = 0;
445 icmp->un.echo.id = ident;
446 icmp->un.echo.sequence = htons(cnt++);
448 data = ((uint8_t *) outpack + sizeof(*icmp));
449 for (i = 0; i < 56; ++i)
450 data[i] = (uint8_t) rand();
452 icmp->checksum = csum((unsigned short *) outpack,
453 len / sizeof(unsigned short));
455 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
456 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
457 if (unlikely(ret != len))
458 panic("Cannot send out probe: %s!\n", strerror(errno));
460 ret = poll(&fds, 1, 50);
461 if (ret < 0)
462 panic("Poll failed!\n");
464 if (fds.revents & POLLIN) {
465 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
466 (struct sockaddr *) &from, &from_len);
467 if (unlikely(ret <= 0))
468 panic("Probe receive failed!\n");
469 if (unlikely(from_len != sizeof(ctx->dest)))
470 continue;
471 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
472 continue;
473 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
474 continue;
475 ip = (void *) outpack;
476 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
477 continue;
478 icmp = (void *) outpack + ip->ihl * 4;
479 for (i = 0; i < array_size(idstore); ++i) {
480 if (unlikely(icmp->un.echo.id != idstore[i]))
481 continue;
482 return 0;
487 return -1;
490 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
492 int ret, icmp_sock = -1;
493 unsigned long num = 1, i = 0;
494 struct timeval start, end, diff;
495 unsigned long long tx_bytes = 0, tx_packets = 0;
496 struct packet_dyn *pktd;
497 struct sockaddr_ll saddr = {
498 .sll_family = PF_PACKET,
499 .sll_halen = ETH_ALEN,
500 .sll_ifindex = device_ifindex(ctx->device),
503 if (ctx->num > 0)
504 num = ctx->num;
506 if (ctx->smoke_test)
507 icmp_sock = xmit_smoke_setup(ctx);
509 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
511 bug_on(gettimeofday(&start, NULL));
513 while (likely(sigint == 0) && likely(num > 0)) {
514 pktd = &packet_dyn[i];
515 if (pktd->clen + pktd->rlen + pktd->slen) {
516 apply_counter(i);
517 apply_randomizer(i);
518 apply_csum16(i);
520 retry:
521 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
522 (struct sockaddr *) &saddr, sizeof(saddr));
523 if (unlikely(ret < 0)) {
524 if (errno == ENOBUFS) {
525 sched_yield();
526 goto retry;
529 panic("Sendto error: %s!\n", strerror(errno));
532 tx_bytes += packets[i].len;
533 tx_packets++;
535 if (ctx->smoke_test) {
536 ret = xmit_smoke_probe(icmp_sock, ctx);
537 if (unlikely(ret < 0)) {
538 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
539 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
540 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
541 i, seed);
543 dump_trafgen_snippet(packets[i].payload, packets[i].len);
544 break;
548 if (!ctx->rand) {
549 i++;
550 if (i >= plen)
551 i = 0;
552 } else
553 i = rand() % plen;
555 if (ctx->num > 0)
556 num--;
558 if (ctx->gap > 0)
559 usleep(ctx->gap);
562 bug_on(gettimeofday(&end, NULL));
563 timersub(&end, &start, &diff);
565 if (ctx->smoke_test)
566 close(icmp_sock);
568 stats[cpu].tx_packets = tx_packets;
569 stats[cpu].tx_bytes = tx_bytes;
570 stats[cpu].tv_sec = diff.tv_sec;
571 stats[cpu].tv_usec = diff.tv_usec;
573 stats[cpu].state |= CPU_STATS_STATE_RES;
576 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
578 int ifindex = device_ifindex(ctx->device);
579 uint8_t *out = NULL;
580 unsigned int it = 0;
581 unsigned long num = 1, i = 0, size;
582 struct ring tx_ring;
583 struct frame_map *hdr;
584 struct timeval start, end, diff;
585 struct packet_dyn *pktd;
586 unsigned long long tx_bytes = 0, tx_packets = 0;
588 fmemset(&tx_ring, 0, sizeof(tx_ring));
590 size = ring_size(ctx->device, ctx->reserve_size);
592 set_sock_prio(sock, 512);
593 set_packet_loss_discard(sock);
595 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
596 create_tx_ring(sock, &tx_ring, ctx->verbose);
597 mmap_tx_ring(sock, &tx_ring);
598 alloc_tx_ring_frames(&tx_ring);
599 bind_tx_ring(sock, &tx_ring, ifindex);
601 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
603 if (ctx->kpull)
604 interval = ctx->kpull;
605 if (ctx->num > 0)
606 num = ctx->num;
608 set_itimer_interval_value(&itimer, 0, interval);
609 setitimer(ITIMER_REAL, &itimer, NULL);
611 bug_on(gettimeofday(&start, NULL));
613 while (likely(sigint == 0) && likely(num > 0)) {
614 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
615 hdr = tx_ring.frames[it].iov_base;
616 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
618 hdr->tp_h.tp_snaplen = packets[i].len;
619 hdr->tp_h.tp_len = packets[i].len;
621 pktd = &packet_dyn[i];
622 if (pktd->clen + pktd->rlen + pktd->slen) {
623 apply_counter(i);
624 apply_randomizer(i);
625 apply_csum16(i);
628 fmemcpy(out, packets[i].payload, packets[i].len);
630 tx_bytes += packets[i].len;
631 tx_packets++;
633 if (!ctx->rand) {
634 i++;
635 if (i >= plen)
636 i = 0;
637 } else
638 i = rand() % plen;
640 kernel_may_pull_from_tx(&hdr->tp_h);
642 it++;
643 if (it >= tx_ring.layout.tp_frame_nr)
644 it = 0;
646 if (ctx->num > 0)
647 num--;
649 if (unlikely(sigint == 1))
650 break;
654 bug_on(gettimeofday(&end, NULL));
655 timersub(&end, &start, &diff);
657 destroy_tx_ring(sock, &tx_ring);
659 stats[cpu].tx_packets = tx_packets;
660 stats[cpu].tx_bytes = tx_bytes;
661 stats[cpu].tv_sec = diff.tv_sec;
662 stats[cpu].tv_usec = diff.tv_usec;
664 stats[cpu].state |= CPU_STATS_STATE_RES;
667 static inline void __set_state(int cpu, sig_atomic_t s)
669 stats[cpu].state = s;
672 static inline sig_atomic_t __get_state(int cpu)
674 return stats[cpu].state;
677 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
679 int i;
680 unsigned long total;
682 for (i = 0, total = plen; i < ctx->cpus; i++) {
683 if (i == cpu)
684 continue;
686 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
687 sigint == 0)
688 sched_yield();
690 total += stats[i].cf_packets;
693 return total;
696 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
698 int i, cpu_sel;
699 unsigned long total;
700 long long delta_correction = 0;
702 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
703 if (i == cpu)
704 continue;
706 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
707 sigint == 0)
708 sched_yield();
710 total += stats[i].cd_packets;
713 if (total > orig)
714 delta_correction = -1 * ((long long) total - orig);
715 if (total < orig)
716 delta_correction = +1 * ((long long) orig - total);
718 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
719 if (stats[i].cd_packets > 0) {
720 if ((long long) stats[i].cd_packets +
721 delta_correction > 0) {
722 cpu_sel = i;
723 break;
728 if (cpu == cpu_sel)
729 ctx->num += delta_correction;
732 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
733 sig_atomic_t s)
735 stats[cpu].cf_packets = p;
736 stats[cpu].cf_bytes = b;
737 stats[cpu].state = s;
740 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
742 stats[cpu].cd_packets = p;
743 stats[cpu].state = s;
746 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
748 int i;
749 unsigned long plen_total, orig = ctx->num;
750 size_t mtu, total_len = 0;
752 bug_on(plen != dlen);
754 for (i = 0; i < plen; ++i)
755 total_len += packets[i].len;
757 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
758 plen_total = __wait_and_sum_others(ctx, cpu);
760 if (orig > 0) {
761 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
763 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
764 CPU_STATS_STATE_CFG);
765 __correct_global_delta(ctx, cpu, orig);
768 if (plen == 0) {
769 __set_state(cpu, CPU_STATS_STATE_RES);
770 return -1;
773 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
774 if (packets[i].len > mtu + 14)
775 panic("Device MTU < than packet%d's size!\n", i);
776 if (packets[i].len <= 14)
777 panic("Packet%d's size too short!\n", i);
780 return 0;
783 static void main_loop(struct ctx *ctx, char *confname, bool slow,
784 int cpu, bool invoke_cpp)
786 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
787 if (xmit_packet_precheck(ctx, cpu) < 0)
788 return;
790 if (cpu == 0) {
791 int i;
792 size_t total_len = 0, total_pkts = 0;
794 for (i = 0; i < ctx->cpus; ++i) {
795 total_len += stats[i].cf_bytes;
796 total_pkts += stats[i].cf_packets;
799 printf("%6zu packets to schedule\n", total_pkts);
800 printf("%6zu bytes in total\n", total_len);
801 printf("Running! Hang up with ^C!\n\n");
802 fflush(stdout);
805 sock = pf_socket();
807 if (slow)
808 xmit_slowpath_or_die(ctx, cpu);
809 else
810 xmit_fastpath_or_die(ctx, cpu);
812 close(sock);
814 cleanup_packets();
817 static unsigned int generate_srand_seed(void)
819 int fd;
820 unsigned int seed;
822 fd = open("/dev/urandom", O_RDONLY);
823 if (fd < 0)
824 return time(0);
826 read_or_die(fd, &seed, sizeof(seed));
828 close(fd);
829 return seed;
832 int main(int argc, char **argv)
834 bool slow = false, invoke_cpp = false, reseed = true;
835 int c, opt_index, i, j, vals[4] = {0}, irq;
836 char *confname = NULL, *ptr;
837 unsigned long cpus_tmp;
838 unsigned long long tx_packets, tx_bytes;
839 struct ctx ctx;
841 fmemset(&ctx, 0, sizeof(ctx));
842 ctx.cpus = get_number_cpus_online();
843 ctx.uid = getuid();
844 ctx.gid = getgid();
846 while ((c = getopt_long(argc, argv, short_options, long_options,
847 &opt_index)) != EOF) {
848 switch (c) {
849 case 'h':
850 help();
851 break;
852 case 'v':
853 version();
854 break;
855 case 'e':
856 example();
857 break;
858 case 'p':
859 invoke_cpp = true;
860 break;
861 case 'V':
862 ctx.verbose = true;
863 break;
864 case 'P':
865 cpus_tmp = strtoul(optarg, NULL, 0);
866 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
867 ctx.cpus = cpus_tmp;
868 break;
869 case 'd':
870 case 'o':
871 ctx.device = xstrndup(optarg, IFNAMSIZ);
872 break;
873 case 'r':
874 ctx.rand = true;
875 break;
876 case 's':
877 slow = true;
878 ctx.cpus = 1;
879 ctx.smoke_test = true;
880 ctx.rhost = xstrdup(optarg);
881 break;
882 case 'R':
883 ctx.rfraw = true;
884 break;
885 case 'J':
886 ctx.jumbo_support = true;
887 break;
888 case 'c':
889 case 'i':
890 confname = xstrdup(optarg);
891 if (!strncmp("-", confname, strlen("-")))
892 ctx.cpus = 1;
893 break;
894 case 'u':
895 ctx.uid = strtoul(optarg, NULL, 0);
896 ctx.enforce = true;
897 break;
898 case 'g':
899 ctx.gid = strtoul(optarg, NULL, 0);
900 ctx.enforce = true;
901 break;
902 case 'k':
903 ctx.kpull = strtoul(optarg, NULL, 0);
904 break;
905 case 'E':
906 seed = strtoul(optarg, NULL, 0);
907 reseed = false;
908 break;
909 case 'n':
910 ctx.num = strtoul(optarg, NULL, 0);
911 break;
912 case 't':
913 slow = true;
914 ctx.gap = strtoul(optarg, NULL, 0);
915 if (ctx.gap > 0)
916 /* Fall back to single core to not
917 * mess up correct timing. We are slow
918 * anyway!
920 ctx.cpus = 1;
921 break;
922 case 'S':
923 ptr = optarg;
924 ctx.reserve_size = 0;
926 for (j = i = strlen(optarg); i > 0; --i) {
927 if (!isdigit(optarg[j - i]))
928 break;
929 ptr++;
932 if (!strncmp(ptr, "KiB", strlen("KiB")))
933 ctx.reserve_size = 1 << 10;
934 else if (!strncmp(ptr, "MiB", strlen("MiB")))
935 ctx.reserve_size = 1 << 20;
936 else if (!strncmp(ptr, "GiB", strlen("GiB")))
937 ctx.reserve_size = 1 << 30;
938 else
939 panic("Syntax error in ring size param!\n");
940 *ptr = 0;
942 ctx.reserve_size *= strtol(optarg, NULL, 0);
943 break;
944 case '?':
945 switch (optopt) {
946 case 'd':
947 case 'c':
948 case 'n':
949 case 'S':
950 case 's':
951 case 'P':
952 case 'o':
953 case 'E':
954 case 'i':
955 case 'k':
956 case 'u':
957 case 'g':
958 case 't':
959 panic("Option -%c requires an argument!\n",
960 optopt);
961 default:
962 if (isprint(optopt))
963 printf("Unknown option character `0x%X\'!\n", optopt);
964 die();
966 default:
967 break;
971 if (argc < 5)
972 help();
973 if (ctx.device == NULL)
974 panic("No networking device given!\n");
975 if (confname == NULL)
976 panic("No configuration file given!\n");
977 if (device_mtu(ctx.device) == 0)
978 panic("This is no networking device!\n");
979 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
980 panic("Networking device not running!\n");
982 register_signal(SIGINT, signal_handler);
983 register_signal(SIGHUP, signal_handler);
984 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
986 set_system_socket_memory(vals, array_size(vals));
987 xlockme();
989 if (ctx.rfraw) {
990 ctx.device_trans = xstrdup(ctx.device);
991 xfree(ctx.device);
993 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
994 sleep(0);
997 irq = device_irq_number(ctx.device);
998 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1000 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1001 ctx.cpus = 1;
1003 stats = setup_shared_var(ctx.cpus);
1005 for (i = 0; i < ctx.cpus; i++) {
1006 pid_t pid = fork();
1008 switch (pid) {
1009 case 0:
1010 if (reseed)
1011 seed = generate_srand_seed();
1012 srand(seed);
1014 cpu_affinity(i);
1015 main_loop(&ctx, confname, slow, i, invoke_cpp);
1017 goto thread_out;
1018 case -1:
1019 panic("Cannot fork processes!\n");
1023 for (i = 0; i < ctx.cpus; i++) {
1024 int status;
1026 wait(&status);
1027 if (WEXITSTATUS(status) == EXIT_FAILURE)
1028 die();
1031 if (ctx.rfraw)
1032 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1034 reset_system_socket_memory(vals, array_size(vals));
1036 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1037 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1038 sched_yield();
1040 tx_packets += stats[i].tx_packets;
1041 tx_bytes += stats[i].tx_bytes;
1044 fflush(stdout);
1045 printf("\n");
1046 printf("\r%12llu packets outgoing\n", tx_packets);
1047 printf("\r%12llu bytes outgoing\n", tx_bytes);
1048 for (i = 0; i < ctx.cpus; i++) {
1049 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1050 stats[i].tv_sec, stats[i].tv_usec, i,
1051 stats[i].tx_packets);
1054 thread_out:
1055 xunlockme();
1056 destroy_shared_var(stats, ctx.cpus);
1058 free(ctx.device);
1059 free(ctx.device_trans);
1060 free(ctx.rhost);
1061 free(confname);
1063 return 0;