ifpps: Properly zero out allocated stats
[netsniff-ng.git] / trafgen.c
blob9fa43fc38c9408e8f74c32be33c0ddfb2c90a760
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 __noreturn 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 and exit\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 __noreturn 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 __noreturn version(void)
278 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_LONG);
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->un.echo.id = ident;
469 icmp->un.echo.sequence = htons(cnt++);
471 data = ((uint8_t *) outpack + sizeof(*icmp));
472 for (i = 0; i < 56; ++i)
473 data[i] = (uint8_t) rand();
475 icmp->checksum = csum((unsigned short *) outpack,
476 len / sizeof(unsigned short));
478 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
479 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
480 if (unlikely(ret != len))
481 panic("Cannot send out probe: %s!\n", strerror(errno));
483 ret = poll(&fds, 1, 50);
484 if (ret < 0)
485 panic("Poll failed!\n");
487 if (fds.revents & POLLIN) {
488 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
489 (struct sockaddr *) &from, &from_len);
490 if (unlikely(ret <= 0))
491 panic("Probe receive failed!\n");
492 if (unlikely(from_len != sizeof(ctx->dest)))
493 continue;
494 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
495 continue;
496 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
497 continue;
498 ip = (void *) outpack;
499 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
500 continue;
501 icmp = (void *) outpack + ip->ihl * 4;
502 for (i = 0; i < array_size(idstore); ++i) {
503 if (unlikely(icmp->un.echo.id != idstore[i]))
504 continue;
505 return 0;
510 return -1;
513 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
515 int ret, icmp_sock = -1;
516 unsigned long num = 1, i = 0;
517 struct timeval start, end, diff;
518 unsigned long long tx_bytes = 0, tx_packets = 0;
519 struct packet_dyn *pktd;
520 struct sockaddr_ll saddr = {
521 .sll_family = PF_PACKET,
522 .sll_halen = ETH_ALEN,
523 .sll_ifindex = device_ifindex(ctx->device),
526 if (ctx->num > 0)
527 num = ctx->num;
528 if (ctx->num == 0 && orig_num > 0)
529 num = 0;
531 if (ctx->smoke_test)
532 icmp_sock = xmit_smoke_setup(ctx);
534 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
536 bug_on(gettimeofday(&start, NULL));
538 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
539 pktd = &packet_dyn[i];
540 if (pktd->clen + pktd->rlen + pktd->slen) {
541 apply_counter(i);
542 apply_randomizer(i);
543 apply_csum16(i);
545 retry:
546 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
547 (struct sockaddr *) &saddr, sizeof(saddr));
548 if (unlikely(ret < 0)) {
549 if (errno == ENOBUFS) {
550 sched_yield();
551 goto retry;
554 panic("Sendto error: %s!\n", strerror(errno));
557 tx_bytes += packets[i].len;
558 tx_packets++;
560 if (ctx->smoke_test) {
561 ret = xmit_smoke_probe(icmp_sock, ctx);
562 if (unlikely(ret < 0)) {
563 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
564 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
565 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
566 i, seed);
568 dump_trafgen_snippet(packets[i].payload, packets[i].len);
569 break;
573 if (!ctx->rand) {
574 i++;
575 if (i >= plen)
576 i = 0;
577 } else
578 i = rand() % plen;
580 if (ctx->num > 0)
581 num--;
583 if (ctx->gap > 0)
584 usleep(ctx->gap);
587 bug_on(gettimeofday(&end, NULL));
588 timersub(&end, &start, &diff);
590 if (ctx->smoke_test)
591 close(icmp_sock);
593 stats[cpu].tx_packets = tx_packets;
594 stats[cpu].tx_bytes = tx_bytes;
595 stats[cpu].tv_sec = diff.tv_sec;
596 stats[cpu].tv_usec = diff.tv_usec;
598 stats[cpu].state |= CPU_STATS_STATE_RES;
601 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
603 int ifindex = device_ifindex(ctx->device);
604 uint8_t *out = NULL;
605 unsigned int it = 0;
606 unsigned long num = 1, i = 0, size;
607 struct ring tx_ring;
608 struct frame_map *hdr;
609 struct timeval start, end, diff;
610 struct packet_dyn *pktd;
611 unsigned long long tx_bytes = 0, tx_packets = 0;
613 fmemset(&tx_ring, 0, sizeof(tx_ring));
615 size = ring_size(ctx->device, ctx->reserve_size);
617 set_sock_prio(sock, 512);
618 set_packet_loss_discard(sock);
620 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
621 create_tx_ring(sock, &tx_ring, ctx->verbose);
622 mmap_tx_ring(sock, &tx_ring);
623 alloc_tx_ring_frames(&tx_ring);
624 bind_tx_ring(sock, &tx_ring, ifindex);
626 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
628 if (ctx->kpull)
629 interval = ctx->kpull;
630 if (ctx->num > 0)
631 num = ctx->num;
632 if (ctx->num == 0 && orig_num > 0)
633 num = 0;
635 set_itimer_interval_value(&itimer, 0, interval);
636 setitimer(ITIMER_REAL, &itimer, NULL);
638 bug_on(gettimeofday(&start, NULL));
640 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
641 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
642 hdr = tx_ring.frames[it].iov_base;
643 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
645 hdr->tp_h.tp_snaplen = packets[i].len;
646 hdr->tp_h.tp_len = packets[i].len;
648 pktd = &packet_dyn[i];
649 if (pktd->clen + pktd->rlen + pktd->slen) {
650 apply_counter(i);
651 apply_randomizer(i);
652 apply_csum16(i);
655 fmemcpy(out, packets[i].payload, packets[i].len);
657 tx_bytes += packets[i].len;
658 tx_packets++;
660 if (!ctx->rand) {
661 i++;
662 if (i >= plen)
663 i = 0;
664 } else
665 i = rand() % plen;
667 kernel_may_pull_from_tx(&hdr->tp_h);
669 it++;
670 if (it >= tx_ring.layout.tp_frame_nr)
671 it = 0;
673 if (ctx->num > 0)
674 num--;
676 if (unlikely(sigint == 1))
677 break;
681 bug_on(gettimeofday(&end, NULL));
682 timersub(&end, &start, &diff);
684 timer_purge();
686 destroy_tx_ring(sock, &tx_ring);
688 stats[cpu].tx_packets = tx_packets;
689 stats[cpu].tx_bytes = tx_bytes;
690 stats[cpu].tv_sec = diff.tv_sec;
691 stats[cpu].tv_usec = diff.tv_usec;
693 stats[cpu].state |= CPU_STATS_STATE_RES;
696 static inline void __set_state(int cpu, sig_atomic_t s)
698 stats[cpu].state = s;
701 static inline sig_atomic_t __get_state(int cpu)
703 return stats[cpu].state;
706 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
708 int i;
709 unsigned long total;
711 for (i = 0, total = plen; i < ctx->cpus; i++) {
712 if (i == cpu)
713 continue;
715 while ((__get_state(i) &
716 (CPU_STATS_STATE_CFG |
717 CPU_STATS_STATE_RES)) == 0 &&
718 sigint == 0)
719 sched_yield();
721 total += stats[i].cf_packets;
724 return total;
727 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
729 int i, cpu_sel;
730 unsigned long total;
731 long long delta_correction = 0;
733 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
734 if (i == cpu)
735 continue;
737 while ((__get_state(i) &
738 (CPU_STATS_STATE_CHK |
739 CPU_STATS_STATE_RES)) == 0 &&
740 sigint == 0)
741 sched_yield();
743 total += stats[i].cd_packets;
746 if (total > orig)
747 delta_correction = -1 * ((long long) total - orig);
748 if (total < orig)
749 delta_correction = +1 * ((long long) orig - total);
751 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
752 if (stats[i].cd_packets > 0) {
753 if ((long long) stats[i].cd_packets +
754 delta_correction > 0) {
755 cpu_sel = i;
756 break;
761 if (cpu == cpu_sel)
762 ctx->num += delta_correction;
765 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
766 sig_atomic_t s)
768 stats[cpu].cf_packets = p;
769 stats[cpu].cf_bytes = b;
770 stats[cpu].state = s;
773 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
775 stats[cpu].cd_packets = p;
776 stats[cpu].state = s;
779 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
781 int i;
782 unsigned long plen_total, orig = ctx->num;
783 size_t mtu, total_len = 0;
785 bug_on(plen != dlen);
787 for (i = 0; i < plen; ++i)
788 total_len += packets[i].len;
790 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
791 plen_total = __wait_and_sum_others(ctx, cpu);
793 if (orig > 0) {
794 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
796 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
797 CPU_STATS_STATE_CFG);
798 __correct_global_delta(ctx, cpu, orig);
801 if (plen == 0) {
802 __set_state(cpu, CPU_STATS_STATE_RES);
803 return 0;
806 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
807 if (packets[i].len > mtu + 14)
808 panic("Device MTU < than packet%d's size!\n", i);
809 if (packets[i].len <= 14)
810 panic("Packet%d's size too short!\n", i);
813 return 0;
816 static void main_loop(struct ctx *ctx, char *confname, bool slow,
817 int cpu, bool invoke_cpp, unsigned long orig_num)
819 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
820 if (xmit_packet_precheck(ctx, cpu) < 0)
821 return;
823 if (cpu == 0) {
824 int i;
825 size_t total_len = 0, total_pkts = 0;
827 for (i = 0; i < ctx->cpus; ++i) {
828 total_len += stats[i].cf_bytes;
829 total_pkts += stats[i].cf_packets;
832 printf("%6zu packets to schedule\n", total_pkts);
833 printf("%6zu bytes in total\n", total_len);
834 printf("Running! Hang up with ^C!\n\n");
835 fflush(stdout);
838 sock = pf_socket();
840 if (slow)
841 xmit_slowpath_or_die(ctx, cpu, orig_num);
842 else
843 xmit_fastpath_or_die(ctx, cpu, orig_num);
845 close(sock);
847 cleanup_packets();
850 static unsigned int generate_srand_seed(void)
852 int fd;
853 unsigned int seed;
855 fd = open("/dev/urandom", O_RDONLY);
856 if (fd < 0)
857 return time(0);
859 read_or_die(fd, &seed, sizeof(seed));
861 close(fd);
862 return seed;
865 int main(int argc, char **argv)
867 bool slow = false, invoke_cpp = false, reseed = true;
868 int c, opt_index, i, j, vals[4] = {0}, irq;
869 char *confname = NULL, *ptr;
870 unsigned long cpus_tmp, orig_num = 0;
871 unsigned long long tx_packets, tx_bytes;
872 struct ctx ctx;
874 fmemset(&ctx, 0, sizeof(ctx));
875 ctx.cpus = get_number_cpus_online();
876 ctx.uid = getuid();
877 ctx.gid = getgid();
879 while ((c = getopt_long(argc, argv, short_options, long_options,
880 &opt_index)) != EOF) {
881 switch (c) {
882 case 'h':
883 help();
884 break;
885 case 'v':
886 version();
887 break;
888 case 'e':
889 example();
890 break;
891 case 'p':
892 invoke_cpp = true;
893 break;
894 case 'V':
895 ctx.verbose = true;
896 break;
897 case 'P':
898 cpus_tmp = strtoul(optarg, NULL, 0);
899 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
900 ctx.cpus = cpus_tmp;
901 break;
902 case 'd':
903 case 'o':
904 ctx.device = xstrndup(optarg, IFNAMSIZ);
905 break;
906 case 'r':
907 ctx.rand = true;
908 break;
909 case 's':
910 slow = true;
911 ctx.cpus = 1;
912 ctx.smoke_test = true;
913 ctx.rhost = xstrdup(optarg);
914 break;
915 case 'R':
916 ctx.rfraw = true;
917 break;
918 case 'J':
919 ctx.jumbo_support = true;
920 break;
921 case 'c':
922 case 'i':
923 confname = xstrdup(optarg);
924 if (!strncmp("-", confname, strlen("-")))
925 ctx.cpus = 1;
926 break;
927 case 'u':
928 ctx.uid = strtoul(optarg, NULL, 0);
929 ctx.enforce = true;
930 break;
931 case 'g':
932 ctx.gid = strtoul(optarg, NULL, 0);
933 ctx.enforce = true;
934 break;
935 case 'k':
936 ctx.kpull = strtoul(optarg, NULL, 0);
937 break;
938 case 'E':
939 seed = strtoul(optarg, NULL, 0);
940 reseed = false;
941 break;
942 case 'n':
943 orig_num = strtoul(optarg, NULL, 0);
944 ctx.num = orig_num;
945 break;
946 case 't':
947 slow = true;
948 ctx.gap = strtoul(optarg, NULL, 0);
949 if (ctx.gap > 0)
950 /* Fall back to single core to not
951 * mess up correct timing. We are slow
952 * anyway!
954 ctx.cpus = 1;
955 break;
956 case 'S':
957 ptr = optarg;
958 ctx.reserve_size = 0;
960 for (j = i = strlen(optarg); i > 0; --i) {
961 if (!isdigit(optarg[j - i]))
962 break;
963 ptr++;
966 if (!strncmp(ptr, "KiB", strlen("KiB")))
967 ctx.reserve_size = 1 << 10;
968 else if (!strncmp(ptr, "MiB", strlen("MiB")))
969 ctx.reserve_size = 1 << 20;
970 else if (!strncmp(ptr, "GiB", strlen("GiB")))
971 ctx.reserve_size = 1 << 30;
972 else
973 panic("Syntax error in ring size param!\n");
974 *ptr = 0;
976 ctx.reserve_size *= strtol(optarg, NULL, 0);
977 break;
978 case '?':
979 switch (optopt) {
980 case 'd':
981 case 'c':
982 case 'n':
983 case 'S':
984 case 's':
985 case 'P':
986 case 'o':
987 case 'E':
988 case 'i':
989 case 'k':
990 case 'u':
991 case 'g':
992 case 't':
993 panic("Option -%c requires an argument!\n",
994 optopt);
995 default:
996 if (isprint(optopt))
997 printf("Unknown option character `0x%X\'!\n", optopt);
998 die();
1000 default:
1001 break;
1005 if (argc < 5)
1006 help();
1007 if (ctx.device == NULL)
1008 panic("No networking device given!\n");
1009 if (confname == NULL)
1010 panic("No configuration file given!\n");
1011 if (device_mtu(ctx.device) == 0)
1012 panic("This is no networking device!\n");
1014 register_signal(SIGINT, signal_handler);
1015 register_signal(SIGHUP, signal_handler);
1016 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1018 set_system_socket_memory(vals, array_size(vals));
1019 xlockme();
1021 if (ctx.rfraw) {
1022 ctx.device_trans = xstrdup(ctx.device);
1023 xfree(ctx.device);
1025 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1026 sleep(0);
1029 irq = device_irq_number(ctx.device);
1030 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1032 stats = setup_shared_var(ctx.cpus);
1034 for (i = 0; i < ctx.cpus; i++) {
1035 pid_t pid = fork();
1037 switch (pid) {
1038 case 0:
1039 if (reseed)
1040 seed = generate_srand_seed();
1041 srand(seed);
1043 cpu_affinity(i);
1044 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1046 goto thread_out;
1047 case -1:
1048 panic("Cannot fork processes!\n");
1052 for (i = 0; i < ctx.cpus; i++) {
1053 int status;
1055 wait(&status);
1056 if (WEXITSTATUS(status) == EXIT_FAILURE)
1057 die();
1060 if (ctx.rfraw)
1061 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1063 reset_system_socket_memory(vals, array_size(vals));
1065 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1066 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1067 sched_yield();
1069 tx_packets += stats[i].tx_packets;
1070 tx_bytes += stats[i].tx_bytes;
1073 fflush(stdout);
1074 printf("\n");
1075 printf("\r%12llu packets outgoing\n", tx_packets);
1076 printf("\r%12llu bytes outgoing\n", tx_bytes);
1077 for (i = 0; i < ctx.cpus; i++) {
1078 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1079 stats[i].tv_sec, stats[i].tv_usec, i,
1080 stats[i].tx_packets);
1083 thread_out:
1084 xunlockme();
1085 destroy_shared_var(stats, ctx.cpus);
1087 free(ctx.device);
1088 free(ctx.device_trans);
1089 free(ctx.rhost);
1090 free(confname);
1092 return 0;