dev: mark paths likely/unlikely
[netsniff-ng.git] / trafgen.c
blob762d0f994abc9917a4a13e5dd16eb17af21f89e1
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(59),\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));
345 if (unlikely(csum->to >= packets[i].len))
346 csum->to = packets[i].len - 1;
348 switch (csum->which) {
349 case CSUM_IP:
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;
365 default:
366 bug();
367 break;
370 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
374 static struct cpu_stats *setup_shared_var(unsigned long cpus)
376 int fd;
377 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
378 struct cpu_stats *buff;
380 fmemset(zbuff, 0, sizeof(zbuff));
381 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
383 fd = creat(file, S_IRUSR | S_IWUSR);
384 bug_on(fd < 0);
385 close(fd);
387 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
388 S_IRUSR | S_IWUSR);
389 write_or_die(fd, zbuff, sizeof(zbuff));
391 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
392 MAP_SHARED, fd, 0);
393 if (buff == (void *) -1)
394 panic("Cannot setup shared variable!\n");
396 close(fd);
397 unlink(file);
399 memset(buff, 0, sizeof(zbuff));
401 return buff;
404 static void destroy_shared_var(void *buff, unsigned long cpus)
406 munmap(buff, cpus * sizeof(struct cpu_stats));
409 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
411 int i;
413 printf("{");
414 for (i = 0; i < len; ++i) {
415 if (i % 15 == 0)
416 printf("\n ");
417 printf("0x%02x, ", payload[i]);
419 printf("\n}\n");
420 fflush(stdout);
423 static int xmit_smoke_setup(struct ctx *ctx)
425 int icmp_sock, ret, ttl = 64;
426 struct icmp_filter filter;
428 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
429 if (icmp_sock < 0)
430 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
432 filter.data = ~(1 << ICMP_ECHOREPLY);
434 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
435 if (ret < 0)
436 panic("Cannot install filter!\n");
438 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
439 if (ret < 0)
440 panic("Cannot set TTL!\n");
442 memset(&ctx->dest, 0, sizeof(ctx->dest));
443 ctx->dest.sin_family = AF_INET;
444 ctx->dest.sin_port = 0;
446 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
447 if (ret < 0)
448 panic("Cannot resolv address!\n");
450 return icmp_sock;
453 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
455 int ret, i, j = 0, probes = 100;
456 short ident, cnt = 1, idstore[probes];
457 uint8_t outpack[512], *data;
458 struct icmphdr *icmp;
459 struct iphdr *ip;
460 size_t len = sizeof(*icmp) + 56;
461 struct sockaddr_in from;
462 socklen_t from_len;
463 struct pollfd fds = {
464 .fd = icmp_sock,
465 .events = POLLIN,
468 fmemset(idstore, 0, sizeof(idstore));
469 while (probes-- > 0) {
470 while ((ident = htons((short) rand())) == 0)
471 sleep(0);
472 idstore[j++] = ident;
474 memset(outpack, 0, sizeof(outpack));
475 icmp = (void *) outpack;
476 icmp->type = ICMP_ECHO;
477 icmp->un.echo.id = ident;
478 icmp->un.echo.sequence = htons(cnt++);
480 data = ((uint8_t *) outpack + sizeof(*icmp));
481 for (i = 0; i < 56; ++i)
482 data[i] = (uint8_t) rand();
484 icmp->checksum = csum((unsigned short *) outpack,
485 len / sizeof(unsigned short));
487 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
488 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
489 if (unlikely(ret != len))
490 panic("Cannot send out probe: %s!\n", strerror(errno));
492 ret = poll(&fds, 1, 50);
493 if (ret < 0)
494 panic("Poll failed!\n");
496 if (fds.revents & POLLIN) {
497 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
498 (struct sockaddr *) &from, &from_len);
499 if (unlikely(ret <= 0))
500 panic("Probe receive failed!\n");
501 if (unlikely(from_len != sizeof(ctx->dest)))
502 continue;
503 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
504 continue;
505 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
506 continue;
507 ip = (void *) outpack;
508 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
509 continue;
510 icmp = (void *) outpack + ip->ihl * 4;
511 for (i = 0; i < array_size(idstore); ++i) {
512 if (unlikely(icmp->un.echo.id != idstore[i]))
513 continue;
514 return 0;
519 return -1;
522 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
524 int ret, icmp_sock = -1;
525 unsigned long num = 1, i = 0;
526 struct timeval start, end, diff;
527 unsigned long long tx_bytes = 0, tx_packets = 0;
528 struct packet_dyn *pktd;
529 struct sockaddr_ll saddr = {
530 .sll_family = PF_PACKET,
531 .sll_halen = ETH_ALEN,
532 .sll_ifindex = device_ifindex(ctx->device),
535 if (ctx->num > 0)
536 num = ctx->num;
537 if (ctx->num == 0 && orig_num > 0)
538 num = 0;
540 if (ctx->smoke_test)
541 icmp_sock = xmit_smoke_setup(ctx);
543 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
545 bug_on(gettimeofday(&start, NULL));
547 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
548 pktd = &packet_dyn[i];
549 if (pktd->clen + pktd->rlen + pktd->slen) {
550 apply_counter(i);
551 apply_randomizer(i);
552 apply_csum16(i);
554 retry:
555 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
556 (struct sockaddr *) &saddr, sizeof(saddr));
557 if (unlikely(ret < 0)) {
558 if (errno == ENOBUFS) {
559 sched_yield();
560 goto retry;
563 panic("Sendto error: %s!\n", strerror(errno));
566 tx_bytes += packets[i].len;
567 tx_packets++;
569 if (ctx->smoke_test) {
570 ret = xmit_smoke_probe(icmp_sock, ctx);
571 if (unlikely(ret < 0)) {
572 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
573 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
574 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
575 i, seed);
577 dump_trafgen_snippet(packets[i].payload, packets[i].len);
578 break;
582 if (!ctx->rand) {
583 i++;
584 if (i >= plen)
585 i = 0;
586 } else
587 i = rand() % plen;
589 if (ctx->num > 0)
590 num--;
592 if (ctx->gap > 0)
593 usleep(ctx->gap);
596 bug_on(gettimeofday(&end, NULL));
597 timersub(&end, &start, &diff);
599 if (ctx->smoke_test)
600 close(icmp_sock);
602 stats[cpu].tx_packets = tx_packets;
603 stats[cpu].tx_bytes = tx_bytes;
604 stats[cpu].tv_sec = diff.tv_sec;
605 stats[cpu].tv_usec = diff.tv_usec;
607 stats[cpu].state |= CPU_STATS_STATE_RES;
610 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
612 int ifindex = device_ifindex(ctx->device);
613 uint8_t *out = NULL;
614 unsigned int it = 0;
615 unsigned long num = 1, i = 0, size;
616 struct ring tx_ring;
617 struct frame_map *hdr;
618 struct timeval start, end, diff;
619 struct packet_dyn *pktd;
620 unsigned long long tx_bytes = 0, tx_packets = 0;
622 fmemset(&tx_ring, 0, sizeof(tx_ring));
624 size = ring_size(ctx->device, ctx->reserve_size);
626 set_sock_prio(sock, 512);
627 set_packet_loss_discard(sock);
629 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
630 create_tx_ring(sock, &tx_ring, ctx->verbose);
631 mmap_tx_ring(sock, &tx_ring);
632 alloc_tx_ring_frames(sock, &tx_ring);
633 bind_tx_ring(sock, &tx_ring, ifindex);
635 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
637 if (ctx->kpull)
638 interval = ctx->kpull;
639 if (ctx->num > 0)
640 num = ctx->num;
641 if (ctx->num == 0 && orig_num > 0)
642 num = 0;
644 set_itimer_interval_value(&itimer, 0, interval);
645 setitimer(ITIMER_REAL, &itimer, NULL);
647 bug_on(gettimeofday(&start, NULL));
649 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
650 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
651 hdr = tx_ring.frames[it].iov_base;
652 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
654 hdr->tp_h.tp_snaplen = packets[i].len;
655 hdr->tp_h.tp_len = packets[i].len;
657 pktd = &packet_dyn[i];
658 if (pktd->clen + pktd->rlen + pktd->slen) {
659 apply_counter(i);
660 apply_randomizer(i);
661 apply_csum16(i);
664 fmemcpy(out, packets[i].payload, packets[i].len);
666 tx_bytes += packets[i].len;
667 tx_packets++;
669 if (!ctx->rand) {
670 i++;
671 if (i >= plen)
672 i = 0;
673 } else
674 i = rand() % plen;
676 kernel_may_pull_from_tx(&hdr->tp_h);
678 it++;
679 if (it >= tx_ring.layout.tp_frame_nr)
680 it = 0;
682 if (ctx->num > 0)
683 num--;
685 if (unlikely(sigint == 1))
686 break;
690 bug_on(gettimeofday(&end, NULL));
691 timersub(&end, &start, &diff);
693 timer_purge();
695 destroy_tx_ring(sock, &tx_ring);
697 stats[cpu].tx_packets = tx_packets;
698 stats[cpu].tx_bytes = tx_bytes;
699 stats[cpu].tv_sec = diff.tv_sec;
700 stats[cpu].tv_usec = diff.tv_usec;
702 stats[cpu].state |= CPU_STATS_STATE_RES;
705 static inline void __set_state(int cpu, sig_atomic_t s)
707 stats[cpu].state = s;
710 static inline sig_atomic_t __get_state(int cpu)
712 return stats[cpu].state;
715 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
717 int i;
718 unsigned long total;
720 for (i = 0, total = plen; i < ctx->cpus; i++) {
721 if (i == cpu)
722 continue;
724 while ((__get_state(i) &
725 (CPU_STATS_STATE_CFG |
726 CPU_STATS_STATE_RES)) == 0 &&
727 sigint == 0)
728 sched_yield();
730 total += stats[i].cf_packets;
733 return total;
736 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
738 int i, cpu_sel;
739 unsigned long total;
740 long long delta_correction = 0;
742 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
743 if (i == cpu)
744 continue;
746 while ((__get_state(i) &
747 (CPU_STATS_STATE_CHK |
748 CPU_STATS_STATE_RES)) == 0 &&
749 sigint == 0)
750 sched_yield();
752 total += stats[i].cd_packets;
755 if (total > orig)
756 delta_correction = -1 * ((long long) total - orig);
757 if (total < orig)
758 delta_correction = +1 * ((long long) orig - total);
760 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
761 if (stats[i].cd_packets > 0) {
762 if ((long long) stats[i].cd_packets +
763 delta_correction >= 0) {
764 cpu_sel = i;
765 break;
770 if (cpu == cpu_sel)
771 ctx->num += delta_correction;
774 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
775 sig_atomic_t s)
777 stats[cpu].cf_packets = p;
778 stats[cpu].cf_bytes = b;
779 stats[cpu].state = s;
782 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
784 stats[cpu].cd_packets = p;
785 stats[cpu].state = s;
788 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
790 int i;
791 unsigned long plen_total, orig = ctx->num;
792 size_t mtu, total_len = 0;
794 bug_on(plen != dlen);
796 for (i = 0; i < plen; ++i)
797 total_len += packets[i].len;
799 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
800 plen_total = __wait_and_sum_others(ctx, cpu);
802 if (orig > 0) {
803 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
805 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
806 CPU_STATS_STATE_CFG);
807 __correct_global_delta(ctx, cpu, orig);
810 if (plen == 0) {
811 __set_state(cpu, CPU_STATS_STATE_RES);
812 return 0;
815 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
816 if (packets[i].len > mtu + 14)
817 panic("Device MTU < than packet%d's size!\n", i);
818 if (packets[i].len <= 14)
819 panic("Packet%d's size too short!\n", i);
822 return 0;
825 static void main_loop(struct ctx *ctx, char *confname, bool slow,
826 int cpu, bool invoke_cpp, unsigned long orig_num)
828 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
829 if (xmit_packet_precheck(ctx, cpu) < 0)
830 return;
832 if (cpu == 0) {
833 int i;
834 size_t total_len = 0, total_pkts = 0;
836 for (i = 0; i < ctx->cpus; ++i) {
837 total_len += stats[i].cf_bytes;
838 total_pkts += stats[i].cf_packets;
841 printf("%6zu packets to schedule\n", total_pkts);
842 printf("%6zu bytes in total\n", total_len);
843 printf("Running! Hang up with ^C!\n\n");
844 fflush(stdout);
847 sock = pf_socket();
849 if (slow)
850 xmit_slowpath_or_die(ctx, cpu, orig_num);
851 else
852 xmit_fastpath_or_die(ctx, cpu, orig_num);
854 close(sock);
856 cleanup_packets();
859 static unsigned int generate_srand_seed(void)
861 int fd;
862 unsigned int seed;
864 fd = open("/dev/urandom", O_RDONLY);
865 if (fd < 0)
866 return time(0);
868 read_or_die(fd, &seed, sizeof(seed));
870 close(fd);
871 return seed;
874 int main(int argc, char **argv)
876 bool slow = false, invoke_cpp = false, reseed = true;
877 int c, opt_index, i, j, vals[4] = {0}, irq;
878 char *confname = NULL, *ptr;
879 unsigned long cpus_tmp, orig_num = 0;
880 unsigned long long tx_packets, tx_bytes;
881 struct ctx ctx;
883 fmemset(&ctx, 0, sizeof(ctx));
884 ctx.cpus = get_number_cpus_online();
885 ctx.uid = getuid();
886 ctx.gid = getgid();
888 while ((c = getopt_long(argc, argv, short_options, long_options,
889 &opt_index)) != EOF) {
890 switch (c) {
891 case 'h':
892 help();
893 break;
894 case 'v':
895 version();
896 break;
897 case 'e':
898 example();
899 break;
900 case 'p':
901 invoke_cpp = true;
902 break;
903 case 'V':
904 ctx.verbose = true;
905 break;
906 case 'P':
907 cpus_tmp = strtoul(optarg, NULL, 0);
908 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
909 ctx.cpus = cpus_tmp;
910 break;
911 case 'd':
912 case 'o':
913 ctx.device = xstrndup(optarg, IFNAMSIZ);
914 break;
915 case 'r':
916 ctx.rand = true;
917 break;
918 case 's':
919 slow = true;
920 ctx.cpus = 1;
921 ctx.smoke_test = true;
922 ctx.rhost = xstrdup(optarg);
923 break;
924 case 'R':
925 ctx.rfraw = true;
926 break;
927 case 'J':
928 ctx.jumbo_support = true;
929 break;
930 case 'c':
931 case 'i':
932 confname = xstrdup(optarg);
933 if (!strncmp("-", confname, strlen("-")))
934 ctx.cpus = 1;
935 break;
936 case 'u':
937 ctx.uid = strtoul(optarg, NULL, 0);
938 ctx.enforce = true;
939 break;
940 case 'g':
941 ctx.gid = strtoul(optarg, NULL, 0);
942 ctx.enforce = true;
943 break;
944 case 'k':
945 ctx.kpull = strtoul(optarg, NULL, 0);
946 break;
947 case 'E':
948 seed = strtoul(optarg, NULL, 0);
949 reseed = false;
950 break;
951 case 'n':
952 orig_num = strtoul(optarg, NULL, 0);
953 ctx.num = orig_num;
954 break;
955 case 't':
956 slow = true;
957 ctx.gap = strtoul(optarg, NULL, 0);
958 if (ctx.gap > 0)
959 /* Fall back to single core to not
960 * mess up correct timing. We are slow
961 * anyway!
963 ctx.cpus = 1;
964 break;
965 case 'S':
966 ptr = optarg;
967 ctx.reserve_size = 0;
969 for (j = i = strlen(optarg); i > 0; --i) {
970 if (!isdigit(optarg[j - i]))
971 break;
972 ptr++;
975 if (!strncmp(ptr, "KiB", strlen("KiB")))
976 ctx.reserve_size = 1 << 10;
977 else if (!strncmp(ptr, "MiB", strlen("MiB")))
978 ctx.reserve_size = 1 << 20;
979 else if (!strncmp(ptr, "GiB", strlen("GiB")))
980 ctx.reserve_size = 1 << 30;
981 else
982 panic("Syntax error in ring size param!\n");
983 *ptr = 0;
985 ctx.reserve_size *= strtol(optarg, NULL, 0);
986 break;
987 case '?':
988 switch (optopt) {
989 case 'd':
990 case 'c':
991 case 'n':
992 case 'S':
993 case 's':
994 case 'P':
995 case 'o':
996 case 'E':
997 case 'i':
998 case 'k':
999 case 'u':
1000 case 'g':
1001 case 't':
1002 panic("Option -%c requires an argument!\n",
1003 optopt);
1004 default:
1005 if (isprint(optopt))
1006 printf("Unknown option character `0x%X\'!\n", optopt);
1007 die();
1009 default:
1010 break;
1014 if (argc < 5)
1015 help();
1016 if (ctx.device == NULL)
1017 panic("No networking device given!\n");
1018 if (confname == NULL)
1019 panic("No configuration file given!\n");
1020 if (device_mtu(ctx.device) == 0)
1021 panic("This is no networking device!\n");
1023 register_signal(SIGINT, signal_handler);
1024 register_signal(SIGHUP, signal_handler);
1025 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1027 set_system_socket_memory(vals, array_size(vals));
1028 xlockme();
1030 if (ctx.rfraw) {
1031 ctx.device_trans = xstrdup(ctx.device);
1032 xfree(ctx.device);
1034 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1035 sleep(0);
1038 irq = device_irq_number(ctx.device);
1039 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1041 stats = setup_shared_var(ctx.cpus);
1043 for (i = 0; i < ctx.cpus; i++) {
1044 pid_t pid = fork();
1046 switch (pid) {
1047 case 0:
1048 if (reseed)
1049 seed = generate_srand_seed();
1050 srand(seed);
1052 cpu_affinity(i);
1053 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1055 goto thread_out;
1056 case -1:
1057 panic("Cannot fork processes!\n");
1061 for (i = 0; i < ctx.cpus; i++) {
1062 int status;
1064 wait(&status);
1065 if (WEXITSTATUS(status) == EXIT_FAILURE)
1066 die();
1069 if (ctx.rfraw)
1070 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1072 reset_system_socket_memory(vals, array_size(vals));
1074 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1075 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1076 sched_yield();
1078 tx_packets += stats[i].tx_packets;
1079 tx_bytes += stats[i].tx_bytes;
1082 fflush(stdout);
1083 printf("\n");
1084 printf("\r%12llu packets outgoing\n", tx_packets);
1085 printf("\r%12llu bytes outgoing\n", tx_bytes);
1086 for (i = 0; i < ctx.cpus; i++) {
1087 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1088 stats[i].tv_sec, stats[i].tv_usec, i,
1089 stats[i].tx_packets);
1092 thread_out:
1093 xunlockme();
1094 destroy_shared_var(stats, ctx.cpus);
1095 device_restore_irq_affinity_list();
1097 free(ctx.device);
1098 free(ctx.device_trans);
1099 free(ctx.rhost);
1100 free(confname);
1102 return 0;