docs: install: Fix a minor typo
[netsniff-ng.git] / trafgen.c
blob5e343e5ef68e6dba11f4ee5a7ea79e71d50bff5f
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 itimerval itimer;
115 static unsigned long interval = TX_KERNEL_PULL_INT;
116 static struct cpu_stats *stats;
117 static unsigned int seed;
119 #define CPU_STATS_STATE_CFG 1
120 #define CPU_STATS_STATE_CHK 2
121 #define CPU_STATS_STATE_RES 4
123 #ifndef ICMP_FILTER
124 # define ICMP_FILTER 1
126 struct icmp_filter {
127 __u32 data;
129 #endif
131 static void signal_handler(int number)
133 switch (number) {
134 case SIGINT:
135 case SIGQUIT:
136 case SIGTERM:
137 sigint = 1;
138 case SIGHUP:
139 default:
140 break;
144 static void timer_elapsed(int unused __maybe_unused)
146 int ret = pull_and_flush_tx_ring(sock);
147 if (unlikely(ret < 0)) {
148 /* We could hit EBADF if the socket has been closed before
149 * the timer was triggered.
151 if (errno != EBADF && errno != ENOBUFS)
152 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
155 set_itimer_interval_value(&itimer, 0, interval);
156 setitimer(ITIMER_REAL, &itimer, NULL);
159 static void timer_purge(void)
161 int ret;
163 ret = pull_and_flush_tx_ring_wait(sock);
164 if (unlikely(ret < 0)) {
165 /* We could hit EBADF if the socket has been closed before
166 * the timer was triggered.
168 if (errno != EBADF && errno != ENOBUFS)
169 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
172 set_itimer_interval_value(&itimer, 0, 0);
173 setitimer(ITIMER_REAL, &itimer, NULL);
176 static void __noreturn help(void)
178 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
179 puts("http://www.netsniff-ng.org\n\n"
180 "Usage: trafgen [options]\n"
181 "Options:\n"
182 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
183 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
184 " -p|--cpp Run packet config through C preprocessor\n"
185 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
186 " -R|--rfraw Inject raw 802.11 frames\n"
187 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
188 " -n|--num <uint> Number of packets until exit (def: 0)\n"
189 " -r|--rand Randomize packet selection (def: round robin)\n"
190 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
191 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
192 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
193 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
194 " -E|--seed <uint> Manually set srand(3) seed\n"
195 " -u|--user <userid> Drop privileges and change to userid\n"
196 " -g|--group <groupid> Drop privileges and change to groupid\n"
197 " -H|--prio-high Make this high priority process\n"
198 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
199 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
200 " -V|--verbose Be more verbose\n"
201 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
202 " -v|--version Show version and exit\n"
203 " -e|--example Show built-in packet config example\n"
204 " -h|--help Guess what?!\n\n"
205 "Examples:\n"
206 " See trafgen.txf for configuration file examples.\n"
207 " trafgen --dev eth0 --conf trafgen.cfg\n"
208 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
209 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
210 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
211 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
212 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
213 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
214 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
215 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
216 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
217 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
218 "Note:\n"
219 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
220 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
221 " we assume the kernel crashed, thus we print the packet and quit.\n"
222 " In case you find a ping-of-death, please mention trafgen in your\n"
223 " commit message of the fix!\n\n"
224 " For introducing bit errors, delays with random variation and more,\n"
225 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
226 " For generating different package distributions, you can use scripting\n"
227 " to generate a trafgen config file with packet ratios as:\n\n"
228 " IMIX 64:7, 570:4, 1518:1\n"
229 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
230 " Cisco 64:7, 594:4, 1518:1\n"
231 " RPR Trimodal 64:60, 512:20, 1518:20\n"
232 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
233 "Please report bugs to <bugs@netsniff-ng.org>\n"
234 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
235 "Swiss federal institute of technology (ETH Zurich)\n"
236 "License: GNU GPL version 2.0\n"
237 "This is free software: you are free to change and redistribute it.\n"
238 "There is NO WARRANTY, to the extent permitted by law.\n");
239 die();
242 static void __noreturn example(void)
244 const char *e =
245 "/* Note: dynamic elements make trafgen slower! */\n"
246 "#include <stddef.h>\n\n"
247 "{\n"
248 " /* MAC Destination */\n"
249 " fill(0xff, ETH_ALEN),\n"
250 " /* MAC Source */\n"
251 " 0x00, 0x02, 0xb3, drnd(3),\n"
252 " /* IPv4 Protocol */\n"
253 " c16(ETH_P_IP),\n"
254 " /* IPv4 Version, IHL, TOS */\n"
255 " 0b01000101, 0,\n"
256 " /* IPv4 Total Len */\n"
257 " c16(59),\n"
258 " /* IPv4 Ident */\n"
259 " drnd(2),\n"
260 " /* IPv4 Flags, Frag Off */\n"
261 " 0b01000000, 0,\n"
262 " /* IPv4 TTL */\n"
263 " 64,\n"
264 " /* Proto TCP */\n"
265 " 0x06,\n"
266 " /* IPv4 Checksum (IP header from, to) */\n"
267 " csumip(14, 33),\n"
268 " /* Source IP */\n"
269 " drnd(4),\n"
270 " /* Dest IP */\n"
271 " drnd(4),\n"
272 " /* TCP Source Port */\n"
273 " drnd(2),\n"
274 " /* TCP Dest Port */\n"
275 " c16(80),\n"
276 " /* TCP Sequence Number */\n"
277 " drnd(4),\n"
278 " /* TCP Ackn. Number */\n"
279 " c32(0),\n"
280 " /* TCP Header length + TCP SYN/ECN Flag */\n"
281 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
282 " /* Window Size */\n"
283 " c16(16),\n"
284 " /* TCP Checksum (offset IP, offset TCP) */\n"
285 " csumtcp(14, 34),\n"
286 " /* TCP Options */\n"
287 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
288 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
289 " /* Data blob */\n"
290 " \"gotcha!\",\n"
291 "}";
292 puts(e);
293 die();
296 static void __noreturn version(void)
298 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
299 puts("multithreaded zero-copy network packet generator\n"
300 "http://www.netsniff-ng.org\n\n"
301 "Please report bugs to <bugs@netsniff-ng.org>\n"
302 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
303 "Swiss federal institute of technology (ETH Zurich)\n"
304 "License: GNU GPL version 2.0\n"
305 "This is free software: you are free to change and redistribute it.\n"
306 "There is NO WARRANTY, to the extent permitted by law.\n");
307 die();
310 static void apply_counter(int id)
312 size_t j, counter_max = packet_dyn[id].clen;
314 for (j = 0; j < counter_max; ++j) {
315 uint8_t val;
316 struct counter *counter = &packet_dyn[id].cnt[j];
318 val = counter->val - counter->min;
320 switch (counter->type) {
321 case TYPE_INC:
322 val = (val + counter->inc) % (counter->max - counter->min + 1);
323 break;
324 case TYPE_DEC:
325 val = (val - counter->inc) % (counter->min - counter->max + 1);
326 break;
327 default:
328 bug();
331 counter->val = val + counter->min;
332 packets[id].payload[counter->off] = val;
336 static void apply_randomizer(int id)
338 size_t j, rand_max = packet_dyn[id].rlen;
340 for (j = 0; j < rand_max; ++j) {
341 uint8_t val = (uint8_t) rand();
342 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
344 packets[id].payload[randomizer->off] = val;
348 static void apply_csum16(int id)
350 size_t j, csum_max = packet_dyn[id].slen;
352 for (j = 0; j < csum_max; ++j) {
353 uint16_t sum = 0;
354 struct csum16 *csum = &packet_dyn[id].csum[j];
356 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
357 if (unlikely((size_t) csum->to >= packets[id].len))
358 csum->to = packets[id].len - 1;
360 switch (csum->which) {
361 case CSUM_IP:
362 sum = calc_csum(packets[id].payload + csum->from,
363 csum->to - csum->from + 1, 0);
364 break;
365 case CSUM_UDP:
366 sum = p4_csum((void *) packets[id].payload + csum->from,
367 packets[id].payload + csum->to,
368 (packets[id].len - csum->to),
369 IPPROTO_UDP);
370 break;
371 case CSUM_TCP:
372 sum = p4_csum((void *) packets[id].payload + csum->from,
373 packets[id].payload + csum->to,
374 (packets[id].len - csum->to),
375 IPPROTO_TCP);
376 break;
377 default:
378 bug();
379 break;
382 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
386 static struct cpu_stats *setup_shared_var(unsigned long cpus)
388 int fd;
389 size_t len = cpus * sizeof(struct cpu_stats);
390 char zbuff[len], file[256];
391 struct cpu_stats *buff;
393 fmemset(zbuff, 0, len);
394 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
396 fd = creat(file, S_IRUSR | S_IWUSR);
397 bug_on(fd < 0);
398 close(fd);
400 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
401 S_IRUSR | S_IWUSR);
402 write_or_die(fd, zbuff, len);
404 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
405 MAP_SHARED, fd, 0);
406 if (buff == MAP_FAILED)
407 panic("Cannot setup shared variable!\n");
409 close(fd);
410 unlink(file);
412 memset(buff, 0, len);
413 return buff;
416 static void destroy_shared_var(void *buff, unsigned long cpus)
418 munmap(buff, cpus * sizeof(struct cpu_stats));
421 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
423 size_t i;
425 printf("{");
426 for (i = 0; i < len; ++i) {
427 if (i % 15 == 0)
428 printf("\n ");
429 printf("0x%02x, ", payload[i]);
431 printf("\n}\n");
432 fflush(stdout);
435 static int xmit_smoke_setup(struct ctx *ctx)
437 int icmp_sock, ret, ttl = 64;
438 struct icmp_filter filter;
440 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
441 if (icmp_sock < 0)
442 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
444 filter.data = ~(1 << ICMP_ECHOREPLY);
446 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
447 if (ret < 0)
448 panic("Cannot install filter!\n");
450 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
451 if (ret < 0)
452 panic("Cannot set TTL!\n");
454 memset(&ctx->dest, 0, sizeof(ctx->dest));
455 ctx->dest.sin_family = AF_INET;
456 ctx->dest.sin_port = 0;
458 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
459 if (ret < 0)
460 panic("Cannot resolv address!\n");
462 return icmp_sock;
465 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
467 int ret;
468 unsigned int i, j = 0, probes = 100;
469 short ident, cnt = 1, idstore[probes];
470 uint8_t outpack[512], *data;
471 struct icmphdr *icmp;
472 struct iphdr *ip;
473 size_t len = sizeof(*icmp) + 56;
474 struct sockaddr_in from;
475 socklen_t from_len;
476 struct pollfd fds = {
477 .fd = icmp_sock,
478 .events = POLLIN,
481 fmemset(idstore, 0, sizeof(idstore));
482 while (probes-- > 0) {
483 while ((ident = htons((short) rand())) == 0)
484 sleep(0);
485 idstore[j++] = ident;
487 memset(outpack, 0, sizeof(outpack));
488 icmp = (void *) outpack;
489 icmp->type = ICMP_ECHO;
490 icmp->un.echo.id = ident;
491 icmp->un.echo.sequence = htons(cnt++);
493 data = ((uint8_t *) outpack + sizeof(*icmp));
494 for (i = 0; i < 56; ++i)
495 data[i] = (uint8_t) rand();
497 icmp->checksum = csum((unsigned short *) outpack,
498 len / sizeof(unsigned short));
500 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
501 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
502 if (unlikely(ret != (int) len))
503 panic("Cannot send out probe: %s!\n", strerror(errno));
505 ret = poll(&fds, 1, 50);
506 if (ret < 0)
507 panic("Poll failed!\n");
509 if (fds.revents & POLLIN) {
510 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
511 (struct sockaddr *) &from, &from_len);
512 if (unlikely(ret <= 0))
513 panic("Probe receive failed!\n");
514 if (unlikely(from_len != sizeof(ctx->dest)))
515 continue;
516 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
517 continue;
518 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
519 continue;
520 ip = (void *) outpack;
521 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
522 continue;
523 icmp = (void *) outpack + ip->ihl * 4;
524 for (i = 0; i < array_size(idstore); ++i) {
525 if (unlikely(icmp->un.echo.id != idstore[i]))
526 continue;
527 return 0;
532 return -1;
535 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
537 int ret, icmp_sock = -1;
538 unsigned long num = 1, i = 0;
539 struct timeval start, end, diff;
540 unsigned long long tx_bytes = 0, tx_packets = 0;
541 struct packet_dyn *pktd;
542 struct sockaddr_ll saddr = {
543 .sll_family = PF_PACKET,
544 .sll_halen = ETH_ALEN,
545 .sll_ifindex = device_ifindex(ctx->device),
548 if (ctx->num > 0)
549 num = ctx->num;
550 if (ctx->num == 0 && orig_num > 0)
551 num = 0;
553 if (ctx->smoke_test)
554 icmp_sock = xmit_smoke_setup(ctx);
556 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
558 bug_on(gettimeofday(&start, NULL));
560 while (likely(sigint == 0 && num > 0 && plen > 0)) {
561 pktd = &packet_dyn[i];
562 if (pktd->clen + pktd->rlen + pktd->slen) {
563 apply_counter(i);
564 apply_randomizer(i);
565 apply_csum16(i);
567 retry:
568 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
569 (struct sockaddr *) &saddr, sizeof(saddr));
570 if (unlikely(ret < 0)) {
571 if (errno == ENOBUFS) {
572 sched_yield();
573 goto retry;
575 if (ctx->smoke_test)
576 panic("Sendto error: %s!\n", strerror(errno));
579 tx_bytes += packets[i].len;
580 tx_packets++;
582 if (ctx->smoke_test) {
583 ret = xmit_smoke_probe(icmp_sock, ctx);
584 if (unlikely(ret < 0)) {
585 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
586 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
587 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
588 i, seed);
590 dump_trafgen_snippet(packets[i].payload, packets[i].len);
591 break;
595 if (!ctx->rand) {
596 i++;
597 if (i >= plen)
598 i = 0;
599 } else
600 i = rand() % plen;
602 if (ctx->num > 0)
603 num--;
605 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
606 nanosleep(&ctx->gap, NULL);
609 bug_on(gettimeofday(&end, NULL));
610 timersub(&end, &start, &diff);
612 if (ctx->smoke_test)
613 close(icmp_sock);
615 stats[cpu].tx_packets = tx_packets;
616 stats[cpu].tx_bytes = tx_bytes;
617 stats[cpu].tv_sec = diff.tv_sec;
618 stats[cpu].tv_usec = diff.tv_usec;
620 stats[cpu].state |= CPU_STATS_STATE_RES;
623 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
625 int ifindex = device_ifindex(ctx->device);
626 uint8_t *out = NULL;
627 unsigned int it = 0;
628 unsigned long num = 1, i = 0, size;
629 struct ring tx_ring;
630 struct frame_map *hdr;
631 struct timeval start, end, diff;
632 struct packet_dyn *pktd;
633 unsigned long long tx_bytes = 0, tx_packets = 0;
635 fmemset(&tx_ring, 0, sizeof(tx_ring));
637 size = ring_size(ctx->device, ctx->reserve_size);
639 set_sock_prio(sock, 512);
640 set_packet_loss_discard(sock);
642 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
643 create_tx_ring(sock, &tx_ring, ctx->verbose);
644 mmap_tx_ring(sock, &tx_ring);
645 alloc_tx_ring_frames(sock, &tx_ring);
646 bind_tx_ring(sock, &tx_ring, ifindex);
648 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
650 if (ctx->kpull)
651 interval = ctx->kpull;
652 if (ctx->num > 0)
653 num = ctx->num;
654 if (ctx->num == 0 && orig_num > 0)
655 num = 0;
657 set_itimer_interval_value(&itimer, 0, interval);
658 setitimer(ITIMER_REAL, &itimer, NULL);
660 bug_on(gettimeofday(&start, NULL));
662 while (likely(sigint == 0 && num > 0 && plen > 0)) {
663 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
664 sched_yield();
665 continue;
668 hdr = tx_ring.frames[it].iov_base;
669 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
671 hdr->tp_h.tp_snaplen = packets[i].len;
672 hdr->tp_h.tp_len = packets[i].len;
674 pktd = &packet_dyn[i];
675 if (pktd->clen + pktd->rlen + pktd->slen) {
676 apply_counter(i);
677 apply_randomizer(i);
678 apply_csum16(i);
681 fmemcpy(out, packets[i].payload, packets[i].len);
683 tx_bytes += packets[i].len;
684 tx_packets++;
686 if (!ctx->rand) {
687 i++;
688 if (i >= plen)
689 i = 0;
690 } else
691 i = rand() % plen;
693 kernel_may_pull_from_tx(&hdr->tp_h);
695 it++;
696 if (it >= tx_ring.layout.tp_frame_nr)
697 it = 0;
699 if (ctx->num > 0)
700 num--;
703 bug_on(gettimeofday(&end, NULL));
704 timersub(&end, &start, &diff);
706 timer_purge();
708 destroy_tx_ring(sock, &tx_ring);
710 stats[cpu].tx_packets = tx_packets;
711 stats[cpu].tx_bytes = tx_bytes;
712 stats[cpu].tv_sec = diff.tv_sec;
713 stats[cpu].tv_usec = diff.tv_usec;
715 stats[cpu].state |= CPU_STATS_STATE_RES;
718 static inline void __set_state(int cpu, sig_atomic_t s)
720 stats[cpu].state = s;
723 static inline sig_atomic_t __get_state(int cpu)
725 return stats[cpu].state;
728 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
730 unsigned int i;
731 unsigned long total;
733 for (i = 0, total = plen; i < ctx->cpus; i++) {
734 if (i == cpu)
735 continue;
737 while ((__get_state(i) &
738 (CPU_STATS_STATE_CFG |
739 CPU_STATS_STATE_RES)) == 0 &&
740 sigint == 0)
741 sched_yield();
743 total += stats[i].cf_packets;
746 return total;
749 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
751 unsigned int i;
752 unsigned long total;
753 int cpu_sel;
754 long long delta_correction = 0;
756 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
757 if (i == cpu)
758 continue;
760 while ((__get_state(i) &
761 (CPU_STATS_STATE_CHK |
762 CPU_STATS_STATE_RES)) == 0 &&
763 sigint == 0)
764 sched_yield();
766 total += stats[i].cd_packets;
769 if (total > orig)
770 delta_correction = -1 * ((long long) total - orig);
771 if (total < orig)
772 delta_correction = +1 * ((long long) orig - total);
774 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
775 if (stats[i].cd_packets > 0) {
776 if ((long long) stats[i].cd_packets +
777 delta_correction >= 0) {
778 cpu_sel = i;
779 break;
784 if ((int) cpu == cpu_sel)
785 ctx->num += delta_correction;
788 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
789 sig_atomic_t s)
791 stats[cpu].cf_packets = p;
792 stats[cpu].cf_bytes = b;
793 stats[cpu].state = s;
796 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
798 stats[cpu].cd_packets = p;
799 stats[cpu].state = s;
802 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
804 unsigned int i;
805 unsigned long plen_total, orig = ctx->num;
806 size_t mtu, total_len = 0;
808 bug_on(plen != dlen);
810 for (i = 0; i < plen; ++i)
811 total_len += packets[i].len;
813 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
814 plen_total = __wait_and_sum_others(ctx, cpu);
816 if (orig > 0) {
817 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
819 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
820 CPU_STATS_STATE_CFG);
821 __correct_global_delta(ctx, cpu, orig);
824 if (plen == 0) {
825 __set_state(cpu, CPU_STATS_STATE_RES);
826 return 0;
829 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
830 if (packets[i].len > mtu + 14)
831 panic("Device MTU < than packet%d's size!\n", i);
832 if (packets[i].len <= 14)
833 panic("Packet%d's size too short!\n", i);
836 return 0;
839 static void main_loop(struct ctx *ctx, char *confname, bool slow,
840 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
842 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
843 if (xmit_packet_precheck(ctx, cpu) < 0)
844 return;
846 if (cpu == 0) {
847 unsigned int i;
848 size_t total_len = 0, total_pkts = 0;
850 for (i = 0; i < ctx->cpus; ++i) {
851 total_len += stats[i].cf_bytes;
852 total_pkts += stats[i].cf_packets;
855 printf("%6zu packets to schedule\n", total_pkts);
856 printf("%6zu bytes in total\n", total_len);
857 printf("Running! Hang up with ^C!\n\n");
858 fflush(stdout);
861 sock = pf_tx_socket();
863 if (ctx->qdisc_path == false)
864 set_sock_qdisc_bypass(sock, ctx->verbose);
866 if (slow)
867 xmit_slowpath_or_die(ctx, cpu, orig_num);
868 else
869 xmit_fastpath_or_die(ctx, cpu, orig_num);
871 close(sock);
873 cleanup_packets();
876 static unsigned int generate_srand_seed(void)
878 int fd;
879 unsigned int _seed;
881 fd = open("/dev/urandom", O_RDONLY);
882 if (fd < 0)
883 return time(NULL);
885 read_or_die(fd, &_seed, sizeof(_seed));
887 close(fd);
888 return _seed;
891 int main(int argc, char **argv)
893 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
894 bool prio_high = false, set_irq_aff = true;
895 int c, opt_index, vals[4] = {0}, irq;
896 uint64_t gap = 0;
897 unsigned int i, j;
898 char *confname = NULL, *ptr;
899 unsigned long cpus_tmp, orig_num = 0;
900 unsigned long long tx_packets, tx_bytes;
901 struct ctx ctx;
903 fmemset(&ctx, 0, sizeof(ctx));
904 ctx.cpus = get_number_cpus_online();
905 ctx.uid = getuid();
906 ctx.gid = getgid();
907 ctx.qdisc_path = false;
909 while ((c = getopt_long(argc, argv, short_options, long_options,
910 &opt_index)) != EOF) {
911 switch (c) {
912 case 'h':
913 help();
914 break;
915 case 'v':
916 version();
917 break;
918 case 'C':
919 cpustats = false;
920 break;
921 case 'e':
922 example();
923 break;
924 case 'p':
925 invoke_cpp = true;
926 break;
927 case 'V':
928 ctx.verbose = true;
929 break;
930 case 'P':
931 cpus_tmp = strtoul(optarg, NULL, 0);
932 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
933 ctx.cpus = cpus_tmp;
934 break;
935 case 'd':
936 case 'o':
937 ctx.device = xstrndup(optarg, IFNAMSIZ);
938 break;
939 case 'H':
940 prio_high = true;
941 break;
942 case 'Q':
943 set_irq_aff = false;
944 break;
945 case 'q':
946 ctx.qdisc_path = true;
947 break;
948 case 'r':
949 ctx.rand = true;
950 break;
951 case 's':
952 slow = true;
953 ctx.cpus = 1;
954 ctx.smoke_test = true;
955 ctx.rhost = xstrdup(optarg);
956 break;
957 case 'R':
958 ctx.rfraw = true;
959 break;
960 case 'J':
961 ctx.jumbo_support = true;
962 break;
963 case 'c':
964 case 'i':
965 confname = xstrdup(optarg);
966 if (!strncmp("-", confname, strlen("-")))
967 ctx.cpus = 1;
968 break;
969 case 'u':
970 ctx.uid = strtoul(optarg, NULL, 0);
971 ctx.enforce = true;
972 break;
973 case 'g':
974 ctx.gid = strtoul(optarg, NULL, 0);
975 ctx.enforce = true;
976 break;
977 case 'k':
978 ctx.kpull = strtoul(optarg, NULL, 0);
979 break;
980 case 'E':
981 seed = strtoul(optarg, NULL, 0);
982 reseed = false;
983 break;
984 case 'n':
985 orig_num = strtoul(optarg, NULL, 0);
986 ctx.num = orig_num;
987 break;
988 case 't':
989 slow = true;
990 ptr = optarg;
991 gap = strtoul(optarg, NULL, 0);
993 for (j = i = strlen(optarg); i > 0; --i) {
994 if (!isdigit(optarg[j - i]))
995 break;
996 ptr++;
999 if (!strncmp(ptr, "ns", strlen("ns"))) {
1000 ctx.gap.tv_sec = gap / 1000000000;
1001 ctx.gap.tv_nsec = gap % 1000000000;
1002 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1003 /* Default to microseconds for backwards
1004 * compatibility if no postfix is given.
1006 ctx.gap.tv_sec = gap / 1000000;
1007 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
1008 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1009 ctx.gap.tv_sec = gap / 1000;
1010 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1011 } else if (!strncmp(ptr, "s", strlen("s"))) {
1012 ctx.gap.tv_sec = gap;
1013 ctx.gap.tv_nsec = 0;
1014 } else
1015 panic("Syntax error in time param!\n");
1017 if (gap > 0)
1018 /* Fall back to single core to not mess up
1019 * correct timing. We are slow anyway!
1021 ctx.cpus = 1;
1022 break;
1023 case 'S':
1024 ptr = optarg;
1025 ctx.reserve_size = 0;
1027 for (j = i = strlen(optarg); i > 0; --i) {
1028 if (!isdigit(optarg[j - i]))
1029 break;
1030 ptr++;
1033 if (!strncmp(ptr, "KiB", strlen("KiB")))
1034 ctx.reserve_size = 1 << 10;
1035 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1036 ctx.reserve_size = 1 << 20;
1037 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1038 ctx.reserve_size = 1 << 30;
1039 else
1040 panic("Syntax error in ring size param!\n");
1042 ctx.reserve_size *= strtol(optarg, NULL, 0);
1043 break;
1044 case '?':
1045 switch (optopt) {
1046 case 'd':
1047 case 'c':
1048 case 'n':
1049 case 'S':
1050 case 's':
1051 case 'P':
1052 case 'o':
1053 case 'E':
1054 case 'i':
1055 case 'k':
1056 case 'u':
1057 case 'g':
1058 case 't':
1059 panic("Option -%c requires an argument!\n",
1060 optopt);
1061 default:
1062 if (isprint(optopt))
1063 printf("Unknown option character `0x%X\'!\n", optopt);
1064 die();
1066 default:
1067 break;
1071 if (argc < 5)
1072 help();
1073 if (ctx.device == NULL)
1074 panic("No networking device given!\n");
1075 if (confname == NULL)
1076 panic("No configuration file given!\n");
1077 if (device_mtu(ctx.device) == 0)
1078 panic("This is no networking device!\n");
1080 register_signal(SIGINT, signal_handler);
1081 register_signal(SIGQUIT, signal_handler);
1082 register_signal(SIGTERM, signal_handler);
1083 register_signal(SIGHUP, signal_handler);
1084 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1086 if (prio_high) {
1087 set_proc_prio(-20);
1088 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1091 set_system_socket_memory(vals, array_size(vals));
1092 xlockme();
1094 if (ctx.rfraw) {
1095 ctx.device_trans = xstrdup(ctx.device);
1096 xfree(ctx.device);
1098 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1099 sleep(0);
1102 irq = device_irq_number(ctx.device);
1103 if (set_irq_aff)
1104 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1106 stats = setup_shared_var(ctx.cpus);
1108 for (i = 0; i < ctx.cpus; i++) {
1109 pid_t pid = fork();
1111 switch (pid) {
1112 case 0:
1113 if (reseed)
1114 seed = generate_srand_seed();
1115 srand(seed);
1117 cpu_affinity(i);
1118 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1120 goto thread_out;
1121 case -1:
1122 panic("Cannot fork processes!\n");
1126 for (i = 0; i < ctx.cpus; i++) {
1127 int status;
1129 wait(&status);
1130 if (WEXITSTATUS(status) == EXIT_FAILURE)
1131 die();
1134 if (ctx.rfraw)
1135 leave_rfmon_mac80211(ctx.device);
1137 reset_system_socket_memory(vals, array_size(vals));
1139 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1140 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1141 sched_yield();
1143 tx_packets += stats[i].tx_packets;
1144 tx_bytes += stats[i].tx_bytes;
1147 fflush(stdout);
1148 printf("\n");
1149 printf("\r%12llu packets outgoing\n", tx_packets);
1150 printf("\r%12llu bytes outgoing\n", tx_bytes);
1151 for (i = 0; cpustats && i < ctx.cpus; i++) {
1152 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1153 stats[i].tv_sec, stats[i].tv_usec, i,
1154 stats[i].tx_packets);
1157 thread_out:
1158 xunlockme();
1159 destroy_shared_var(stats, ctx.cpus);
1160 if (set_irq_aff)
1161 device_restore_irq_affinity_list();
1163 free(ctx.device);
1164 free(ctx.device_trans);
1165 free(ctx.rhost);
1166 free(confname);
1168 return 0;