build: fixed PREFIX usage
[netsniff-ng.git] / trafgen.c
blobaf15ef28c794d071bd48748d731dfc75f83b2b64
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 unsigned long kpull, num, reserve_size;
60 unsigned int cpus;
61 uid_t uid; gid_t gid;
62 char *device, *device_trans, *rhost;
63 struct timespec gap;
64 struct sockaddr_in dest;
67 struct cpu_stats {
68 unsigned long tv_sec, tv_usec;
69 unsigned long long tx_packets, tx_bytes;
70 unsigned long long cf_packets, cf_bytes;
71 unsigned long long cd_packets;
72 sig_atomic_t state;
75 static sig_atomic_t sigint = 0;
77 struct packet *packets = NULL;
78 size_t plen = 0;
80 struct packet_dyn *packet_dyn = NULL;
81 size_t dlen = 0;
83 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
84 static const struct option long_options[] = {
85 {"dev", required_argument, NULL, 'd'},
86 {"out", required_argument, NULL, 'o'},
87 {"in", required_argument, NULL, 'i'},
88 {"conf", required_argument, NULL, 'c'},
89 {"num", required_argument, NULL, 'n'},
90 {"gap", required_argument, NULL, 't'},
91 {"cpus", required_argument, NULL, 'P'},
92 {"ring-size", required_argument, NULL, 'S'},
93 {"kernel-pull", required_argument, NULL, 'k'},
94 {"smoke-test", required_argument, NULL, 's'},
95 {"seed", required_argument, NULL, 'E'},
96 {"user", required_argument, NULL, 'u'},
97 {"group", required_argument, NULL, 'g'},
98 {"prio-high", no_argument, NULL, 'H'},
99 {"notouch-irq", no_argument, NULL, 'Q'},
100 {"qdisc-path", no_argument, NULL, 'q'},
101 {"jumbo-support", no_argument, NULL, 'J'},
102 {"no-cpu-stats", no_argument, NULL, 'C'},
103 {"cpp", no_argument, NULL, 'p'},
104 {"rfraw", no_argument, NULL, 'R'},
105 {"rand", no_argument, NULL, 'r'},
106 {"verbose", no_argument, NULL, 'V'},
107 {"version", no_argument, NULL, 'v'},
108 {"example", no_argument, NULL, 'e'},
109 {"help", no_argument, NULL, 'h'},
110 {NULL, 0, NULL, 0}
113 static int sock;
114 static struct cpu_stats *stats;
115 static unsigned int seed;
117 #define CPU_STATS_STATE_CFG 1
118 #define CPU_STATS_STATE_CHK 2
119 #define CPU_STATS_STATE_RES 4
121 #ifndef ICMP_FILTER
122 # define ICMP_FILTER 1
124 struct icmp_filter {
125 __u32 data;
127 #endif
129 static void signal_handler(int number)
131 switch (number) {
132 case SIGINT:
133 case SIGQUIT:
134 case SIGTERM:
135 sigint = 1;
136 case SIGHUP:
137 default:
138 break;
142 static void __noreturn help(void)
144 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
145 puts("http://www.netsniff-ng.org\n\n"
146 "Usage: trafgen [options]\n"
147 "Options:\n"
148 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
149 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
150 " -p|--cpp Run packet config through C preprocessor\n"
151 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
152 " -R|--rfraw Inject raw 802.11 frames\n"
153 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
154 " -n|--num <uint> Number of packets until exit (def: 0)\n"
155 " -r|--rand Randomize packet selection (def: round robin)\n"
156 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
157 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
158 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
159 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\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, size;
595 struct ring tx_ring;
596 struct frame_map *hdr;
597 struct timeval start, end, diff;
598 struct packet_dyn *pktd;
599 unsigned long long tx_bytes = 0, tx_packets = 0;
601 fmemset(&tx_ring, 0, sizeof(tx_ring));
603 size = ring_size(ctx->device, ctx->reserve_size);
605 set_sock_prio(sock, 512);
606 set_packet_loss_discard(sock);
608 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
609 create_tx_ring(sock, &tx_ring, ctx->verbose);
610 mmap_tx_ring(sock, &tx_ring);
611 alloc_tx_ring_frames(sock, &tx_ring);
612 bind_tx_ring(sock, &tx_ring, ifindex);
614 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
616 if (ctx->num > 0)
617 num = ctx->num;
618 if (ctx->num == 0 && orig_num > 0)
619 num = 0;
621 bug_on(gettimeofday(&start, NULL));
623 while (likely(sigint == 0 && num > 0 && plen > 0)) {
624 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
625 int ret = pull_and_flush_tx_ring(sock);
626 if (unlikely(ret < 0)) {
627 /* We could hit EBADF if the socket has been closed before
628 * the timer was triggered.
630 if (errno != EBADF && errno != ENOBUFS)
631 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
634 continue;
637 hdr = tx_ring.frames[it].iov_base;
638 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
640 hdr->tp_h.tp_snaplen = packets[i].len;
641 hdr->tp_h.tp_len = packets[i].len;
643 pktd = &packet_dyn[i];
644 if (pktd->clen + pktd->rlen + pktd->slen) {
645 apply_counter(i);
646 apply_randomizer(i);
647 apply_csum16(i);
650 fmemcpy(out, packets[i].payload, packets[i].len);
652 tx_bytes += packets[i].len;
653 tx_packets++;
655 if (!ctx->rand) {
656 i++;
657 if (i >= plen)
658 i = 0;
659 } else
660 i = rand() % plen;
662 kernel_may_pull_from_tx(&hdr->tp_h);
664 it++;
665 if (it >= tx_ring.layout.tp_frame_nr)
666 it = 0;
668 if (ctx->num > 0)
669 num--;
672 bug_on(gettimeofday(&end, NULL));
673 timersub(&end, &start, &diff);
675 pull_and_flush_tx_ring_wait(sock);
676 destroy_tx_ring(sock, &tx_ring);
678 stats[cpu].tx_packets = tx_packets;
679 stats[cpu].tx_bytes = tx_bytes;
680 stats[cpu].tv_sec = diff.tv_sec;
681 stats[cpu].tv_usec = diff.tv_usec;
683 stats[cpu].state |= CPU_STATS_STATE_RES;
686 static inline void __set_state(int cpu, sig_atomic_t s)
688 stats[cpu].state = s;
691 static inline sig_atomic_t __get_state(int cpu)
693 return stats[cpu].state;
696 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
698 unsigned int i;
699 unsigned long total;
701 for (i = 0, total = plen; i < ctx->cpus; i++) {
702 if (i == cpu)
703 continue;
705 while ((__get_state(i) &
706 (CPU_STATS_STATE_CFG |
707 CPU_STATS_STATE_RES)) == 0 &&
708 sigint == 0)
709 sched_yield();
711 total += stats[i].cf_packets;
714 return total;
717 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
719 unsigned int i;
720 unsigned long total;
721 int cpu_sel;
722 long long delta_correction = 0;
724 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
725 if (i == cpu)
726 continue;
728 while ((__get_state(i) &
729 (CPU_STATS_STATE_CHK |
730 CPU_STATS_STATE_RES)) == 0 &&
731 sigint == 0)
732 sched_yield();
734 total += stats[i].cd_packets;
737 if (total > orig)
738 delta_correction = -1 * ((long long) total - orig);
739 if (total < orig)
740 delta_correction = +1 * ((long long) orig - total);
742 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
743 if (stats[i].cd_packets > 0) {
744 if ((long long) stats[i].cd_packets +
745 delta_correction >= 0) {
746 cpu_sel = i;
747 break;
752 if ((int) cpu == cpu_sel)
753 ctx->num += delta_correction;
756 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
757 sig_atomic_t s)
759 stats[cpu].cf_packets = p;
760 stats[cpu].cf_bytes = b;
761 stats[cpu].state = s;
764 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
766 stats[cpu].cd_packets = p;
767 stats[cpu].state = s;
770 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
772 unsigned int i;
773 unsigned long plen_total, orig = ctx->num;
774 size_t mtu, total_len = 0;
776 bug_on(plen != dlen);
778 for (i = 0; i < plen; ++i)
779 total_len += packets[i].len;
781 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
782 plen_total = __wait_and_sum_others(ctx, cpu);
784 if (orig > 0) {
785 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
787 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
788 CPU_STATS_STATE_CFG);
789 __correct_global_delta(ctx, cpu, orig);
792 if (plen == 0) {
793 __set_state(cpu, CPU_STATS_STATE_RES);
794 return 0;
797 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
798 if (packets[i].len > mtu + 14)
799 panic("Device MTU < than packet%d's size!\n", i);
800 if (packets[i].len <= 14)
801 panic("Packet%d's size too short!\n", i);
804 return 0;
807 static void main_loop(struct ctx *ctx, char *confname, bool slow,
808 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
810 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
811 if (xmit_packet_precheck(ctx, cpu) < 0)
812 return;
814 if (cpu == 0) {
815 unsigned int i;
816 size_t total_len = 0, total_pkts = 0;
818 for (i = 0; i < ctx->cpus; ++i) {
819 total_len += stats[i].cf_bytes;
820 total_pkts += stats[i].cf_packets;
823 printf("%6zu packets to schedule\n", total_pkts);
824 printf("%6zu bytes in total\n", total_len);
825 printf("Running! Hang up with ^C!\n\n");
826 fflush(stdout);
829 sock = pf_tx_socket();
831 if (ctx->qdisc_path == false)
832 set_sock_qdisc_bypass(sock, ctx->verbose);
834 if (slow)
835 xmit_slowpath_or_die(ctx, cpu, orig_num);
836 else
837 xmit_fastpath_or_die(ctx, cpu, orig_num);
839 close(sock);
841 cleanup_packets();
844 static unsigned int generate_srand_seed(void)
846 int fd;
847 unsigned int _seed;
849 fd = open("/dev/urandom", O_RDONLY);
850 if (fd < 0)
851 return time(NULL);
853 read_or_die(fd, &_seed, sizeof(_seed));
855 close(fd);
856 return _seed;
859 int main(int argc, char **argv)
861 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
862 bool prio_high = false, set_irq_aff = true;
863 int c, opt_index, vals[4] = {0}, irq;
864 uint64_t gap = 0;
865 unsigned int i, j;
866 char *confname = NULL, *ptr;
867 unsigned long cpus_tmp, orig_num = 0;
868 unsigned long long tx_packets, tx_bytes;
869 struct ctx ctx;
871 fmemset(&ctx, 0, sizeof(ctx));
872 ctx.cpus = get_number_cpus_online();
873 ctx.uid = getuid();
874 ctx.gid = getgid();
875 ctx.qdisc_path = false;
877 /* Keep an initial small default size to reduce cache-misses. */
878 ctx.reserve_size = 196 * (1 << 10);
880 while ((c = getopt_long(argc, argv, short_options, long_options,
881 &opt_index)) != EOF) {
882 switch (c) {
883 case 'h':
884 help();
885 break;
886 case 'v':
887 version();
888 break;
889 case 'C':
890 cpustats = false;
891 break;
892 case 'e':
893 example();
894 break;
895 case 'p':
896 invoke_cpp = true;
897 break;
898 case 'V':
899 ctx.verbose = true;
900 break;
901 case 'P':
902 cpus_tmp = strtoul(optarg, NULL, 0);
903 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
904 ctx.cpus = cpus_tmp;
905 break;
906 case 'd':
907 case 'o':
908 ctx.device = xstrndup(optarg, IFNAMSIZ);
909 break;
910 case 'H':
911 prio_high = true;
912 break;
913 case 'Q':
914 set_irq_aff = false;
915 break;
916 case 'q':
917 ctx.qdisc_path = true;
918 break;
919 case 'r':
920 ctx.rand = true;
921 break;
922 case 's':
923 slow = true;
924 ctx.cpus = 1;
925 ctx.smoke_test = true;
926 ctx.rhost = xstrdup(optarg);
927 break;
928 case 'R':
929 ctx.rfraw = true;
930 break;
931 case 'J':
932 ctx.jumbo_support = true;
933 break;
934 case 'c':
935 case 'i':
936 confname = xstrdup(optarg);
937 if (!strncmp("-", confname, strlen("-")))
938 ctx.cpus = 1;
939 break;
940 case 'u':
941 ctx.uid = strtoul(optarg, NULL, 0);
942 ctx.enforce = true;
943 break;
944 case 'g':
945 ctx.gid = strtoul(optarg, NULL, 0);
946 ctx.enforce = true;
947 break;
948 case 'k':
949 ctx.kpull = strtoul(optarg, NULL, 0);
950 break;
951 case 'E':
952 seed = strtoul(optarg, NULL, 0);
953 reseed = false;
954 break;
955 case 'n':
956 orig_num = strtoul(optarg, NULL, 0);
957 ctx.num = orig_num;
958 break;
959 case 't':
960 slow = true;
961 ptr = optarg;
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;
996 ctx.reserve_size = 0;
998 for (j = i = strlen(optarg); i > 0; --i) {
999 if (!isdigit(optarg[j - i]))
1000 break;
1001 ptr++;
1004 if (!strncmp(ptr, "KiB", strlen("KiB")))
1005 ctx.reserve_size = 1 << 10;
1006 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1007 ctx.reserve_size = 1 << 20;
1008 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1009 ctx.reserve_size = 1 << 30;
1010 else
1011 panic("Syntax error in ring size param!\n");
1013 ctx.reserve_size *= strtol(optarg, NULL, 0);
1014 break;
1015 case '?':
1016 switch (optopt) {
1017 case 'd':
1018 case 'c':
1019 case 'n':
1020 case 'S':
1021 case 's':
1022 case 'P':
1023 case 'o':
1024 case 'E':
1025 case 'i':
1026 case 'k':
1027 case 'u':
1028 case 'g':
1029 case 't':
1030 panic("Option -%c requires an argument!\n",
1031 optopt);
1032 default:
1033 if (isprint(optopt))
1034 printf("Unknown option character `0x%X\'!\n", optopt);
1035 die();
1037 default:
1038 break;
1042 if (argc < 5)
1043 help();
1044 if (ctx.device == NULL)
1045 panic("No networking device given!\n");
1046 if (confname == NULL)
1047 panic("No configuration file given!\n");
1048 if (device_mtu(ctx.device) == 0)
1049 panic("This is no networking device!\n");
1051 register_signal(SIGINT, signal_handler);
1052 register_signal(SIGQUIT, signal_handler);
1053 register_signal(SIGTERM, signal_handler);
1054 register_signal(SIGHUP, signal_handler);
1056 if (prio_high) {
1057 set_proc_prio(-20);
1058 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
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 reset_system_socket_memory(vals, array_size(vals));
1109 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1110 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1111 sched_yield();
1113 tx_packets += stats[i].tx_packets;
1114 tx_bytes += stats[i].tx_bytes;
1117 fflush(stdout);
1118 printf("\n");
1119 printf("\r%12llu packets outgoing\n", tx_packets);
1120 printf("\r%12llu bytes outgoing\n", tx_bytes);
1121 for (i = 0; cpustats && i < ctx.cpus; i++) {
1122 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1123 stats[i].tv_sec, stats[i].tv_usec, i,
1124 stats[i].tx_packets);
1127 thread_out:
1128 xunlockme();
1129 destroy_shared_var(stats, ctx.cpus);
1130 if (set_irq_aff)
1131 device_restore_irq_affinity_list();
1133 free(ctx.device);
1134 free(ctx.device_trans);
1135 free(ctx.rhost);
1136 free(confname);
1138 return 0;