proto: Make protocol->key member const
[netsniff-ng.git] / trafgen.c
blob9151b5df2d3db06b4729b145c58fe15978e4010d
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/prctl.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <sys/mman.h>
22 #include <net/ethernet.h>
23 #include <netinet/in.h>
24 #include <netinet/ip.h>
25 #include <linux/icmp.h>
26 #include <linux/if.h>
27 #include <arpa/inet.h>
28 #include <signal.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <poll.h>
34 #include <netdb.h>
35 #include <math.h>
36 #include <unistd.h>
38 #include "xmalloc.h"
39 #include "die.h"
40 #include "str.h"
41 #include "sig.h"
42 #include "sock.h"
43 #include "cpus.h"
44 #include "lockme.h"
45 #include "privs.h"
46 #include "proc.h"
47 #include "mac80211.h"
48 #include "ioops.h"
49 #include "irq.h"
50 #include "config.h"
51 #include "built_in.h"
52 #include "trafgen_conf.h"
53 #include "tprintf.h"
54 #include "timer.h"
55 #include "ring_tx.h"
56 #include "csum.h"
58 struct ctx {
59 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
60 size_t reserve_size;
61 unsigned long num;
62 unsigned int cpus;
63 uid_t uid; gid_t gid;
64 char *device, *device_trans, *rhost;
65 struct timespec gap;
66 struct sockaddr_in dest;
69 struct cpu_stats {
70 unsigned long tv_sec, tv_usec;
71 unsigned long long tx_packets, tx_bytes;
72 unsigned long long cf_packets, cf_bytes;
73 unsigned long long cd_packets;
74 sig_atomic_t state;
77 static sig_atomic_t sigint = 0;
79 struct packet *packets = NULL;
80 size_t plen = 0;
82 struct packet_dyn *packet_dyn = NULL;
83 size_t dlen = 0;
85 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
86 static const struct option long_options[] = {
87 {"dev", required_argument, NULL, 'd'},
88 {"out", required_argument, NULL, 'o'},
89 {"in", required_argument, NULL, 'i'},
90 {"conf", required_argument, NULL, 'c'},
91 {"num", required_argument, NULL, 'n'},
92 {"gap", required_argument, NULL, 't'},
93 {"cpus", required_argument, NULL, 'P'},
94 {"ring-size", required_argument, NULL, 'S'},
95 {"kernel-pull", required_argument, NULL, 'k'},
96 {"smoke-test", required_argument, NULL, 's'},
97 {"seed", required_argument, NULL, 'E'},
98 {"user", required_argument, NULL, 'u'},
99 {"group", required_argument, NULL, 'g'},
100 {"prio-high", no_argument, NULL, 'H'},
101 {"notouch-irq", no_argument, NULL, 'Q'},
102 {"no-sock-mem", no_argument, NULL, 'A'},
103 {"qdisc-path", no_argument, NULL, 'q'},
104 {"jumbo-support", no_argument, NULL, 'J'},
105 {"no-cpu-stats", no_argument, NULL, 'C'},
106 {"cpp", no_argument, NULL, 'p'},
107 {"rfraw", no_argument, NULL, 'R'},
108 {"rand", no_argument, NULL, 'r'},
109 {"verbose", no_argument, NULL, 'V'},
110 {"version", no_argument, NULL, 'v'},
111 {"example", no_argument, NULL, 'e'},
112 {"help", no_argument, NULL, 'h'},
113 {NULL, 0, NULL, 0}
116 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
117 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
118 "Swiss federal institute of technology (ETH Zurich)\n"
119 "License: GNU GPL version 2.0\n"
120 "This is free software: you are free to change and redistribute it.\n"
121 "There is NO WARRANTY, to the extent permitted by law.";
123 static int sock;
124 static struct cpu_stats *stats;
125 static unsigned int seed;
127 #define CPU_STATS_STATE_CFG 1
128 #define CPU_STATS_STATE_CHK 2
129 #define CPU_STATS_STATE_RES 4
131 #ifndef ICMP_FILTER
132 # define ICMP_FILTER 1
134 struct icmp_filter {
135 __u32 data;
137 #endif
139 #define SMOKE_N_PROBES 100
141 static void signal_handler(int number)
143 switch (number) {
144 case SIGINT:
145 case SIGQUIT:
146 case SIGTERM:
147 sigint = 1;
148 case SIGHUP:
149 default:
150 break;
154 static void __noreturn help(void)
156 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
157 puts("http://www.netsniff-ng.org\n\n"
158 "Usage: trafgen [options]\n"
159 "Options:\n"
160 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
161 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
162 " -p|--cpp Run packet config through C preprocessor\n"
163 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
164 " -R|--rfraw Inject raw 802.11 frames\n"
165 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
166 " -n|--num <uint> Number of packets until exit (def: 0)\n"
167 " -r|--rand Randomize packet selection (def: round robin)\n"
168 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
169 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
170 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
171 " -E|--seed <uint> Manually set srand(3) seed\n"
172 " -u|--user <userid> Drop privileges and change to userid\n"
173 " -g|--group <groupid> Drop privileges and change to groupid\n"
174 " -H|--prio-high Make this high priority process\n"
175 " -A|--no-sock-mem Don't tune core socket memory\n"
176 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
177 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
178 " -V|--verbose Be more verbose\n"
179 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
180 " -v|--version Show version and exit\n"
181 " -e|--example Show built-in packet config example\n"
182 " -h|--help Guess what?!\n\n"
183 "Examples:\n"
184 " See trafgen.txf for configuration file examples.\n"
185 " trafgen --dev eth0 --conf trafgen.cfg\n"
186 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
187 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
188 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
189 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
190 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
191 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
192 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
193 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
194 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
195 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
196 "Note:\n"
197 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
198 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
199 " we assume the kernel crashed, thus we print the packet and quit.\n"
200 " In case you find a ping-of-death, please mention trafgen in your\n"
201 " commit message of the fix!\n\n"
202 " For introducing bit errors, delays with random variation and more,\n"
203 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
204 " For generating different package distributions, you can use scripting\n"
205 " to generate a trafgen config file with packet ratios as:\n\n"
206 " IMIX 64:7, 570:4, 1518:1\n"
207 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
208 " Cisco 64:7, 594:4, 1518:1\n"
209 " RPR Trimodal 64:60, 512:20, 1518:20\n"
210 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
211 puts(copyright);
212 die();
215 static void __noreturn example(void)
217 const char *e =
218 "/* Note: dynamic elements make trafgen slower! */\n"
219 "#include <stddef.h>\n\n"
220 "{\n"
221 " /* MAC Destination */\n"
222 " fill(0xff, ETH_ALEN),\n"
223 " /* MAC Source */\n"
224 " 0x00, 0x02, 0xb3, drnd(3),\n"
225 " /* IPv4 Protocol */\n"
226 " c16(ETH_P_IP),\n"
227 " /* IPv4 Version, IHL, TOS */\n"
228 " 0b01000101, 0,\n"
229 " /* IPv4 Total Len */\n"
230 " c16(59),\n"
231 " /* IPv4 Ident */\n"
232 " drnd(2),\n"
233 " /* IPv4 Flags, Frag Off */\n"
234 " 0b01000000, 0,\n"
235 " /* IPv4 TTL */\n"
236 " 64,\n"
237 " /* Proto TCP */\n"
238 " 0x06,\n"
239 " /* IPv4 Checksum (IP header from, to) */\n"
240 " csumip(14, 33),\n"
241 " /* Source IP */\n"
242 " drnd(4),\n"
243 " /* Dest IP */\n"
244 " drnd(4),\n"
245 " /* TCP Source Port */\n"
246 " drnd(2),\n"
247 " /* TCP Dest Port */\n"
248 " c16(80),\n"
249 " /* TCP Sequence Number */\n"
250 " drnd(4),\n"
251 " /* TCP Ackn. Number */\n"
252 " c32(0),\n"
253 " /* TCP Header length + TCP SYN/ECN Flag */\n"
254 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
255 " /* Window Size */\n"
256 " c16(16),\n"
257 " /* TCP Checksum (offset IP, offset TCP) */\n"
258 " csumtcp(14, 34),\n"
259 " /* TCP Options */\n"
260 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
261 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
262 " /* Data blob */\n"
263 " \"gotcha!\",\n"
264 "}";
265 puts(e);
266 die();
269 static void __noreturn version(void)
271 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
272 puts("multithreaded zero-copy network packet generator\n"
273 "http://www.netsniff-ng.org\n");
274 puts(copyright);
275 die();
278 static void apply_counter(int id)
280 size_t j, counter_max = packet_dyn[id].clen;
282 for (j = 0; j < counter_max; ++j) {
283 uint8_t val;
284 struct counter *counter = &packet_dyn[id].cnt[j];
286 val = counter->val - counter->min;
288 switch (counter->type) {
289 case TYPE_INC:
290 val = (val + counter->inc) % (counter->max - counter->min + 1);
291 break;
292 case TYPE_DEC:
293 val = (val - counter->inc) % (counter->min - counter->max + 1);
294 break;
295 default:
296 bug();
299 counter->val = val + counter->min;
300 packets[id].payload[counter->off] = val;
304 static void apply_randomizer(int id)
306 size_t j, rand_max = packet_dyn[id].rlen;
308 for (j = 0; j < rand_max; ++j) {
309 uint8_t val = (uint8_t) rand();
310 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
312 packets[id].payload[randomizer->off] = val;
316 static void apply_csum16(int id)
318 size_t j, csum_max = packet_dyn[id].slen;
320 for (j = 0; j < csum_max; ++j) {
321 uint16_t sum = 0;
322 struct csum16 *csum = &packet_dyn[id].csum[j];
324 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
325 if (unlikely((size_t) csum->to >= packets[id].len))
326 csum->to = packets[id].len - 1;
328 switch (csum->which) {
329 case CSUM_IP:
330 sum = calc_csum(packets[id].payload + csum->from,
331 csum->to - csum->from + 1, 0);
332 break;
333 case CSUM_UDP:
334 sum = p4_csum((void *) packets[id].payload + csum->from,
335 packets[id].payload + csum->to,
336 (packets[id].len - csum->to),
337 IPPROTO_UDP);
338 break;
339 case CSUM_TCP:
340 sum = p4_csum((void *) packets[id].payload + csum->from,
341 packets[id].payload + csum->to,
342 (packets[id].len - csum->to),
343 IPPROTO_TCP);
344 break;
345 default:
346 bug();
347 break;
350 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
354 static struct cpu_stats *setup_shared_var(unsigned int cpus)
356 int fd;
357 size_t len = cpus * sizeof(struct cpu_stats);
358 char *zbuff, file[256];
359 struct cpu_stats *buff;
361 zbuff = xzmalloc(len);
362 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
364 fd = creat(file, S_IRUSR | S_IWUSR);
365 bug_on(fd < 0);
366 close(fd);
368 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
369 S_IRUSR | S_IWUSR);
370 write_or_die(fd, zbuff, len);
371 xfree(zbuff);
373 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
374 MAP_SHARED, fd, 0);
375 if (buff == MAP_FAILED)
376 panic("Cannot setup shared variable!\n");
378 close(fd);
379 unlink(file);
381 memset(buff, 0, len);
382 return buff;
385 static void destroy_shared_var(void *buff, unsigned int cpus)
387 munmap(buff, cpus * sizeof(struct cpu_stats));
390 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
392 size_t i;
394 printf("{");
395 for (i = 0; i < len; ++i) {
396 if (i % 15 == 0)
397 printf("\n ");
398 printf("0x%02x, ", payload[i]);
400 printf("\n}\n");
401 fflush(stdout);
404 static int xmit_smoke_setup(struct ctx *ctx)
406 int icmp_sock, ret, ttl = 64;
407 struct icmp_filter filter;
409 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
410 if (icmp_sock < 0)
411 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
413 filter.data = ~(1 << ICMP_ECHOREPLY);
415 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
416 if (ret < 0)
417 panic("Cannot install filter!\n");
419 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
420 if (ret < 0)
421 panic("Cannot set TTL!\n");
423 memset(&ctx->dest, 0, sizeof(ctx->dest));
424 ctx->dest.sin_family = AF_INET;
425 ctx->dest.sin_port = 0;
427 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
428 if (ret < 0)
429 panic("Cannot resolv address!\n");
431 return icmp_sock;
434 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
436 int ret;
437 unsigned int i, j;
438 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
439 uint8_t outpack[512], *data;
440 struct icmphdr *icmp;
441 struct iphdr *ip;
442 size_t len = sizeof(*icmp) + 56;
443 struct sockaddr_in from;
444 socklen_t from_len;
445 struct pollfd fds = {
446 .fd = icmp_sock,
447 .events = POLLIN,
450 fmemset(idstore, 0, sizeof(idstore));
451 for (j = 0; j < SMOKE_N_PROBES; j++) {
452 while ((ident = htons((short) rand())) == 0)
453 sleep(0);
454 idstore[j] = ident;
456 memset(outpack, 0, sizeof(outpack));
457 icmp = (void *) outpack;
458 icmp->type = ICMP_ECHO;
459 icmp->un.echo.id = ident;
460 icmp->un.echo.sequence = htons(cnt++);
462 data = ((uint8_t *) outpack + sizeof(*icmp));
463 for (i = 0; i < 56; ++i)
464 data[i] = (uint8_t) rand();
466 icmp->checksum = csum((unsigned short *) outpack,
467 len / sizeof(unsigned short));
469 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
470 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
471 if (unlikely(ret != (int) len))
472 panic("Cannot send out probe: %s!\n", strerror(errno));
474 ret = poll(&fds, 1, 50);
475 if (ret < 0)
476 panic("Poll failed!\n");
478 if (fds.revents & POLLIN) {
479 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
480 (struct sockaddr *) &from, &from_len);
481 if (unlikely(ret <= 0))
482 panic("Probe receive failed!\n");
483 if (unlikely(from_len != sizeof(ctx->dest)))
484 continue;
485 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
486 continue;
487 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
488 continue;
489 ip = (void *) outpack;
490 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
491 continue;
492 icmp = (void *) outpack + ip->ihl * 4;
493 for (i = 0; i < array_size(idstore); ++i) {
494 if (unlikely(icmp->un.echo.id != idstore[i]))
495 continue;
496 return 0;
501 return -1;
504 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
506 int ret, icmp_sock = -1;
507 unsigned long num = 1, i = 0;
508 struct timeval start, end, diff;
509 unsigned long long tx_bytes = 0, tx_packets = 0;
510 struct packet_dyn *pktd;
511 struct sockaddr_ll saddr = {
512 .sll_family = PF_PACKET,
513 .sll_halen = ETH_ALEN,
514 .sll_ifindex = device_ifindex(ctx->device),
517 if (ctx->num > 0)
518 num = ctx->num;
519 if (ctx->num == 0 && orig_num > 0)
520 num = 0;
522 if (ctx->smoke_test)
523 icmp_sock = xmit_smoke_setup(ctx);
525 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
527 bug_on(gettimeofday(&start, NULL));
529 while (likely(sigint == 0 && num > 0 && plen > 0)) {
530 pktd = &packet_dyn[i];
531 if (pktd->clen + pktd->rlen + pktd->slen) {
532 apply_counter(i);
533 apply_randomizer(i);
534 apply_csum16(i);
536 retry:
537 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
538 (struct sockaddr *) &saddr, sizeof(saddr));
539 if (unlikely(ret < 0)) {
540 if (errno == ENOBUFS) {
541 sched_yield();
542 goto retry;
544 if (ctx->smoke_test)
545 panic("Sendto error: %s!\n", strerror(errno));
548 tx_bytes += packets[i].len;
549 tx_packets++;
551 if (ctx->smoke_test) {
552 ret = xmit_smoke_probe(icmp_sock, ctx);
553 if (unlikely(ret < 0)) {
554 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
555 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
556 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
557 i, seed);
559 dump_trafgen_snippet(packets[i].payload, packets[i].len);
560 break;
564 if (!ctx->rand) {
565 i++;
566 if (i >= plen)
567 i = 0;
568 } else
569 i = rand() % plen;
571 if (ctx->num > 0)
572 num--;
574 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
575 nanosleep(&ctx->gap, NULL);
578 bug_on(gettimeofday(&end, NULL));
579 timersub(&end, &start, &diff);
581 if (ctx->smoke_test)
582 close(icmp_sock);
584 stats[cpu].tx_packets = tx_packets;
585 stats[cpu].tx_bytes = tx_bytes;
586 stats[cpu].tv_sec = diff.tv_sec;
587 stats[cpu].tv_usec = diff.tv_usec;
589 stats[cpu].state |= CPU_STATS_STATE_RES;
592 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
594 int ifindex = device_ifindex(ctx->device);
595 uint8_t *out = NULL;
596 unsigned int it = 0;
597 unsigned long num = 1, i = 0;
598 size_t size = ring_size(ctx->device, ctx->reserve_size);
599 struct ring tx_ring;
600 struct frame_map *hdr;
601 struct timeval start, end, diff;
602 struct packet_dyn *pktd;
603 unsigned long long tx_bytes = 0, tx_packets = 0;
605 set_sock_prio(sock, 512);
607 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
609 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
611 if (ctx->num > 0)
612 num = ctx->num;
613 if (ctx->num == 0 && orig_num > 0)
614 num = 0;
616 bug_on(gettimeofday(&start, NULL));
618 while (likely(sigint == 0 && num > 0 && plen > 0)) {
619 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
620 int ret = pull_and_flush_tx_ring(sock);
621 if (unlikely(ret < 0)) {
622 /* We could hit EBADF if the socket has been closed before
623 * the timer was triggered.
625 if (errno != EBADF && errno != ENOBUFS)
626 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
629 continue;
632 hdr = tx_ring.frames[it].iov_base;
633 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
635 hdr->tp_h.tp_snaplen = packets[i].len;
636 hdr->tp_h.tp_len = packets[i].len;
638 pktd = &packet_dyn[i];
639 if (pktd->clen + pktd->rlen + pktd->slen) {
640 apply_counter(i);
641 apply_randomizer(i);
642 apply_csum16(i);
645 fmemcpy(out, packets[i].payload, packets[i].len);
647 tx_bytes += packets[i].len;
648 tx_packets++;
650 if (!ctx->rand) {
651 i++;
652 if (i >= plen)
653 i = 0;
654 } else
655 i = rand() % plen;
657 kernel_may_pull_from_tx(&hdr->tp_h);
659 it++;
660 if (it >= tx_ring.layout.tp_frame_nr)
661 it = 0;
663 if (ctx->num > 0)
664 num--;
667 bug_on(gettimeofday(&end, NULL));
668 timersub(&end, &start, &diff);
670 pull_and_flush_tx_ring_wait(sock);
671 destroy_tx_ring(sock, &tx_ring);
673 stats[cpu].tx_packets = tx_packets;
674 stats[cpu].tx_bytes = tx_bytes;
675 stats[cpu].tv_sec = diff.tv_sec;
676 stats[cpu].tv_usec = diff.tv_usec;
678 stats[cpu].state |= CPU_STATS_STATE_RES;
681 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
683 stats[cpu].state = s;
686 static inline sig_atomic_t __get_state(unsigned int cpu)
688 return stats[cpu].state;
691 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
693 unsigned int i;
694 unsigned long total;
696 for (i = 0, total = plen; i < ctx->cpus; i++) {
697 if (i == cpu)
698 continue;
700 while ((__get_state(i) &
701 (CPU_STATS_STATE_CFG |
702 CPU_STATS_STATE_RES)) == 0 &&
703 sigint == 0)
704 sched_yield();
706 total += stats[i].cf_packets;
709 return total;
712 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
714 unsigned int i;
715 unsigned long total;
716 int cpu_sel;
717 long long delta_correction = 0;
719 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
720 if (i == cpu)
721 continue;
723 while ((__get_state(i) &
724 (CPU_STATS_STATE_CHK |
725 CPU_STATS_STATE_RES)) == 0 &&
726 sigint == 0)
727 sched_yield();
729 total += stats[i].cd_packets;
732 if (total > orig)
733 delta_correction = -1 * ((long long) total - orig);
734 if (total < orig)
735 delta_correction = +1 * ((long long) orig - total);
737 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
738 if (stats[i].cd_packets > 0) {
739 if ((long long) stats[i].cd_packets +
740 delta_correction >= 0) {
741 cpu_sel = i;
742 break;
747 if ((int) cpu == cpu_sel)
748 ctx->num += delta_correction;
751 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
752 sig_atomic_t s)
754 stats[cpu].cf_packets = p;
755 stats[cpu].cf_bytes = b;
756 stats[cpu].state = s;
759 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
761 stats[cpu].cd_packets = p;
762 stats[cpu].state = s;
765 static int xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
767 unsigned int i;
768 unsigned long plen_total, orig = ctx->num;
769 size_t mtu, total_len = 0;
771 bug_on(plen != dlen);
773 for (i = 0; i < plen; ++i)
774 total_len += packets[i].len;
776 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
777 plen_total = __wait_and_sum_others(ctx, cpu);
779 if (orig > 0) {
780 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
782 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
783 CPU_STATS_STATE_CFG);
784 __correct_global_delta(ctx, cpu, orig);
787 if (plen == 0) {
788 __set_state(cpu, CPU_STATS_STATE_RES);
789 return 0;
792 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
793 if (packets[i].len > mtu + 14)
794 panic("Device MTU < than packet%d's size!\n", i);
795 if (packets[i].len <= 14)
796 panic("Packet%d's size too short!\n", i);
799 return 0;
802 static void main_loop(struct ctx *ctx, char *confname, bool slow,
803 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
805 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
806 if (xmit_packet_precheck(ctx, cpu) < 0)
807 return;
809 if (cpu == 0) {
810 unsigned int i;
811 size_t total_len = 0, total_pkts = 0;
813 for (i = 0; i < ctx->cpus; ++i) {
814 total_len += stats[i].cf_bytes;
815 total_pkts += stats[i].cf_packets;
818 printf("%6zu packets to schedule\n", total_pkts);
819 printf("%6zu bytes in total\n", total_len);
820 printf("Running! Hang up with ^C!\n\n");
821 fflush(stdout);
824 sock = pf_tx_socket();
826 if (ctx->qdisc_path == false)
827 set_sock_qdisc_bypass(sock, ctx->verbose);
829 if (slow)
830 xmit_slowpath_or_die(ctx, cpu, orig_num);
831 else
832 xmit_fastpath_or_die(ctx, cpu, orig_num);
834 close(sock);
836 cleanup_packets();
839 static unsigned int generate_srand_seed(void)
841 int fd;
842 unsigned int _seed;
844 fd = open("/dev/urandom", O_RDONLY);
845 if (fd < 0)
846 return time(NULL);
848 read_or_die(fd, &_seed, sizeof(_seed));
850 close(fd);
851 return _seed;
854 int main(int argc, char **argv)
856 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
857 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
858 int c, opt_index, vals[4] = {0}, irq;
859 uint64_t gap = 0;
860 unsigned int i, j;
861 char *confname = NULL, *ptr;
862 unsigned long cpus_tmp, orig_num = 0;
863 unsigned long long tx_packets, tx_bytes;
864 struct ctx ctx;
866 fmemset(&ctx, 0, sizeof(ctx));
867 ctx.cpus = get_number_cpus_online();
868 ctx.uid = getuid();
869 ctx.gid = getgid();
870 ctx.qdisc_path = false;
872 /* Keep an initial small default size to reduce cache-misses. */
873 ctx.reserve_size = 512 * (1 << 10);
875 while ((c = getopt_long(argc, argv, short_options, long_options,
876 &opt_index)) != EOF) {
877 switch (c) {
878 case 'h':
879 help();
880 break;
881 case 'v':
882 version();
883 break;
884 case 'C':
885 cpustats = false;
886 break;
887 case 'e':
888 example();
889 break;
890 case 'p':
891 invoke_cpp = true;
892 break;
893 case 'V':
894 ctx.verbose = true;
895 break;
896 case 'P':
897 cpus_tmp = strtoul(optarg, NULL, 0);
898 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
899 ctx.cpus = cpus_tmp;
900 break;
901 case 'd':
902 case 'o':
903 ctx.device = xstrndup(optarg, IFNAMSIZ);
904 break;
905 case 'H':
906 prio_high = true;
907 break;
908 case 'A':
909 set_sock_mem = false;
910 break;
911 case 'Q':
912 set_irq_aff = false;
913 break;
914 case 'q':
915 ctx.qdisc_path = true;
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 printf("Option -k/--kernel-pull is no longer used and "
948 "will be removed in a future release!\n");
949 break;
950 case 'E':
951 seed = strtoul(optarg, NULL, 0);
952 reseed = false;
953 break;
954 case 'n':
955 orig_num = strtoul(optarg, NULL, 0);
956 ctx.num = orig_num;
957 break;
958 case 't':
959 slow = true;
960 ptr = optarg;
961 prctl(PR_SET_TIMERSLACK, 1UL);
962 gap = strtoul(optarg, NULL, 0);
964 for (j = i = strlen(optarg); i > 0; --i) {
965 if (!isdigit(optarg[j - i]))
966 break;
967 ptr++;
970 if (!strncmp(ptr, "ns", strlen("ns"))) {
971 ctx.gap.tv_sec = gap / 1000000000;
972 ctx.gap.tv_nsec = gap % 1000000000;
973 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
974 /* Default to microseconds for backwards
975 * compatibility if no postfix is given.
977 ctx.gap.tv_sec = gap / 1000000;
978 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
979 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
980 ctx.gap.tv_sec = gap / 1000;
981 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
982 } else if (!strncmp(ptr, "s", strlen("s"))) {
983 ctx.gap.tv_sec = gap;
984 ctx.gap.tv_nsec = 0;
985 } else
986 panic("Syntax error in time param!\n");
988 if (gap > 0)
989 /* Fall back to single core to not mess up
990 * correct timing. We are slow anyway!
992 ctx.cpus = 1;
993 break;
994 case 'S':
995 ptr = optarg;
997 for (j = i = strlen(optarg); i > 0; --i) {
998 if (!isdigit(optarg[j - i]))
999 break;
1000 ptr++;
1003 if (!strncmp(ptr, "KiB", strlen("KiB")))
1004 ctx.reserve_size = 1 << 10;
1005 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1006 ctx.reserve_size = 1 << 20;
1007 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1008 ctx.reserve_size = 1 << 30;
1009 else
1010 panic("Syntax error in ring size param!\n");
1012 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1013 break;
1014 case '?':
1015 switch (optopt) {
1016 case 'd':
1017 case 'c':
1018 case 'n':
1019 case 'S':
1020 case 's':
1021 case 'P':
1022 case 'o':
1023 case 'E':
1024 case 'i':
1025 case 'k':
1026 case 'u':
1027 case 'g':
1028 case 't':
1029 panic("Option -%c requires an argument!\n",
1030 optopt);
1031 default:
1032 if (isprint(optopt))
1033 printf("Unknown option character `0x%X\'!\n", optopt);
1034 die();
1036 default:
1037 break;
1041 if (argc < 5)
1042 help();
1043 if (ctx.device == NULL)
1044 panic("No networking device given!\n");
1045 if (confname == NULL)
1046 panic("No configuration file given!\n");
1047 if (device_mtu(ctx.device) == 0)
1048 panic("This is no networking device!\n");
1050 register_signal(SIGINT, signal_handler);
1051 register_signal(SIGQUIT, signal_handler);
1052 register_signal(SIGTERM, signal_handler);
1053 register_signal(SIGHUP, signal_handler);
1055 if (prio_high) {
1056 set_proc_prio(-20);
1057 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1060 if (set_sock_mem)
1061 set_system_socket_memory(vals, array_size(vals));
1062 xlockme();
1064 if (ctx.rfraw) {
1065 ctx.device_trans = xstrdup(ctx.device);
1066 xfree(ctx.device);
1068 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1069 sleep(0);
1072 irq = device_irq_number(ctx.device);
1073 if (set_irq_aff)
1074 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1076 stats = setup_shared_var(ctx.cpus);
1078 for (i = 0; i < ctx.cpus; i++) {
1079 pid_t pid = fork();
1081 switch (pid) {
1082 case 0:
1083 if (reseed)
1084 seed = generate_srand_seed();
1085 srand(seed);
1087 cpu_affinity(i);
1088 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1090 goto thread_out;
1091 case -1:
1092 panic("Cannot fork processes!\n");
1096 for (i = 0; i < ctx.cpus; i++) {
1097 int status;
1099 wait(&status);
1100 if (WEXITSTATUS(status) == EXIT_FAILURE)
1101 die();
1104 if (ctx.rfraw)
1105 leave_rfmon_mac80211(ctx.device);
1107 if (set_sock_mem)
1108 reset_system_socket_memory(vals, array_size(vals));
1110 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1111 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1112 sched_yield();
1114 tx_packets += stats[i].tx_packets;
1115 tx_bytes += stats[i].tx_bytes;
1118 fflush(stdout);
1119 printf("\n");
1120 printf("\r%12llu packets outgoing\n", tx_packets);
1121 printf("\r%12llu bytes outgoing\n", tx_bytes);
1122 for (i = 0; cpustats && i < ctx.cpus; i++) {
1123 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1124 stats[i].tv_sec, stats[i].tv_usec, i,
1125 stats[i].tx_packets);
1128 thread_out:
1129 xunlockme();
1130 destroy_shared_var(stats, ctx.cpus);
1131 if (set_irq_aff)
1132 device_restore_irq_affinity_list();
1134 free(ctx.device);
1135 free(ctx.device_trans);
1136 free(ctx.rhost);
1137 free(confname);
1139 return 0;