trafgen: Print min packet size in error message
[netsniff-ng.git] / trafgen.c
blob93bb1b4bd5c4b5456a593ded8962c4366945fab3
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 #define PKT_MIN_LEN 14
143 static void signal_handler(int number)
145 switch (number) {
146 case SIGINT:
147 case SIGQUIT:
148 case SIGTERM:
149 sigint = 1;
150 case SIGHUP:
151 default:
152 break;
156 static void __noreturn help(void)
158 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
159 puts("http://www.netsniff-ng.org\n\n"
160 "Usage: trafgen [options]\n"
161 "Options:\n"
162 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
163 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
164 " -p|--cpp Run packet config through C preprocessor\n"
165 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
166 " -R|--rfraw Inject raw 802.11 frames\n"
167 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
168 " -n|--num <uint> Number of packets until exit (def: 0)\n"
169 " -r|--rand Randomize packet selection (def: round robin)\n"
170 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
171 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
172 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
173 " -E|--seed <uint> Manually set srand(3) seed\n"
174 " -u|--user <userid> Drop privileges and change to userid\n"
175 " -g|--group <groupid> Drop privileges and change to groupid\n"
176 " -H|--prio-high Make this high priority process\n"
177 " -A|--no-sock-mem Don't tune core socket memory\n"
178 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
179 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
180 " -V|--verbose Be more verbose\n"
181 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
182 " -v|--version Show version and exit\n"
183 " -e|--example Show built-in packet config example\n"
184 " -h|--help Guess what?!\n\n"
185 "Examples:\n"
186 " trafgen --dev eth0 --conf trafgen.cfg\n"
187 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
188 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
189 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
190 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
191 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
192 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
193 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
194 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
195 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
196 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
197 "Generate config files from existing pcap using netsniff-ng:\n"
198 " netsniff-ng --in dump.pcap --out dump.cfg\n"
199 "Note:\n"
200 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
201 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
202 " we assume the kernel crashed, thus we print the packet and quit.\n"
203 " In case you find a ping-of-death, please mention trafgen in your\n"
204 " commit message of the fix!\n\n"
205 " For introducing bit errors, delays with random variation and more,\n"
206 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
207 " For generating different package distributions, you can use scripting\n"
208 " to generate a trafgen config file with packet ratios as:\n\n"
209 " IMIX 64:7, 570:4, 1518:1\n"
210 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
211 " Cisco 64:7, 594:4, 1518:1\n"
212 " RPR Trimodal 64:60, 512:20, 1518:20\n"
213 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
214 puts(copyright);
215 die();
218 static void __noreturn example(void)
220 const char *e =
221 "/* Note: dynamic elements make trafgen slower! */\n"
222 "#include <stddef.h>\n\n"
223 "{\n"
224 " /* MAC Destination */\n"
225 " fill(0xff, ETH_ALEN),\n"
226 " /* MAC Source */\n"
227 " 0x00, 0x02, 0xb3, drnd(3),\n"
228 " /* IPv4 Protocol */\n"
229 " c16(ETH_P_IP),\n"
230 " /* IPv4 Version, IHL, TOS */\n"
231 " 0b01000101, 0,\n"
232 " /* IPv4 Total Len */\n"
233 " c16(59),\n"
234 " /* IPv4 Ident */\n"
235 " drnd(2),\n"
236 " /* IPv4 Flags, Frag Off */\n"
237 " 0b01000000, 0,\n"
238 " /* IPv4 TTL */\n"
239 " 64,\n"
240 " /* Proto TCP */\n"
241 " 0x06,\n"
242 " /* IPv4 Checksum (IP header from, to) */\n"
243 " csumip(14, 33),\n"
244 " /* Source IP */\n"
245 " drnd(4),\n"
246 " /* Dest IP */\n"
247 " drnd(4),\n"
248 " /* TCP Source Port */\n"
249 " drnd(2),\n"
250 " /* TCP Dest Port */\n"
251 " c16(80),\n"
252 " /* TCP Sequence Number */\n"
253 " drnd(4),\n"
254 " /* TCP Ackn. Number */\n"
255 " c32(0),\n"
256 " /* TCP Header length + TCP SYN/ECN Flag */\n"
257 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
258 " /* Window Size */\n"
259 " c16(16),\n"
260 " /* TCP Checksum (offset IP, offset TCP) */\n"
261 " csumtcp(14, 34),\n"
262 " /* TCP Options */\n"
263 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
264 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
265 " /* Data blob */\n"
266 " \"gotcha!\",\n"
267 "}";
268 puts(e);
269 die();
272 static void __noreturn version(void)
274 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
275 puts("multithreaded zero-copy network packet generator\n"
276 "http://www.netsniff-ng.org\n");
277 puts(copyright);
278 die();
281 static void apply_counter(int id)
283 size_t j, counter_max = packet_dyn[id].clen;
285 for (j = 0; j < counter_max; ++j) {
286 uint8_t val;
287 struct counter *counter = &packet_dyn[id].cnt[j];
289 val = counter->val - counter->min;
291 switch (counter->type) {
292 case TYPE_INC:
293 val = (val + counter->inc) % (counter->max - counter->min + 1);
294 break;
295 case TYPE_DEC:
296 val = (val - counter->inc) % (counter->min - counter->max + 1);
297 break;
298 default:
299 bug();
302 counter->val = val + counter->min;
303 packets[id].payload[counter->off] = val;
307 static void apply_randomizer(int id)
309 size_t j, rand_max = packet_dyn[id].rlen;
311 for (j = 0; j < rand_max; ++j) {
312 uint8_t val = (uint8_t) rand();
313 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
315 packets[id].payload[randomizer->off] = val;
319 static void apply_csum16(int id)
321 size_t j, csum_max = packet_dyn[id].slen;
323 for (j = 0; j < csum_max; ++j) {
324 uint16_t sum = 0;
325 struct csum16 *csum = &packet_dyn[id].csum[j];
327 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
328 if (unlikely((size_t) csum->to >= packets[id].len))
329 csum->to = packets[id].len - 1;
331 switch (csum->which) {
332 case CSUM_IP:
333 sum = calc_csum(packets[id].payload + csum->from,
334 csum->to - csum->from + 1, 0);
335 break;
336 case CSUM_UDP:
337 sum = p4_csum((void *) packets[id].payload + csum->from,
338 packets[id].payload + csum->to,
339 (packets[id].len - csum->to),
340 IPPROTO_UDP);
341 break;
342 case CSUM_TCP:
343 sum = p4_csum((void *) packets[id].payload + csum->from,
344 packets[id].payload + csum->to,
345 (packets[id].len - csum->to),
346 IPPROTO_TCP);
347 break;
348 default:
349 bug();
350 break;
353 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
357 static struct cpu_stats *setup_shared_var(unsigned int cpus)
359 int fd;
360 size_t len = cpus * sizeof(struct cpu_stats);
361 char *zbuff, file[256];
362 struct cpu_stats *buff;
364 zbuff = xzmalloc(len);
365 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
367 fd = creat(file, S_IRUSR | S_IWUSR);
368 bug_on(fd < 0);
369 close(fd);
371 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
372 S_IRUSR | S_IWUSR);
373 write_or_die(fd, zbuff, len);
374 xfree(zbuff);
376 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
377 MAP_SHARED, fd, 0);
378 if (buff == MAP_FAILED)
379 panic("Cannot setup shared variable!\n");
381 close(fd);
382 unlink(file);
384 memset(buff, 0, len);
385 return buff;
388 static void destroy_shared_var(void *buff, unsigned int cpus)
390 munmap(buff, cpus * sizeof(struct cpu_stats));
393 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
395 size_t i;
397 printf("{");
398 for (i = 0; i < len; ++i) {
399 if (i % 15 == 0)
400 printf("\n ");
401 printf("0x%02x, ", payload[i]);
403 printf("\n}\n");
404 fflush(stdout);
407 static int xmit_smoke_setup(struct ctx *ctx)
409 int icmp_sock, ret, ttl = 64;
410 struct icmp_filter filter;
412 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
413 if (icmp_sock < 0)
414 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
416 filter.data = ~(1 << ICMP_ECHOREPLY);
418 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
419 if (ret < 0)
420 panic("Cannot install filter!\n");
422 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
423 if (ret < 0)
424 panic("Cannot set TTL!\n");
426 memset(&ctx->dest, 0, sizeof(ctx->dest));
427 ctx->dest.sin_family = AF_INET;
428 ctx->dest.sin_port = 0;
430 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
431 if (ret < 0)
432 panic("Cannot resolv address!\n");
434 return icmp_sock;
437 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
439 int ret;
440 unsigned int i, j;
441 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
442 uint8_t outpack[512], *data;
443 struct icmphdr *icmp;
444 struct iphdr *ip;
445 size_t len = sizeof(*icmp) + 56;
446 struct sockaddr_in from;
447 socklen_t from_len;
448 struct pollfd fds = {
449 .fd = icmp_sock,
450 .events = POLLIN,
453 fmemset(idstore, 0, sizeof(idstore));
454 for (j = 0; j < SMOKE_N_PROBES; j++) {
455 while ((ident = htons((short) rand())) == 0)
456 sleep(0);
457 idstore[j] = ident;
459 memset(outpack, 0, sizeof(outpack));
460 icmp = (void *) outpack;
461 icmp->type = ICMP_ECHO;
462 icmp->un.echo.id = ident;
463 icmp->un.echo.sequence = htons(cnt++);
465 data = ((uint8_t *) outpack + sizeof(*icmp));
466 for (i = 0; i < 56; ++i)
467 data[i] = (uint8_t) rand();
469 icmp->checksum = csum((unsigned short *) outpack,
470 len / sizeof(unsigned short));
472 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
473 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
474 if (unlikely(ret != (int) len))
475 panic("Cannot send out probe: %s!\n", strerror(errno));
477 ret = poll(&fds, 1, 50);
478 if (ret < 0)
479 panic("Poll failed!\n");
481 if (fds.revents & POLLIN) {
482 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
483 (struct sockaddr *) &from, &from_len);
484 if (unlikely(ret <= 0))
485 panic("Probe receive failed!\n");
486 if (unlikely(from_len != sizeof(ctx->dest)))
487 continue;
488 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
489 continue;
490 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
491 continue;
492 ip = (void *) outpack;
493 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
494 continue;
495 icmp = (void *) outpack + ip->ihl * 4;
496 for (i = 0; i < array_size(idstore); ++i) {
497 if (unlikely(icmp->un.echo.id != idstore[i]))
498 continue;
499 return 0;
504 return -1;
507 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
509 int ret, icmp_sock = -1;
510 unsigned long num = 1, i = 0;
511 struct timeval start, end, diff;
512 unsigned long long tx_bytes = 0, tx_packets = 0;
513 struct packet_dyn *pktd;
514 struct sockaddr_ll saddr = {
515 .sll_family = PF_PACKET,
516 .sll_halen = ETH_ALEN,
517 .sll_ifindex = device_ifindex(ctx->device),
520 if (ctx->num > 0)
521 num = ctx->num;
522 if (ctx->num == 0 && orig_num > 0)
523 num = 0;
525 if (ctx->smoke_test)
526 icmp_sock = xmit_smoke_setup(ctx);
528 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
530 bug_on(gettimeofday(&start, NULL));
532 while (likely(sigint == 0 && num > 0 && plen > 0)) {
533 pktd = &packet_dyn[i];
534 if (pktd->clen + pktd->rlen + pktd->slen) {
535 apply_counter(i);
536 apply_randomizer(i);
537 apply_csum16(i);
539 retry:
540 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
541 (struct sockaddr *) &saddr, sizeof(saddr));
542 if (unlikely(ret < 0)) {
543 if (errno == ENOBUFS) {
544 sched_yield();
545 goto retry;
547 if (ctx->smoke_test)
548 panic("Sendto error: %s!\n", strerror(errno));
551 tx_bytes += packets[i].len;
552 tx_packets++;
554 if (ctx->smoke_test) {
555 ret = xmit_smoke_probe(icmp_sock, ctx);
556 if (unlikely(ret < 0)) {
557 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
558 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
559 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
560 i, seed);
562 dump_trafgen_snippet(packets[i].payload, packets[i].len);
563 break;
567 if (!ctx->rand) {
568 i++;
569 if (i >= plen)
570 i = 0;
571 } else
572 i = rand() % plen;
574 if (ctx->num > 0)
575 num--;
577 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
578 nanosleep(&ctx->gap, NULL);
581 bug_on(gettimeofday(&end, NULL));
582 timersub(&end, &start, &diff);
584 if (ctx->smoke_test)
585 close(icmp_sock);
587 stats[cpu].tx_packets = tx_packets;
588 stats[cpu].tx_bytes = tx_bytes;
589 stats[cpu].tv_sec = diff.tv_sec;
590 stats[cpu].tv_usec = diff.tv_usec;
592 stats[cpu].state |= CPU_STATS_STATE_RES;
595 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
597 int ifindex = device_ifindex(ctx->device);
598 uint8_t *out = NULL;
599 unsigned int it = 0;
600 unsigned long num = 1, i = 0;
601 size_t size = ring_size(ctx->device, ctx->reserve_size);
602 struct ring tx_ring;
603 struct frame_map *hdr;
604 struct timeval start, end, diff;
605 struct packet_dyn *pktd;
606 unsigned long long tx_bytes = 0, tx_packets = 0;
608 set_sock_prio(sock, 512);
610 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
612 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
614 if (ctx->num > 0)
615 num = ctx->num;
616 if (ctx->num == 0 && orig_num > 0)
617 num = 0;
619 bug_on(gettimeofday(&start, NULL));
621 while (likely(sigint == 0 && num > 0 && plen > 0)) {
622 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
623 int ret = pull_and_flush_tx_ring(sock);
624 if (unlikely(ret < 0)) {
625 /* We could hit EBADF if the socket has been closed before
626 * the timer was triggered.
628 if (errno != EBADF && errno != ENOBUFS)
629 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
632 continue;
635 hdr = tx_ring.frames[it].iov_base;
636 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
638 hdr->tp_h.tp_snaplen = packets[i].len;
639 hdr->tp_h.tp_len = packets[i].len;
641 pktd = &packet_dyn[i];
642 if (pktd->clen + pktd->rlen + pktd->slen) {
643 apply_counter(i);
644 apply_randomizer(i);
645 apply_csum16(i);
648 fmemcpy(out, packets[i].payload, packets[i].len);
650 tx_bytes += packets[i].len;
651 tx_packets++;
653 if (!ctx->rand) {
654 i++;
655 if (i >= plen)
656 i = 0;
657 } else
658 i = rand() % plen;
660 kernel_may_pull_from_tx(&hdr->tp_h);
662 it++;
663 if (it >= tx_ring.layout.tp_frame_nr)
664 it = 0;
666 if (ctx->num > 0)
667 num--;
670 bug_on(gettimeofday(&end, NULL));
671 timersub(&end, &start, &diff);
673 pull_and_flush_tx_ring_wait(sock);
674 destroy_tx_ring(sock, &tx_ring);
676 stats[cpu].tx_packets = tx_packets;
677 stats[cpu].tx_bytes = tx_bytes;
678 stats[cpu].tv_sec = diff.tv_sec;
679 stats[cpu].tv_usec = diff.tv_usec;
681 stats[cpu].state |= CPU_STATS_STATE_RES;
684 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
686 stats[cpu].state = s;
689 static inline sig_atomic_t __get_state(unsigned int cpu)
691 return stats[cpu].state;
694 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
696 unsigned int i;
697 unsigned long total;
699 for (i = 0, total = plen; i < ctx->cpus; i++) {
700 if (i == cpu)
701 continue;
703 while ((__get_state(i) &
704 (CPU_STATS_STATE_CFG |
705 CPU_STATS_STATE_RES)) == 0 &&
706 sigint == 0)
707 sched_yield();
709 total += stats[i].cf_packets;
712 return total;
715 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
717 unsigned int i;
718 unsigned long total;
719 int cpu_sel;
720 long long delta_correction = 0;
722 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
723 if (i == cpu)
724 continue;
726 while ((__get_state(i) &
727 (CPU_STATS_STATE_CHK |
728 CPU_STATS_STATE_RES)) == 0 &&
729 sigint == 0)
730 sched_yield();
732 total += stats[i].cd_packets;
735 if (total > orig)
736 delta_correction = -1 * ((long long) total - orig);
737 if (total < orig)
738 delta_correction = +1 * ((long long) orig - total);
740 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
741 if (stats[i].cd_packets > 0) {
742 if ((long long) stats[i].cd_packets +
743 delta_correction >= 0) {
744 cpu_sel = i;
745 break;
750 if ((int) cpu == cpu_sel)
751 ctx->num += delta_correction;
754 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
755 sig_atomic_t s)
757 stats[cpu].cf_packets = p;
758 stats[cpu].cf_bytes = b;
759 stats[cpu].state = s;
762 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
764 stats[cpu].cd_packets = p;
765 stats[cpu].state = s;
768 static int xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
770 unsigned int i;
771 unsigned long plen_total, orig = ctx->num;
772 size_t mtu, total_len = 0;
774 bug_on(plen != dlen);
776 for (i = 0; i < plen; ++i)
777 total_len += packets[i].len;
779 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
780 plen_total = __wait_and_sum_others(ctx, cpu);
782 if (orig > 0) {
783 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
785 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
786 CPU_STATS_STATE_CFG);
787 __correct_global_delta(ctx, cpu, orig);
790 if (plen == 0) {
791 __set_state(cpu, CPU_STATS_STATE_RES);
792 return 0;
795 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
796 if (packets[i].len > mtu + PKT_MIN_LEN)
797 panic("Device MTU < than packet%d's size!\n", i);
798 if (packets[i].len <= PKT_MIN_LEN)
799 panic("Packet%d's size must be > %d bytes!\n",
800 i, PKT_MIN_LEN);
803 return 0;
806 static void main_loop(struct ctx *ctx, char *confname, bool slow,
807 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
809 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
810 if (xmit_packet_precheck(ctx, cpu) < 0)
811 return;
813 if (cpu == 0) {
814 unsigned int i;
815 size_t total_len = 0, total_pkts = 0;
817 for (i = 0; i < ctx->cpus; ++i) {
818 total_len += stats[i].cf_bytes;
819 total_pkts += stats[i].cf_packets;
822 printf("%6zu packets to schedule\n", total_pkts);
823 printf("%6zu bytes in total\n", total_len);
824 printf("Running! Hang up with ^C!\n\n");
825 fflush(stdout);
828 sock = pf_socket();
830 if (ctx->qdisc_path == false)
831 set_sock_qdisc_bypass(sock, ctx->verbose);
833 if (slow)
834 xmit_slowpath_or_die(ctx, cpu, orig_num);
835 else
836 xmit_fastpath_or_die(ctx, cpu, orig_num);
838 close(sock);
840 cleanup_packets();
843 static unsigned int generate_srand_seed(void)
845 int fd;
846 unsigned int _seed;
848 fd = open("/dev/urandom", O_RDONLY);
849 if (fd < 0)
850 return time(NULL);
852 read_or_die(fd, &_seed, sizeof(_seed));
854 close(fd);
855 return _seed;
858 static void on_panic_del_rfmon(void *arg)
860 leave_rfmon_mac80211(arg);
863 int main(int argc, char **argv)
865 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
866 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
867 int c, opt_index, vals[4] = {0}, irq;
868 uint64_t gap = 0;
869 unsigned int i, j;
870 char *confname = NULL, *ptr;
871 unsigned long cpus_tmp, orig_num = 0;
872 unsigned long long tx_packets, tx_bytes;
873 struct ctx ctx;
875 fmemset(&ctx, 0, sizeof(ctx));
876 ctx.cpus = get_number_cpus_online();
877 ctx.uid = getuid();
878 ctx.gid = getgid();
879 ctx.qdisc_path = false;
881 /* Keep an initial small default size to reduce cache-misses. */
882 ctx.reserve_size = 512 * (1 << 10);
884 while ((c = getopt_long(argc, argv, short_options, long_options,
885 &opt_index)) != EOF) {
886 switch (c) {
887 case 'h':
888 help();
889 break;
890 case 'v':
891 version();
892 break;
893 case 'C':
894 cpustats = false;
895 break;
896 case 'e':
897 example();
898 break;
899 case 'p':
900 invoke_cpp = true;
901 break;
902 case 'V':
903 ctx.verbose = true;
904 break;
905 case 'P':
906 cpus_tmp = strtoul(optarg, NULL, 0);
907 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
908 ctx.cpus = cpus_tmp;
909 break;
910 case 'd':
911 case 'o':
912 ctx.device = xstrndup(optarg, IFNAMSIZ);
913 break;
914 case 'H':
915 prio_high = true;
916 break;
917 case 'A':
918 set_sock_mem = false;
919 break;
920 case 'Q':
921 set_irq_aff = false;
922 break;
923 case 'q':
924 ctx.qdisc_path = true;
925 break;
926 case 'r':
927 ctx.rand = true;
928 break;
929 case 's':
930 slow = true;
931 ctx.cpus = 1;
932 ctx.smoke_test = true;
933 ctx.rhost = xstrdup(optarg);
934 break;
935 case 'R':
936 ctx.rfraw = true;
937 break;
938 case 'J':
939 ctx.jumbo_support = true;
940 break;
941 case 'c':
942 case 'i':
943 confname = xstrdup(optarg);
944 if (!strncmp("-", confname, strlen("-")))
945 ctx.cpus = 1;
946 break;
947 case 'u':
948 ctx.uid = strtoul(optarg, NULL, 0);
949 ctx.enforce = true;
950 break;
951 case 'g':
952 ctx.gid = strtoul(optarg, NULL, 0);
953 ctx.enforce = true;
954 break;
955 case 'k':
956 printf("Option -k/--kernel-pull is no longer used and "
957 "will be removed in a future release!\n");
958 break;
959 case 'E':
960 seed = strtoul(optarg, NULL, 0);
961 reseed = false;
962 break;
963 case 'n':
964 orig_num = strtoul(optarg, NULL, 0);
965 ctx.num = orig_num;
966 break;
967 case 't':
968 slow = true;
969 ptr = optarg;
970 prctl(PR_SET_TIMERSLACK, 1UL);
971 gap = strtoul(optarg, NULL, 0);
973 for (j = i = strlen(optarg); i > 0; --i) {
974 if (!isdigit(optarg[j - i]))
975 break;
976 ptr++;
979 if (!strncmp(ptr, "ns", strlen("ns"))) {
980 ctx.gap.tv_sec = gap / 1000000000;
981 ctx.gap.tv_nsec = gap % 1000000000;
982 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
983 /* Default to microseconds for backwards
984 * compatibility if no postfix is given.
986 ctx.gap.tv_sec = gap / 1000000;
987 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
988 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
989 ctx.gap.tv_sec = gap / 1000;
990 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
991 } else if (!strncmp(ptr, "s", strlen("s"))) {
992 ctx.gap.tv_sec = gap;
993 ctx.gap.tv_nsec = 0;
994 } else
995 panic("Syntax error in time param!\n");
997 if (gap > 0)
998 /* Fall back to single core to not mess up
999 * correct timing. We are slow anyway!
1001 ctx.cpus = 1;
1002 break;
1003 case 'S':
1004 ptr = optarg;
1006 for (j = i = strlen(optarg); i > 0; --i) {
1007 if (!isdigit(optarg[j - i]))
1008 break;
1009 ptr++;
1012 if (!strncmp(ptr, "KiB", strlen("KiB")))
1013 ctx.reserve_size = 1 << 10;
1014 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1015 ctx.reserve_size = 1 << 20;
1016 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1017 ctx.reserve_size = 1 << 30;
1018 else
1019 panic("Syntax error in ring size param!\n");
1021 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1022 break;
1023 case '?':
1024 switch (optopt) {
1025 case 'd':
1026 case 'c':
1027 case 'n':
1028 case 'S':
1029 case 's':
1030 case 'P':
1031 case 'o':
1032 case 'E':
1033 case 'i':
1034 case 'k':
1035 case 'u':
1036 case 'g':
1037 case 't':
1038 panic("Option -%c requires an argument!\n",
1039 optopt);
1040 default:
1041 if (isprint(optopt))
1042 printf("Unknown option character `0x%X\'!\n", optopt);
1043 die();
1045 default:
1046 break;
1050 if (argc < 5)
1051 help();
1052 if (ctx.device == NULL)
1053 panic("No networking device given!\n");
1054 if (confname == NULL)
1055 panic("No configuration file given!\n");
1056 if (device_mtu(ctx.device) == 0)
1057 panic("This is no networking device!\n");
1059 register_signal(SIGINT, signal_handler);
1060 register_signal(SIGQUIT, signal_handler);
1061 register_signal(SIGTERM, signal_handler);
1062 register_signal(SIGHUP, signal_handler);
1064 if (prio_high) {
1065 set_proc_prio(-20);
1066 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1069 if (set_sock_mem)
1070 set_system_socket_memory(vals, array_size(vals));
1071 xlockme();
1073 if (ctx.rfraw) {
1074 ctx.device_trans = xstrdup(ctx.device);
1075 xfree(ctx.device);
1077 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1078 panic_handler_add(on_panic_del_rfmon, ctx.device);
1079 sleep(0);
1083 * If number of packets is smaller than number of CPUs use only as
1084 * many CPUs as there are packets. Otherwise we end up sending more
1085 * packets than intended or none at all.
1087 if (ctx.num)
1088 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1090 irq = device_irq_number(ctx.device);
1091 if (set_irq_aff)
1092 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1094 stats = setup_shared_var(ctx.cpus);
1096 for (i = 0; i < ctx.cpus; i++) {
1097 pid_t pid = fork();
1099 switch (pid) {
1100 case 0:
1101 if (reseed)
1102 seed = generate_srand_seed();
1103 srand(seed);
1105 cpu_affinity(i);
1106 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1108 goto thread_out;
1109 case -1:
1110 panic("Cannot fork processes!\n");
1114 for (i = 0; i < ctx.cpus; i++) {
1115 int status;
1117 wait(&status);
1118 if (WEXITSTATUS(status) == EXIT_FAILURE)
1119 die();
1122 if (ctx.rfraw)
1123 leave_rfmon_mac80211(ctx.device);
1125 if (set_sock_mem)
1126 reset_system_socket_memory(vals, array_size(vals));
1128 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1129 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1130 sched_yield();
1132 tx_packets += stats[i].tx_packets;
1133 tx_bytes += stats[i].tx_bytes;
1136 fflush(stdout);
1137 printf("\n");
1138 printf("\r%12llu packets outgoing\n", tx_packets);
1139 printf("\r%12llu bytes outgoing\n", tx_bytes);
1140 for (i = 0; cpustats && i < ctx.cpus; i++) {
1141 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1142 stats[i].tv_sec, stats[i].tv_usec, i,
1143 stats[i].tx_packets);
1146 thread_out:
1147 xunlockme();
1148 destroy_shared_var(stats, ctx.cpus);
1149 if (set_irq_aff)
1150 device_restore_irq_affinity_list();
1152 free(ctx.device);
1153 free(ctx.device_trans);
1154 free(ctx.rhost);
1155 free(confname);
1157 return 0;