timer: add time management functions
[netsniff-ng.git] / trafgen.c
blobfc15e207487acf524908ef47cf9069935ee0a889
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 <sys/socket.h>
14 #include <sys/types.h>
15 #include <sys/fsuid.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/wait.h>
19 #include <sys/mman.h>
20 #include <net/ethernet.h>
21 #include <netinet/in.h>
22 #include <netinet/ip.h>
23 #include <linux/icmp.h>
24 #include <arpa/inet.h>
25 #include <signal.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <fcntl.h>
29 #include <time.h>
30 #include <poll.h>
31 #include <netdb.h>
32 #include <math.h>
33 #include <unistd.h>
35 #include "xmalloc.h"
36 #include "die.h"
37 #include "str.h"
38 #include "sig.h"
39 #include "sock.h"
40 #include "cpus.h"
41 #include "lockme.h"
42 #include "privs.h"
43 #include "proc.h"
44 #include "mac80211.h"
45 #include "xutils.h"
46 #include "ioops.h"
47 #include "irq.h"
48 #include "built_in.h"
49 #include "trafgen_conf.h"
50 #include "tprintf.h"
51 #include "timer.h"
52 #include "ring_tx.h"
53 #include "csum.h"
55 struct ctx {
56 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
57 unsigned long kpull, num, gap, reserve_size, cpus;
58 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
59 struct sockaddr_in dest;
62 struct cpu_stats {
63 unsigned long tv_sec, tv_usec;
64 unsigned long long tx_packets, tx_bytes;
65 unsigned long long cf_packets, cf_bytes;
66 unsigned long long cd_packets;
67 sig_atomic_t state;
70 static sig_atomic_t sigint = 0;
72 struct packet *packets = NULL;
73 size_t plen = 0;
75 struct packet_dyn *packet_dyn = NULL;
76 size_t dlen = 0;
78 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
79 static const struct option long_options[] = {
80 {"dev", required_argument, NULL, 'd'},
81 {"out", required_argument, NULL, 'o'},
82 {"in", required_argument, NULL, 'i'},
83 {"conf", required_argument, NULL, 'c'},
84 {"num", required_argument, NULL, 'n'},
85 {"gap", required_argument, NULL, 't'},
86 {"cpus", required_argument, NULL, 'P'},
87 {"ring-size", required_argument, NULL, 'S'},
88 {"kernel-pull", required_argument, NULL, 'k'},
89 {"smoke-test", required_argument, NULL, 's'},
90 {"seed", required_argument, NULL, 'E'},
91 {"user", required_argument, NULL, 'u'},
92 {"group", required_argument, NULL, 'g'},
93 {"jumbo-support", no_argument, NULL, 'J'},
94 {"cpp", no_argument, NULL, 'p'},
95 {"rfraw", no_argument, NULL, 'R'},
96 {"rand", no_argument, NULL, 'r'},
97 {"verbose", no_argument, NULL, 'V'},
98 {"version", no_argument, NULL, 'v'},
99 {"example", no_argument, NULL, 'e'},
100 {"help", no_argument, NULL, 'h'},
101 {NULL, 0, NULL, 0}
104 static int sock;
105 static struct itimerval itimer;
106 static unsigned long interval = TX_KERNEL_PULL_INT;
107 static struct cpu_stats *stats;
108 unsigned int seed;
110 #define CPU_STATS_STATE_CFG 1
111 #define CPU_STATS_STATE_CHK 2
112 #define CPU_STATS_STATE_RES 4
114 #ifndef ICMP_FILTER
115 # define ICMP_FILTER 1
117 struct icmp_filter {
118 __u32 data;
120 #endif
122 static void signal_handler(int number)
124 switch (number) {
125 case SIGINT:
126 sigint = 1;
127 case SIGHUP:
128 default:
129 break;
133 static void timer_elapsed(int number)
135 int ret = pull_and_flush_tx_ring(sock);
136 if (unlikely(ret < 0)) {
137 /* We could hit EBADF if the socket has been closed before
138 * the timer was triggered.
140 if (errno != EBADF && errno != ENOBUFS)
141 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
144 set_itimer_interval_value(&itimer, 0, interval);
145 setitimer(ITIMER_REAL, &itimer, NULL);
148 static void timer_purge(void)
150 int ret;
152 ret = pull_and_flush_tx_ring_wait(sock);
153 if (unlikely(ret < 0)) {
154 /* We could hit EBADF if the socket has been closed before
155 * the timer was triggered.
157 if (errno != EBADF && errno != ENOBUFS)
158 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
161 set_itimer_interval_value(&itimer, 0, 0);
162 setitimer(ITIMER_REAL, &itimer, NULL);
165 static void __noreturn help(void)
167 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
168 puts("http://www.netsniff-ng.org\n\n"
169 "Usage: trafgen [options]\n"
170 "Options:\n"
171 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
172 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
173 " -p|--cpp Run packet config through C preprocessor\n"
174 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
175 " -R|--rfraw Inject raw 802.11 frames\n"
176 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
177 " -n|--num <uint> Number of packets until exit (def: 0)\n"
178 " -r|--rand Randomize packet selection (def: round robin)\n"
179 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
180 " -t|--gap <uint> Interpacket gap in us (approx)\n"
181 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
182 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
183 " -E|--seed <uint> Manually set srand(3) seed\n"
184 " -u|--user <userid> Drop privileges and change to userid\n"
185 " -g|--group <groupid> Drop privileges and change to groupid\n"
186 " -V|--verbose Be more verbose\n"
187 " -v|--version Show version and exit\n"
188 " -e|--example Show built-in packet config example\n"
189 " -h|--help Guess what?!\n\n"
190 "Examples:\n"
191 " See trafgen.txf for configuration file examples.\n"
192 " trafgen --dev eth0 --conf trafgen.cfg\n"
193 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
194 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
195 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
196 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
197 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
198 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
199 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
200 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
201 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
202 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
203 "Note:\n"
204 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
205 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
206 " we assume the kernel crashed, thus we print the packet and quit.\n"
207 " In case you find a ping-of-death, please mention trafgen in your\n"
208 " commit message of the fix!\n\n"
209 " For introducing bit errors, delays with random variation and more,\n"
210 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
211 " For generating different package distributions, you can use scripting\n"
212 " to generate a trafgen config file with packet ratios as:\n\n"
213 " IMIX 64:7, 570:4, 1518:1\n"
214 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
215 " Cisco 64:7, 594:4, 1518:1\n"
216 " RPR Trimodal 64:60, 512:20, 1518:20\n"
217 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
218 "Please report bugs to <bugs@netsniff-ng.org>\n"
219 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
220 "Swiss federal institute of technology (ETH Zurich)\n"
221 "License: GNU GPL version 2.0\n"
222 "This is free software: you are free to change and redistribute it.\n"
223 "There is NO WARRANTY, to the extent permitted by law.\n");
224 die();
227 static void __noreturn example(void)
229 const char *e =
230 "/* Note: dynamic elements make trafgen slower! */\n"
231 "#include <stddef.h>\n\n"
232 "{\n"
233 " /* MAC Destination */\n"
234 " fill(0xff, ETH_ALEN),\n"
235 " /* MAC Source */\n"
236 " 0x00, 0x02, 0xb3, drnd(3),\n"
237 " /* IPv4 Protocol */\n"
238 " c16(ETH_P_IP),\n"
239 " /* IPv4 Version, IHL, TOS */\n"
240 " 0b01000101, 0,\n"
241 " /* IPv4 Total Len */\n"
242 " c16(58),\n"
243 " /* IPv4 Ident */\n"
244 " drnd(2),\n"
245 " /* IPv4 Flags, Frag Off */\n"
246 " 0b01000000, 0,\n"
247 " /* IPv4 TTL */\n"
248 " 64,\n"
249 " /* Proto TCP */\n"
250 " 0x06,\n"
251 " /* IPv4 Checksum (IP header from, to) */\n"
252 " csumip(14, 33),\n"
253 " /* Source IP */\n"
254 " drnd(4),\n"
255 " /* Dest IP */\n"
256 " drnd(4),\n"
257 " /* TCP Source Port */\n"
258 " drnd(2),\n"
259 " /* TCP Dest Port */\n"
260 " c16(80),\n"
261 " /* TCP Sequence Number */\n"
262 " drnd(4),\n"
263 " /* TCP Ackn. Number */\n"
264 " c32(0),\n"
265 " /* TCP Header length + TCP SYN/ECN Flag */\n"
266 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
267 " /* Window Size */\n"
268 " c16(16),\n"
269 " /* TCP Checksum (offset IP, offset TCP) */\n"
270 " csumtcp(14, 34),\n"
271 " /* TCP Options */\n"
272 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
273 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
274 " /* Data blob */\n"
275 " \"gotcha!\",\n"
276 "}";
277 puts(e);
278 die();
281 static void __noreturn version(void)
283 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_LONG);
284 puts("http://www.netsniff-ng.org\n\n"
285 "Please report bugs to <bugs@netsniff-ng.org>\n"
286 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
287 "Swiss federal institute of technology (ETH Zurich)\n"
288 "License: GNU GPL version 2.0\n"
289 "This is free software: you are free to change and redistribute it.\n"
290 "There is NO WARRANTY, to the extent permitted by law.\n");
291 die();
294 static void apply_counter(int counter_id)
296 int j, i = counter_id;
297 size_t counter_max = packet_dyn[i].clen;
299 for (j = 0; j < counter_max; ++j) {
300 uint8_t val;
301 struct counter *counter = &packet_dyn[i].cnt[j];
303 val = counter->val - counter->min;
305 switch (counter->type) {
306 case TYPE_INC:
307 val = (val + counter->inc) % (counter->max - counter->min + 1);
308 break;
309 case TYPE_DEC:
310 val = (val - counter->inc) % (counter->min - counter->max + 1);
311 break;
312 default:
313 bug();
316 counter->val = val + counter->min;
317 packets[i].payload[counter->off] = val;
321 static void apply_randomizer(int rand_id)
323 int j, i = rand_id;
324 size_t rand_max = packet_dyn[i].rlen;
326 for (j = 0; j < rand_max; ++j) {
327 uint8_t val = (uint8_t) rand();
328 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
330 packets[i].payload[randomizer->off] = val;
334 static void apply_csum16(int csum_id)
336 int j, i = csum_id;
337 size_t csum_max = packet_dyn[i].slen;
339 for (j = 0; j < csum_max; ++j) {
340 uint16_t sum = 0;
341 struct csum16 *csum = &packet_dyn[i].csum[j];
343 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
345 switch (csum->which) {
346 case CSUM_IP:
347 if (csum->to >= packets[i].len)
348 csum->to = packets[i].len - 1;
349 sum = calc_csum(packets[i].payload + csum->from,
350 csum->to - csum->from + 1, 0);
351 break;
352 case CSUM_UDP:
353 sum = p4_csum((void *) packets[i].payload + csum->from,
354 packets[i].payload + csum->to,
355 (packets[i].len - csum->to),
356 IPPROTO_UDP);
357 break;
358 case CSUM_TCP:
359 sum = p4_csum((void *) packets[i].payload + csum->from,
360 packets[i].payload + csum->to,
361 (packets[i].len - csum->to),
362 IPPROTO_TCP);
363 break;
366 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
370 static struct cpu_stats *setup_shared_var(unsigned long cpus)
372 int fd;
373 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
374 struct cpu_stats *buff;
376 fmemset(zbuff, 0, sizeof(zbuff));
377 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
379 fd = creat(file, S_IRUSR | S_IWUSR);
380 bug_on(fd < 0);
381 close(fd);
383 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
384 S_IRUSR | S_IWUSR);
385 write_or_die(fd, zbuff, sizeof(zbuff));
387 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
388 MAP_SHARED, fd, 0);
389 if (buff == (void *) -1)
390 panic("Cannot setup shared variable!\n");
392 close(fd);
393 unlink(file);
395 memset(buff, 0, sizeof(zbuff));
397 return buff;
400 static void destroy_shared_var(void *buff, unsigned long cpus)
402 munmap(buff, cpus * sizeof(struct cpu_stats));
405 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
407 int i;
409 printf("{");
410 for (i = 0; i < len; ++i) {
411 if (i % 15 == 0)
412 printf("\n ");
413 printf("0x%02x, ", payload[i]);
415 printf("\n}\n");
416 fflush(stdout);
419 static int xmit_smoke_setup(struct ctx *ctx)
421 int icmp_sock, ret, ttl = 64;
422 struct icmp_filter filter;
424 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
425 if (icmp_sock < 0)
426 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
428 filter.data = ~(1 << ICMP_ECHOREPLY);
430 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
431 if (ret < 0)
432 panic("Cannot install filter!\n");
434 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
435 if (ret < 0)
436 panic("Cannot set TTL!\n");
438 memset(&ctx->dest, 0, sizeof(ctx->dest));
439 ctx->dest.sin_family = AF_INET;
440 ctx->dest.sin_port = 0;
442 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
443 if (ret < 0)
444 panic("Cannot resolv address!\n");
446 return icmp_sock;
449 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
451 int ret, i, j = 0, probes = 100;
452 short ident, cnt = 1, idstore[probes];
453 uint8_t outpack[512], *data;
454 struct icmphdr *icmp;
455 struct iphdr *ip;
456 size_t len = sizeof(*icmp) + 56;
457 struct sockaddr_in from;
458 socklen_t from_len;
459 struct pollfd fds = {
460 .fd = icmp_sock,
461 .events = POLLIN,
464 fmemset(idstore, 0, sizeof(idstore));
465 while (probes-- > 0) {
466 while ((ident = htons((short) rand())) == 0)
467 sleep(0);
468 idstore[j++] = ident;
470 memset(outpack, 0, sizeof(outpack));
471 icmp = (void *) outpack;
472 icmp->type = ICMP_ECHO;
473 icmp->un.echo.id = ident;
474 icmp->un.echo.sequence = htons(cnt++);
476 data = ((uint8_t *) outpack + sizeof(*icmp));
477 for (i = 0; i < 56; ++i)
478 data[i] = (uint8_t) rand();
480 icmp->checksum = csum((unsigned short *) outpack,
481 len / sizeof(unsigned short));
483 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
484 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
485 if (unlikely(ret != len))
486 panic("Cannot send out probe: %s!\n", strerror(errno));
488 ret = poll(&fds, 1, 50);
489 if (ret < 0)
490 panic("Poll failed!\n");
492 if (fds.revents & POLLIN) {
493 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
494 (struct sockaddr *) &from, &from_len);
495 if (unlikely(ret <= 0))
496 panic("Probe receive failed!\n");
497 if (unlikely(from_len != sizeof(ctx->dest)))
498 continue;
499 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
500 continue;
501 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
502 continue;
503 ip = (void *) outpack;
504 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
505 continue;
506 icmp = (void *) outpack + ip->ihl * 4;
507 for (i = 0; i < array_size(idstore); ++i) {
508 if (unlikely(icmp->un.echo.id != idstore[i]))
509 continue;
510 return 0;
515 return -1;
518 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
520 int ret, icmp_sock = -1;
521 unsigned long num = 1, i = 0;
522 struct timeval start, end, diff;
523 unsigned long long tx_bytes = 0, tx_packets = 0;
524 struct packet_dyn *pktd;
525 struct sockaddr_ll saddr = {
526 .sll_family = PF_PACKET,
527 .sll_halen = ETH_ALEN,
528 .sll_ifindex = device_ifindex(ctx->device),
531 if (ctx->num > 0)
532 num = ctx->num;
533 if (ctx->num == 0 && orig_num > 0)
534 num = 0;
536 if (ctx->smoke_test)
537 icmp_sock = xmit_smoke_setup(ctx);
539 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
541 bug_on(gettimeofday(&start, NULL));
543 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
544 pktd = &packet_dyn[i];
545 if (pktd->clen + pktd->rlen + pktd->slen) {
546 apply_counter(i);
547 apply_randomizer(i);
548 apply_csum16(i);
550 retry:
551 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
552 (struct sockaddr *) &saddr, sizeof(saddr));
553 if (unlikely(ret < 0)) {
554 if (errno == ENOBUFS) {
555 sched_yield();
556 goto retry;
559 panic("Sendto error: %s!\n", strerror(errno));
562 tx_bytes += packets[i].len;
563 tx_packets++;
565 if (ctx->smoke_test) {
566 ret = xmit_smoke_probe(icmp_sock, ctx);
567 if (unlikely(ret < 0)) {
568 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
569 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
570 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
571 i, seed);
573 dump_trafgen_snippet(packets[i].payload, packets[i].len);
574 break;
578 if (!ctx->rand) {
579 i++;
580 if (i >= plen)
581 i = 0;
582 } else
583 i = rand() % plen;
585 if (ctx->num > 0)
586 num--;
588 if (ctx->gap > 0)
589 usleep(ctx->gap);
592 bug_on(gettimeofday(&end, NULL));
593 timersub(&end, &start, &diff);
595 if (ctx->smoke_test)
596 close(icmp_sock);
598 stats[cpu].tx_packets = tx_packets;
599 stats[cpu].tx_bytes = tx_bytes;
600 stats[cpu].tv_sec = diff.tv_sec;
601 stats[cpu].tv_usec = diff.tv_usec;
603 stats[cpu].state |= CPU_STATS_STATE_RES;
606 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
608 int ifindex = device_ifindex(ctx->device);
609 uint8_t *out = NULL;
610 unsigned int it = 0;
611 unsigned long num = 1, i = 0, size;
612 struct ring tx_ring;
613 struct frame_map *hdr;
614 struct timeval start, end, diff;
615 struct packet_dyn *pktd;
616 unsigned long long tx_bytes = 0, tx_packets = 0;
618 fmemset(&tx_ring, 0, sizeof(tx_ring));
620 size = ring_size(ctx->device, ctx->reserve_size);
622 set_sock_prio(sock, 512);
623 set_packet_loss_discard(sock);
625 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
626 create_tx_ring(sock, &tx_ring, ctx->verbose);
627 mmap_tx_ring(sock, &tx_ring);
628 alloc_tx_ring_frames(sock, &tx_ring);
629 bind_tx_ring(sock, &tx_ring, ifindex);
631 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
633 if (ctx->kpull)
634 interval = ctx->kpull;
635 if (ctx->num > 0)
636 num = ctx->num;
637 if (ctx->num == 0 && orig_num > 0)
638 num = 0;
640 set_itimer_interval_value(&itimer, 0, interval);
641 setitimer(ITIMER_REAL, &itimer, NULL);
643 bug_on(gettimeofday(&start, NULL));
645 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
646 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
647 hdr = tx_ring.frames[it].iov_base;
648 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
650 hdr->tp_h.tp_snaplen = packets[i].len;
651 hdr->tp_h.tp_len = packets[i].len;
653 pktd = &packet_dyn[i];
654 if (pktd->clen + pktd->rlen + pktd->slen) {
655 apply_counter(i);
656 apply_randomizer(i);
657 apply_csum16(i);
660 fmemcpy(out, packets[i].payload, packets[i].len);
662 tx_bytes += packets[i].len;
663 tx_packets++;
665 if (!ctx->rand) {
666 i++;
667 if (i >= plen)
668 i = 0;
669 } else
670 i = rand() % plen;
672 kernel_may_pull_from_tx(&hdr->tp_h);
674 it++;
675 if (it >= tx_ring.layout.tp_frame_nr)
676 it = 0;
678 if (ctx->num > 0)
679 num--;
681 if (unlikely(sigint == 1))
682 break;
686 bug_on(gettimeofday(&end, NULL));
687 timersub(&end, &start, &diff);
689 timer_purge();
691 destroy_tx_ring(sock, &tx_ring);
693 stats[cpu].tx_packets = tx_packets;
694 stats[cpu].tx_bytes = tx_bytes;
695 stats[cpu].tv_sec = diff.tv_sec;
696 stats[cpu].tv_usec = diff.tv_usec;
698 stats[cpu].state |= CPU_STATS_STATE_RES;
701 static inline void __set_state(int cpu, sig_atomic_t s)
703 stats[cpu].state = s;
706 static inline sig_atomic_t __get_state(int cpu)
708 return stats[cpu].state;
711 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
713 int i;
714 unsigned long total;
716 for (i = 0, total = plen; i < ctx->cpus; i++) {
717 if (i == cpu)
718 continue;
720 while ((__get_state(i) &
721 (CPU_STATS_STATE_CFG |
722 CPU_STATS_STATE_RES)) == 0 &&
723 sigint == 0)
724 sched_yield();
726 total += stats[i].cf_packets;
729 return total;
732 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
734 int i, cpu_sel;
735 unsigned long total;
736 long long delta_correction = 0;
738 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
739 if (i == cpu)
740 continue;
742 while ((__get_state(i) &
743 (CPU_STATS_STATE_CHK |
744 CPU_STATS_STATE_RES)) == 0 &&
745 sigint == 0)
746 sched_yield();
748 total += stats[i].cd_packets;
751 if (total > orig)
752 delta_correction = -1 * ((long long) total - orig);
753 if (total < orig)
754 delta_correction = +1 * ((long long) orig - total);
756 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
757 if (stats[i].cd_packets > 0) {
758 if ((long long) stats[i].cd_packets +
759 delta_correction > 0) {
760 cpu_sel = i;
761 break;
766 if (cpu == cpu_sel)
767 ctx->num += delta_correction;
770 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
771 sig_atomic_t s)
773 stats[cpu].cf_packets = p;
774 stats[cpu].cf_bytes = b;
775 stats[cpu].state = s;
778 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
780 stats[cpu].cd_packets = p;
781 stats[cpu].state = s;
784 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
786 int i;
787 unsigned long plen_total, orig = ctx->num;
788 size_t mtu, total_len = 0;
790 bug_on(plen != dlen);
792 for (i = 0; i < plen; ++i)
793 total_len += packets[i].len;
795 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
796 plen_total = __wait_and_sum_others(ctx, cpu);
798 if (orig > 0) {
799 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
801 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
802 CPU_STATS_STATE_CFG);
803 __correct_global_delta(ctx, cpu, orig);
806 if (plen == 0) {
807 __set_state(cpu, CPU_STATS_STATE_RES);
808 return 0;
811 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
812 if (packets[i].len > mtu + 14)
813 panic("Device MTU < than packet%d's size!\n", i);
814 if (packets[i].len <= 14)
815 panic("Packet%d's size too short!\n", i);
818 return 0;
821 static void main_loop(struct ctx *ctx, char *confname, bool slow,
822 int cpu, bool invoke_cpp, unsigned long orig_num)
824 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
825 if (xmit_packet_precheck(ctx, cpu) < 0)
826 return;
828 if (cpu == 0) {
829 int i;
830 size_t total_len = 0, total_pkts = 0;
832 for (i = 0; i < ctx->cpus; ++i) {
833 total_len += stats[i].cf_bytes;
834 total_pkts += stats[i].cf_packets;
837 printf("%6zu packets to schedule\n", total_pkts);
838 printf("%6zu bytes in total\n", total_len);
839 printf("Running! Hang up with ^C!\n\n");
840 fflush(stdout);
843 sock = pf_socket();
845 if (slow)
846 xmit_slowpath_or_die(ctx, cpu, orig_num);
847 else
848 xmit_fastpath_or_die(ctx, cpu, orig_num);
850 close(sock);
852 cleanup_packets();
855 static unsigned int generate_srand_seed(void)
857 int fd;
858 unsigned int seed;
860 fd = open("/dev/urandom", O_RDONLY);
861 if (fd < 0)
862 return time(0);
864 read_or_die(fd, &seed, sizeof(seed));
866 close(fd);
867 return seed;
870 int main(int argc, char **argv)
872 bool slow = false, invoke_cpp = false, reseed = true;
873 int c, opt_index, i, j, vals[4] = {0}, irq;
874 char *confname = NULL, *ptr;
875 unsigned long cpus_tmp, orig_num = 0;
876 unsigned long long tx_packets, tx_bytes;
877 struct ctx ctx;
879 fmemset(&ctx, 0, sizeof(ctx));
880 ctx.cpus = get_number_cpus_online();
881 ctx.uid = getuid();
882 ctx.gid = getgid();
884 while ((c = getopt_long(argc, argv, short_options, long_options,
885 &opt_index)) != EOF) {
886 switch (c) {
887 case 'h':
888 help();
889 break;
890 case 'v':
891 version();
892 break;
893 case 'e':
894 example();
895 break;
896 case 'p':
897 invoke_cpp = true;
898 break;
899 case 'V':
900 ctx.verbose = true;
901 break;
902 case 'P':
903 cpus_tmp = strtoul(optarg, NULL, 0);
904 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
905 ctx.cpus = cpus_tmp;
906 break;
907 case 'd':
908 case 'o':
909 ctx.device = xstrndup(optarg, IFNAMSIZ);
910 break;
911 case 'r':
912 ctx.rand = true;
913 break;
914 case 's':
915 slow = true;
916 ctx.cpus = 1;
917 ctx.smoke_test = true;
918 ctx.rhost = xstrdup(optarg);
919 break;
920 case 'R':
921 ctx.rfraw = true;
922 break;
923 case 'J':
924 ctx.jumbo_support = true;
925 break;
926 case 'c':
927 case 'i':
928 confname = xstrdup(optarg);
929 if (!strncmp("-", confname, strlen("-")))
930 ctx.cpus = 1;
931 break;
932 case 'u':
933 ctx.uid = strtoul(optarg, NULL, 0);
934 ctx.enforce = true;
935 break;
936 case 'g':
937 ctx.gid = strtoul(optarg, NULL, 0);
938 ctx.enforce = true;
939 break;
940 case 'k':
941 ctx.kpull = strtoul(optarg, NULL, 0);
942 break;
943 case 'E':
944 seed = strtoul(optarg, NULL, 0);
945 reseed = false;
946 break;
947 case 'n':
948 orig_num = strtoul(optarg, NULL, 0);
949 ctx.num = orig_num;
950 break;
951 case 't':
952 slow = true;
953 ctx.gap = strtoul(optarg, NULL, 0);
954 if (ctx.gap > 0)
955 /* Fall back to single core to not
956 * mess up correct timing. We are slow
957 * anyway!
959 ctx.cpus = 1;
960 break;
961 case 'S':
962 ptr = optarg;
963 ctx.reserve_size = 0;
965 for (j = i = strlen(optarg); i > 0; --i) {
966 if (!isdigit(optarg[j - i]))
967 break;
968 ptr++;
971 if (!strncmp(ptr, "KiB", strlen("KiB")))
972 ctx.reserve_size = 1 << 10;
973 else if (!strncmp(ptr, "MiB", strlen("MiB")))
974 ctx.reserve_size = 1 << 20;
975 else if (!strncmp(ptr, "GiB", strlen("GiB")))
976 ctx.reserve_size = 1 << 30;
977 else
978 panic("Syntax error in ring size param!\n");
979 *ptr = 0;
981 ctx.reserve_size *= strtol(optarg, NULL, 0);
982 break;
983 case '?':
984 switch (optopt) {
985 case 'd':
986 case 'c':
987 case 'n':
988 case 'S':
989 case 's':
990 case 'P':
991 case 'o':
992 case 'E':
993 case 'i':
994 case 'k':
995 case 'u':
996 case 'g':
997 case 't':
998 panic("Option -%c requires an argument!\n",
999 optopt);
1000 default:
1001 if (isprint(optopt))
1002 printf("Unknown option character `0x%X\'!\n", optopt);
1003 die();
1005 default:
1006 break;
1010 if (argc < 5)
1011 help();
1012 if (ctx.device == NULL)
1013 panic("No networking device given!\n");
1014 if (confname == NULL)
1015 panic("No configuration file given!\n");
1016 if (device_mtu(ctx.device) == 0)
1017 panic("This is no networking device!\n");
1019 register_signal(SIGINT, signal_handler);
1020 register_signal(SIGHUP, signal_handler);
1021 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1023 set_system_socket_memory(vals, array_size(vals));
1024 xlockme();
1026 if (ctx.rfraw) {
1027 ctx.device_trans = xstrdup(ctx.device);
1028 xfree(ctx.device);
1030 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1031 sleep(0);
1034 irq = device_irq_number(ctx.device);
1035 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1037 stats = setup_shared_var(ctx.cpus);
1039 for (i = 0; i < ctx.cpus; i++) {
1040 pid_t pid = fork();
1042 switch (pid) {
1043 case 0:
1044 if (reseed)
1045 seed = generate_srand_seed();
1046 srand(seed);
1048 cpu_affinity(i);
1049 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1051 goto thread_out;
1052 case -1:
1053 panic("Cannot fork processes!\n");
1057 for (i = 0; i < ctx.cpus; i++) {
1058 int status;
1060 wait(&status);
1061 if (WEXITSTATUS(status) == EXIT_FAILURE)
1062 die();
1065 if (ctx.rfraw)
1066 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1068 reset_system_socket_memory(vals, array_size(vals));
1070 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1071 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1072 sched_yield();
1074 tx_packets += stats[i].tx_packets;
1075 tx_bytes += stats[i].tx_bytes;
1078 fflush(stdout);
1079 printf("\n");
1080 printf("\r%12llu packets outgoing\n", tx_packets);
1081 printf("\r%12llu bytes outgoing\n", tx_bytes);
1082 for (i = 0; i < ctx.cpus; i++) {
1083 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1084 stats[i].tv_sec, stats[i].tv_usec, i,
1085 stats[i].tx_packets);
1088 thread_out:
1089 xunlockme();
1090 destroy_shared_var(stats, ctx.cpus);
1091 device_restore_irq_affinity_list();
1093 free(ctx.device);
1094 free(ctx.device_trans);
1095 free(ctx.rhost);
1096 free(confname);
1098 return 0;