configure: fix libnetfilter_conntrack dependency removal
[netsniff-ng.git] / trafgen.c
blob3457bfd3428d8d51262460662edb7b3d6d4d2c5c
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 <sched.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
16 #include <sys/fsuid.h>
17 #include <sys/stat.h>
18 #include <sys/time.h>
19 #include <sys/wait.h>
20 #include <sys/mman.h>
21 #include <net/ethernet.h>
22 #include <netinet/in.h>
23 #include <netinet/ip.h>
24 #include <linux/icmp.h>
25 #include <linux/if.h>
26 #include <arpa/inet.h>
27 #include <signal.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <poll.h>
33 #include <netdb.h>
34 #include <math.h>
35 #include <unistd.h>
37 #include "xmalloc.h"
38 #include "die.h"
39 #include "str.h"
40 #include "sig.h"
41 #include "sock.h"
42 #include "cpus.h"
43 #include "lockme.h"
44 #include "privs.h"
45 #include "proc.h"
46 #include "mac80211.h"
47 #include "ioops.h"
48 #include "irq.h"
49 #include "config.h"
50 #include "built_in.h"
51 #include "trafgen_conf.h"
52 #include "tprintf.h"
53 #include "timer.h"
54 #include "ring_tx.h"
55 #include "csum.h"
57 struct ctx {
58 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
59 unsigned long kpull, num, gap, reserve_size, cpus;
60 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
61 struct sockaddr_in dest;
64 struct cpu_stats {
65 unsigned long tv_sec, tv_usec;
66 unsigned long long tx_packets, tx_bytes;
67 unsigned long long cf_packets, cf_bytes;
68 unsigned long long cd_packets;
69 sig_atomic_t state;
72 static sig_atomic_t sigint = 0;
74 struct packet *packets = NULL;
75 size_t plen = 0;
77 struct packet_dyn *packet_dyn = NULL;
78 size_t dlen = 0;
80 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
81 static const struct option long_options[] = {
82 {"dev", required_argument, NULL, 'd'},
83 {"out", required_argument, NULL, 'o'},
84 {"in", required_argument, NULL, 'i'},
85 {"conf", required_argument, NULL, 'c'},
86 {"num", required_argument, NULL, 'n'},
87 {"gap", required_argument, NULL, 't'},
88 {"cpus", required_argument, NULL, 'P'},
89 {"ring-size", required_argument, NULL, 'S'},
90 {"kernel-pull", required_argument, NULL, 'k'},
91 {"smoke-test", required_argument, NULL, 's'},
92 {"seed", required_argument, NULL, 'E'},
93 {"user", required_argument, NULL, 'u'},
94 {"group", required_argument, NULL, 'g'},
95 {"jumbo-support", no_argument, NULL, 'J'},
96 {"cpp", no_argument, NULL, 'p'},
97 {"rfraw", no_argument, NULL, 'R'},
98 {"rand", no_argument, NULL, 'r'},
99 {"verbose", no_argument, NULL, 'V'},
100 {"version", no_argument, NULL, 'v'},
101 {"example", no_argument, NULL, 'e'},
102 {"help", no_argument, NULL, 'h'},
103 {NULL, 0, NULL, 0}
106 static int sock;
107 static struct itimerval itimer;
108 static unsigned long interval = TX_KERNEL_PULL_INT;
109 static struct cpu_stats *stats;
110 unsigned int seed;
112 #define CPU_STATS_STATE_CFG 1
113 #define CPU_STATS_STATE_CHK 2
114 #define CPU_STATS_STATE_RES 4
116 #ifndef ICMP_FILTER
117 # define ICMP_FILTER 1
119 struct icmp_filter {
120 __u32 data;
122 #endif
124 static void signal_handler(int number)
126 switch (number) {
127 case SIGINT:
128 sigint = 1;
129 case SIGHUP:
130 default:
131 break;
135 static void timer_elapsed(int number)
137 int ret = pull_and_flush_tx_ring(sock);
138 if (unlikely(ret < 0)) {
139 /* We could hit EBADF if the socket has been closed before
140 * the timer was triggered.
142 if (errno != EBADF && errno != ENOBUFS)
143 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
146 set_itimer_interval_value(&itimer, 0, interval);
147 setitimer(ITIMER_REAL, &itimer, NULL);
150 static void timer_purge(void)
152 int ret;
154 ret = pull_and_flush_tx_ring_wait(sock);
155 if (unlikely(ret < 0)) {
156 /* We could hit EBADF if the socket has been closed before
157 * the timer was triggered.
159 if (errno != EBADF && errno != ENOBUFS)
160 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
163 set_itimer_interval_value(&itimer, 0, 0);
164 setitimer(ITIMER_REAL, &itimer, NULL);
167 static void __noreturn help(void)
169 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
170 puts("http://www.netsniff-ng.org\n\n"
171 "Usage: trafgen [options]\n"
172 "Options:\n"
173 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
174 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
175 " -p|--cpp Run packet config through C preprocessor\n"
176 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
177 " -R|--rfraw Inject raw 802.11 frames\n"
178 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
179 " -n|--num <uint> Number of packets until exit (def: 0)\n"
180 " -r|--rand Randomize packet selection (def: round robin)\n"
181 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
182 " -t|--gap <uint> Interpacket gap in us (approx)\n"
183 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
184 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
185 " -E|--seed <uint> Manually set srand(3) seed\n"
186 " -u|--user <userid> Drop privileges and change to userid\n"
187 " -g|--group <groupid> Drop privileges and change to groupid\n"
188 " -V|--verbose Be more verbose\n"
189 " -v|--version Show version and exit\n"
190 " -e|--example Show built-in packet config example\n"
191 " -h|--help Guess what?!\n\n"
192 "Examples:\n"
193 " See trafgen.txf for configuration file examples.\n"
194 " trafgen --dev eth0 --conf trafgen.cfg\n"
195 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
196 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
197 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
198 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
199 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
200 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
201 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
202 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
203 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
204 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
205 "Note:\n"
206 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
207 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
208 " we assume the kernel crashed, thus we print the packet and quit.\n"
209 " In case you find a ping-of-death, please mention trafgen in your\n"
210 " commit message of the fix!\n\n"
211 " For introducing bit errors, delays with random variation and more,\n"
212 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
213 " For generating different package distributions, you can use scripting\n"
214 " to generate a trafgen config file with packet ratios as:\n\n"
215 " IMIX 64:7, 570:4, 1518:1\n"
216 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
217 " Cisco 64:7, 594:4, 1518:1\n"
218 " RPR Trimodal 64:60, 512:20, 1518:20\n"
219 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
220 "Please report bugs to <bugs@netsniff-ng.org>\n"
221 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
222 "Swiss federal institute of technology (ETH Zurich)\n"
223 "License: GNU GPL version 2.0\n"
224 "This is free software: you are free to change and redistribute it.\n"
225 "There is NO WARRANTY, to the extent permitted by law.\n");
226 die();
229 static void __noreturn example(void)
231 const char *e =
232 "/* Note: dynamic elements make trafgen slower! */\n"
233 "#include <stddef.h>\n\n"
234 "{\n"
235 " /* MAC Destination */\n"
236 " fill(0xff, ETH_ALEN),\n"
237 " /* MAC Source */\n"
238 " 0x00, 0x02, 0xb3, drnd(3),\n"
239 " /* IPv4 Protocol */\n"
240 " c16(ETH_P_IP),\n"
241 " /* IPv4 Version, IHL, TOS */\n"
242 " 0b01000101, 0,\n"
243 " /* IPv4 Total Len */\n"
244 " c16(59),\n"
245 " /* IPv4 Ident */\n"
246 " drnd(2),\n"
247 " /* IPv4 Flags, Frag Off */\n"
248 " 0b01000000, 0,\n"
249 " /* IPv4 TTL */\n"
250 " 64,\n"
251 " /* Proto TCP */\n"
252 " 0x06,\n"
253 " /* IPv4 Checksum (IP header from, to) */\n"
254 " csumip(14, 33),\n"
255 " /* Source IP */\n"
256 " drnd(4),\n"
257 " /* Dest IP */\n"
258 " drnd(4),\n"
259 " /* TCP Source Port */\n"
260 " drnd(2),\n"
261 " /* TCP Dest Port */\n"
262 " c16(80),\n"
263 " /* TCP Sequence Number */\n"
264 " drnd(4),\n"
265 " /* TCP Ackn. Number */\n"
266 " c32(0),\n"
267 " /* TCP Header length + TCP SYN/ECN Flag */\n"
268 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
269 " /* Window Size */\n"
270 " c16(16),\n"
271 " /* TCP Checksum (offset IP, offset TCP) */\n"
272 " csumtcp(14, 34),\n"
273 " /* TCP Options */\n"
274 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
275 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
276 " /* Data blob */\n"
277 " \"gotcha!\",\n"
278 "}";
279 puts(e);
280 die();
283 static void __noreturn version(void)
285 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
286 puts("multithreaded zero-copy network packet generator\n"
287 "http://www.netsniff-ng.org\n\n"
288 "Please report bugs to <bugs@netsniff-ng.org>\n"
289 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
290 "Swiss federal institute of technology (ETH Zurich)\n"
291 "License: GNU GPL version 2.0\n"
292 "This is free software: you are free to change and redistribute it.\n"
293 "There is NO WARRANTY, to the extent permitted by law.\n");
294 die();
297 static void apply_counter(int counter_id)
299 int j, i = counter_id;
300 size_t counter_max = packet_dyn[i].clen;
302 for (j = 0; j < counter_max; ++j) {
303 uint8_t val;
304 struct counter *counter = &packet_dyn[i].cnt[j];
306 val = counter->val - counter->min;
308 switch (counter->type) {
309 case TYPE_INC:
310 val = (val + counter->inc) % (counter->max - counter->min + 1);
311 break;
312 case TYPE_DEC:
313 val = (val - counter->inc) % (counter->min - counter->max + 1);
314 break;
315 default:
316 bug();
319 counter->val = val + counter->min;
320 packets[i].payload[counter->off] = val;
324 static void apply_randomizer(int rand_id)
326 int j, i = rand_id;
327 size_t rand_max = packet_dyn[i].rlen;
329 for (j = 0; j < rand_max; ++j) {
330 uint8_t val = (uint8_t) rand();
331 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
333 packets[i].payload[randomizer->off] = val;
337 static void apply_csum16(int csum_id)
339 int j, i = csum_id;
340 size_t csum_max = packet_dyn[i].slen;
342 for (j = 0; j < csum_max; ++j) {
343 uint16_t sum = 0;
344 struct csum16 *csum = &packet_dyn[i].csum[j];
346 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
347 if (unlikely(csum->to >= packets[i].len))
348 csum->to = packets[i].len - 1;
350 switch (csum->which) {
351 case CSUM_IP:
352 sum = calc_csum(packets[i].payload + csum->from,
353 csum->to - csum->from + 1, 0);
354 break;
355 case CSUM_UDP:
356 sum = p4_csum((void *) packets[i].payload + csum->from,
357 packets[i].payload + csum->to,
358 (packets[i].len - csum->to),
359 IPPROTO_UDP);
360 break;
361 case CSUM_TCP:
362 sum = p4_csum((void *) packets[i].payload + csum->from,
363 packets[i].payload + csum->to,
364 (packets[i].len - csum->to),
365 IPPROTO_TCP);
366 break;
367 default:
368 bug();
369 break;
372 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
376 static struct cpu_stats *setup_shared_var(unsigned long cpus)
378 int fd;
379 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
380 struct cpu_stats *buff;
382 fmemset(zbuff, 0, sizeof(zbuff));
383 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
385 fd = creat(file, S_IRUSR | S_IWUSR);
386 bug_on(fd < 0);
387 close(fd);
389 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
390 S_IRUSR | S_IWUSR);
391 write_or_die(fd, zbuff, sizeof(zbuff));
393 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
394 MAP_SHARED, fd, 0);
395 if (buff == (void *) -1)
396 panic("Cannot setup shared variable!\n");
398 close(fd);
399 unlink(file);
401 memset(buff, 0, sizeof(zbuff));
403 return buff;
406 static void destroy_shared_var(void *buff, unsigned long cpus)
408 munmap(buff, cpus * sizeof(struct cpu_stats));
411 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
413 int i;
415 printf("{");
416 for (i = 0; i < len; ++i) {
417 if (i % 15 == 0)
418 printf("\n ");
419 printf("0x%02x, ", payload[i]);
421 printf("\n}\n");
422 fflush(stdout);
425 static int xmit_smoke_setup(struct ctx *ctx)
427 int icmp_sock, ret, ttl = 64;
428 struct icmp_filter filter;
430 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
431 if (icmp_sock < 0)
432 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
434 filter.data = ~(1 << ICMP_ECHOREPLY);
436 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
437 if (ret < 0)
438 panic("Cannot install filter!\n");
440 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
441 if (ret < 0)
442 panic("Cannot set TTL!\n");
444 memset(&ctx->dest, 0, sizeof(ctx->dest));
445 ctx->dest.sin_family = AF_INET;
446 ctx->dest.sin_port = 0;
448 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
449 if (ret < 0)
450 panic("Cannot resolv address!\n");
452 return icmp_sock;
455 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
457 int ret, i, j = 0, probes = 100;
458 short ident, cnt = 1, idstore[probes];
459 uint8_t outpack[512], *data;
460 struct icmphdr *icmp;
461 struct iphdr *ip;
462 size_t len = sizeof(*icmp) + 56;
463 struct sockaddr_in from;
464 socklen_t from_len;
465 struct pollfd fds = {
466 .fd = icmp_sock,
467 .events = POLLIN,
470 fmemset(idstore, 0, sizeof(idstore));
471 while (probes-- > 0) {
472 while ((ident = htons((short) rand())) == 0)
473 sleep(0);
474 idstore[j++] = ident;
476 memset(outpack, 0, sizeof(outpack));
477 icmp = (void *) outpack;
478 icmp->type = ICMP_ECHO;
479 icmp->un.echo.id = ident;
480 icmp->un.echo.sequence = htons(cnt++);
482 data = ((uint8_t *) outpack + sizeof(*icmp));
483 for (i = 0; i < 56; ++i)
484 data[i] = (uint8_t) rand();
486 icmp->checksum = csum((unsigned short *) outpack,
487 len / sizeof(unsigned short));
489 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
490 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
491 if (unlikely(ret != len))
492 panic("Cannot send out probe: %s!\n", strerror(errno));
494 ret = poll(&fds, 1, 50);
495 if (ret < 0)
496 panic("Poll failed!\n");
498 if (fds.revents & POLLIN) {
499 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
500 (struct sockaddr *) &from, &from_len);
501 if (unlikely(ret <= 0))
502 panic("Probe receive failed!\n");
503 if (unlikely(from_len != sizeof(ctx->dest)))
504 continue;
505 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
506 continue;
507 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
508 continue;
509 ip = (void *) outpack;
510 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
511 continue;
512 icmp = (void *) outpack + ip->ihl * 4;
513 for (i = 0; i < array_size(idstore); ++i) {
514 if (unlikely(icmp->un.echo.id != idstore[i]))
515 continue;
516 return 0;
521 return -1;
524 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
526 int ret, icmp_sock = -1;
527 unsigned long num = 1, i = 0;
528 struct timeval start, end, diff;
529 unsigned long long tx_bytes = 0, tx_packets = 0;
530 struct packet_dyn *pktd;
531 struct sockaddr_ll saddr = {
532 .sll_family = PF_PACKET,
533 .sll_halen = ETH_ALEN,
534 .sll_ifindex = device_ifindex(ctx->device),
537 if (ctx->num > 0)
538 num = ctx->num;
539 if (ctx->num == 0 && orig_num > 0)
540 num = 0;
542 if (ctx->smoke_test)
543 icmp_sock = xmit_smoke_setup(ctx);
545 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
547 bug_on(gettimeofday(&start, NULL));
549 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
550 pktd = &packet_dyn[i];
551 if (pktd->clen + pktd->rlen + pktd->slen) {
552 apply_counter(i);
553 apply_randomizer(i);
554 apply_csum16(i);
556 retry:
557 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
558 (struct sockaddr *) &saddr, sizeof(saddr));
559 if (unlikely(ret < 0)) {
560 if (errno == ENOBUFS) {
561 sched_yield();
562 goto retry;
565 panic("Sendto error: %s!\n", strerror(errno));
568 tx_bytes += packets[i].len;
569 tx_packets++;
571 if (ctx->smoke_test) {
572 ret = xmit_smoke_probe(icmp_sock, ctx);
573 if (unlikely(ret < 0)) {
574 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
575 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
576 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
577 i, seed);
579 dump_trafgen_snippet(packets[i].payload, packets[i].len);
580 break;
584 if (!ctx->rand) {
585 i++;
586 if (i >= plen)
587 i = 0;
588 } else
589 i = rand() % plen;
591 if (ctx->num > 0)
592 num--;
594 if (ctx->gap > 0)
595 usleep(ctx->gap);
598 bug_on(gettimeofday(&end, NULL));
599 timersub(&end, &start, &diff);
601 if (ctx->smoke_test)
602 close(icmp_sock);
604 stats[cpu].tx_packets = tx_packets;
605 stats[cpu].tx_bytes = tx_bytes;
606 stats[cpu].tv_sec = diff.tv_sec;
607 stats[cpu].tv_usec = diff.tv_usec;
609 stats[cpu].state |= CPU_STATS_STATE_RES;
612 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
614 int ifindex = device_ifindex(ctx->device);
615 uint8_t *out = NULL;
616 unsigned int it = 0;
617 unsigned long num = 1, i = 0, size;
618 struct ring tx_ring;
619 struct frame_map *hdr;
620 struct timeval start, end, diff;
621 struct packet_dyn *pktd;
622 unsigned long long tx_bytes = 0, tx_packets = 0;
624 fmemset(&tx_ring, 0, sizeof(tx_ring));
626 size = ring_size(ctx->device, ctx->reserve_size);
628 set_sock_prio(sock, 512);
629 set_packet_loss_discard(sock);
631 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
632 create_tx_ring(sock, &tx_ring, ctx->verbose);
633 mmap_tx_ring(sock, &tx_ring);
634 alloc_tx_ring_frames(sock, &tx_ring);
635 bind_tx_ring(sock, &tx_ring, ifindex);
637 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
639 if (ctx->kpull)
640 interval = ctx->kpull;
641 if (ctx->num > 0)
642 num = ctx->num;
643 if (ctx->num == 0 && orig_num > 0)
644 num = 0;
646 set_itimer_interval_value(&itimer, 0, interval);
647 setitimer(ITIMER_REAL, &itimer, NULL);
649 bug_on(gettimeofday(&start, NULL));
651 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
652 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
653 hdr = tx_ring.frames[it].iov_base;
654 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
656 hdr->tp_h.tp_snaplen = packets[i].len;
657 hdr->tp_h.tp_len = packets[i].len;
659 pktd = &packet_dyn[i];
660 if (pktd->clen + pktd->rlen + pktd->slen) {
661 apply_counter(i);
662 apply_randomizer(i);
663 apply_csum16(i);
666 fmemcpy(out, packets[i].payload, packets[i].len);
668 tx_bytes += packets[i].len;
669 tx_packets++;
671 if (!ctx->rand) {
672 i++;
673 if (i >= plen)
674 i = 0;
675 } else
676 i = rand() % plen;
678 kernel_may_pull_from_tx(&hdr->tp_h);
680 it++;
681 if (it >= tx_ring.layout.tp_frame_nr)
682 it = 0;
684 if (ctx->num > 0)
685 num--;
687 if (unlikely(sigint == 1))
688 break;
692 bug_on(gettimeofday(&end, NULL));
693 timersub(&end, &start, &diff);
695 timer_purge();
697 destroy_tx_ring(sock, &tx_ring);
699 stats[cpu].tx_packets = tx_packets;
700 stats[cpu].tx_bytes = tx_bytes;
701 stats[cpu].tv_sec = diff.tv_sec;
702 stats[cpu].tv_usec = diff.tv_usec;
704 stats[cpu].state |= CPU_STATS_STATE_RES;
707 static inline void __set_state(int cpu, sig_atomic_t s)
709 stats[cpu].state = s;
712 static inline sig_atomic_t __get_state(int cpu)
714 return stats[cpu].state;
717 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
719 int i;
720 unsigned long total;
722 for (i = 0, total = plen; i < ctx->cpus; i++) {
723 if (i == cpu)
724 continue;
726 while ((__get_state(i) &
727 (CPU_STATS_STATE_CFG |
728 CPU_STATS_STATE_RES)) == 0 &&
729 sigint == 0)
730 sched_yield();
732 total += stats[i].cf_packets;
735 return total;
738 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
740 int i, cpu_sel;
741 unsigned long total;
742 long long delta_correction = 0;
744 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
745 if (i == cpu)
746 continue;
748 while ((__get_state(i) &
749 (CPU_STATS_STATE_CHK |
750 CPU_STATS_STATE_RES)) == 0 &&
751 sigint == 0)
752 sched_yield();
754 total += stats[i].cd_packets;
757 if (total > orig)
758 delta_correction = -1 * ((long long) total - orig);
759 if (total < orig)
760 delta_correction = +1 * ((long long) orig - total);
762 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
763 if (stats[i].cd_packets > 0) {
764 if ((long long) stats[i].cd_packets +
765 delta_correction >= 0) {
766 cpu_sel = i;
767 break;
772 if (cpu == cpu_sel)
773 ctx->num += delta_correction;
776 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
777 sig_atomic_t s)
779 stats[cpu].cf_packets = p;
780 stats[cpu].cf_bytes = b;
781 stats[cpu].state = s;
784 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
786 stats[cpu].cd_packets = p;
787 stats[cpu].state = s;
790 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
792 int i;
793 unsigned long plen_total, orig = ctx->num;
794 size_t mtu, total_len = 0;
796 bug_on(plen != dlen);
798 for (i = 0; i < plen; ++i)
799 total_len += packets[i].len;
801 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
802 plen_total = __wait_and_sum_others(ctx, cpu);
804 if (orig > 0) {
805 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
807 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
808 CPU_STATS_STATE_CFG);
809 __correct_global_delta(ctx, cpu, orig);
812 if (plen == 0) {
813 __set_state(cpu, CPU_STATS_STATE_RES);
814 return 0;
817 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
818 if (packets[i].len > mtu + 14)
819 panic("Device MTU < than packet%d's size!\n", i);
820 if (packets[i].len <= 14)
821 panic("Packet%d's size too short!\n", i);
824 return 0;
827 static void main_loop(struct ctx *ctx, char *confname, bool slow,
828 int cpu, bool invoke_cpp, unsigned long orig_num)
830 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
831 if (xmit_packet_precheck(ctx, cpu) < 0)
832 return;
834 if (cpu == 0) {
835 int i;
836 size_t total_len = 0, total_pkts = 0;
838 for (i = 0; i < ctx->cpus; ++i) {
839 total_len += stats[i].cf_bytes;
840 total_pkts += stats[i].cf_packets;
843 printf("%6zu packets to schedule\n", total_pkts);
844 printf("%6zu bytes in total\n", total_len);
845 printf("Running! Hang up with ^C!\n\n");
846 fflush(stdout);
849 sock = pf_socket();
851 if (slow)
852 xmit_slowpath_or_die(ctx, cpu, orig_num);
853 else
854 xmit_fastpath_or_die(ctx, cpu, orig_num);
856 close(sock);
858 cleanup_packets();
861 static unsigned int generate_srand_seed(void)
863 int fd;
864 unsigned int seed;
866 fd = open("/dev/urandom", O_RDONLY);
867 if (fd < 0)
868 return time(0);
870 read_or_die(fd, &seed, sizeof(seed));
872 close(fd);
873 return seed;
876 int main(int argc, char **argv)
878 bool slow = false, invoke_cpp = false, reseed = true;
879 int c, opt_index, i, j, vals[4] = {0}, irq;
880 char *confname = NULL, *ptr;
881 unsigned long cpus_tmp, orig_num = 0;
882 unsigned long long tx_packets, tx_bytes;
883 struct ctx ctx;
885 fmemset(&ctx, 0, sizeof(ctx));
886 ctx.cpus = get_number_cpus_online();
887 ctx.uid = getuid();
888 ctx.gid = getgid();
890 while ((c = getopt_long(argc, argv, short_options, long_options,
891 &opt_index)) != EOF) {
892 switch (c) {
893 case 'h':
894 help();
895 break;
896 case 'v':
897 version();
898 break;
899 case 'e':
900 example();
901 break;
902 case 'p':
903 invoke_cpp = true;
904 break;
905 case 'V':
906 ctx.verbose = true;
907 break;
908 case 'P':
909 cpus_tmp = strtoul(optarg, NULL, 0);
910 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
911 ctx.cpus = cpus_tmp;
912 break;
913 case 'd':
914 case 'o':
915 ctx.device = xstrndup(optarg, IFNAMSIZ);
916 break;
917 case 'r':
918 ctx.rand = true;
919 break;
920 case 's':
921 slow = true;
922 ctx.cpus = 1;
923 ctx.smoke_test = true;
924 ctx.rhost = xstrdup(optarg);
925 break;
926 case 'R':
927 ctx.rfraw = true;
928 break;
929 case 'J':
930 ctx.jumbo_support = true;
931 break;
932 case 'c':
933 case 'i':
934 confname = xstrdup(optarg);
935 if (!strncmp("-", confname, strlen("-")))
936 ctx.cpus = 1;
937 break;
938 case 'u':
939 ctx.uid = strtoul(optarg, NULL, 0);
940 ctx.enforce = true;
941 break;
942 case 'g':
943 ctx.gid = strtoul(optarg, NULL, 0);
944 ctx.enforce = true;
945 break;
946 case 'k':
947 ctx.kpull = strtoul(optarg, NULL, 0);
948 break;
949 case 'E':
950 seed = strtoul(optarg, NULL, 0);
951 reseed = false;
952 break;
953 case 'n':
954 orig_num = strtoul(optarg, NULL, 0);
955 ctx.num = orig_num;
956 break;
957 case 't':
958 slow = true;
959 ctx.gap = strtoul(optarg, NULL, 0);
960 if (ctx.gap > 0)
961 /* Fall back to single core to not
962 * mess up correct timing. We are slow
963 * anyway!
965 ctx.cpus = 1;
966 break;
967 case 'S':
968 ptr = optarg;
969 ctx.reserve_size = 0;
971 for (j = i = strlen(optarg); i > 0; --i) {
972 if (!isdigit(optarg[j - i]))
973 break;
974 ptr++;
977 if (!strncmp(ptr, "KiB", strlen("KiB")))
978 ctx.reserve_size = 1 << 10;
979 else if (!strncmp(ptr, "MiB", strlen("MiB")))
980 ctx.reserve_size = 1 << 20;
981 else if (!strncmp(ptr, "GiB", strlen("GiB")))
982 ctx.reserve_size = 1 << 30;
983 else
984 panic("Syntax error in ring size param!\n");
985 *ptr = 0;
987 ctx.reserve_size *= strtol(optarg, NULL, 0);
988 break;
989 case '?':
990 switch (optopt) {
991 case 'd':
992 case 'c':
993 case 'n':
994 case 'S':
995 case 's':
996 case 'P':
997 case 'o':
998 case 'E':
999 case 'i':
1000 case 'k':
1001 case 'u':
1002 case 'g':
1003 case 't':
1004 panic("Option -%c requires an argument!\n",
1005 optopt);
1006 default:
1007 if (isprint(optopt))
1008 printf("Unknown option character `0x%X\'!\n", optopt);
1009 die();
1011 default:
1012 break;
1016 if (argc < 5)
1017 help();
1018 if (ctx.device == NULL)
1019 panic("No networking device given!\n");
1020 if (confname == NULL)
1021 panic("No configuration file given!\n");
1022 if (device_mtu(ctx.device) == 0)
1023 panic("This is no networking device!\n");
1025 register_signal(SIGINT, signal_handler);
1026 register_signal(SIGHUP, signal_handler);
1027 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1029 set_system_socket_memory(vals, array_size(vals));
1030 xlockme();
1032 if (ctx.rfraw) {
1033 ctx.device_trans = xstrdup(ctx.device);
1034 xfree(ctx.device);
1036 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1037 sleep(0);
1040 irq = device_irq_number(ctx.device);
1041 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1043 stats = setup_shared_var(ctx.cpus);
1045 for (i = 0; i < ctx.cpus; i++) {
1046 pid_t pid = fork();
1048 switch (pid) {
1049 case 0:
1050 if (reseed)
1051 seed = generate_srand_seed();
1052 srand(seed);
1054 cpu_affinity(i);
1055 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1057 goto thread_out;
1058 case -1:
1059 panic("Cannot fork processes!\n");
1063 for (i = 0; i < ctx.cpus; i++) {
1064 int status;
1066 wait(&status);
1067 if (WEXITSTATUS(status) == EXIT_FAILURE)
1068 die();
1071 if (ctx.rfraw)
1072 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1074 reset_system_socket_memory(vals, array_size(vals));
1076 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1077 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1078 sched_yield();
1080 tx_packets += stats[i].tx_packets;
1081 tx_bytes += stats[i].tx_bytes;
1084 fflush(stdout);
1085 printf("\n");
1086 printf("\r%12llu packets outgoing\n", tx_packets);
1087 printf("\r%12llu bytes outgoing\n", tx_bytes);
1088 for (i = 0; i < ctx.cpus; i++) {
1089 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1090 stats[i].tv_sec, stats[i].tv_usec, i,
1091 stats[i].tx_packets);
1094 thread_out:
1095 xunlockme();
1096 destroy_shared_var(stats, ctx.cpus);
1097 device_restore_irq_affinity_list();
1099 free(ctx.device);
1100 free(ctx.device_trans);
1101 free(ctx.rhost);
1102 free(confname);
1104 return 0;