ifpps: Remove unused 'forks' member from struct ifstat
[netsniff-ng.git] / trafgen.c
blob2d99a4b39a88a595403cc29810e9442e507499f5
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 "built_in.h"
50 #include "trafgen_conf.h"
51 #include "tprintf.h"
52 #include "timer.h"
53 #include "ring_tx.h"
54 #include "csum.h"
56 struct ctx {
57 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
58 unsigned long kpull, num, gap, reserve_size, cpus;
59 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
60 struct sockaddr_in dest;
63 struct cpu_stats {
64 unsigned long tv_sec, tv_usec;
65 unsigned long long tx_packets, tx_bytes;
66 unsigned long long cf_packets, cf_bytes;
67 unsigned long long cd_packets;
68 sig_atomic_t state;
71 static sig_atomic_t sigint = 0;
73 struct packet *packets = NULL;
74 size_t plen = 0;
76 struct packet_dyn *packet_dyn = NULL;
77 size_t dlen = 0;
79 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
80 static const struct option long_options[] = {
81 {"dev", required_argument, NULL, 'd'},
82 {"out", required_argument, NULL, 'o'},
83 {"in", required_argument, NULL, 'i'},
84 {"conf", required_argument, NULL, 'c'},
85 {"num", required_argument, NULL, 'n'},
86 {"gap", required_argument, NULL, 't'},
87 {"cpus", required_argument, NULL, 'P'},
88 {"ring-size", required_argument, NULL, 'S'},
89 {"kernel-pull", required_argument, NULL, 'k'},
90 {"smoke-test", required_argument, NULL, 's'},
91 {"seed", required_argument, NULL, 'E'},
92 {"user", required_argument, NULL, 'u'},
93 {"group", required_argument, NULL, 'g'},
94 {"jumbo-support", no_argument, NULL, 'J'},
95 {"cpp", no_argument, NULL, 'p'},
96 {"rfraw", no_argument, NULL, 'R'},
97 {"rand", no_argument, NULL, 'r'},
98 {"verbose", no_argument, NULL, 'V'},
99 {"version", no_argument, NULL, 'v'},
100 {"example", no_argument, NULL, 'e'},
101 {"help", no_argument, NULL, 'h'},
102 {NULL, 0, NULL, 0}
105 static int sock;
106 static struct itimerval itimer;
107 static unsigned long interval = TX_KERNEL_PULL_INT;
108 static struct cpu_stats *stats;
109 unsigned int seed;
111 #define CPU_STATS_STATE_CFG 1
112 #define CPU_STATS_STATE_CHK 2
113 #define CPU_STATS_STATE_RES 4
115 #ifndef ICMP_FILTER
116 # define ICMP_FILTER 1
118 struct icmp_filter {
119 __u32 data;
121 #endif
123 static void signal_handler(int number)
125 switch (number) {
126 case SIGINT:
127 sigint = 1;
128 case SIGHUP:
129 default:
130 break;
134 static void timer_elapsed(int number)
136 int ret = pull_and_flush_tx_ring(sock);
137 if (unlikely(ret < 0)) {
138 /* We could hit EBADF if the socket has been closed before
139 * the timer was triggered.
141 if (errno != EBADF && errno != ENOBUFS)
142 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
145 set_itimer_interval_value(&itimer, 0, interval);
146 setitimer(ITIMER_REAL, &itimer, NULL);
149 static void timer_purge(void)
151 int ret;
153 ret = pull_and_flush_tx_ring_wait(sock);
154 if (unlikely(ret < 0)) {
155 /* We could hit EBADF if the socket has been closed before
156 * the timer was triggered.
158 if (errno != EBADF && errno != ENOBUFS)
159 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
162 set_itimer_interval_value(&itimer, 0, 0);
163 setitimer(ITIMER_REAL, &itimer, NULL);
166 static void __noreturn help(void)
168 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
169 puts("http://www.netsniff-ng.org\n\n"
170 "Usage: trafgen [options]\n"
171 "Options:\n"
172 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
173 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
174 " -p|--cpp Run packet config through C preprocessor\n"
175 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
176 " -R|--rfraw Inject raw 802.11 frames\n"
177 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
178 " -n|--num <uint> Number of packets until exit (def: 0)\n"
179 " -r|--rand Randomize packet selection (def: round robin)\n"
180 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
181 " -t|--gap <uint> Interpacket gap in us (approx)\n"
182 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
183 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
184 " -E|--seed <uint> Manually set srand(3) seed\n"
185 " -u|--user <userid> Drop privileges and change to userid\n"
186 " -g|--group <groupid> Drop privileges and change to groupid\n"
187 " -V|--verbose Be more verbose\n"
188 " -v|--version Show version and exit\n"
189 " -e|--example Show built-in packet config example\n"
190 " -h|--help Guess what?!\n\n"
191 "Examples:\n"
192 " See trafgen.txf for configuration file examples.\n"
193 " trafgen --dev eth0 --conf trafgen.cfg\n"
194 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
195 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
196 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
197 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
198 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
199 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
200 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
201 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
202 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
203 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
204 "Note:\n"
205 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
206 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
207 " we assume the kernel crashed, thus we print the packet and quit.\n"
208 " In case you find a ping-of-death, please mention trafgen in your\n"
209 " commit message of the fix!\n\n"
210 " For introducing bit errors, delays with random variation and more,\n"
211 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
212 " For generating different package distributions, you can use scripting\n"
213 " to generate a trafgen config file with packet ratios as:\n\n"
214 " IMIX 64:7, 570:4, 1518:1\n"
215 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
216 " Cisco 64:7, 594:4, 1518:1\n"
217 " RPR Trimodal 64:60, 512:20, 1518:20\n"
218 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
219 "Please report bugs to <bugs@netsniff-ng.org>\n"
220 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
221 "Swiss federal institute of technology (ETH Zurich)\n"
222 "License: GNU GPL version 2.0\n"
223 "This is free software: you are free to change and redistribute it.\n"
224 "There is NO WARRANTY, to the extent permitted by law.\n");
225 die();
228 static void __noreturn example(void)
230 const char *e =
231 "/* Note: dynamic elements make trafgen slower! */\n"
232 "#include <stddef.h>\n\n"
233 "{\n"
234 " /* MAC Destination */\n"
235 " fill(0xff, ETH_ALEN),\n"
236 " /* MAC Source */\n"
237 " 0x00, 0x02, 0xb3, drnd(3),\n"
238 " /* IPv4 Protocol */\n"
239 " c16(ETH_P_IP),\n"
240 " /* IPv4 Version, IHL, TOS */\n"
241 " 0b01000101, 0,\n"
242 " /* IPv4 Total Len */\n"
243 " c16(58),\n"
244 " /* IPv4 Ident */\n"
245 " drnd(2),\n"
246 " /* IPv4 Flags, Frag Off */\n"
247 " 0b01000000, 0,\n"
248 " /* IPv4 TTL */\n"
249 " 64,\n"
250 " /* Proto TCP */\n"
251 " 0x06,\n"
252 " /* IPv4 Checksum (IP header from, to) */\n"
253 " csumip(14, 33),\n"
254 " /* Source IP */\n"
255 " drnd(4),\n"
256 " /* Dest IP */\n"
257 " drnd(4),\n"
258 " /* TCP Source Port */\n"
259 " drnd(2),\n"
260 " /* TCP Dest Port */\n"
261 " c16(80),\n"
262 " /* TCP Sequence Number */\n"
263 " drnd(4),\n"
264 " /* TCP Ackn. Number */\n"
265 " c32(0),\n"
266 " /* TCP Header length + TCP SYN/ECN Flag */\n"
267 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
268 " /* Window Size */\n"
269 " c16(16),\n"
270 " /* TCP Checksum (offset IP, offset TCP) */\n"
271 " csumtcp(14, 34),\n"
272 " /* TCP Options */\n"
273 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
274 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
275 " /* Data blob */\n"
276 " \"gotcha!\",\n"
277 "}";
278 puts(e);
279 die();
282 static void __noreturn version(void)
284 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_LONG);
285 puts("http://www.netsniff-ng.org\n\n"
286 "Please report bugs to <bugs@netsniff-ng.org>\n"
287 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
288 "Swiss federal institute of technology (ETH Zurich)\n"
289 "License: GNU GPL version 2.0\n"
290 "This is free software: you are free to change and redistribute it.\n"
291 "There is NO WARRANTY, to the extent permitted by law.\n");
292 die();
295 static void apply_counter(int counter_id)
297 int j, i = counter_id;
298 size_t counter_max = packet_dyn[i].clen;
300 for (j = 0; j < counter_max; ++j) {
301 uint8_t val;
302 struct counter *counter = &packet_dyn[i].cnt[j];
304 val = counter->val - counter->min;
306 switch (counter->type) {
307 case TYPE_INC:
308 val = (val + counter->inc) % (counter->max - counter->min + 1);
309 break;
310 case TYPE_DEC:
311 val = (val - counter->inc) % (counter->min - counter->max + 1);
312 break;
313 default:
314 bug();
317 counter->val = val + counter->min;
318 packets[i].payload[counter->off] = val;
322 static void apply_randomizer(int rand_id)
324 int j, i = rand_id;
325 size_t rand_max = packet_dyn[i].rlen;
327 for (j = 0; j < rand_max; ++j) {
328 uint8_t val = (uint8_t) rand();
329 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
331 packets[i].payload[randomizer->off] = val;
335 static void apply_csum16(int csum_id)
337 int j, i = csum_id;
338 size_t csum_max = packet_dyn[i].slen;
340 for (j = 0; j < csum_max; ++j) {
341 uint16_t sum = 0;
342 struct csum16 *csum = &packet_dyn[i].csum[j];
344 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
346 switch (csum->which) {
347 case CSUM_IP:
348 if (csum->to >= packets[i].len)
349 csum->to = packets[i].len - 1;
350 sum = calc_csum(packets[i].payload + csum->from,
351 csum->to - csum->from + 1, 0);
352 break;
353 case CSUM_UDP:
354 sum = p4_csum((void *) packets[i].payload + csum->from,
355 packets[i].payload + csum->to,
356 (packets[i].len - csum->to),
357 IPPROTO_UDP);
358 break;
359 case CSUM_TCP:
360 sum = p4_csum((void *) packets[i].payload + csum->from,
361 packets[i].payload + csum->to,
362 (packets[i].len - csum->to),
363 IPPROTO_TCP);
364 break;
367 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
371 static struct cpu_stats *setup_shared_var(unsigned long cpus)
373 int fd;
374 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
375 struct cpu_stats *buff;
377 fmemset(zbuff, 0, sizeof(zbuff));
378 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
380 fd = creat(file, S_IRUSR | S_IWUSR);
381 bug_on(fd < 0);
382 close(fd);
384 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
385 S_IRUSR | S_IWUSR);
386 write_or_die(fd, zbuff, sizeof(zbuff));
388 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
389 MAP_SHARED, fd, 0);
390 if (buff == (void *) -1)
391 panic("Cannot setup shared variable!\n");
393 close(fd);
394 unlink(file);
396 memset(buff, 0, sizeof(zbuff));
398 return buff;
401 static void destroy_shared_var(void *buff, unsigned long cpus)
403 munmap(buff, cpus * sizeof(struct cpu_stats));
406 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
408 int i;
410 printf("{");
411 for (i = 0; i < len; ++i) {
412 if (i % 15 == 0)
413 printf("\n ");
414 printf("0x%02x, ", payload[i]);
416 printf("\n}\n");
417 fflush(stdout);
420 static int xmit_smoke_setup(struct ctx *ctx)
422 int icmp_sock, ret, ttl = 64;
423 struct icmp_filter filter;
425 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
426 if (icmp_sock < 0)
427 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
429 filter.data = ~(1 << ICMP_ECHOREPLY);
431 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
432 if (ret < 0)
433 panic("Cannot install filter!\n");
435 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
436 if (ret < 0)
437 panic("Cannot set TTL!\n");
439 memset(&ctx->dest, 0, sizeof(ctx->dest));
440 ctx->dest.sin_family = AF_INET;
441 ctx->dest.sin_port = 0;
443 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
444 if (ret < 0)
445 panic("Cannot resolv address!\n");
447 return icmp_sock;
450 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
452 int ret, i, j = 0, probes = 100;
453 short ident, cnt = 1, idstore[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 while (probes-- > 0) {
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 != 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(ret < sizeof(*ip) + sizeof(*icmp)))
503 continue;
504 ip = (void *) outpack;
505 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > 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, 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) && likely(num > 0) && likely(plen > 0)) {
545 pktd = &packet_dyn[i];
546 if (pktd->clen + pktd->rlen + pktd->slen) {
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;
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 > 0)
590 usleep(ctx->gap);
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, 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, size;
613 struct ring tx_ring;
614 struct frame_map *hdr;
615 struct timeval start, end, diff;
616 struct packet_dyn *pktd;
617 unsigned long long tx_bytes = 0, tx_packets = 0;
619 fmemset(&tx_ring, 0, sizeof(tx_ring));
621 size = ring_size(ctx->device, ctx->reserve_size);
623 set_sock_prio(sock, 512);
624 set_packet_loss_discard(sock);
626 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
627 create_tx_ring(sock, &tx_ring, ctx->verbose);
628 mmap_tx_ring(sock, &tx_ring);
629 alloc_tx_ring_frames(sock, &tx_ring);
630 bind_tx_ring(sock, &tx_ring, ifindex);
632 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
634 if (ctx->kpull)
635 interval = ctx->kpull;
636 if (ctx->num > 0)
637 num = ctx->num;
638 if (ctx->num == 0 && orig_num > 0)
639 num = 0;
641 set_itimer_interval_value(&itimer, 0, interval);
642 setitimer(ITIMER_REAL, &itimer, NULL);
644 bug_on(gettimeofday(&start, NULL));
646 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
647 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
648 hdr = tx_ring.frames[it].iov_base;
649 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
651 hdr->tp_h.tp_snaplen = packets[i].len;
652 hdr->tp_h.tp_len = packets[i].len;
654 pktd = &packet_dyn[i];
655 if (pktd->clen + pktd->rlen + pktd->slen) {
656 apply_counter(i);
657 apply_randomizer(i);
658 apply_csum16(i);
661 fmemcpy(out, packets[i].payload, packets[i].len);
663 tx_bytes += packets[i].len;
664 tx_packets++;
666 if (!ctx->rand) {
667 i++;
668 if (i >= plen)
669 i = 0;
670 } else
671 i = rand() % plen;
673 kernel_may_pull_from_tx(&hdr->tp_h);
675 it++;
676 if (it >= tx_ring.layout.tp_frame_nr)
677 it = 0;
679 if (ctx->num > 0)
680 num--;
682 if (unlikely(sigint == 1))
683 break;
687 bug_on(gettimeofday(&end, NULL));
688 timersub(&end, &start, &diff);
690 timer_purge();
692 destroy_tx_ring(sock, &tx_ring);
694 stats[cpu].tx_packets = tx_packets;
695 stats[cpu].tx_bytes = tx_bytes;
696 stats[cpu].tv_sec = diff.tv_sec;
697 stats[cpu].tv_usec = diff.tv_usec;
699 stats[cpu].state |= CPU_STATS_STATE_RES;
702 static inline void __set_state(int cpu, sig_atomic_t s)
704 stats[cpu].state = s;
707 static inline sig_atomic_t __get_state(int cpu)
709 return stats[cpu].state;
712 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
714 int i;
715 unsigned long total;
717 for (i = 0, total = plen; i < ctx->cpus; i++) {
718 if (i == cpu)
719 continue;
721 while ((__get_state(i) &
722 (CPU_STATS_STATE_CFG |
723 CPU_STATS_STATE_RES)) == 0 &&
724 sigint == 0)
725 sched_yield();
727 total += stats[i].cf_packets;
730 return total;
733 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
735 int i, cpu_sel;
736 unsigned long total;
737 long long delta_correction = 0;
739 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
740 if (i == cpu)
741 continue;
743 while ((__get_state(i) &
744 (CPU_STATS_STATE_CHK |
745 CPU_STATS_STATE_RES)) == 0 &&
746 sigint == 0)
747 sched_yield();
749 total += stats[i].cd_packets;
752 if (total > orig)
753 delta_correction = -1 * ((long long) total - orig);
754 if (total < orig)
755 delta_correction = +1 * ((long long) orig - total);
757 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
758 if (stats[i].cd_packets > 0) {
759 if ((long long) stats[i].cd_packets +
760 delta_correction > 0) {
761 cpu_sel = i;
762 break;
767 if (cpu == cpu_sel)
768 ctx->num += delta_correction;
771 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
772 sig_atomic_t s)
774 stats[cpu].cf_packets = p;
775 stats[cpu].cf_bytes = b;
776 stats[cpu].state = s;
779 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
781 stats[cpu].cd_packets = p;
782 stats[cpu].state = s;
785 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
787 int i;
788 unsigned long plen_total, orig = ctx->num;
789 size_t mtu, total_len = 0;
791 bug_on(plen != dlen);
793 for (i = 0; i < plen; ++i)
794 total_len += packets[i].len;
796 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
797 plen_total = __wait_and_sum_others(ctx, cpu);
799 if (orig > 0) {
800 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
802 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
803 CPU_STATS_STATE_CFG);
804 __correct_global_delta(ctx, cpu, orig);
807 if (plen == 0) {
808 __set_state(cpu, CPU_STATS_STATE_RES);
809 return 0;
812 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
813 if (packets[i].len > mtu + 14)
814 panic("Device MTU < than packet%d's size!\n", i);
815 if (packets[i].len <= 14)
816 panic("Packet%d's size too short!\n", i);
819 return 0;
822 static void main_loop(struct ctx *ctx, char *confname, bool slow,
823 int cpu, bool invoke_cpp, unsigned long orig_num)
825 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
826 if (xmit_packet_precheck(ctx, cpu) < 0)
827 return;
829 if (cpu == 0) {
830 int i;
831 size_t total_len = 0, total_pkts = 0;
833 for (i = 0; i < ctx->cpus; ++i) {
834 total_len += stats[i].cf_bytes;
835 total_pkts += stats[i].cf_packets;
838 printf("%6zu packets to schedule\n", total_pkts);
839 printf("%6zu bytes in total\n", total_len);
840 printf("Running! Hang up with ^C!\n\n");
841 fflush(stdout);
844 sock = pf_socket();
846 if (slow)
847 xmit_slowpath_or_die(ctx, cpu, orig_num);
848 else
849 xmit_fastpath_or_die(ctx, cpu, orig_num);
851 close(sock);
853 cleanup_packets();
856 static unsigned int generate_srand_seed(void)
858 int fd;
859 unsigned int seed;
861 fd = open("/dev/urandom", O_RDONLY);
862 if (fd < 0)
863 return time(0);
865 read_or_die(fd, &seed, sizeof(seed));
867 close(fd);
868 return seed;
871 int main(int argc, char **argv)
873 bool slow = false, invoke_cpp = false, reseed = true;
874 int c, opt_index, i, j, vals[4] = {0}, irq;
875 char *confname = NULL, *ptr;
876 unsigned long cpus_tmp, orig_num = 0;
877 unsigned long long tx_packets, tx_bytes;
878 struct ctx ctx;
880 fmemset(&ctx, 0, sizeof(ctx));
881 ctx.cpus = get_number_cpus_online();
882 ctx.uid = getuid();
883 ctx.gid = getgid();
885 while ((c = getopt_long(argc, argv, short_options, long_options,
886 &opt_index)) != EOF) {
887 switch (c) {
888 case 'h':
889 help();
890 break;
891 case 'v':
892 version();
893 break;
894 case 'e':
895 example();
896 break;
897 case 'p':
898 invoke_cpp = true;
899 break;
900 case 'V':
901 ctx.verbose = true;
902 break;
903 case 'P':
904 cpus_tmp = strtoul(optarg, NULL, 0);
905 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
906 ctx.cpus = cpus_tmp;
907 break;
908 case 'd':
909 case 'o':
910 ctx.device = xstrndup(optarg, IFNAMSIZ);
911 break;
912 case 'r':
913 ctx.rand = true;
914 break;
915 case 's':
916 slow = true;
917 ctx.cpus = 1;
918 ctx.smoke_test = true;
919 ctx.rhost = xstrdup(optarg);
920 break;
921 case 'R':
922 ctx.rfraw = true;
923 break;
924 case 'J':
925 ctx.jumbo_support = true;
926 break;
927 case 'c':
928 case 'i':
929 confname = xstrdup(optarg);
930 if (!strncmp("-", confname, strlen("-")))
931 ctx.cpus = 1;
932 break;
933 case 'u':
934 ctx.uid = strtoul(optarg, NULL, 0);
935 ctx.enforce = true;
936 break;
937 case 'g':
938 ctx.gid = strtoul(optarg, NULL, 0);
939 ctx.enforce = true;
940 break;
941 case 'k':
942 ctx.kpull = strtoul(optarg, NULL, 0);
943 break;
944 case 'E':
945 seed = strtoul(optarg, NULL, 0);
946 reseed = false;
947 break;
948 case 'n':
949 orig_num = strtoul(optarg, NULL, 0);
950 ctx.num = orig_num;
951 break;
952 case 't':
953 slow = true;
954 ctx.gap = strtoul(optarg, NULL, 0);
955 if (ctx.gap > 0)
956 /* Fall back to single core to not
957 * mess up correct timing. We are slow
958 * anyway!
960 ctx.cpus = 1;
961 break;
962 case 'S':
963 ptr = optarg;
964 ctx.reserve_size = 0;
966 for (j = i = strlen(optarg); i > 0; --i) {
967 if (!isdigit(optarg[j - i]))
968 break;
969 ptr++;
972 if (!strncmp(ptr, "KiB", strlen("KiB")))
973 ctx.reserve_size = 1 << 10;
974 else if (!strncmp(ptr, "MiB", strlen("MiB")))
975 ctx.reserve_size = 1 << 20;
976 else if (!strncmp(ptr, "GiB", strlen("GiB")))
977 ctx.reserve_size = 1 << 30;
978 else
979 panic("Syntax error in ring size param!\n");
980 *ptr = 0;
982 ctx.reserve_size *= strtol(optarg, NULL, 0);
983 break;
984 case '?':
985 switch (optopt) {
986 case 'd':
987 case 'c':
988 case 'n':
989 case 'S':
990 case 's':
991 case 'P':
992 case 'o':
993 case 'E':
994 case 'i':
995 case 'k':
996 case 'u':
997 case 'g':
998 case 't':
999 panic("Option -%c requires an argument!\n",
1000 optopt);
1001 default:
1002 if (isprint(optopt))
1003 printf("Unknown option character `0x%X\'!\n", optopt);
1004 die();
1006 default:
1007 break;
1011 if (argc < 5)
1012 help();
1013 if (ctx.device == NULL)
1014 panic("No networking device given!\n");
1015 if (confname == NULL)
1016 panic("No configuration file given!\n");
1017 if (device_mtu(ctx.device) == 0)
1018 panic("This is no networking device!\n");
1020 register_signal(SIGINT, signal_handler);
1021 register_signal(SIGHUP, signal_handler);
1022 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1024 set_system_socket_memory(vals, array_size(vals));
1025 xlockme();
1027 if (ctx.rfraw) {
1028 ctx.device_trans = xstrdup(ctx.device);
1029 xfree(ctx.device);
1031 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1032 sleep(0);
1035 irq = device_irq_number(ctx.device);
1036 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1038 stats = setup_shared_var(ctx.cpus);
1040 for (i = 0; i < ctx.cpus; i++) {
1041 pid_t pid = fork();
1043 switch (pid) {
1044 case 0:
1045 if (reseed)
1046 seed = generate_srand_seed();
1047 srand(seed);
1049 cpu_affinity(i);
1050 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1052 goto thread_out;
1053 case -1:
1054 panic("Cannot fork processes!\n");
1058 for (i = 0; i < ctx.cpus; i++) {
1059 int status;
1061 wait(&status);
1062 if (WEXITSTATUS(status) == EXIT_FAILURE)
1063 die();
1066 if (ctx.rfraw)
1067 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1069 reset_system_socket_memory(vals, array_size(vals));
1071 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1072 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1073 sched_yield();
1075 tx_packets += stats[i].tx_packets;
1076 tx_bytes += stats[i].tx_bytes;
1079 fflush(stdout);
1080 printf("\n");
1081 printf("\r%12llu packets outgoing\n", tx_packets);
1082 printf("\r%12llu bytes outgoing\n", tx_bytes);
1083 for (i = 0; i < ctx.cpus; i++) {
1084 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1085 stats[i].tv_sec, stats[i].tv_usec, i,
1086 stats[i].tx_packets);
1089 thread_out:
1090 xunlockme();
1091 destroy_shared_var(stats, ctx.cpus);
1092 device_restore_irq_affinity_list();
1094 free(ctx.device);
1095 free(ctx.device_trans);
1096 free(ctx.rhost);
1097 free(confname);
1099 return 0;