flowtop: Fix missing --no-geoip option in usage output
[netsniff-ng.git] / trafgen.c
blobc35182e37f89dacfcee3ffe844fb2a9000c97f36
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 <netsniff-ng@googlegroups.com>\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 case CSUM_UDP6:
349 sum = p6_csum((void *) packets[id].payload + csum->from,
350 packets[id].payload + csum->to,
351 (packets[id].len - csum->to),
352 IPPROTO_UDP);
353 break;
354 case CSUM_TCP6:
355 sum = p6_csum((void *) packets[id].payload + csum->from,
356 packets[id].payload + csum->to,
357 (packets[id].len - csum->to),
358 IPPROTO_TCP);
359 break;
360 default:
361 bug();
362 break;
365 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
369 static struct cpu_stats *setup_shared_var(unsigned int cpus)
371 int fd;
372 size_t len = cpus * sizeof(struct cpu_stats);
373 char *zbuff, file[256];
374 struct cpu_stats *buff;
376 zbuff = xzmalloc(len);
377 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
379 fd = creat(file, S_IRUSR | S_IWUSR);
380 bug_on(fd < 0);
381 close(fd);
383 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
384 S_IRUSR | S_IWUSR);
385 write_or_die(fd, zbuff, len);
386 xfree(zbuff);
388 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
389 MAP_SHARED, fd, 0);
390 if (buff == MAP_FAILED)
391 panic("Cannot setup shared variable!\n");
393 close(fd);
394 unlink(file);
396 memset(buff, 0, len);
397 return buff;
400 static void destroy_shared_var(void *buff, unsigned int cpus)
402 munmap(buff, cpus * sizeof(struct cpu_stats));
405 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
407 size_t i;
409 printf("{");
410 for (i = 0; i < len; ++i) {
411 if (i % 15 == 0)
412 printf("\n ");
413 printf("0x%02x, ", payload[i]);
415 printf("\n}\n");
416 fflush(stdout);
419 static int xmit_smoke_setup(struct ctx *ctx)
421 int icmp_sock, ret, ttl = 64;
422 struct icmp_filter filter;
424 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
425 if (icmp_sock < 0)
426 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
428 filter.data = ~(1 << ICMP_ECHOREPLY);
430 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
431 if (ret < 0)
432 panic("Cannot install filter!\n");
434 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
435 if (ret < 0)
436 panic("Cannot set TTL!\n");
438 memset(&ctx->dest, 0, sizeof(ctx->dest));
439 ctx->dest.sin_family = AF_INET;
440 ctx->dest.sin_port = 0;
442 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
443 if (ret < 0)
444 panic("Cannot resolv address!\n");
446 return icmp_sock;
449 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
451 int ret;
452 unsigned int i, j;
453 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
454 uint8_t outpack[512], *data;
455 struct icmphdr *icmp;
456 struct iphdr *ip;
457 size_t len = sizeof(*icmp) + 56;
458 struct sockaddr_in from;
459 socklen_t from_len;
460 struct pollfd fds = {
461 .fd = icmp_sock,
462 .events = POLLIN,
465 fmemset(idstore, 0, sizeof(idstore));
466 for (j = 0; j < SMOKE_N_PROBES; j++) {
467 while ((ident = htons((short) rand())) == 0)
468 sleep(0);
469 idstore[j] = ident;
471 memset(outpack, 0, sizeof(outpack));
472 icmp = (void *) outpack;
473 icmp->type = ICMP_ECHO;
474 icmp->un.echo.id = ident;
475 icmp->un.echo.sequence = htons(cnt++);
477 data = ((uint8_t *) outpack + sizeof(*icmp));
478 for (i = 0; i < 56; ++i)
479 data[i] = (uint8_t) rand();
481 icmp->checksum = csum((unsigned short *) outpack,
482 len / sizeof(unsigned short));
484 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
485 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
486 if (unlikely(ret != (int) len))
487 panic("Cannot send out probe: %s!\n", strerror(errno));
489 ret = poll(&fds, 1, 50);
490 if (ret < 0)
491 panic("Poll failed!\n");
493 if (fds.revents & POLLIN) {
494 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
495 (struct sockaddr *) &from, &from_len);
496 if (unlikely(ret <= 0))
497 panic("Probe receive failed!\n");
498 if (unlikely(from_len != sizeof(ctx->dest)))
499 continue;
500 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
501 continue;
502 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
503 continue;
504 ip = (void *) outpack;
505 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
506 continue;
507 icmp = (void *) outpack + ip->ihl * 4;
508 for (i = 0; i < array_size(idstore); ++i) {
509 if (unlikely(icmp->un.echo.id != idstore[i]))
510 continue;
511 return 0;
516 return -1;
519 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
521 int ret, icmp_sock = -1;
522 unsigned long num = 1, i = 0;
523 struct timeval start, end, diff;
524 unsigned long long tx_bytes = 0, tx_packets = 0;
525 struct packet_dyn *pktd;
526 struct sockaddr_ll saddr = {
527 .sll_family = PF_PACKET,
528 .sll_halen = ETH_ALEN,
529 .sll_ifindex = device_ifindex(ctx->device),
532 if (ctx->num > 0)
533 num = ctx->num;
534 if (ctx->num == 0 && orig_num > 0)
535 num = 0;
537 if (ctx->smoke_test)
538 icmp_sock = xmit_smoke_setup(ctx);
540 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
542 bug_on(gettimeofday(&start, NULL));
544 while (likely(sigint == 0 && num > 0 && plen > 0)) {
545 pktd = &packet_dyn[i];
546 if (packet_dyn_has_elems(pktd)) {
547 apply_counter(i);
548 apply_randomizer(i);
549 apply_csum16(i);
551 retry:
552 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
553 (struct sockaddr *) &saddr, sizeof(saddr));
554 if (unlikely(ret < 0)) {
555 if (errno == ENOBUFS) {
556 sched_yield();
557 goto retry;
559 if (ctx->smoke_test)
560 panic("Sendto error: %s!\n", strerror(errno));
563 tx_bytes += packets[i].len;
564 tx_packets++;
566 if (ctx->smoke_test) {
567 ret = xmit_smoke_probe(icmp_sock, ctx);
568 if (unlikely(ret < 0)) {
569 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
570 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
571 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
572 i, seed);
574 dump_trafgen_snippet(packets[i].payload, packets[i].len);
575 break;
579 if (!ctx->rand) {
580 i++;
581 if (i >= plen)
582 i = 0;
583 } else
584 i = rand() % plen;
586 if (ctx->num > 0)
587 num--;
589 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
590 nanosleep(&ctx->gap, NULL);
593 bug_on(gettimeofday(&end, NULL));
594 timersub(&end, &start, &diff);
596 if (ctx->smoke_test)
597 close(icmp_sock);
599 stats[cpu].tx_packets = tx_packets;
600 stats[cpu].tx_bytes = tx_bytes;
601 stats[cpu].tv_sec = diff.tv_sec;
602 stats[cpu].tv_usec = diff.tv_usec;
604 stats[cpu].state |= CPU_STATS_STATE_RES;
607 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
609 int ifindex = device_ifindex(ctx->device);
610 uint8_t *out = NULL;
611 unsigned int it = 0;
612 unsigned long num = 1, i = 0;
613 size_t size = ring_size(ctx->device, ctx->reserve_size);
614 struct ring tx_ring;
615 struct frame_map *hdr;
616 struct timeval start, end, diff;
617 struct packet_dyn *pktd;
618 unsigned long long tx_bytes = 0, tx_packets = 0;
620 set_sock_prio(sock, 512);
622 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
624 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
626 if (ctx->num > 0)
627 num = ctx->num;
628 if (ctx->num == 0 && orig_num > 0)
629 num = 0;
631 bug_on(gettimeofday(&start, NULL));
633 while (likely(sigint == 0 && num > 0 && plen > 0)) {
634 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
635 int ret = pull_and_flush_tx_ring(sock);
636 if (unlikely(ret < 0)) {
637 /* We could hit EBADF if the socket has been closed before
638 * the timer was triggered.
640 if (errno != EBADF && errno != ENOBUFS)
641 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
644 continue;
647 hdr = tx_ring.frames[it].iov_base;
648 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
650 hdr->tp_h.tp_snaplen = packets[i].len;
651 hdr->tp_h.tp_len = packets[i].len;
653 pktd = &packet_dyn[i];
654 if (packet_dyn_has_elems(pktd)) {
655 apply_counter(i);
656 apply_randomizer(i);
657 apply_csum16(i);
660 fmemcpy(out, packets[i].payload, packets[i].len);
662 tx_bytes += packets[i].len;
663 tx_packets++;
665 if (!ctx->rand) {
666 i++;
667 if (i >= plen)
668 i = 0;
669 } else
670 i = rand() % plen;
672 kernel_may_pull_from_tx(&hdr->tp_h);
674 it++;
675 if (it >= tx_ring.layout.tp_frame_nr)
676 it = 0;
678 if (ctx->num > 0)
679 num--;
682 bug_on(gettimeofday(&end, NULL));
683 timersub(&end, &start, &diff);
685 pull_and_flush_tx_ring_wait(sock);
686 destroy_tx_ring(sock, &tx_ring);
688 stats[cpu].tx_packets = tx_packets;
689 stats[cpu].tx_bytes = tx_bytes;
690 stats[cpu].tv_sec = diff.tv_sec;
691 stats[cpu].tv_usec = diff.tv_usec;
693 stats[cpu].state |= CPU_STATS_STATE_RES;
696 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
698 stats[cpu].state = s;
701 static inline sig_atomic_t __get_state(unsigned int cpu)
703 return stats[cpu].state;
706 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
708 unsigned int i;
709 unsigned long total;
711 for (i = 0, total = plen; i < ctx->cpus; i++) {
712 if (i == cpu)
713 continue;
715 while ((__get_state(i) &
716 (CPU_STATS_STATE_CFG |
717 CPU_STATS_STATE_RES)) == 0 &&
718 sigint == 0)
719 sched_yield();
721 total += stats[i].cf_packets;
724 return total;
727 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
729 unsigned int i;
730 unsigned long total;
731 int cpu_sel;
732 long long delta_correction = 0;
734 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
735 if (i == cpu)
736 continue;
738 while ((__get_state(i) &
739 (CPU_STATS_STATE_CHK |
740 CPU_STATS_STATE_RES)) == 0 &&
741 sigint == 0)
742 sched_yield();
744 total += stats[i].cd_packets;
747 if (total > orig)
748 delta_correction = -1 * ((long long) total - orig);
749 if (total < orig)
750 delta_correction = +1 * ((long long) orig - total);
752 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
753 if (stats[i].cd_packets > 0) {
754 if ((long long) stats[i].cd_packets +
755 delta_correction >= 0) {
756 cpu_sel = i;
757 break;
762 if ((int) cpu == cpu_sel)
763 ctx->num += delta_correction;
766 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
767 sig_atomic_t s)
769 stats[cpu].cf_packets = p;
770 stats[cpu].cf_bytes = b;
771 stats[cpu].state = s;
774 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
776 stats[cpu].cd_packets = p;
777 stats[cpu].state = s;
780 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
782 unsigned int i;
783 unsigned long plen_total, orig = ctx->num;
784 size_t mtu, total_len = 0;
786 bug_on(plen != dlen);
788 for (i = 0; i < plen; ++i)
789 total_len += packets[i].len;
791 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
792 plen_total = __wait_and_sum_others(ctx, cpu);
794 if (orig > 0) {
795 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
797 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
798 CPU_STATS_STATE_CFG);
799 __correct_global_delta(ctx, cpu, orig);
802 if (plen == 0) {
803 __set_state(cpu, CPU_STATS_STATE_RES);
804 return;
807 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
808 if (packets[i].len > mtu + PKT_MIN_LEN)
809 panic("Device MTU < than packet%d's size!\n", i);
810 if (packets[i].len <= PKT_MIN_LEN)
811 panic("Packet%d's size must be > %d bytes!\n",
812 i, PKT_MIN_LEN);
816 static void main_loop(struct ctx *ctx, char *confname, bool slow,
817 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
819 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
820 xmit_packet_precheck(ctx, cpu);
822 if (cpu == 0) {
823 unsigned int i;
824 size_t total_len = 0, total_pkts = 0;
826 for (i = 0; i < ctx->cpus; ++i) {
827 total_len += stats[i].cf_bytes;
828 total_pkts += stats[i].cf_packets;
831 printf("%6zu packets to schedule\n", total_pkts);
832 printf("%6zu bytes in total\n", total_len);
833 printf("Running! Hang up with ^C!\n\n");
834 fflush(stdout);
837 sock = pf_socket();
839 if (ctx->qdisc_path == false)
840 set_sock_qdisc_bypass(sock, ctx->verbose);
842 if (slow)
843 xmit_slowpath_or_die(ctx, cpu, orig_num);
844 else
845 xmit_fastpath_or_die(ctx, cpu, orig_num);
847 close(sock);
849 cleanup_packets();
852 static unsigned int generate_srand_seed(void)
854 int fd;
855 unsigned int _seed;
857 fd = open("/dev/urandom", O_RDONLY);
858 if (fd < 0)
859 return time(NULL);
861 read_or_die(fd, &_seed, sizeof(_seed));
863 close(fd);
864 return _seed;
867 static void on_panic_del_rfmon(void *arg)
869 leave_rfmon_mac80211(arg);
872 int main(int argc, char **argv)
874 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
875 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
876 int c, opt_index, vals[4] = {0}, irq;
877 uint64_t gap = 0;
878 unsigned int i, j;
879 char *confname = NULL, *ptr;
880 unsigned long cpus_tmp, orig_num = 0;
881 unsigned long long tx_packets, tx_bytes;
882 struct ctx ctx;
884 fmemset(&ctx, 0, sizeof(ctx));
885 ctx.cpus = get_number_cpus_online();
886 ctx.uid = getuid();
887 ctx.gid = getgid();
888 ctx.qdisc_path = false;
890 /* Keep an initial small default size to reduce cache-misses. */
891 ctx.reserve_size = 512 * (1 << 10);
893 while ((c = getopt_long(argc, argv, short_options, long_options,
894 &opt_index)) != EOF) {
895 switch (c) {
896 case 'h':
897 help();
898 break;
899 case 'v':
900 version();
901 break;
902 case 'C':
903 cpustats = false;
904 break;
905 case 'e':
906 example();
907 break;
908 case 'p':
909 invoke_cpp = true;
910 break;
911 case 'V':
912 ctx.verbose = true;
913 break;
914 case 'P':
915 cpus_tmp = strtoul(optarg, NULL, 0);
916 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
917 ctx.cpus = cpus_tmp;
918 break;
919 case 'd':
920 case 'o':
921 ctx.device = xstrndup(optarg, IFNAMSIZ);
922 break;
923 case 'H':
924 prio_high = true;
925 break;
926 case 'A':
927 set_sock_mem = false;
928 break;
929 case 'Q':
930 set_irq_aff = false;
931 break;
932 case 'q':
933 ctx.qdisc_path = true;
934 break;
935 case 'r':
936 ctx.rand = true;
937 break;
938 case 's':
939 slow = true;
940 ctx.cpus = 1;
941 ctx.smoke_test = true;
942 ctx.rhost = xstrdup(optarg);
943 break;
944 case 'R':
945 ctx.rfraw = true;
946 break;
947 case 'J':
948 ctx.jumbo_support = true;
949 break;
950 case 'c':
951 case 'i':
952 confname = xstrdup(optarg);
953 if (!strncmp("-", confname, strlen("-")))
954 ctx.cpus = 1;
955 break;
956 case 'u':
957 ctx.uid = strtoul(optarg, NULL, 0);
958 ctx.enforce = true;
959 break;
960 case 'g':
961 ctx.gid = strtoul(optarg, NULL, 0);
962 ctx.enforce = true;
963 break;
964 case 'k':
965 printf("Option -k/--kernel-pull is no longer used and "
966 "will be removed in a future release!\n");
967 break;
968 case 'E':
969 seed = strtoul(optarg, NULL, 0);
970 reseed = false;
971 break;
972 case 'n':
973 orig_num = strtoul(optarg, NULL, 0);
974 ctx.num = orig_num;
975 break;
976 case 't':
977 slow = true;
978 ptr = optarg;
979 prctl(PR_SET_TIMERSLACK, 1UL);
980 gap = strtoul(optarg, NULL, 0);
982 for (j = i = strlen(optarg); i > 0; --i) {
983 if (!isdigit(optarg[j - i]))
984 break;
985 ptr++;
988 if (!strncmp(ptr, "ns", strlen("ns"))) {
989 ctx.gap.tv_sec = gap / 1000000000;
990 ctx.gap.tv_nsec = gap % 1000000000;
991 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
992 /* Default to microseconds for backwards
993 * compatibility if no postfix is given.
995 ctx.gap.tv_sec = gap / 1000000;
996 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
997 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
998 ctx.gap.tv_sec = gap / 1000;
999 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1000 } else if (!strncmp(ptr, "s", strlen("s"))) {
1001 ctx.gap.tv_sec = gap;
1002 ctx.gap.tv_nsec = 0;
1003 } else
1004 panic("Syntax error in time param!\n");
1006 if (gap > 0)
1007 /* Fall back to single core to not mess up
1008 * correct timing. We are slow anyway!
1010 ctx.cpus = 1;
1011 break;
1012 case 'S':
1013 ptr = optarg;
1015 for (j = i = strlen(optarg); i > 0; --i) {
1016 if (!isdigit(optarg[j - i]))
1017 break;
1018 ptr++;
1021 if (!strncmp(ptr, "KiB", strlen("KiB")))
1022 ctx.reserve_size = 1 << 10;
1023 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1024 ctx.reserve_size = 1 << 20;
1025 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1026 ctx.reserve_size = 1 << 30;
1027 else
1028 panic("Syntax error in ring size param!\n");
1030 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1031 break;
1032 case '?':
1033 switch (optopt) {
1034 case 'd':
1035 case 'c':
1036 case 'n':
1037 case 'S':
1038 case 's':
1039 case 'P':
1040 case 'o':
1041 case 'E':
1042 case 'i':
1043 case 'k':
1044 case 'u':
1045 case 'g':
1046 case 't':
1047 panic("Option -%c requires an argument!\n",
1048 optopt);
1049 default:
1050 if (isprint(optopt))
1051 printf("Unknown option character `0x%X\'!\n", optopt);
1052 die();
1054 default:
1055 break;
1059 if (argc < 5)
1060 help();
1061 if (ctx.device == NULL)
1062 panic("No networking device given!\n");
1063 if (confname == NULL)
1064 panic("No configuration file given!\n");
1065 if (device_mtu(ctx.device) == 0)
1066 panic("This is no networking device!\n");
1068 register_signal(SIGINT, signal_handler);
1069 register_signal(SIGQUIT, signal_handler);
1070 register_signal(SIGTERM, signal_handler);
1071 register_signal(SIGHUP, signal_handler);
1073 if (prio_high) {
1074 set_proc_prio(-20);
1075 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1078 if (set_sock_mem)
1079 set_system_socket_memory(vals, array_size(vals));
1080 xlockme();
1082 if (ctx.rfraw) {
1083 ctx.device_trans = xstrdup(ctx.device);
1084 xfree(ctx.device);
1086 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1087 panic_handler_add(on_panic_del_rfmon, ctx.device);
1088 sleep(0);
1092 * If number of packets is smaller than number of CPUs use only as
1093 * many CPUs as there are packets. Otherwise we end up sending more
1094 * packets than intended or none at all.
1096 if (ctx.num)
1097 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1099 irq = device_irq_number(ctx.device);
1100 if (set_irq_aff)
1101 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1103 stats = setup_shared_var(ctx.cpus);
1105 for (i = 0; i < ctx.cpus; i++) {
1106 pid_t pid = fork();
1108 switch (pid) {
1109 case 0:
1110 if (reseed)
1111 seed = generate_srand_seed();
1112 srand(seed);
1114 cpu_affinity(i);
1115 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1117 goto thread_out;
1118 case -1:
1119 panic("Cannot fork processes!\n");
1123 for (i = 0; i < ctx.cpus; i++) {
1124 int status;
1126 wait(&status);
1127 if (WEXITSTATUS(status) == EXIT_FAILURE)
1128 die();
1131 if (ctx.rfraw)
1132 leave_rfmon_mac80211(ctx.device);
1134 if (set_sock_mem)
1135 reset_system_socket_memory(vals, array_size(vals));
1137 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1138 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1139 sched_yield();
1141 tx_packets += stats[i].tx_packets;
1142 tx_bytes += stats[i].tx_bytes;
1145 fflush(stdout);
1146 printf("\n");
1147 printf("\r%12llu packets outgoing\n", tx_packets);
1148 printf("\r%12llu bytes outgoing\n", tx_bytes);
1149 for (i = 0; cpustats && i < ctx.cpus; i++) {
1150 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1151 stats[i].tv_sec, stats[i].tv_usec, i,
1152 stats[i].tx_packets);
1155 thread_out:
1156 xunlockme();
1157 destroy_shared_var(stats, ctx.cpus);
1158 if (set_irq_aff)
1159 device_restore_irq_affinity_list();
1161 free(ctx.device);
1162 free(ctx.device_trans);
1163 free(ctx.rhost);
1164 free(confname);
1166 return 0;