mausezahn: Don't use ternary operator to decide which function to call
[netsniff-ng.git] / trafgen.c
blob307d5967ea72478b2a27ff1d13c2286154588a57
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, qdisc_path;
59 size_t reserve_size;
60 unsigned long num;
61 unsigned int cpus;
62 uid_t uid; gid_t gid;
63 char *device, *device_trans, *rhost;
64 struct timespec gap;
65 struct sockaddr_in dest;
68 struct cpu_stats {
69 unsigned long tv_sec, tv_usec;
70 unsigned long long tx_packets, tx_bytes;
71 unsigned long long cf_packets, cf_bytes;
72 unsigned long long cd_packets;
73 sig_atomic_t state;
76 static sig_atomic_t sigint = 0;
78 struct packet *packets = NULL;
79 size_t plen = 0;
81 struct packet_dyn *packet_dyn = NULL;
82 size_t dlen = 0;
84 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
85 static const struct option long_options[] = {
86 {"dev", required_argument, NULL, 'd'},
87 {"out", required_argument, NULL, 'o'},
88 {"in", required_argument, NULL, 'i'},
89 {"conf", required_argument, NULL, 'c'},
90 {"num", required_argument, NULL, 'n'},
91 {"gap", required_argument, NULL, 't'},
92 {"cpus", required_argument, NULL, 'P'},
93 {"ring-size", required_argument, NULL, 'S'},
94 {"kernel-pull", required_argument, NULL, 'k'},
95 {"smoke-test", required_argument, NULL, 's'},
96 {"seed", required_argument, NULL, 'E'},
97 {"user", required_argument, NULL, 'u'},
98 {"group", required_argument, NULL, 'g'},
99 {"prio-high", no_argument, NULL, 'H'},
100 {"notouch-irq", no_argument, NULL, 'Q'},
101 {"qdisc-path", no_argument, NULL, 'q'},
102 {"jumbo-support", no_argument, NULL, 'J'},
103 {"no-cpu-stats", no_argument, NULL, 'C'},
104 {"cpp", no_argument, NULL, 'p'},
105 {"rfraw", no_argument, NULL, 'R'},
106 {"rand", no_argument, NULL, 'r'},
107 {"verbose", no_argument, NULL, 'V'},
108 {"version", no_argument, NULL, 'v'},
109 {"example", no_argument, NULL, 'e'},
110 {"help", no_argument, NULL, 'h'},
111 {NULL, 0, NULL, 0}
114 static int sock;
115 static struct cpu_stats *stats;
116 static unsigned int seed;
118 #define CPU_STATS_STATE_CFG 1
119 #define CPU_STATS_STATE_CHK 2
120 #define CPU_STATS_STATE_RES 4
122 #ifndef ICMP_FILTER
123 # define ICMP_FILTER 1
125 struct icmp_filter {
126 __u32 data;
128 #endif
130 static void signal_handler(int number)
132 switch (number) {
133 case SIGINT:
134 case SIGQUIT:
135 case SIGTERM:
136 sigint = 1;
137 case SIGHUP:
138 default:
139 break;
143 static void __noreturn help(void)
145 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
146 puts("http://www.netsniff-ng.org\n\n"
147 "Usage: trafgen [options]\n"
148 "Options:\n"
149 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
150 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
151 " -p|--cpp Run packet config through C preprocessor\n"
152 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
153 " -R|--rfraw Inject raw 802.11 frames\n"
154 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
155 " -n|--num <uint> Number of packets until exit (def: 0)\n"
156 " -r|--rand Randomize packet selection (def: round robin)\n"
157 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
158 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
159 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
160 " -E|--seed <uint> Manually set srand(3) seed\n"
161 " -u|--user <userid> Drop privileges and change to userid\n"
162 " -g|--group <groupid> Drop privileges and change to groupid\n"
163 " -H|--prio-high Make this high priority process\n"
164 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
165 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
166 " -V|--verbose Be more verbose\n"
167 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
168 " -v|--version Show version and exit\n"
169 " -e|--example Show built-in packet config example\n"
170 " -h|--help Guess what?!\n\n"
171 "Examples:\n"
172 " See trafgen.txf for configuration file examples.\n"
173 " trafgen --dev eth0 --conf trafgen.cfg\n"
174 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
175 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
176 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
177 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
178 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
179 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
180 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
181 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
182 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
183 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
184 "Note:\n"
185 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
186 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
187 " we assume the kernel crashed, thus we print the packet and quit.\n"
188 " In case you find a ping-of-death, please mention trafgen in your\n"
189 " commit message of the fix!\n\n"
190 " For introducing bit errors, delays with random variation and more,\n"
191 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
192 " For generating different package distributions, you can use scripting\n"
193 " to generate a trafgen config file with packet ratios as:\n\n"
194 " IMIX 64:7, 570:4, 1518:1\n"
195 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
196 " Cisco 64:7, 594:4, 1518:1\n"
197 " RPR Trimodal 64:60, 512:20, 1518:20\n"
198 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
199 "Please report bugs to <bugs@netsniff-ng.org>\n"
200 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
201 "Swiss federal institute of technology (ETH Zurich)\n"
202 "License: GNU GPL version 2.0\n"
203 "This is free software: you are free to change and redistribute it.\n"
204 "There is NO WARRANTY, to the extent permitted by law.\n");
205 die();
208 static void __noreturn example(void)
210 const char *e =
211 "/* Note: dynamic elements make trafgen slower! */\n"
212 "#include <stddef.h>\n\n"
213 "{\n"
214 " /* MAC Destination */\n"
215 " fill(0xff, ETH_ALEN),\n"
216 " /* MAC Source */\n"
217 " 0x00, 0x02, 0xb3, drnd(3),\n"
218 " /* IPv4 Protocol */\n"
219 " c16(ETH_P_IP),\n"
220 " /* IPv4 Version, IHL, TOS */\n"
221 " 0b01000101, 0,\n"
222 " /* IPv4 Total Len */\n"
223 " c16(59),\n"
224 " /* IPv4 Ident */\n"
225 " drnd(2),\n"
226 " /* IPv4 Flags, Frag Off */\n"
227 " 0b01000000, 0,\n"
228 " /* IPv4 TTL */\n"
229 " 64,\n"
230 " /* Proto TCP */\n"
231 " 0x06,\n"
232 " /* IPv4 Checksum (IP header from, to) */\n"
233 " csumip(14, 33),\n"
234 " /* Source IP */\n"
235 " drnd(4),\n"
236 " /* Dest IP */\n"
237 " drnd(4),\n"
238 " /* TCP Source Port */\n"
239 " drnd(2),\n"
240 " /* TCP Dest Port */\n"
241 " c16(80),\n"
242 " /* TCP Sequence Number */\n"
243 " drnd(4),\n"
244 " /* TCP Ackn. Number */\n"
245 " c32(0),\n"
246 " /* TCP Header length + TCP SYN/ECN Flag */\n"
247 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
248 " /* Window Size */\n"
249 " c16(16),\n"
250 " /* TCP Checksum (offset IP, offset TCP) */\n"
251 " csumtcp(14, 34),\n"
252 " /* TCP Options */\n"
253 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
254 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
255 " /* Data blob */\n"
256 " \"gotcha!\",\n"
257 "}";
258 puts(e);
259 die();
262 static void __noreturn version(void)
264 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
265 puts("multithreaded zero-copy network packet generator\n"
266 "http://www.netsniff-ng.org\n\n"
267 "Please report bugs to <bugs@netsniff-ng.org>\n"
268 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
269 "Swiss federal institute of technology (ETH Zurich)\n"
270 "License: GNU GPL version 2.0\n"
271 "This is free software: you are free to change and redistribute it.\n"
272 "There is NO WARRANTY, to the extent permitted by law.\n");
273 die();
276 static void apply_counter(int id)
278 size_t j, counter_max = packet_dyn[id].clen;
280 for (j = 0; j < counter_max; ++j) {
281 uint8_t val;
282 struct counter *counter = &packet_dyn[id].cnt[j];
284 val = counter->val - counter->min;
286 switch (counter->type) {
287 case TYPE_INC:
288 val = (val + counter->inc) % (counter->max - counter->min + 1);
289 break;
290 case TYPE_DEC:
291 val = (val - counter->inc) % (counter->min - counter->max + 1);
292 break;
293 default:
294 bug();
297 counter->val = val + counter->min;
298 packets[id].payload[counter->off] = val;
302 static void apply_randomizer(int id)
304 size_t j, rand_max = packet_dyn[id].rlen;
306 for (j = 0; j < rand_max; ++j) {
307 uint8_t val = (uint8_t) rand();
308 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
310 packets[id].payload[randomizer->off] = val;
314 static void apply_csum16(int id)
316 size_t j, csum_max = packet_dyn[id].slen;
318 for (j = 0; j < csum_max; ++j) {
319 uint16_t sum = 0;
320 struct csum16 *csum = &packet_dyn[id].csum[j];
322 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
323 if (unlikely((size_t) csum->to >= packets[id].len))
324 csum->to = packets[id].len - 1;
326 switch (csum->which) {
327 case CSUM_IP:
328 sum = calc_csum(packets[id].payload + csum->from,
329 csum->to - csum->from + 1, 0);
330 break;
331 case CSUM_UDP:
332 sum = p4_csum((void *) packets[id].payload + csum->from,
333 packets[id].payload + csum->to,
334 (packets[id].len - csum->to),
335 IPPROTO_UDP);
336 break;
337 case CSUM_TCP:
338 sum = p4_csum((void *) packets[id].payload + csum->from,
339 packets[id].payload + csum->to,
340 (packets[id].len - csum->to),
341 IPPROTO_TCP);
342 break;
343 default:
344 bug();
345 break;
348 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
352 static struct cpu_stats *setup_shared_var(unsigned long cpus)
354 int fd;
355 size_t len = cpus * sizeof(struct cpu_stats);
356 char zbuff[len], file[256];
357 struct cpu_stats *buff;
359 fmemset(zbuff, 0, len);
360 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
362 fd = creat(file, S_IRUSR | S_IWUSR);
363 bug_on(fd < 0);
364 close(fd);
366 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
367 S_IRUSR | S_IWUSR);
368 write_or_die(fd, zbuff, len);
370 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
371 MAP_SHARED, fd, 0);
372 if (buff == MAP_FAILED)
373 panic("Cannot setup shared variable!\n");
375 close(fd);
376 unlink(file);
378 memset(buff, 0, len);
379 return buff;
382 static void destroy_shared_var(void *buff, unsigned long cpus)
384 munmap(buff, cpus * sizeof(struct cpu_stats));
387 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
389 size_t i;
391 printf("{");
392 for (i = 0; i < len; ++i) {
393 if (i % 15 == 0)
394 printf("\n ");
395 printf("0x%02x, ", payload[i]);
397 printf("\n}\n");
398 fflush(stdout);
401 static int xmit_smoke_setup(struct ctx *ctx)
403 int icmp_sock, ret, ttl = 64;
404 struct icmp_filter filter;
406 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
407 if (icmp_sock < 0)
408 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
410 filter.data = ~(1 << ICMP_ECHOREPLY);
412 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
413 if (ret < 0)
414 panic("Cannot install filter!\n");
416 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
417 if (ret < 0)
418 panic("Cannot set TTL!\n");
420 memset(&ctx->dest, 0, sizeof(ctx->dest));
421 ctx->dest.sin_family = AF_INET;
422 ctx->dest.sin_port = 0;
424 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
425 if (ret < 0)
426 panic("Cannot resolv address!\n");
428 return icmp_sock;
431 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
433 int ret;
434 unsigned int i, j = 0, probes = 100;
435 short ident, cnt = 1, idstore[probes];
436 uint8_t outpack[512], *data;
437 struct icmphdr *icmp;
438 struct iphdr *ip;
439 size_t len = sizeof(*icmp) + 56;
440 struct sockaddr_in from;
441 socklen_t from_len;
442 struct pollfd fds = {
443 .fd = icmp_sock,
444 .events = POLLIN,
447 fmemset(idstore, 0, sizeof(idstore));
448 while (probes-- > 0) {
449 while ((ident = htons((short) rand())) == 0)
450 sleep(0);
451 idstore[j++] = ident;
453 memset(outpack, 0, sizeof(outpack));
454 icmp = (void *) outpack;
455 icmp->type = ICMP_ECHO;
456 icmp->un.echo.id = ident;
457 icmp->un.echo.sequence = htons(cnt++);
459 data = ((uint8_t *) outpack + sizeof(*icmp));
460 for (i = 0; i < 56; ++i)
461 data[i] = (uint8_t) rand();
463 icmp->checksum = csum((unsigned short *) outpack,
464 len / sizeof(unsigned short));
466 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
467 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
468 if (unlikely(ret != (int) len))
469 panic("Cannot send out probe: %s!\n", strerror(errno));
471 ret = poll(&fds, 1, 50);
472 if (ret < 0)
473 panic("Poll failed!\n");
475 if (fds.revents & POLLIN) {
476 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
477 (struct sockaddr *) &from, &from_len);
478 if (unlikely(ret <= 0))
479 panic("Probe receive failed!\n");
480 if (unlikely(from_len != sizeof(ctx->dest)))
481 continue;
482 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
483 continue;
484 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
485 continue;
486 ip = (void *) outpack;
487 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
488 continue;
489 icmp = (void *) outpack + ip->ihl * 4;
490 for (i = 0; i < array_size(idstore); ++i) {
491 if (unlikely(icmp->un.echo.id != idstore[i]))
492 continue;
493 return 0;
498 return -1;
501 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
503 int ret, icmp_sock = -1;
504 unsigned long num = 1, i = 0;
505 struct timeval start, end, diff;
506 unsigned long long tx_bytes = 0, tx_packets = 0;
507 struct packet_dyn *pktd;
508 struct sockaddr_ll saddr = {
509 .sll_family = PF_PACKET,
510 .sll_halen = ETH_ALEN,
511 .sll_ifindex = device_ifindex(ctx->device),
514 if (ctx->num > 0)
515 num = ctx->num;
516 if (ctx->num == 0 && orig_num > 0)
517 num = 0;
519 if (ctx->smoke_test)
520 icmp_sock = xmit_smoke_setup(ctx);
522 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
524 bug_on(gettimeofday(&start, NULL));
526 while (likely(sigint == 0 && num > 0 && plen > 0)) {
527 pktd = &packet_dyn[i];
528 if (pktd->clen + pktd->rlen + pktd->slen) {
529 apply_counter(i);
530 apply_randomizer(i);
531 apply_csum16(i);
533 retry:
534 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
535 (struct sockaddr *) &saddr, sizeof(saddr));
536 if (unlikely(ret < 0)) {
537 if (errno == ENOBUFS) {
538 sched_yield();
539 goto retry;
541 if (ctx->smoke_test)
542 panic("Sendto error: %s!\n", strerror(errno));
545 tx_bytes += packets[i].len;
546 tx_packets++;
548 if (ctx->smoke_test) {
549 ret = xmit_smoke_probe(icmp_sock, ctx);
550 if (unlikely(ret < 0)) {
551 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
552 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
553 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
554 i, seed);
556 dump_trafgen_snippet(packets[i].payload, packets[i].len);
557 break;
561 if (!ctx->rand) {
562 i++;
563 if (i >= plen)
564 i = 0;
565 } else
566 i = rand() % plen;
568 if (ctx->num > 0)
569 num--;
571 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
572 nanosleep(&ctx->gap, NULL);
575 bug_on(gettimeofday(&end, NULL));
576 timersub(&end, &start, &diff);
578 if (ctx->smoke_test)
579 close(icmp_sock);
581 stats[cpu].tx_packets = tx_packets;
582 stats[cpu].tx_bytes = tx_bytes;
583 stats[cpu].tv_sec = diff.tv_sec;
584 stats[cpu].tv_usec = diff.tv_usec;
586 stats[cpu].state |= CPU_STATS_STATE_RES;
589 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
591 int ifindex = device_ifindex(ctx->device);
592 uint8_t *out = NULL;
593 unsigned int it = 0;
594 unsigned long num = 1, i = 0;
595 size_t size = ring_size(ctx->device, ctx->reserve_size);
596 struct ring tx_ring;
597 struct frame_map *hdr;
598 struct timeval start, end, diff;
599 struct packet_dyn *pktd;
600 unsigned long long tx_bytes = 0, tx_packets = 0;
602 set_sock_prio(sock, 512);
604 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
606 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
608 if (ctx->num > 0)
609 num = ctx->num;
610 if (ctx->num == 0 && orig_num > 0)
611 num = 0;
613 bug_on(gettimeofday(&start, NULL));
615 while (likely(sigint == 0 && num > 0 && plen > 0)) {
616 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
617 int ret = pull_and_flush_tx_ring(sock);
618 if (unlikely(ret < 0)) {
619 /* We could hit EBADF if the socket has been closed before
620 * the timer was triggered.
622 if (errno != EBADF && errno != ENOBUFS)
623 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
626 continue;
629 hdr = tx_ring.frames[it].iov_base;
630 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
632 hdr->tp_h.tp_snaplen = packets[i].len;
633 hdr->tp_h.tp_len = packets[i].len;
635 pktd = &packet_dyn[i];
636 if (pktd->clen + pktd->rlen + pktd->slen) {
637 apply_counter(i);
638 apply_randomizer(i);
639 apply_csum16(i);
642 fmemcpy(out, packets[i].payload, packets[i].len);
644 tx_bytes += packets[i].len;
645 tx_packets++;
647 if (!ctx->rand) {
648 i++;
649 if (i >= plen)
650 i = 0;
651 } else
652 i = rand() % plen;
654 kernel_may_pull_from_tx(&hdr->tp_h);
656 it++;
657 if (it >= tx_ring.layout.tp_frame_nr)
658 it = 0;
660 if (ctx->num > 0)
661 num--;
664 bug_on(gettimeofday(&end, NULL));
665 timersub(&end, &start, &diff);
667 pull_and_flush_tx_ring_wait(sock);
668 destroy_tx_ring(sock, &tx_ring);
670 stats[cpu].tx_packets = tx_packets;
671 stats[cpu].tx_bytes = tx_bytes;
672 stats[cpu].tv_sec = diff.tv_sec;
673 stats[cpu].tv_usec = diff.tv_usec;
675 stats[cpu].state |= CPU_STATS_STATE_RES;
678 static inline void __set_state(int cpu, sig_atomic_t s)
680 stats[cpu].state = s;
683 static inline sig_atomic_t __get_state(int cpu)
685 return stats[cpu].state;
688 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
690 unsigned int i;
691 unsigned long total;
693 for (i = 0, total = plen; i < ctx->cpus; i++) {
694 if (i == cpu)
695 continue;
697 while ((__get_state(i) &
698 (CPU_STATS_STATE_CFG |
699 CPU_STATS_STATE_RES)) == 0 &&
700 sigint == 0)
701 sched_yield();
703 total += stats[i].cf_packets;
706 return total;
709 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
711 unsigned int i;
712 unsigned long total;
713 int cpu_sel;
714 long long delta_correction = 0;
716 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
717 if (i == cpu)
718 continue;
720 while ((__get_state(i) &
721 (CPU_STATS_STATE_CHK |
722 CPU_STATS_STATE_RES)) == 0 &&
723 sigint == 0)
724 sched_yield();
726 total += stats[i].cd_packets;
729 if (total > orig)
730 delta_correction = -1 * ((long long) total - orig);
731 if (total < orig)
732 delta_correction = +1 * ((long long) orig - total);
734 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
735 if (stats[i].cd_packets > 0) {
736 if ((long long) stats[i].cd_packets +
737 delta_correction >= 0) {
738 cpu_sel = i;
739 break;
744 if ((int) cpu == cpu_sel)
745 ctx->num += delta_correction;
748 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
749 sig_atomic_t s)
751 stats[cpu].cf_packets = p;
752 stats[cpu].cf_bytes = b;
753 stats[cpu].state = s;
756 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
758 stats[cpu].cd_packets = p;
759 stats[cpu].state = s;
762 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
764 unsigned int i;
765 unsigned long plen_total, orig = ctx->num;
766 size_t mtu, total_len = 0;
768 bug_on(plen != dlen);
770 for (i = 0; i < plen; ++i)
771 total_len += packets[i].len;
773 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
774 plen_total = __wait_and_sum_others(ctx, cpu);
776 if (orig > 0) {
777 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
779 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
780 CPU_STATS_STATE_CFG);
781 __correct_global_delta(ctx, cpu, orig);
784 if (plen == 0) {
785 __set_state(cpu, CPU_STATS_STATE_RES);
786 return 0;
789 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
790 if (packets[i].len > mtu + 14)
791 panic("Device MTU < than packet%d's size!\n", i);
792 if (packets[i].len <= 14)
793 panic("Packet%d's size too short!\n", i);
796 return 0;
799 static void main_loop(struct ctx *ctx, char *confname, bool slow,
800 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
802 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
803 if (xmit_packet_precheck(ctx, cpu) < 0)
804 return;
806 if (cpu == 0) {
807 unsigned int i;
808 size_t total_len = 0, total_pkts = 0;
810 for (i = 0; i < ctx->cpus; ++i) {
811 total_len += stats[i].cf_bytes;
812 total_pkts += stats[i].cf_packets;
815 printf("%6zu packets to schedule\n", total_pkts);
816 printf("%6zu bytes in total\n", total_len);
817 printf("Running! Hang up with ^C!\n\n");
818 fflush(stdout);
821 sock = pf_tx_socket();
823 if (ctx->qdisc_path == false)
824 set_sock_qdisc_bypass(sock, ctx->verbose);
826 if (slow)
827 xmit_slowpath_or_die(ctx, cpu, orig_num);
828 else
829 xmit_fastpath_or_die(ctx, cpu, orig_num);
831 close(sock);
833 cleanup_packets();
836 static unsigned int generate_srand_seed(void)
838 int fd;
839 unsigned int _seed;
841 fd = open("/dev/urandom", O_RDONLY);
842 if (fd < 0)
843 return time(NULL);
845 read_or_die(fd, &_seed, sizeof(_seed));
847 close(fd);
848 return _seed;
851 int main(int argc, char **argv)
853 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
854 bool prio_high = false, set_irq_aff = true;
855 int c, opt_index, vals[4] = {0}, irq;
856 uint64_t gap = 0;
857 unsigned int i, j;
858 char *confname = NULL, *ptr;
859 unsigned long cpus_tmp, orig_num = 0;
860 unsigned long long tx_packets, tx_bytes;
861 struct ctx ctx;
863 fmemset(&ctx, 0, sizeof(ctx));
864 ctx.cpus = get_number_cpus_online();
865 ctx.uid = getuid();
866 ctx.gid = getgid();
867 ctx.qdisc_path = false;
869 /* Keep an initial small default size to reduce cache-misses. */
870 ctx.reserve_size = 512 * (1 << 10);
872 while ((c = getopt_long(argc, argv, short_options, long_options,
873 &opt_index)) != EOF) {
874 switch (c) {
875 case 'h':
876 help();
877 break;
878 case 'v':
879 version();
880 break;
881 case 'C':
882 cpustats = false;
883 break;
884 case 'e':
885 example();
886 break;
887 case 'p':
888 invoke_cpp = true;
889 break;
890 case 'V':
891 ctx.verbose = true;
892 break;
893 case 'P':
894 cpus_tmp = strtoul(optarg, NULL, 0);
895 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
896 ctx.cpus = cpus_tmp;
897 break;
898 case 'd':
899 case 'o':
900 ctx.device = xstrndup(optarg, IFNAMSIZ);
901 break;
902 case 'H':
903 prio_high = true;
904 break;
905 case 'Q':
906 set_irq_aff = false;
907 break;
908 case 'q':
909 ctx.qdisc_path = true;
910 break;
911 case 'r':
912 ctx.rand = true;
913 break;
914 case 's':
915 slow = true;
916 ctx.cpus = 1;
917 ctx.smoke_test = true;
918 ctx.rhost = xstrdup(optarg);
919 break;
920 case 'R':
921 ctx.rfraw = true;
922 break;
923 case 'J':
924 ctx.jumbo_support = true;
925 break;
926 case 'c':
927 case 'i':
928 confname = xstrdup(optarg);
929 if (!strncmp("-", confname, strlen("-")))
930 ctx.cpus = 1;
931 break;
932 case 'u':
933 ctx.uid = strtoul(optarg, NULL, 0);
934 ctx.enforce = true;
935 break;
936 case 'g':
937 ctx.gid = strtoul(optarg, NULL, 0);
938 ctx.enforce = true;
939 break;
940 case 'k':
941 printf("Option -k/--kernel-pull is no longer used and "
942 "will be removed in a future release!\n");
943 break;
944 case 'E':
945 seed = strtoul(optarg, NULL, 0);
946 reseed = false;
947 break;
948 case 'n':
949 orig_num = strtoul(optarg, NULL, 0);
950 ctx.num = orig_num;
951 break;
952 case 't':
953 slow = true;
954 ptr = optarg;
955 gap = strtoul(optarg, NULL, 0);
957 for (j = i = strlen(optarg); i > 0; --i) {
958 if (!isdigit(optarg[j - i]))
959 break;
960 ptr++;
963 if (!strncmp(ptr, "ns", strlen("ns"))) {
964 ctx.gap.tv_sec = gap / 1000000000;
965 ctx.gap.tv_nsec = gap % 1000000000;
966 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
967 /* Default to microseconds for backwards
968 * compatibility if no postfix is given.
970 ctx.gap.tv_sec = gap / 1000000;
971 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
972 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
973 ctx.gap.tv_sec = gap / 1000;
974 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
975 } else if (!strncmp(ptr, "s", strlen("s"))) {
976 ctx.gap.tv_sec = gap;
977 ctx.gap.tv_nsec = 0;
978 } else
979 panic("Syntax error in time param!\n");
981 if (gap > 0)
982 /* Fall back to single core to not mess up
983 * correct timing. We are slow anyway!
985 ctx.cpus = 1;
986 break;
987 case 'S':
988 ptr = optarg;
990 for (j = i = strlen(optarg); i > 0; --i) {
991 if (!isdigit(optarg[j - i]))
992 break;
993 ptr++;
996 if (!strncmp(ptr, "KiB", strlen("KiB")))
997 ctx.reserve_size = 1 << 10;
998 else if (!strncmp(ptr, "MiB", strlen("MiB")))
999 ctx.reserve_size = 1 << 20;
1000 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1001 ctx.reserve_size = 1 << 30;
1002 else
1003 panic("Syntax error in ring size param!\n");
1005 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1006 break;
1007 case '?':
1008 switch (optopt) {
1009 case 'd':
1010 case 'c':
1011 case 'n':
1012 case 'S':
1013 case 's':
1014 case 'P':
1015 case 'o':
1016 case 'E':
1017 case 'i':
1018 case 'k':
1019 case 'u':
1020 case 'g':
1021 case 't':
1022 panic("Option -%c requires an argument!\n",
1023 optopt);
1024 default:
1025 if (isprint(optopt))
1026 printf("Unknown option character `0x%X\'!\n", optopt);
1027 die();
1029 default:
1030 break;
1034 if (argc < 5)
1035 help();
1036 if (ctx.device == NULL)
1037 panic("No networking device given!\n");
1038 if (confname == NULL)
1039 panic("No configuration file given!\n");
1040 if (device_mtu(ctx.device) == 0)
1041 panic("This is no networking device!\n");
1043 register_signal(SIGINT, signal_handler);
1044 register_signal(SIGQUIT, signal_handler);
1045 register_signal(SIGTERM, signal_handler);
1046 register_signal(SIGHUP, signal_handler);
1048 if (prio_high) {
1049 set_proc_prio(-20);
1050 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1053 set_system_socket_memory(vals, array_size(vals));
1054 xlockme();
1056 if (ctx.rfraw) {
1057 ctx.device_trans = xstrdup(ctx.device);
1058 xfree(ctx.device);
1060 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1061 sleep(0);
1064 irq = device_irq_number(ctx.device);
1065 if (set_irq_aff)
1066 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1068 stats = setup_shared_var(ctx.cpus);
1070 for (i = 0; i < ctx.cpus; i++) {
1071 pid_t pid = fork();
1073 switch (pid) {
1074 case 0:
1075 if (reseed)
1076 seed = generate_srand_seed();
1077 srand(seed);
1079 cpu_affinity(i);
1080 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1082 goto thread_out;
1083 case -1:
1084 panic("Cannot fork processes!\n");
1088 for (i = 0; i < ctx.cpus; i++) {
1089 int status;
1091 wait(&status);
1092 if (WEXITSTATUS(status) == EXIT_FAILURE)
1093 die();
1096 if (ctx.rfraw)
1097 leave_rfmon_mac80211(ctx.device);
1099 reset_system_socket_memory(vals, array_size(vals));
1101 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1102 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1103 sched_yield();
1105 tx_packets += stats[i].tx_packets;
1106 tx_bytes += stats[i].tx_bytes;
1109 fflush(stdout);
1110 printf("\n");
1111 printf("\r%12llu packets outgoing\n", tx_packets);
1112 printf("\r%12llu bytes outgoing\n", tx_bytes);
1113 for (i = 0; cpustats && i < ctx.cpus; i++) {
1114 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1115 stats[i].tv_sec, stats[i].tv_usec, i,
1116 stats[i].tx_packets);
1119 thread_out:
1120 xunlockme();
1121 destroy_shared_var(stats, ctx.cpus);
1122 if (set_irq_aff)
1123 device_restore_irq_affinity_list();
1125 free(ctx.device);
1126 free(ctx.device_trans);
1127 free(ctx.rhost);
1128 free(confname);
1130 return 0;