make: allow to overwrite CFLAGS, CCACHE
[netsniff-ng.git] / trafgen.c
blob4e670ed448c00959295f8a65f3abc4c3ef5a2765
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 = pull_and_flush_tx_ring(sock);
131 if (unlikely(ret < 0)) {
132 /* We could hit EBADF if the socket has been closed before
133 * the timer was triggered.
135 if (errno != EBADF && errno != ENOBUFS)
136 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
139 set_itimer_interval_value(&itimer, 0, interval);
140 setitimer(ITIMER_REAL, &itimer, NULL);
143 static void timer_purge(void)
145 int ret;
147 ret = pull_and_flush_tx_ring_wait(sock);
148 if (unlikely(ret < 0)) {
149 /* We could hit EBADF if the socket has been closed before
150 * the timer was triggered.
152 if (errno != EBADF && errno != ENOBUFS)
153 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
156 set_itimer_interval_value(&itimer, 0, 0);
157 setitimer(ITIMER_REAL, &itimer, NULL);
160 static void help(void)
162 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
163 puts("http://www.netsniff-ng.org\n\n"
164 "Usage: trafgen [options]\n"
165 "Options:\n"
166 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
167 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
168 " -p|--cpp Run packet config through C preprocessor\n"
169 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
170 " -R|--rfraw Inject raw 802.11 frames\n"
171 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
172 " -n|--num <uint> Number of packets until exit (def: 0)\n"
173 " -r|--rand Randomize packet selection (def: round robin)\n"
174 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
175 " -t|--gap <uint> Interpacket gap in us (approx)\n"
176 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
177 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
178 " -E|--seed <uint> Manually set srand(3) seed\n"
179 " -u|--user <userid> Drop privileges and change to userid\n"
180 " -g|--group <groupid> Drop privileges and change to groupid\n"
181 " -V|--verbose Be more verbose\n"
182 " -v|--version Show version\n"
183 " -e|--example Show built-in packet config example\n"
184 " -h|--help Guess what?!\n\n"
185 "Examples:\n"
186 " See trafgen.txf for configuration file examples.\n"
187 " trafgen --dev eth0 --conf trafgen.cfg\n"
188 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
189 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
190 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
191 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
192 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
193 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
194 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
195 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
196 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
197 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
198 "Note:\n"
199 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
200 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
201 " we assume the kernel crashed, thus we print the packet and quit.\n"
202 " In case you find a ping-of-death, please mention trafgen in your\n"
203 " commit message of the fix!\n\n"
204 " For introducing bit errors, delays with random variation and more,\n"
205 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
206 " For generating different package distributions, you can use scripting\n"
207 " to generate a trafgen config file with packet ratios as:\n\n"
208 " IMIX 64:7, 570:4, 1518:1\n"
209 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
210 " Cisco 64:7, 594:4, 1518:1\n"
211 " RPR Trimodal 64:60, 512:20, 1518:20\n"
212 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
213 "Please report bugs to <bugs@netsniff-ng.org>\n"
214 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
215 "Swiss federal institute of technology (ETH Zurich)\n"
216 "License: GNU GPL version 2.0\n"
217 "This is free software: you are free to change and redistribute it.\n"
218 "There is NO WARRANTY, to the extent permitted by law.\n");
219 die();
222 static void example(void)
224 const char *e =
225 "/* Note: dynamic elements make trafgen slower! */\n"
226 "#include <stddef.h>\n\n"
227 "{\n"
228 " /* MAC Destination */\n"
229 " fill(0xff, ETH_ALEN),\n"
230 " /* MAC Source */\n"
231 " 0x00, 0x02, 0xb3, drnd(3),\n"
232 " /* IPv4 Protocol */\n"
233 " c16(ETH_P_IP),\n"
234 " /* IPv4 Version, IHL, TOS */\n"
235 " 0b01000101, 0,\n"
236 " /* IPv4 Total Len */\n"
237 " c16(58),\n"
238 " /* IPv4 Ident */\n"
239 " drnd(2),\n"
240 " /* IPv4 Flags, Frag Off */\n"
241 " 0b01000000, 0,\n"
242 " /* IPv4 TTL */\n"
243 " 64,\n"
244 " /* Proto TCP */\n"
245 " 0x06,\n"
246 " /* IPv4 Checksum (IP header from, to) */\n"
247 " csumip(14, 33),\n"
248 " /* Source IP */\n"
249 " drnd(4),\n"
250 " /* Dest IP */\n"
251 " drnd(4),\n"
252 " /* TCP Source Port */\n"
253 " drnd(2),\n"
254 " /* TCP Dest Port */\n"
255 " c16(80),\n"
256 " /* TCP Sequence Number */\n"
257 " drnd(4),\n"
258 " /* TCP Ackn. Number */\n"
259 " c32(0),\n"
260 " /* TCP Header length + TCP SYN/ECN Flag */\n"
261 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
262 " /* Window Size */\n"
263 " c16(16),\n"
264 " /* TCP Checksum (offset IP, offset TCP) */\n"
265 " csumtcp(14, 34),\n"
266 " /* TCP Options */\n"
267 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
268 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
269 " /* Data blob */\n"
270 " \"gotcha!\",\n"
271 "}";
272 puts(e);
273 die();
276 static void version(void)
278 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
279 puts("http://www.netsniff-ng.org\n\n"
280 "Please report bugs to <bugs@netsniff-ng.org>\n"
281 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
282 "Swiss federal institute of technology (ETH Zurich)\n"
283 "License: GNU GPL version 2.0\n"
284 "This is free software: you are free to change and redistribute it.\n"
285 "There is NO WARRANTY, to the extent permitted by law.\n");
286 die();
289 static void apply_counter(int counter_id)
291 int j, i = counter_id;
292 size_t counter_max = packet_dyn[i].clen;
294 for (j = 0; j < counter_max; ++j) {
295 uint8_t val;
296 struct counter *counter = &packet_dyn[i].cnt[j];
298 val = counter->val - counter->min;
300 switch (counter->type) {
301 case TYPE_INC:
302 val = (val + counter->inc) % (counter->max - counter->min + 1);
303 break;
304 case TYPE_DEC:
305 val = (val - counter->inc) % (counter->min - counter->max + 1);
306 break;
307 default:
308 bug();
311 counter->val = val + counter->min;
312 packets[i].payload[counter->off] = val;
316 static void apply_randomizer(int rand_id)
318 int j, i = rand_id;
319 size_t rand_max = packet_dyn[i].rlen;
321 for (j = 0; j < rand_max; ++j) {
322 uint8_t val = (uint8_t) rand();
323 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
325 packets[i].payload[randomizer->off] = val;
329 static void apply_csum16(int csum_id)
331 int j, i = csum_id;
332 size_t csum_max = packet_dyn[i].slen;
334 for (j = 0; j < csum_max; ++j) {
335 uint16_t sum = 0;
336 struct csum16 *csum = &packet_dyn[i].csum[j];
338 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
340 switch (csum->which) {
341 case CSUM_IP:
342 if (csum->to >= packets[i].len)
343 csum->to = packets[i].len - 1;
344 sum = calc_csum(packets[i].payload + csum->from,
345 csum->to - csum->from + 1, 0);
346 break;
347 case CSUM_UDP:
348 sum = p4_csum((void *) packets[i].payload + csum->from,
349 packets[i].payload + csum->to,
350 (packets[i].len - csum->to),
351 IPPROTO_UDP);
352 break;
353 case CSUM_TCP:
354 sum = p4_csum((void *) packets[i].payload + csum->from,
355 packets[i].payload + csum->to,
356 (packets[i].len - csum->to),
357 IPPROTO_TCP);
358 break;
361 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
365 static struct cpu_stats *setup_shared_var(unsigned long cpus)
367 int fd;
368 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
369 struct cpu_stats *buff;
371 fmemset(zbuff, 0, sizeof(zbuff));
372 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
374 fd = creat(file, S_IRUSR | S_IWUSR);
375 bug_on(fd < 0);
376 close(fd);
378 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
379 S_IRUSR | S_IWUSR);
380 write_or_die(fd, zbuff, sizeof(zbuff));
382 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
383 MAP_SHARED, fd, 0);
384 if (buff == (void *) -1)
385 panic("Cannot setup shared variable!\n");
387 close(fd);
388 unlink(file);
390 memset(buff, 0, sizeof(zbuff));
392 return buff;
395 static void destroy_shared_var(void *buff, unsigned long cpus)
397 munmap(buff, cpus * sizeof(struct cpu_stats));
400 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
402 int i;
404 printf("{");
405 for (i = 0; i < len; ++i) {
406 if (i % 15 == 0)
407 printf("\n ");
408 printf("0x%02x, ", payload[i]);
410 printf("\n}\n");
411 fflush(stdout);
414 static int xmit_smoke_setup(struct ctx *ctx)
416 int icmp_sock, ret, ttl = 64;
417 struct icmp_filter filter;
419 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
420 if (icmp_sock < 0)
421 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
423 filter.data = ~(1 << ICMP_ECHOREPLY);
425 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
426 if (ret < 0)
427 panic("Cannot install filter!\n");
429 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
430 if (ret < 0)
431 panic("Cannot set TTL!\n");
433 memset(&ctx->dest, 0, sizeof(ctx->dest));
434 ctx->dest.sin_family = AF_INET;
435 ctx->dest.sin_port = 0;
437 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
438 if (ret < 0)
439 panic("Cannot resolv address!\n");
441 return icmp_sock;
444 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
446 int ret, i, j = 0, probes = 100;
447 short ident, cnt = 1, idstore[probes];
448 uint8_t outpack[512], *data;
449 struct icmphdr *icmp;
450 struct iphdr *ip;
451 size_t len = sizeof(*icmp) + 56;
452 struct sockaddr_in from;
453 socklen_t from_len;
454 struct pollfd fds = {
455 .fd = icmp_sock,
456 .events = POLLIN,
459 fmemset(idstore, 0, sizeof(idstore));
460 while (probes-- > 0) {
461 while ((ident = htons((short) rand())) == 0)
462 sleep(0);
463 idstore[j++] = ident;
465 memset(outpack, 0, sizeof(outpack));
466 icmp = (void *) outpack;
467 icmp->type = ICMP_ECHO;
468 icmp->code = 0;
469 icmp->checksum = 0;
470 icmp->un.echo.id = ident;
471 icmp->un.echo.sequence = htons(cnt++);
473 data = ((uint8_t *) outpack + sizeof(*icmp));
474 for (i = 0; i < 56; ++i)
475 data[i] = (uint8_t) rand();
477 icmp->checksum = csum((unsigned short *) outpack,
478 len / sizeof(unsigned short));
480 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
481 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
482 if (unlikely(ret != len))
483 panic("Cannot send out probe: %s!\n", strerror(errno));
485 ret = poll(&fds, 1, 50);
486 if (ret < 0)
487 panic("Poll failed!\n");
489 if (fds.revents & POLLIN) {
490 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
491 (struct sockaddr *) &from, &from_len);
492 if (unlikely(ret <= 0))
493 panic("Probe receive failed!\n");
494 if (unlikely(from_len != sizeof(ctx->dest)))
495 continue;
496 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
497 continue;
498 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
499 continue;
500 ip = (void *) outpack;
501 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
502 continue;
503 icmp = (void *) outpack + ip->ihl * 4;
504 for (i = 0; i < array_size(idstore); ++i) {
505 if (unlikely(icmp->un.echo.id != idstore[i]))
506 continue;
507 return 0;
512 return -1;
515 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
517 int ret, icmp_sock = -1;
518 unsigned long num = 1, i = 0;
519 struct timeval start, end, diff;
520 unsigned long long tx_bytes = 0, tx_packets = 0;
521 struct packet_dyn *pktd;
522 struct sockaddr_ll saddr = {
523 .sll_family = PF_PACKET,
524 .sll_halen = ETH_ALEN,
525 .sll_ifindex = device_ifindex(ctx->device),
528 if (ctx->num > 0)
529 num = ctx->num;
530 if (ctx->num == 0 && orig_num > 0)
531 num = 0;
533 if (ctx->smoke_test)
534 icmp_sock = xmit_smoke_setup(ctx);
536 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
538 bug_on(gettimeofday(&start, NULL));
540 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
541 pktd = &packet_dyn[i];
542 if (pktd->clen + pktd->rlen + pktd->slen) {
543 apply_counter(i);
544 apply_randomizer(i);
545 apply_csum16(i);
547 retry:
548 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
549 (struct sockaddr *) &saddr, sizeof(saddr));
550 if (unlikely(ret < 0)) {
551 if (errno == ENOBUFS) {
552 sched_yield();
553 goto retry;
556 panic("Sendto error: %s!\n", strerror(errno));
559 tx_bytes += packets[i].len;
560 tx_packets++;
562 if (ctx->smoke_test) {
563 ret = xmit_smoke_probe(icmp_sock, ctx);
564 if (unlikely(ret < 0)) {
565 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
566 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
567 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
568 i, seed);
570 dump_trafgen_snippet(packets[i].payload, packets[i].len);
571 break;
575 if (!ctx->rand) {
576 i++;
577 if (i >= plen)
578 i = 0;
579 } else
580 i = rand() % plen;
582 if (ctx->num > 0)
583 num--;
585 if (ctx->gap > 0)
586 usleep(ctx->gap);
589 bug_on(gettimeofday(&end, NULL));
590 timersub(&end, &start, &diff);
592 if (ctx->smoke_test)
593 close(icmp_sock);
595 stats[cpu].tx_packets = tx_packets;
596 stats[cpu].tx_bytes = tx_bytes;
597 stats[cpu].tv_sec = diff.tv_sec;
598 stats[cpu].tv_usec = diff.tv_usec;
600 stats[cpu].state |= CPU_STATS_STATE_RES;
603 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
605 int ifindex = device_ifindex(ctx->device);
606 uint8_t *out = NULL;
607 unsigned int it = 0;
608 unsigned long num = 1, i = 0, size;
609 struct ring tx_ring;
610 struct frame_map *hdr;
611 struct timeval start, end, diff;
612 struct packet_dyn *pktd;
613 unsigned long long tx_bytes = 0, tx_packets = 0;
615 fmemset(&tx_ring, 0, sizeof(tx_ring));
617 size = ring_size(ctx->device, ctx->reserve_size);
619 set_sock_prio(sock, 512);
620 set_packet_loss_discard(sock);
622 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
623 create_tx_ring(sock, &tx_ring, ctx->verbose);
624 mmap_tx_ring(sock, &tx_ring);
625 alloc_tx_ring_frames(&tx_ring);
626 bind_tx_ring(sock, &tx_ring, ifindex);
628 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
630 if (ctx->kpull)
631 interval = ctx->kpull;
632 if (ctx->num > 0)
633 num = ctx->num;
634 if (ctx->num == 0 && orig_num > 0)
635 num = 0;
637 set_itimer_interval_value(&itimer, 0, interval);
638 setitimer(ITIMER_REAL, &itimer, NULL);
640 bug_on(gettimeofday(&start, NULL));
642 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
643 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
644 hdr = tx_ring.frames[it].iov_base;
645 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
647 hdr->tp_h.tp_snaplen = packets[i].len;
648 hdr->tp_h.tp_len = packets[i].len;
650 pktd = &packet_dyn[i];
651 if (pktd->clen + pktd->rlen + pktd->slen) {
652 apply_counter(i);
653 apply_randomizer(i);
654 apply_csum16(i);
657 fmemcpy(out, packets[i].payload, packets[i].len);
659 tx_bytes += packets[i].len;
660 tx_packets++;
662 if (!ctx->rand) {
663 i++;
664 if (i >= plen)
665 i = 0;
666 } else
667 i = rand() % plen;
669 kernel_may_pull_from_tx(&hdr->tp_h);
671 it++;
672 if (it >= tx_ring.layout.tp_frame_nr)
673 it = 0;
675 if (ctx->num > 0)
676 num--;
678 if (unlikely(sigint == 1))
679 break;
683 bug_on(gettimeofday(&end, NULL));
684 timersub(&end, &start, &diff);
686 timer_purge();
688 destroy_tx_ring(sock, &tx_ring);
690 stats[cpu].tx_packets = tx_packets;
691 stats[cpu].tx_bytes = tx_bytes;
692 stats[cpu].tv_sec = diff.tv_sec;
693 stats[cpu].tv_usec = diff.tv_usec;
695 stats[cpu].state |= CPU_STATS_STATE_RES;
698 static inline void __set_state(int cpu, sig_atomic_t s)
700 stats[cpu].state = s;
703 static inline sig_atomic_t __get_state(int cpu)
705 return stats[cpu].state;
708 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
710 int i;
711 unsigned long total;
713 for (i = 0, total = plen; i < ctx->cpus; i++) {
714 if (i == cpu)
715 continue;
717 while ((__get_state(i) &
718 (CPU_STATS_STATE_CFG |
719 CPU_STATS_STATE_RES)) == 0 &&
720 sigint == 0)
721 sched_yield();
723 total += stats[i].cf_packets;
726 return total;
729 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
731 int i, cpu_sel;
732 unsigned long total;
733 long long delta_correction = 0;
735 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
736 if (i == cpu)
737 continue;
739 while ((__get_state(i) &
740 (CPU_STATS_STATE_CHK |
741 CPU_STATS_STATE_RES)) == 0 &&
742 sigint == 0)
743 sched_yield();
745 total += stats[i].cd_packets;
748 if (total > orig)
749 delta_correction = -1 * ((long long) total - orig);
750 if (total < orig)
751 delta_correction = +1 * ((long long) orig - total);
753 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
754 if (stats[i].cd_packets > 0) {
755 if ((long long) stats[i].cd_packets +
756 delta_correction > 0) {
757 cpu_sel = i;
758 break;
763 if (cpu == cpu_sel)
764 ctx->num += delta_correction;
767 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
768 sig_atomic_t s)
770 stats[cpu].cf_packets = p;
771 stats[cpu].cf_bytes = b;
772 stats[cpu].state = s;
775 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
777 stats[cpu].cd_packets = p;
778 stats[cpu].state = s;
781 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
783 int i;
784 unsigned long plen_total, orig = ctx->num;
785 size_t mtu, total_len = 0;
787 bug_on(plen != dlen);
789 for (i = 0; i < plen; ++i)
790 total_len += packets[i].len;
792 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
793 plen_total = __wait_and_sum_others(ctx, cpu);
795 if (orig > 0) {
796 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
798 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
799 CPU_STATS_STATE_CFG);
800 __correct_global_delta(ctx, cpu, orig);
803 if (plen == 0) {
804 __set_state(cpu, CPU_STATS_STATE_RES);
805 return 0;
808 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
809 if (packets[i].len > mtu + 14)
810 panic("Device MTU < than packet%d's size!\n", i);
811 if (packets[i].len <= 14)
812 panic("Packet%d's size too short!\n", i);
815 return 0;
818 static void main_loop(struct ctx *ctx, char *confname, bool slow,
819 int cpu, bool invoke_cpp, unsigned long orig_num)
821 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
822 if (xmit_packet_precheck(ctx, cpu) < 0)
823 return;
825 if (cpu == 0) {
826 int i;
827 size_t total_len = 0, total_pkts = 0;
829 for (i = 0; i < ctx->cpus; ++i) {
830 total_len += stats[i].cf_bytes;
831 total_pkts += stats[i].cf_packets;
834 printf("%6zu packets to schedule\n", total_pkts);
835 printf("%6zu bytes in total\n", total_len);
836 printf("Running! Hang up with ^C!\n\n");
837 fflush(stdout);
840 sock = pf_socket();
842 if (slow)
843 xmit_slowpath_or_die(ctx, cpu, orig_num);
844 else
845 xmit_fastpath_or_die(ctx, cpu, orig_num);
847 close(sock);
849 cleanup_packets();
852 static unsigned int generate_srand_seed(void)
854 int fd;
855 unsigned int seed;
857 fd = open("/dev/urandom", O_RDONLY);
858 if (fd < 0)
859 return time(0);
861 read_or_die(fd, &seed, sizeof(seed));
863 close(fd);
864 return seed;
867 int main(int argc, char **argv)
869 bool slow = false, invoke_cpp = false, reseed = true;
870 int c, opt_index, i, j, vals[4] = {0}, irq;
871 char *confname = NULL, *ptr;
872 unsigned long cpus_tmp, orig_num = 0;
873 unsigned long long tx_packets, tx_bytes;
874 struct ctx ctx;
876 fmemset(&ctx, 0, sizeof(ctx));
877 ctx.cpus = get_number_cpus_online();
878 ctx.uid = getuid();
879 ctx.gid = getgid();
881 while ((c = getopt_long(argc, argv, short_options, long_options,
882 &opt_index)) != EOF) {
883 switch (c) {
884 case 'h':
885 help();
886 break;
887 case 'v':
888 version();
889 break;
890 case 'e':
891 example();
892 break;
893 case 'p':
894 invoke_cpp = true;
895 break;
896 case 'V':
897 ctx.verbose = true;
898 break;
899 case 'P':
900 cpus_tmp = strtoul(optarg, NULL, 0);
901 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
902 ctx.cpus = cpus_tmp;
903 break;
904 case 'd':
905 case 'o':
906 ctx.device = xstrndup(optarg, IFNAMSIZ);
907 break;
908 case 'r':
909 ctx.rand = true;
910 break;
911 case 's':
912 slow = true;
913 ctx.cpus = 1;
914 ctx.smoke_test = true;
915 ctx.rhost = xstrdup(optarg);
916 break;
917 case 'R':
918 ctx.rfraw = true;
919 break;
920 case 'J':
921 ctx.jumbo_support = true;
922 break;
923 case 'c':
924 case 'i':
925 confname = xstrdup(optarg);
926 if (!strncmp("-", confname, strlen("-")))
927 ctx.cpus = 1;
928 break;
929 case 'u':
930 ctx.uid = strtoul(optarg, NULL, 0);
931 ctx.enforce = true;
932 break;
933 case 'g':
934 ctx.gid = strtoul(optarg, NULL, 0);
935 ctx.enforce = true;
936 break;
937 case 'k':
938 ctx.kpull = strtoul(optarg, NULL, 0);
939 break;
940 case 'E':
941 seed = strtoul(optarg, NULL, 0);
942 reseed = false;
943 break;
944 case 'n':
945 orig_num = strtoul(optarg, NULL, 0);
946 ctx.num = orig_num;
947 break;
948 case 't':
949 slow = true;
950 ctx.gap = strtoul(optarg, NULL, 0);
951 if (ctx.gap > 0)
952 /* Fall back to single core to not
953 * mess up correct timing. We are slow
954 * anyway!
956 ctx.cpus = 1;
957 break;
958 case 'S':
959 ptr = optarg;
960 ctx.reserve_size = 0;
962 for (j = i = strlen(optarg); i > 0; --i) {
963 if (!isdigit(optarg[j - i]))
964 break;
965 ptr++;
968 if (!strncmp(ptr, "KiB", strlen("KiB")))
969 ctx.reserve_size = 1 << 10;
970 else if (!strncmp(ptr, "MiB", strlen("MiB")))
971 ctx.reserve_size = 1 << 20;
972 else if (!strncmp(ptr, "GiB", strlen("GiB")))
973 ctx.reserve_size = 1 << 30;
974 else
975 panic("Syntax error in ring size param!\n");
976 *ptr = 0;
978 ctx.reserve_size *= strtol(optarg, NULL, 0);
979 break;
980 case '?':
981 switch (optopt) {
982 case 'd':
983 case 'c':
984 case 'n':
985 case 'S':
986 case 's':
987 case 'P':
988 case 'o':
989 case 'E':
990 case 'i':
991 case 'k':
992 case 'u':
993 case 'g':
994 case 't':
995 panic("Option -%c requires an argument!\n",
996 optopt);
997 default:
998 if (isprint(optopt))
999 printf("Unknown option character `0x%X\'!\n", optopt);
1000 die();
1002 default:
1003 break;
1007 if (argc < 5)
1008 help();
1009 if (ctx.device == NULL)
1010 panic("No networking device given!\n");
1011 if (confname == NULL)
1012 panic("No configuration file given!\n");
1013 if (device_mtu(ctx.device) == 0)
1014 panic("This is no networking device!\n");
1016 register_signal(SIGINT, signal_handler);
1017 register_signal(SIGHUP, signal_handler);
1018 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1020 set_system_socket_memory(vals, array_size(vals));
1021 xlockme();
1023 if (ctx.rfraw) {
1024 ctx.device_trans = xstrdup(ctx.device);
1025 xfree(ctx.device);
1027 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1028 sleep(0);
1031 irq = device_irq_number(ctx.device);
1032 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1034 stats = setup_shared_var(ctx.cpus);
1036 for (i = 0; i < ctx.cpus; i++) {
1037 pid_t pid = fork();
1039 switch (pid) {
1040 case 0:
1041 if (reseed)
1042 seed = generate_srand_seed();
1043 srand(seed);
1045 cpu_affinity(i);
1046 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1048 goto thread_out;
1049 case -1:
1050 panic("Cannot fork processes!\n");
1054 for (i = 0; i < ctx.cpus; i++) {
1055 int status;
1057 wait(&status);
1058 if (WEXITSTATUS(status) == EXIT_FAILURE)
1059 die();
1062 if (ctx.rfraw)
1063 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1065 reset_system_socket_memory(vals, array_size(vals));
1067 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1068 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1069 sched_yield();
1071 tx_packets += stats[i].tx_packets;
1072 tx_bytes += stats[i].tx_bytes;
1075 fflush(stdout);
1076 printf("\n");
1077 printf("\r%12llu packets outgoing\n", tx_packets);
1078 printf("\r%12llu bytes outgoing\n", tx_bytes);
1079 for (i = 0; i < ctx.cpus; i++) {
1080 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1081 stats[i].tv_sec, stats[i].tv_usec, i,
1082 stats[i].tx_packets);
1085 thread_out:
1086 xunlockme();
1087 destroy_shared_var(stats, ctx.cpus);
1089 free(ctx.device);
1090 free(ctx.device_trans);
1091 free(ctx.rhost);
1092 free(confname);
1094 return 0;