xio: refactor fopencookie related functions
[netsniff-ng.git] / trafgen.c
blob725b3607ee49ef7b389884c9f22d7b99f5c20192
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 "str.h"
38 #include "cpus.h"
39 #include "lockme.h"
40 #include "mac80211.h"
41 #include "xutils.h"
42 #include "xio.h"
43 #include "irq.h"
44 #include "built_in.h"
45 #include "trafgen_conf.h"
46 #include "tprintf.h"
47 #include "ring_tx.h"
48 #include "csum.h"
50 struct ctx {
51 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
52 unsigned long kpull, num, gap, reserve_size, cpus;
53 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
54 struct sockaddr_in dest;
57 struct cpu_stats {
58 unsigned long tv_sec, tv_usec;
59 unsigned long long tx_packets, tx_bytes;
60 unsigned long long cf_packets, cf_bytes;
61 unsigned long long cd_packets;
62 sig_atomic_t state;
65 sig_atomic_t sigint = 0;
67 struct packet *packets = NULL;
68 size_t plen = 0;
70 struct packet_dyn *packet_dyn = NULL;
71 size_t dlen = 0;
73 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
74 static const struct option long_options[] = {
75 {"dev", required_argument, NULL, 'd'},
76 {"out", required_argument, NULL, 'o'},
77 {"in", required_argument, NULL, 'i'},
78 {"conf", required_argument, NULL, 'c'},
79 {"num", required_argument, NULL, 'n'},
80 {"gap", required_argument, NULL, 't'},
81 {"cpus", required_argument, NULL, 'P'},
82 {"ring-size", required_argument, NULL, 'S'},
83 {"kernel-pull", required_argument, NULL, 'k'},
84 {"smoke-test", required_argument, NULL, 's'},
85 {"seed", required_argument, NULL, 'E'},
86 {"user", required_argument, NULL, 'u'},
87 {"group", required_argument, NULL, 'g'},
88 {"jumbo-support", no_argument, NULL, 'J'},
89 {"cpp", no_argument, NULL, 'p'},
90 {"rfraw", no_argument, NULL, 'R'},
91 {"rand", no_argument, NULL, 'r'},
92 {"verbose", no_argument, NULL, 'V'},
93 {"version", no_argument, NULL, 'v'},
94 {"example", no_argument, NULL, 'e'},
95 {"help", no_argument, NULL, 'h'},
96 {NULL, 0, NULL, 0}
99 static int sock;
101 static struct itimerval itimer;
103 static unsigned long interval = TX_KERNEL_PULL_INT;
105 static struct cpu_stats *stats;
107 unsigned int seed;
109 #define CPU_STATS_STATE_CFG 1
110 #define CPU_STATS_STATE_CHK 2
111 #define CPU_STATS_STATE_RES 4
113 #ifndef ICMP_FILTER
114 # define ICMP_FILTER 1
116 struct icmp_filter {
117 __u32 data;
119 #endif
121 static void signal_handler(int number)
123 switch (number) {
124 case SIGINT:
125 sigint = 1;
126 case SIGHUP:
127 default:
128 break;
132 static void timer_elapsed(int number)
134 int 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 set_itimer_interval_value(&itimer, 0, interval);
144 setitimer(ITIMER_REAL, &itimer, NULL);
147 static void timer_purge(void)
149 int ret;
151 ret = pull_and_flush_tx_ring_wait(sock);
152 if (unlikely(ret < 0)) {
153 /* We could hit EBADF if the socket has been closed before
154 * the timer was triggered.
156 if (errno != EBADF && errno != ENOBUFS)
157 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
160 set_itimer_interval_value(&itimer, 0, 0);
161 setitimer(ITIMER_REAL, &itimer, NULL);
164 static void __noreturn help(void)
166 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
167 puts("http://www.netsniff-ng.org\n\n"
168 "Usage: trafgen [options]\n"
169 "Options:\n"
170 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
171 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
172 " -p|--cpp Run packet config through C preprocessor\n"
173 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
174 " -R|--rfraw Inject raw 802.11 frames\n"
175 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
176 " -n|--num <uint> Number of packets until exit (def: 0)\n"
177 " -r|--rand Randomize packet selection (def: round robin)\n"
178 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
179 " -t|--gap <uint> Interpacket gap in us (approx)\n"
180 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
181 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
182 " -E|--seed <uint> Manually set srand(3) seed\n"
183 " -u|--user <userid> Drop privileges and change to userid\n"
184 " -g|--group <groupid> Drop privileges and change to groupid\n"
185 " -V|--verbose Be more verbose\n"
186 " -v|--version Show version and exit\n"
187 " -e|--example Show built-in packet config example\n"
188 " -h|--help Guess what?!\n\n"
189 "Examples:\n"
190 " See trafgen.txf for configuration file examples.\n"
191 " trafgen --dev eth0 --conf trafgen.cfg\n"
192 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
193 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
194 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
195 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
196 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
197 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
198 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
199 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
200 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
201 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
202 "Note:\n"
203 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
204 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
205 " we assume the kernel crashed, thus we print the packet and quit.\n"
206 " In case you find a ping-of-death, please mention trafgen in your\n"
207 " commit message of the fix!\n\n"
208 " For introducing bit errors, delays with random variation and more,\n"
209 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
210 " For generating different package distributions, you can use scripting\n"
211 " to generate a trafgen config file with packet ratios as:\n\n"
212 " IMIX 64:7, 570:4, 1518:1\n"
213 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
214 " Cisco 64:7, 594:4, 1518:1\n"
215 " RPR Trimodal 64:60, 512:20, 1518:20\n"
216 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
217 "Please report bugs to <bugs@netsniff-ng.org>\n"
218 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
219 "Swiss federal institute of technology (ETH Zurich)\n"
220 "License: GNU GPL version 2.0\n"
221 "This is free software: you are free to change and redistribute it.\n"
222 "There is NO WARRANTY, to the extent permitted by law.\n");
223 die();
226 static void __noreturn example(void)
228 const char *e =
229 "/* Note: dynamic elements make trafgen slower! */\n"
230 "#include <stddef.h>\n\n"
231 "{\n"
232 " /* MAC Destination */\n"
233 " fill(0xff, ETH_ALEN),\n"
234 " /* MAC Source */\n"
235 " 0x00, 0x02, 0xb3, drnd(3),\n"
236 " /* IPv4 Protocol */\n"
237 " c16(ETH_P_IP),\n"
238 " /* IPv4 Version, IHL, TOS */\n"
239 " 0b01000101, 0,\n"
240 " /* IPv4 Total Len */\n"
241 " c16(58),\n"
242 " /* IPv4 Ident */\n"
243 " drnd(2),\n"
244 " /* IPv4 Flags, Frag Off */\n"
245 " 0b01000000, 0,\n"
246 " /* IPv4 TTL */\n"
247 " 64,\n"
248 " /* Proto TCP */\n"
249 " 0x06,\n"
250 " /* IPv4 Checksum (IP header from, to) */\n"
251 " csumip(14, 33),\n"
252 " /* Source IP */\n"
253 " drnd(4),\n"
254 " /* Dest IP */\n"
255 " drnd(4),\n"
256 " /* TCP Source Port */\n"
257 " drnd(2),\n"
258 " /* TCP Dest Port */\n"
259 " c16(80),\n"
260 " /* TCP Sequence Number */\n"
261 " drnd(4),\n"
262 " /* TCP Ackn. Number */\n"
263 " c32(0),\n"
264 " /* TCP Header length + TCP SYN/ECN Flag */\n"
265 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
266 " /* Window Size */\n"
267 " c16(16),\n"
268 " /* TCP Checksum (offset IP, offset TCP) */\n"
269 " csumtcp(14, 34),\n"
270 " /* TCP Options */\n"
271 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
272 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
273 " /* Data blob */\n"
274 " \"gotcha!\",\n"
275 "}";
276 puts(e);
277 die();
280 static void __noreturn version(void)
282 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_LONG);
283 puts("http://www.netsniff-ng.org\n\n"
284 "Please report bugs to <bugs@netsniff-ng.org>\n"
285 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
286 "Swiss federal institute of technology (ETH Zurich)\n"
287 "License: GNU GPL version 2.0\n"
288 "This is free software: you are free to change and redistribute it.\n"
289 "There is NO WARRANTY, to the extent permitted by law.\n");
290 die();
293 static void apply_counter(int counter_id)
295 int j, i = counter_id;
296 size_t counter_max = packet_dyn[i].clen;
298 for (j = 0; j < counter_max; ++j) {
299 uint8_t val;
300 struct counter *counter = &packet_dyn[i].cnt[j];
302 val = counter->val - counter->min;
304 switch (counter->type) {
305 case TYPE_INC:
306 val = (val + counter->inc) % (counter->max - counter->min + 1);
307 break;
308 case TYPE_DEC:
309 val = (val - counter->inc) % (counter->min - counter->max + 1);
310 break;
311 default:
312 bug();
315 counter->val = val + counter->min;
316 packets[i].payload[counter->off] = val;
320 static void apply_randomizer(int rand_id)
322 int j, i = rand_id;
323 size_t rand_max = packet_dyn[i].rlen;
325 for (j = 0; j < rand_max; ++j) {
326 uint8_t val = (uint8_t) rand();
327 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
329 packets[i].payload[randomizer->off] = val;
333 static void apply_csum16(int csum_id)
335 int j, i = csum_id;
336 size_t csum_max = packet_dyn[i].slen;
338 for (j = 0; j < csum_max; ++j) {
339 uint16_t sum = 0;
340 struct csum16 *csum = &packet_dyn[i].csum[j];
342 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
344 switch (csum->which) {
345 case CSUM_IP:
346 if (csum->to >= packets[i].len)
347 csum->to = packets[i].len - 1;
348 sum = calc_csum(packets[i].payload + csum->from,
349 csum->to - csum->from + 1, 0);
350 break;
351 case CSUM_UDP:
352 sum = p4_csum((void *) packets[i].payload + csum->from,
353 packets[i].payload + csum->to,
354 (packets[i].len - csum->to),
355 IPPROTO_UDP);
356 break;
357 case CSUM_TCP:
358 sum = p4_csum((void *) packets[i].payload + csum->from,
359 packets[i].payload + csum->to,
360 (packets[i].len - csum->to),
361 IPPROTO_TCP);
362 break;
365 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
369 static struct cpu_stats *setup_shared_var(unsigned long cpus)
371 int fd;
372 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
373 struct cpu_stats *buff;
375 fmemset(zbuff, 0, sizeof(zbuff));
376 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
378 fd = creat(file, S_IRUSR | S_IWUSR);
379 bug_on(fd < 0);
380 close(fd);
382 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
383 S_IRUSR | S_IWUSR);
384 write_or_die(fd, zbuff, sizeof(zbuff));
386 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
387 MAP_SHARED, fd, 0);
388 if (buff == (void *) -1)
389 panic("Cannot setup shared variable!\n");
391 close(fd);
392 unlink(file);
394 memset(buff, 0, sizeof(zbuff));
396 return buff;
399 static void destroy_shared_var(void *buff, unsigned long cpus)
401 munmap(buff, cpus * sizeof(struct cpu_stats));
404 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
406 int i;
408 printf("{");
409 for (i = 0; i < len; ++i) {
410 if (i % 15 == 0)
411 printf("\n ");
412 printf("0x%02x, ", payload[i]);
414 printf("\n}\n");
415 fflush(stdout);
418 static int xmit_smoke_setup(struct ctx *ctx)
420 int icmp_sock, ret, ttl = 64;
421 struct icmp_filter filter;
423 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
424 if (icmp_sock < 0)
425 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
427 filter.data = ~(1 << ICMP_ECHOREPLY);
429 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
430 if (ret < 0)
431 panic("Cannot install filter!\n");
433 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
434 if (ret < 0)
435 panic("Cannot set TTL!\n");
437 memset(&ctx->dest, 0, sizeof(ctx->dest));
438 ctx->dest.sin_family = AF_INET;
439 ctx->dest.sin_port = 0;
441 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
442 if (ret < 0)
443 panic("Cannot resolv address!\n");
445 return icmp_sock;
448 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
450 int ret, i, j = 0, probes = 100;
451 short ident, cnt = 1, idstore[probes];
452 uint8_t outpack[512], *data;
453 struct icmphdr *icmp;
454 struct iphdr *ip;
455 size_t len = sizeof(*icmp) + 56;
456 struct sockaddr_in from;
457 socklen_t from_len;
458 struct pollfd fds = {
459 .fd = icmp_sock,
460 .events = POLLIN,
463 fmemset(idstore, 0, sizeof(idstore));
464 while (probes-- > 0) {
465 while ((ident = htons((short) rand())) == 0)
466 sleep(0);
467 idstore[j++] = ident;
469 memset(outpack, 0, sizeof(outpack));
470 icmp = (void *) outpack;
471 icmp->type = ICMP_ECHO;
472 icmp->un.echo.id = ident;
473 icmp->un.echo.sequence = htons(cnt++);
475 data = ((uint8_t *) outpack + sizeof(*icmp));
476 for (i = 0; i < 56; ++i)
477 data[i] = (uint8_t) rand();
479 icmp->checksum = csum((unsigned short *) outpack,
480 len / sizeof(unsigned short));
482 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
483 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
484 if (unlikely(ret != len))
485 panic("Cannot send out probe: %s!\n", strerror(errno));
487 ret = poll(&fds, 1, 50);
488 if (ret < 0)
489 panic("Poll failed!\n");
491 if (fds.revents & POLLIN) {
492 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
493 (struct sockaddr *) &from, &from_len);
494 if (unlikely(ret <= 0))
495 panic("Probe receive failed!\n");
496 if (unlikely(from_len != sizeof(ctx->dest)))
497 continue;
498 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
499 continue;
500 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
501 continue;
502 ip = (void *) outpack;
503 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
504 continue;
505 icmp = (void *) outpack + ip->ihl * 4;
506 for (i = 0; i < array_size(idstore); ++i) {
507 if (unlikely(icmp->un.echo.id != idstore[i]))
508 continue;
509 return 0;
514 return -1;
517 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
519 int ret, icmp_sock = -1;
520 unsigned long num = 1, i = 0;
521 struct timeval start, end, diff;
522 unsigned long long tx_bytes = 0, tx_packets = 0;
523 struct packet_dyn *pktd;
524 struct sockaddr_ll saddr = {
525 .sll_family = PF_PACKET,
526 .sll_halen = ETH_ALEN,
527 .sll_ifindex = device_ifindex(ctx->device),
530 if (ctx->num > 0)
531 num = ctx->num;
532 if (ctx->num == 0 && orig_num > 0)
533 num = 0;
535 if (ctx->smoke_test)
536 icmp_sock = xmit_smoke_setup(ctx);
538 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
540 bug_on(gettimeofday(&start, NULL));
542 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
543 pktd = &packet_dyn[i];
544 if (pktd->clen + pktd->rlen + pktd->slen) {
545 apply_counter(i);
546 apply_randomizer(i);
547 apply_csum16(i);
549 retry:
550 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
551 (struct sockaddr *) &saddr, sizeof(saddr));
552 if (unlikely(ret < 0)) {
553 if (errno == ENOBUFS) {
554 sched_yield();
555 goto retry;
558 panic("Sendto error: %s!\n", strerror(errno));
561 tx_bytes += packets[i].len;
562 tx_packets++;
564 if (ctx->smoke_test) {
565 ret = xmit_smoke_probe(icmp_sock, ctx);
566 if (unlikely(ret < 0)) {
567 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
568 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
569 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
570 i, seed);
572 dump_trafgen_snippet(packets[i].payload, packets[i].len);
573 break;
577 if (!ctx->rand) {
578 i++;
579 if (i >= plen)
580 i = 0;
581 } else
582 i = rand() % plen;
584 if (ctx->num > 0)
585 num--;
587 if (ctx->gap > 0)
588 usleep(ctx->gap);
591 bug_on(gettimeofday(&end, NULL));
592 timersub(&end, &start, &diff);
594 if (ctx->smoke_test)
595 close(icmp_sock);
597 stats[cpu].tx_packets = tx_packets;
598 stats[cpu].tx_bytes = tx_bytes;
599 stats[cpu].tv_sec = diff.tv_sec;
600 stats[cpu].tv_usec = diff.tv_usec;
602 stats[cpu].state |= CPU_STATS_STATE_RES;
605 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
607 int ifindex = device_ifindex(ctx->device);
608 uint8_t *out = NULL;
609 unsigned int it = 0;
610 unsigned long num = 1, i = 0, size;
611 struct ring tx_ring;
612 struct frame_map *hdr;
613 struct timeval start, end, diff;
614 struct packet_dyn *pktd;
615 unsigned long long tx_bytes = 0, tx_packets = 0;
617 fmemset(&tx_ring, 0, sizeof(tx_ring));
619 size = ring_size(ctx->device, ctx->reserve_size);
621 set_sock_prio(sock, 512);
622 set_packet_loss_discard(sock);
624 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
625 create_tx_ring(sock, &tx_ring, ctx->verbose);
626 mmap_tx_ring(sock, &tx_ring);
627 alloc_tx_ring_frames(sock, &tx_ring);
628 bind_tx_ring(sock, &tx_ring, ifindex);
630 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
632 if (ctx->kpull)
633 interval = ctx->kpull;
634 if (ctx->num > 0)
635 num = ctx->num;
636 if (ctx->num == 0 && orig_num > 0)
637 num = 0;
639 set_itimer_interval_value(&itimer, 0, interval);
640 setitimer(ITIMER_REAL, &itimer, NULL);
642 bug_on(gettimeofday(&start, NULL));
644 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
645 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
646 hdr = tx_ring.frames[it].iov_base;
647 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
649 hdr->tp_h.tp_snaplen = packets[i].len;
650 hdr->tp_h.tp_len = packets[i].len;
652 pktd = &packet_dyn[i];
653 if (pktd->clen + pktd->rlen + pktd->slen) {
654 apply_counter(i);
655 apply_randomizer(i);
656 apply_csum16(i);
659 fmemcpy(out, packets[i].payload, packets[i].len);
661 tx_bytes += packets[i].len;
662 tx_packets++;
664 if (!ctx->rand) {
665 i++;
666 if (i >= plen)
667 i = 0;
668 } else
669 i = rand() % plen;
671 kernel_may_pull_from_tx(&hdr->tp_h);
673 it++;
674 if (it >= tx_ring.layout.tp_frame_nr)
675 it = 0;
677 if (ctx->num > 0)
678 num--;
680 if (unlikely(sigint == 1))
681 break;
685 bug_on(gettimeofday(&end, NULL));
686 timersub(&end, &start, &diff);
688 timer_purge();
690 destroy_tx_ring(sock, &tx_ring);
692 stats[cpu].tx_packets = tx_packets;
693 stats[cpu].tx_bytes = tx_bytes;
694 stats[cpu].tv_sec = diff.tv_sec;
695 stats[cpu].tv_usec = diff.tv_usec;
697 stats[cpu].state |= CPU_STATS_STATE_RES;
700 static inline void __set_state(int cpu, sig_atomic_t s)
702 stats[cpu].state = s;
705 static inline sig_atomic_t __get_state(int cpu)
707 return stats[cpu].state;
710 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
712 int i;
713 unsigned long total;
715 for (i = 0, total = plen; i < ctx->cpus; i++) {
716 if (i == cpu)
717 continue;
719 while ((__get_state(i) &
720 (CPU_STATS_STATE_CFG |
721 CPU_STATS_STATE_RES)) == 0 &&
722 sigint == 0)
723 sched_yield();
725 total += stats[i].cf_packets;
728 return total;
731 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
733 int i, cpu_sel;
734 unsigned long total;
735 long long delta_correction = 0;
737 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
738 if (i == cpu)
739 continue;
741 while ((__get_state(i) &
742 (CPU_STATS_STATE_CHK |
743 CPU_STATS_STATE_RES)) == 0 &&
744 sigint == 0)
745 sched_yield();
747 total += stats[i].cd_packets;
750 if (total > orig)
751 delta_correction = -1 * ((long long) total - orig);
752 if (total < orig)
753 delta_correction = +1 * ((long long) orig - total);
755 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
756 if (stats[i].cd_packets > 0) {
757 if ((long long) stats[i].cd_packets +
758 delta_correction > 0) {
759 cpu_sel = i;
760 break;
765 if (cpu == cpu_sel)
766 ctx->num += delta_correction;
769 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
770 sig_atomic_t s)
772 stats[cpu].cf_packets = p;
773 stats[cpu].cf_bytes = b;
774 stats[cpu].state = s;
777 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
779 stats[cpu].cd_packets = p;
780 stats[cpu].state = s;
783 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
785 int i;
786 unsigned long plen_total, orig = ctx->num;
787 size_t mtu, total_len = 0;
789 bug_on(plen != dlen);
791 for (i = 0; i < plen; ++i)
792 total_len += packets[i].len;
794 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
795 plen_total = __wait_and_sum_others(ctx, cpu);
797 if (orig > 0) {
798 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
800 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
801 CPU_STATS_STATE_CFG);
802 __correct_global_delta(ctx, cpu, orig);
805 if (plen == 0) {
806 __set_state(cpu, CPU_STATS_STATE_RES);
807 return 0;
810 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
811 if (packets[i].len > mtu + 14)
812 panic("Device MTU < than packet%d's size!\n", i);
813 if (packets[i].len <= 14)
814 panic("Packet%d's size too short!\n", i);
817 return 0;
820 static void main_loop(struct ctx *ctx, char *confname, bool slow,
821 int cpu, bool invoke_cpp, unsigned long orig_num)
823 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
824 if (xmit_packet_precheck(ctx, cpu) < 0)
825 return;
827 if (cpu == 0) {
828 int i;
829 size_t total_len = 0, total_pkts = 0;
831 for (i = 0; i < ctx->cpus; ++i) {
832 total_len += stats[i].cf_bytes;
833 total_pkts += stats[i].cf_packets;
836 printf("%6zu packets to schedule\n", total_pkts);
837 printf("%6zu bytes in total\n", total_len);
838 printf("Running! Hang up with ^C!\n\n");
839 fflush(stdout);
842 sock = pf_socket();
844 if (slow)
845 xmit_slowpath_or_die(ctx, cpu, orig_num);
846 else
847 xmit_fastpath_or_die(ctx, cpu, orig_num);
849 close(sock);
851 cleanup_packets();
854 static unsigned int generate_srand_seed(void)
856 int fd;
857 unsigned int seed;
859 fd = open("/dev/urandom", O_RDONLY);
860 if (fd < 0)
861 return time(0);
863 read_or_die(fd, &seed, sizeof(seed));
865 close(fd);
866 return seed;
869 int main(int argc, char **argv)
871 bool slow = false, invoke_cpp = false, reseed = true;
872 int c, opt_index, i, j, vals[4] = {0}, irq;
873 char *confname = NULL, *ptr;
874 unsigned long cpus_tmp, orig_num = 0;
875 unsigned long long tx_packets, tx_bytes;
876 struct ctx ctx;
878 fmemset(&ctx, 0, sizeof(ctx));
879 ctx.cpus = get_number_cpus_online();
880 ctx.uid = getuid();
881 ctx.gid = getgid();
883 while ((c = getopt_long(argc, argv, short_options, long_options,
884 &opt_index)) != EOF) {
885 switch (c) {
886 case 'h':
887 help();
888 break;
889 case 'v':
890 version();
891 break;
892 case 'e':
893 example();
894 break;
895 case 'p':
896 invoke_cpp = true;
897 break;
898 case 'V':
899 ctx.verbose = true;
900 break;
901 case 'P':
902 cpus_tmp = strtoul(optarg, NULL, 0);
903 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
904 ctx.cpus = cpus_tmp;
905 break;
906 case 'd':
907 case 'o':
908 ctx.device = xstrndup(optarg, IFNAMSIZ);
909 break;
910 case 'r':
911 ctx.rand = true;
912 break;
913 case 's':
914 slow = true;
915 ctx.cpus = 1;
916 ctx.smoke_test = true;
917 ctx.rhost = xstrdup(optarg);
918 break;
919 case 'R':
920 ctx.rfraw = true;
921 break;
922 case 'J':
923 ctx.jumbo_support = true;
924 break;
925 case 'c':
926 case 'i':
927 confname = xstrdup(optarg);
928 if (!strncmp("-", confname, strlen("-")))
929 ctx.cpus = 1;
930 break;
931 case 'u':
932 ctx.uid = strtoul(optarg, NULL, 0);
933 ctx.enforce = true;
934 break;
935 case 'g':
936 ctx.gid = strtoul(optarg, NULL, 0);
937 ctx.enforce = true;
938 break;
939 case 'k':
940 ctx.kpull = strtoul(optarg, NULL, 0);
941 break;
942 case 'E':
943 seed = strtoul(optarg, NULL, 0);
944 reseed = false;
945 break;
946 case 'n':
947 orig_num = strtoul(optarg, NULL, 0);
948 ctx.num = orig_num;
949 break;
950 case 't':
951 slow = true;
952 ctx.gap = strtoul(optarg, NULL, 0);
953 if (ctx.gap > 0)
954 /* Fall back to single core to not
955 * mess up correct timing. We are slow
956 * anyway!
958 ctx.cpus = 1;
959 break;
960 case 'S':
961 ptr = optarg;
962 ctx.reserve_size = 0;
964 for (j = i = strlen(optarg); i > 0; --i) {
965 if (!isdigit(optarg[j - i]))
966 break;
967 ptr++;
970 if (!strncmp(ptr, "KiB", strlen("KiB")))
971 ctx.reserve_size = 1 << 10;
972 else if (!strncmp(ptr, "MiB", strlen("MiB")))
973 ctx.reserve_size = 1 << 20;
974 else if (!strncmp(ptr, "GiB", strlen("GiB")))
975 ctx.reserve_size = 1 << 30;
976 else
977 panic("Syntax error in ring size param!\n");
978 *ptr = 0;
980 ctx.reserve_size *= strtol(optarg, NULL, 0);
981 break;
982 case '?':
983 switch (optopt) {
984 case 'd':
985 case 'c':
986 case 'n':
987 case 'S':
988 case 's':
989 case 'P':
990 case 'o':
991 case 'E':
992 case 'i':
993 case 'k':
994 case 'u':
995 case 'g':
996 case 't':
997 panic("Option -%c requires an argument!\n",
998 optopt);
999 default:
1000 if (isprint(optopt))
1001 printf("Unknown option character `0x%X\'!\n", optopt);
1002 die();
1004 default:
1005 break;
1009 if (argc < 5)
1010 help();
1011 if (ctx.device == NULL)
1012 panic("No networking device given!\n");
1013 if (confname == NULL)
1014 panic("No configuration file given!\n");
1015 if (device_mtu(ctx.device) == 0)
1016 panic("This is no networking device!\n");
1018 register_signal(SIGINT, signal_handler);
1019 register_signal(SIGHUP, signal_handler);
1020 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1022 set_system_socket_memory(vals, array_size(vals));
1023 xlockme();
1025 if (ctx.rfraw) {
1026 ctx.device_trans = xstrdup(ctx.device);
1027 xfree(ctx.device);
1029 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1030 sleep(0);
1033 irq = device_irq_number(ctx.device);
1034 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1036 stats = setup_shared_var(ctx.cpus);
1038 for (i = 0; i < ctx.cpus; i++) {
1039 pid_t pid = fork();
1041 switch (pid) {
1042 case 0:
1043 if (reseed)
1044 seed = generate_srand_seed();
1045 srand(seed);
1047 cpu_affinity(i);
1048 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1050 goto thread_out;
1051 case -1:
1052 panic("Cannot fork processes!\n");
1056 for (i = 0; i < ctx.cpus; i++) {
1057 int status;
1059 wait(&status);
1060 if (WEXITSTATUS(status) == EXIT_FAILURE)
1061 die();
1064 if (ctx.rfraw)
1065 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1067 reset_system_socket_memory(vals, array_size(vals));
1069 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1070 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1071 sched_yield();
1073 tx_packets += stats[i].tx_packets;
1074 tx_bytes += stats[i].tx_bytes;
1077 fflush(stdout);
1078 printf("\n");
1079 printf("\r%12llu packets outgoing\n", tx_packets);
1080 printf("\r%12llu bytes outgoing\n", tx_bytes);
1081 for (i = 0; i < ctx.cpus; i++) {
1082 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1083 stats[i].tv_sec, stats[i].tv_usec, i,
1084 stats[i].tx_packets);
1087 thread_out:
1088 xunlockme();
1089 destroy_shared_var(stats, ctx.cpus);
1090 device_restore_irq_affinity_list();
1092 free(ctx.device);
1093 free(ctx.device_trans);
1094 free(ctx.rhost);
1095 free(confname);
1097 return 0;