build: travis: Pass on CC environment variable to make
[netsniff-ng.git] / trafgen.c
blob03a165e787c4c54d9db4f2b04befa018caa0382a
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 size_t reserve_size;
60 unsigned long num;
61 unsigned int cpus;
62 uid_t uid; gid_t gid;
63 char *device, *device_trans, *rhost;
64 struct timespec gap;
65 struct sockaddr_in dest;
68 struct cpu_stats {
69 unsigned long tv_sec, tv_usec;
70 unsigned long long tx_packets, tx_bytes;
71 unsigned long long cf_packets, cf_bytes;
72 unsigned long long cd_packets;
73 sig_atomic_t state;
76 static sig_atomic_t sigint = 0;
78 struct packet *packets = NULL;
79 size_t plen = 0;
81 struct packet_dyn *packet_dyn = NULL;
82 size_t dlen = 0;
84 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
85 static const struct option long_options[] = {
86 {"dev", required_argument, NULL, 'd'},
87 {"out", required_argument, NULL, 'o'},
88 {"in", required_argument, NULL, 'i'},
89 {"conf", required_argument, NULL, 'c'},
90 {"num", required_argument, NULL, 'n'},
91 {"gap", required_argument, NULL, 't'},
92 {"cpus", required_argument, NULL, 'P'},
93 {"ring-size", required_argument, NULL, 'S'},
94 {"kernel-pull", required_argument, NULL, 'k'},
95 {"smoke-test", required_argument, NULL, 's'},
96 {"seed", required_argument, NULL, 'E'},
97 {"user", required_argument, NULL, 'u'},
98 {"group", required_argument, NULL, 'g'},
99 {"prio-high", no_argument, NULL, 'H'},
100 {"notouch-irq", no_argument, NULL, 'Q'},
101 {"no-sock-mem", no_argument, NULL, 'A'},
102 {"qdisc-path", no_argument, NULL, 'q'},
103 {"jumbo-support", no_argument, NULL, 'J'},
104 {"no-cpu-stats", no_argument, NULL, 'C'},
105 {"cpp", no_argument, NULL, 'p'},
106 {"rfraw", no_argument, NULL, 'R'},
107 {"rand", no_argument, NULL, 'r'},
108 {"verbose", no_argument, NULL, 'V'},
109 {"version", no_argument, NULL, 'v'},
110 {"example", no_argument, NULL, 'e'},
111 {"help", no_argument, NULL, 'h'},
112 {NULL, 0, NULL, 0}
115 static int sock;
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 #define SMOKE_N_PROBES 100
133 static void signal_handler(int number)
135 switch (number) {
136 case SIGINT:
137 case SIGQUIT:
138 case SIGTERM:
139 sigint = 1;
140 case SIGHUP:
141 default:
142 break;
146 static void __noreturn help(void)
148 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
149 puts("http://www.netsniff-ng.org\n\n"
150 "Usage: trafgen [options]\n"
151 "Options:\n"
152 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
153 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
154 " -p|--cpp Run packet config through C preprocessor\n"
155 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
156 " -R|--rfraw Inject raw 802.11 frames\n"
157 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
158 " -n|--num <uint> Number of packets until exit (def: 0)\n"
159 " -r|--rand Randomize packet selection (def: round robin)\n"
160 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
161 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
162 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
163 " -E|--seed <uint> Manually set srand(3) seed\n"
164 " -u|--user <userid> Drop privileges and change to userid\n"
165 " -g|--group <groupid> Drop privileges and change to groupid\n"
166 " -H|--prio-high Make this high priority process\n"
167 " -A|--no-sock-mem Don't tune core socket memory\n"
168 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
169 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
170 " -V|--verbose Be more verbose\n"
171 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
172 " -v|--version Show version and exit\n"
173 " -e|--example Show built-in packet config example\n"
174 " -h|--help Guess what?!\n\n"
175 "Examples:\n"
176 " See trafgen.txf for configuration file examples.\n"
177 " trafgen --dev eth0 --conf trafgen.cfg\n"
178 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
179 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
180 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
181 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
182 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
183 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
184 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
185 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
186 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
187 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
188 "Note:\n"
189 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
190 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
191 " we assume the kernel crashed, thus we print the packet and quit.\n"
192 " In case you find a ping-of-death, please mention trafgen in your\n"
193 " commit message of the fix!\n\n"
194 " For introducing bit errors, delays with random variation and more,\n"
195 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
196 " For generating different package distributions, you can use scripting\n"
197 " to generate a trafgen config file with packet ratios as:\n\n"
198 " IMIX 64:7, 570:4, 1518:1\n"
199 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
200 " Cisco 64:7, 594:4, 1518:1\n"
201 " RPR Trimodal 64:60, 512:20, 1518:20\n"
202 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
203 "Please report bugs to <bugs@netsniff-ng.org>\n"
204 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
205 "Swiss federal institute of technology (ETH Zurich)\n"
206 "License: GNU GPL version 2.0\n"
207 "This is free software: you are free to change and redistribute it.\n"
208 "There is NO WARRANTY, to the extent permitted by law.\n");
209 die();
212 static void __noreturn example(void)
214 const char *e =
215 "/* Note: dynamic elements make trafgen slower! */\n"
216 "#include <stddef.h>\n\n"
217 "{\n"
218 " /* MAC Destination */\n"
219 " fill(0xff, ETH_ALEN),\n"
220 " /* MAC Source */\n"
221 " 0x00, 0x02, 0xb3, drnd(3),\n"
222 " /* IPv4 Protocol */\n"
223 " c16(ETH_P_IP),\n"
224 " /* IPv4 Version, IHL, TOS */\n"
225 " 0b01000101, 0,\n"
226 " /* IPv4 Total Len */\n"
227 " c16(59),\n"
228 " /* IPv4 Ident */\n"
229 " drnd(2),\n"
230 " /* IPv4 Flags, Frag Off */\n"
231 " 0b01000000, 0,\n"
232 " /* IPv4 TTL */\n"
233 " 64,\n"
234 " /* Proto TCP */\n"
235 " 0x06,\n"
236 " /* IPv4 Checksum (IP header from, to) */\n"
237 " csumip(14, 33),\n"
238 " /* Source IP */\n"
239 " drnd(4),\n"
240 " /* Dest IP */\n"
241 " drnd(4),\n"
242 " /* TCP Source Port */\n"
243 " drnd(2),\n"
244 " /* TCP Dest Port */\n"
245 " c16(80),\n"
246 " /* TCP Sequence Number */\n"
247 " drnd(4),\n"
248 " /* TCP Ackn. Number */\n"
249 " c32(0),\n"
250 " /* TCP Header length + TCP SYN/ECN Flag */\n"
251 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
252 " /* Window Size */\n"
253 " c16(16),\n"
254 " /* TCP Checksum (offset IP, offset TCP) */\n"
255 " csumtcp(14, 34),\n"
256 " /* TCP Options */\n"
257 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
258 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
259 " /* Data blob */\n"
260 " \"gotcha!\",\n"
261 "}";
262 puts(e);
263 die();
266 static void __noreturn version(void)
268 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
269 puts("multithreaded zero-copy network packet generator\n"
270 "http://www.netsniff-ng.org\n\n"
271 "Please report bugs to <bugs@netsniff-ng.org>\n"
272 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
273 "Swiss federal institute of technology (ETH Zurich)\n"
274 "License: GNU GPL version 2.0\n"
275 "This is free software: you are free to change and redistribute it.\n"
276 "There is NO WARRANTY, to the extent permitted by law.\n");
277 die();
280 static void apply_counter(int id)
282 size_t j, counter_max = packet_dyn[id].clen;
284 for (j = 0; j < counter_max; ++j) {
285 uint8_t val;
286 struct counter *counter = &packet_dyn[id].cnt[j];
288 val = counter->val - counter->min;
290 switch (counter->type) {
291 case TYPE_INC:
292 val = (val + counter->inc) % (counter->max - counter->min + 1);
293 break;
294 case TYPE_DEC:
295 val = (val - counter->inc) % (counter->min - counter->max + 1);
296 break;
297 default:
298 bug();
301 counter->val = val + counter->min;
302 packets[id].payload[counter->off] = val;
306 static void apply_randomizer(int id)
308 size_t j, rand_max = packet_dyn[id].rlen;
310 for (j = 0; j < rand_max; ++j) {
311 uint8_t val = (uint8_t) rand();
312 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
314 packets[id].payload[randomizer->off] = val;
318 static void apply_csum16(int id)
320 size_t j, csum_max = packet_dyn[id].slen;
322 for (j = 0; j < csum_max; ++j) {
323 uint16_t sum = 0;
324 struct csum16 *csum = &packet_dyn[id].csum[j];
326 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
327 if (unlikely((size_t) csum->to >= packets[id].len))
328 csum->to = packets[id].len - 1;
330 switch (csum->which) {
331 case CSUM_IP:
332 sum = calc_csum(packets[id].payload + csum->from,
333 csum->to - csum->from + 1, 0);
334 break;
335 case CSUM_UDP:
336 sum = p4_csum((void *) packets[id].payload + csum->from,
337 packets[id].payload + csum->to,
338 (packets[id].len - csum->to),
339 IPPROTO_UDP);
340 break;
341 case CSUM_TCP:
342 sum = p4_csum((void *) packets[id].payload + csum->from,
343 packets[id].payload + csum->to,
344 (packets[id].len - csum->to),
345 IPPROTO_TCP);
346 break;
347 default:
348 bug();
349 break;
352 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
356 static struct cpu_stats *setup_shared_var(unsigned long cpus)
358 int fd;
359 size_t len = cpus * sizeof(struct cpu_stats);
360 char *zbuff, file[256];
361 struct cpu_stats *buff;
363 zbuff = xzmalloc(len);
364 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
366 fd = creat(file, S_IRUSR | S_IWUSR);
367 bug_on(fd < 0);
368 close(fd);
370 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
371 S_IRUSR | S_IWUSR);
372 write_or_die(fd, zbuff, len);
373 xfree(zbuff);
375 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
376 MAP_SHARED, fd, 0);
377 if (buff == MAP_FAILED)
378 panic("Cannot setup shared variable!\n");
380 close(fd);
381 unlink(file);
383 memset(buff, 0, len);
384 return buff;
387 static void destroy_shared_var(void *buff, unsigned long cpus)
389 munmap(buff, cpus * sizeof(struct cpu_stats));
392 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
394 size_t i;
396 printf("{");
397 for (i = 0; i < len; ++i) {
398 if (i % 15 == 0)
399 printf("\n ");
400 printf("0x%02x, ", payload[i]);
402 printf("\n}\n");
403 fflush(stdout);
406 static int xmit_smoke_setup(struct ctx *ctx)
408 int icmp_sock, ret, ttl = 64;
409 struct icmp_filter filter;
411 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
412 if (icmp_sock < 0)
413 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
415 filter.data = ~(1 << ICMP_ECHOREPLY);
417 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
418 if (ret < 0)
419 panic("Cannot install filter!\n");
421 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
422 if (ret < 0)
423 panic("Cannot set TTL!\n");
425 memset(&ctx->dest, 0, sizeof(ctx->dest));
426 ctx->dest.sin_family = AF_INET;
427 ctx->dest.sin_port = 0;
429 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
430 if (ret < 0)
431 panic("Cannot resolv address!\n");
433 return icmp_sock;
436 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
438 int ret;
439 unsigned int i, j;
440 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
441 uint8_t outpack[512], *data;
442 struct icmphdr *icmp;
443 struct iphdr *ip;
444 size_t len = sizeof(*icmp) + 56;
445 struct sockaddr_in from;
446 socklen_t from_len;
447 struct pollfd fds = {
448 .fd = icmp_sock,
449 .events = POLLIN,
452 fmemset(idstore, 0, sizeof(idstore));
453 for (j = 0; j < SMOKE_N_PROBES; j++) {
454 while ((ident = htons((short) rand())) == 0)
455 sleep(0);
456 idstore[j] = ident;
458 memset(outpack, 0, sizeof(outpack));
459 icmp = (void *) outpack;
460 icmp->type = ICMP_ECHO;
461 icmp->un.echo.id = ident;
462 icmp->un.echo.sequence = htons(cnt++);
464 data = ((uint8_t *) outpack + sizeof(*icmp));
465 for (i = 0; i < 56; ++i)
466 data[i] = (uint8_t) rand();
468 icmp->checksum = csum((unsigned short *) outpack,
469 len / sizeof(unsigned short));
471 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
472 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
473 if (unlikely(ret != (int) len))
474 panic("Cannot send out probe: %s!\n", strerror(errno));
476 ret = poll(&fds, 1, 50);
477 if (ret < 0)
478 panic("Poll failed!\n");
480 if (fds.revents & POLLIN) {
481 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
482 (struct sockaddr *) &from, &from_len);
483 if (unlikely(ret <= 0))
484 panic("Probe receive failed!\n");
485 if (unlikely(from_len != sizeof(ctx->dest)))
486 continue;
487 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
488 continue;
489 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
490 continue;
491 ip = (void *) outpack;
492 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
493 continue;
494 icmp = (void *) outpack + ip->ihl * 4;
495 for (i = 0; i < array_size(idstore); ++i) {
496 if (unlikely(icmp->un.echo.id != idstore[i]))
497 continue;
498 return 0;
503 return -1;
506 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
508 int ret, icmp_sock = -1;
509 unsigned long num = 1, i = 0;
510 struct timeval start, end, diff;
511 unsigned long long tx_bytes = 0, tx_packets = 0;
512 struct packet_dyn *pktd;
513 struct sockaddr_ll saddr = {
514 .sll_family = PF_PACKET,
515 .sll_halen = ETH_ALEN,
516 .sll_ifindex = device_ifindex(ctx->device),
519 if (ctx->num > 0)
520 num = ctx->num;
521 if (ctx->num == 0 && orig_num > 0)
522 num = 0;
524 if (ctx->smoke_test)
525 icmp_sock = xmit_smoke_setup(ctx);
527 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
529 bug_on(gettimeofday(&start, NULL));
531 while (likely(sigint == 0 && num > 0 && plen > 0)) {
532 pktd = &packet_dyn[i];
533 if (pktd->clen + pktd->rlen + pktd->slen) {
534 apply_counter(i);
535 apply_randomizer(i);
536 apply_csum16(i);
538 retry:
539 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
540 (struct sockaddr *) &saddr, sizeof(saddr));
541 if (unlikely(ret < 0)) {
542 if (errno == ENOBUFS) {
543 sched_yield();
544 goto retry;
546 if (ctx->smoke_test)
547 panic("Sendto error: %s!\n", strerror(errno));
550 tx_bytes += packets[i].len;
551 tx_packets++;
553 if (ctx->smoke_test) {
554 ret = xmit_smoke_probe(icmp_sock, ctx);
555 if (unlikely(ret < 0)) {
556 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
557 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
558 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
559 i, seed);
561 dump_trafgen_snippet(packets[i].payload, packets[i].len);
562 break;
566 if (!ctx->rand) {
567 i++;
568 if (i >= plen)
569 i = 0;
570 } else
571 i = rand() % plen;
573 if (ctx->num > 0)
574 num--;
576 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
577 nanosleep(&ctx->gap, NULL);
580 bug_on(gettimeofday(&end, NULL));
581 timersub(&end, &start, &diff);
583 if (ctx->smoke_test)
584 close(icmp_sock);
586 stats[cpu].tx_packets = tx_packets;
587 stats[cpu].tx_bytes = tx_bytes;
588 stats[cpu].tv_sec = diff.tv_sec;
589 stats[cpu].tv_usec = diff.tv_usec;
591 stats[cpu].state |= CPU_STATS_STATE_RES;
594 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
596 int ifindex = device_ifindex(ctx->device);
597 uint8_t *out = NULL;
598 unsigned int it = 0;
599 unsigned long num = 1, i = 0;
600 size_t size = ring_size(ctx->device, ctx->reserve_size);
601 struct ring tx_ring;
602 struct frame_map *hdr;
603 struct timeval start, end, diff;
604 struct packet_dyn *pktd;
605 unsigned long long tx_bytes = 0, tx_packets = 0;
607 set_sock_prio(sock, 512);
609 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
611 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
613 if (ctx->num > 0)
614 num = ctx->num;
615 if (ctx->num == 0 && orig_num > 0)
616 num = 0;
618 bug_on(gettimeofday(&start, NULL));
620 while (likely(sigint == 0 && num > 0 && plen > 0)) {
621 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
622 int ret = pull_and_flush_tx_ring(sock);
623 if (unlikely(ret < 0)) {
624 /* We could hit EBADF if the socket has been closed before
625 * the timer was triggered.
627 if (errno != EBADF && errno != ENOBUFS)
628 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
631 continue;
634 hdr = tx_ring.frames[it].iov_base;
635 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
637 hdr->tp_h.tp_snaplen = packets[i].len;
638 hdr->tp_h.tp_len = packets[i].len;
640 pktd = &packet_dyn[i];
641 if (pktd->clen + pktd->rlen + pktd->slen) {
642 apply_counter(i);
643 apply_randomizer(i);
644 apply_csum16(i);
647 fmemcpy(out, packets[i].payload, packets[i].len);
649 tx_bytes += packets[i].len;
650 tx_packets++;
652 if (!ctx->rand) {
653 i++;
654 if (i >= plen)
655 i = 0;
656 } else
657 i = rand() % plen;
659 kernel_may_pull_from_tx(&hdr->tp_h);
661 it++;
662 if (it >= tx_ring.layout.tp_frame_nr)
663 it = 0;
665 if (ctx->num > 0)
666 num--;
669 bug_on(gettimeofday(&end, NULL));
670 timersub(&end, &start, &diff);
672 pull_and_flush_tx_ring_wait(sock);
673 destroy_tx_ring(sock, &tx_ring);
675 stats[cpu].tx_packets = tx_packets;
676 stats[cpu].tx_bytes = tx_bytes;
677 stats[cpu].tv_sec = diff.tv_sec;
678 stats[cpu].tv_usec = diff.tv_usec;
680 stats[cpu].state |= CPU_STATS_STATE_RES;
683 static inline void __set_state(int cpu, sig_atomic_t s)
685 stats[cpu].state = s;
688 static inline sig_atomic_t __get_state(int cpu)
690 return stats[cpu].state;
693 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
695 unsigned int i;
696 unsigned long total;
698 for (i = 0, total = plen; i < ctx->cpus; i++) {
699 if (i == cpu)
700 continue;
702 while ((__get_state(i) &
703 (CPU_STATS_STATE_CFG |
704 CPU_STATS_STATE_RES)) == 0 &&
705 sigint == 0)
706 sched_yield();
708 total += stats[i].cf_packets;
711 return total;
714 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
716 unsigned int i;
717 unsigned long total;
718 int cpu_sel;
719 long long delta_correction = 0;
721 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
722 if (i == cpu)
723 continue;
725 while ((__get_state(i) &
726 (CPU_STATS_STATE_CHK |
727 CPU_STATS_STATE_RES)) == 0 &&
728 sigint == 0)
729 sched_yield();
731 total += stats[i].cd_packets;
734 if (total > orig)
735 delta_correction = -1 * ((long long) total - orig);
736 if (total < orig)
737 delta_correction = +1 * ((long long) orig - total);
739 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
740 if (stats[i].cd_packets > 0) {
741 if ((long long) stats[i].cd_packets +
742 delta_correction >= 0) {
743 cpu_sel = i;
744 break;
749 if ((int) cpu == cpu_sel)
750 ctx->num += delta_correction;
753 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
754 sig_atomic_t s)
756 stats[cpu].cf_packets = p;
757 stats[cpu].cf_bytes = b;
758 stats[cpu].state = s;
761 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
763 stats[cpu].cd_packets = p;
764 stats[cpu].state = s;
767 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
769 unsigned int i;
770 unsigned long plen_total, orig = ctx->num;
771 size_t mtu, total_len = 0;
773 bug_on(plen != dlen);
775 for (i = 0; i < plen; ++i)
776 total_len += packets[i].len;
778 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
779 plen_total = __wait_and_sum_others(ctx, cpu);
781 if (orig > 0) {
782 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
784 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
785 CPU_STATS_STATE_CFG);
786 __correct_global_delta(ctx, cpu, orig);
789 if (plen == 0) {
790 __set_state(cpu, CPU_STATS_STATE_RES);
791 return 0;
794 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
795 if (packets[i].len > mtu + 14)
796 panic("Device MTU < than packet%d's size!\n", i);
797 if (packets[i].len <= 14)
798 panic("Packet%d's size too short!\n", i);
801 return 0;
804 static void main_loop(struct ctx *ctx, char *confname, bool slow,
805 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
807 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
808 if (xmit_packet_precheck(ctx, cpu) < 0)
809 return;
811 if (cpu == 0) {
812 unsigned int i;
813 size_t total_len = 0, total_pkts = 0;
815 for (i = 0; i < ctx->cpus; ++i) {
816 total_len += stats[i].cf_bytes;
817 total_pkts += stats[i].cf_packets;
820 printf("%6zu packets to schedule\n", total_pkts);
821 printf("%6zu bytes in total\n", total_len);
822 printf("Running! Hang up with ^C!\n\n");
823 fflush(stdout);
826 sock = pf_tx_socket();
828 if (ctx->qdisc_path == false)
829 set_sock_qdisc_bypass(sock, ctx->verbose);
831 if (slow)
832 xmit_slowpath_or_die(ctx, cpu, orig_num);
833 else
834 xmit_fastpath_or_die(ctx, cpu, orig_num);
836 close(sock);
838 cleanup_packets();
841 static unsigned int generate_srand_seed(void)
843 int fd;
844 unsigned int _seed;
846 fd = open("/dev/urandom", O_RDONLY);
847 if (fd < 0)
848 return time(NULL);
850 read_or_die(fd, &_seed, sizeof(_seed));
852 close(fd);
853 return _seed;
856 int main(int argc, char **argv)
858 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
859 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
860 int c, opt_index, vals[4] = {0}, irq;
861 uint64_t gap = 0;
862 unsigned int i, j;
863 char *confname = NULL, *ptr;
864 unsigned long cpus_tmp, orig_num = 0;
865 unsigned long long tx_packets, tx_bytes;
866 struct ctx ctx;
868 fmemset(&ctx, 0, sizeof(ctx));
869 ctx.cpus = get_number_cpus_online();
870 ctx.uid = getuid();
871 ctx.gid = getgid();
872 ctx.qdisc_path = false;
874 /* Keep an initial small default size to reduce cache-misses. */
875 ctx.reserve_size = 512 * (1 << 10);
877 while ((c = getopt_long(argc, argv, short_options, long_options,
878 &opt_index)) != EOF) {
879 switch (c) {
880 case 'h':
881 help();
882 break;
883 case 'v':
884 version();
885 break;
886 case 'C':
887 cpustats = false;
888 break;
889 case 'e':
890 example();
891 break;
892 case 'p':
893 invoke_cpp = true;
894 break;
895 case 'V':
896 ctx.verbose = true;
897 break;
898 case 'P':
899 cpus_tmp = strtoul(optarg, NULL, 0);
900 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
901 ctx.cpus = cpus_tmp;
902 break;
903 case 'd':
904 case 'o':
905 ctx.device = xstrndup(optarg, IFNAMSIZ);
906 break;
907 case 'H':
908 prio_high = true;
909 break;
910 case 'A':
911 set_sock_mem = false;
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 printf("Option -k/--kernel-pull is no longer used and "
950 "will be removed in a future release!\n");
951 break;
952 case 'E':
953 seed = strtoul(optarg, NULL, 0);
954 reseed = false;
955 break;
956 case 'n':
957 orig_num = strtoul(optarg, NULL, 0);
958 ctx.num = orig_num;
959 break;
960 case 't':
961 slow = true;
962 ptr = optarg;
963 gap = strtoul(optarg, NULL, 0);
965 for (j = i = strlen(optarg); i > 0; --i) {
966 if (!isdigit(optarg[j - i]))
967 break;
968 ptr++;
971 if (!strncmp(ptr, "ns", strlen("ns"))) {
972 ctx.gap.tv_sec = gap / 1000000000;
973 ctx.gap.tv_nsec = gap % 1000000000;
974 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
975 /* Default to microseconds for backwards
976 * compatibility if no postfix is given.
978 ctx.gap.tv_sec = gap / 1000000;
979 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
980 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
981 ctx.gap.tv_sec = gap / 1000;
982 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
983 } else if (!strncmp(ptr, "s", strlen("s"))) {
984 ctx.gap.tv_sec = gap;
985 ctx.gap.tv_nsec = 0;
986 } else
987 panic("Syntax error in time param!\n");
989 if (gap > 0)
990 /* Fall back to single core to not mess up
991 * correct timing. We are slow anyway!
993 ctx.cpus = 1;
994 break;
995 case 'S':
996 ptr = optarg;
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 *= strtoul(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 if (set_sock_mem)
1062 set_system_socket_memory(vals, array_size(vals));
1063 xlockme();
1065 if (ctx.rfraw) {
1066 ctx.device_trans = xstrdup(ctx.device);
1067 xfree(ctx.device);
1069 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1070 sleep(0);
1073 irq = device_irq_number(ctx.device);
1074 if (set_irq_aff)
1075 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1077 stats = setup_shared_var(ctx.cpus);
1079 for (i = 0; i < ctx.cpus; i++) {
1080 pid_t pid = fork();
1082 switch (pid) {
1083 case 0:
1084 if (reseed)
1085 seed = generate_srand_seed();
1086 srand(seed);
1088 cpu_affinity(i);
1089 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1091 goto thread_out;
1092 case -1:
1093 panic("Cannot fork processes!\n");
1097 for (i = 0; i < ctx.cpus; i++) {
1098 int status;
1100 wait(&status);
1101 if (WEXITSTATUS(status) == EXIT_FAILURE)
1102 die();
1105 if (ctx.rfraw)
1106 leave_rfmon_mac80211(ctx.device);
1108 if (set_sock_mem)
1109 reset_system_socket_memory(vals, array_size(vals));
1111 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1112 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1113 sched_yield();
1115 tx_packets += stats[i].tx_packets;
1116 tx_bytes += stats[i].tx_bytes;
1119 fflush(stdout);
1120 printf("\n");
1121 printf("\r%12llu packets outgoing\n", tx_packets);
1122 printf("\r%12llu bytes outgoing\n", tx_bytes);
1123 for (i = 0; cpustats && i < ctx.cpus; i++) {
1124 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1125 stats[i].tv_sec, stats[i].tv_usec, i,
1126 stats[i].tx_packets);
1129 thread_out:
1130 xunlockme();
1131 destroy_shared_var(stats, ctx.cpus);
1132 if (set_irq_aff)
1133 device_restore_irq_affinity_list();
1135 free(ctx.device);
1136 free(ctx.device_trans);
1137 free(ctx.rhost);
1138 free(confname);
1140 return 0;