rnd: Fix compiler warning
[netsniff-ng.git] / trafgen.c
blob7d51746a9ffec95de30c9841ae3c80dbce20f711
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;
59 unsigned long kpull, num, gap, reserve_size, cpus;
60 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
61 struct sockaddr_in dest;
64 struct cpu_stats {
65 unsigned long tv_sec, tv_usec;
66 unsigned long long tx_packets, tx_bytes;
67 unsigned long long cf_packets, cf_bytes;
68 unsigned long long cd_packets;
69 sig_atomic_t state;
72 static sig_atomic_t sigint = 0;
74 struct packet *packets = NULL;
75 size_t plen = 0;
77 struct packet_dyn *packet_dyn = NULL;
78 size_t dlen = 0;
80 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:C";
81 static const struct option long_options[] = {
82 {"dev", required_argument, NULL, 'd'},
83 {"out", required_argument, NULL, 'o'},
84 {"in", required_argument, NULL, 'i'},
85 {"conf", required_argument, NULL, 'c'},
86 {"num", required_argument, NULL, 'n'},
87 {"gap", required_argument, NULL, 't'},
88 {"cpus", required_argument, NULL, 'P'},
89 {"ring-size", required_argument, NULL, 'S'},
90 {"kernel-pull", required_argument, NULL, 'k'},
91 {"smoke-test", required_argument, NULL, 's'},
92 {"seed", required_argument, NULL, 'E'},
93 {"user", required_argument, NULL, 'u'},
94 {"group", required_argument, NULL, 'g'},
95 {"jumbo-support", no_argument, NULL, 'J'},
96 {"no-cpu-stats", no_argument, NULL, 'C'},
97 {"cpp", no_argument, NULL, 'p'},
98 {"rfraw", no_argument, NULL, 'R'},
99 {"rand", no_argument, NULL, 'r'},
100 {"verbose", no_argument, NULL, 'V'},
101 {"version", no_argument, NULL, 'v'},
102 {"example", no_argument, NULL, 'e'},
103 {"help", no_argument, NULL, 'h'},
104 {NULL, 0, NULL, 0}
107 static int sock;
108 static struct itimerval itimer;
109 static unsigned long interval = TX_KERNEL_PULL_INT;
110 static struct cpu_stats *stats;
111 static unsigned int seed;
113 #define CPU_STATS_STATE_CFG 1
114 #define CPU_STATS_STATE_CHK 2
115 #define CPU_STATS_STATE_RES 4
117 #ifndef ICMP_FILTER
118 # define ICMP_FILTER 1
120 struct icmp_filter {
121 __u32 data;
123 #endif
125 static void signal_handler(int number)
127 switch (number) {
128 case SIGINT:
129 sigint = 1;
130 case SIGHUP:
131 default:
132 break;
136 static void timer_elapsed(int number)
138 int ret = pull_and_flush_tx_ring(sock);
139 if (unlikely(ret < 0)) {
140 /* We could hit EBADF if the socket has been closed before
141 * the timer was triggered.
143 if (errno != EBADF && errno != ENOBUFS)
144 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
147 set_itimer_interval_value(&itimer, 0, interval);
148 setitimer(ITIMER_REAL, &itimer, NULL);
151 static void timer_purge(void)
153 int ret;
155 ret = pull_and_flush_tx_ring_wait(sock);
156 if (unlikely(ret < 0)) {
157 /* We could hit EBADF if the socket has been closed before
158 * the timer was triggered.
160 if (errno != EBADF && errno != ENOBUFS)
161 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
164 set_itimer_interval_value(&itimer, 0, 0);
165 setitimer(ITIMER_REAL, &itimer, NULL);
168 static void __noreturn help(void)
170 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
171 puts("http://www.netsniff-ng.org\n\n"
172 "Usage: trafgen [options]\n"
173 "Options:\n"
174 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
175 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
176 " -p|--cpp Run packet config through C preprocessor\n"
177 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
178 " -R|--rfraw Inject raw 802.11 frames\n"
179 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
180 " -n|--num <uint> Number of packets until exit (def: 0)\n"
181 " -r|--rand Randomize packet selection (def: round robin)\n"
182 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
183 " -t|--gap <uint> Interpacket gap in us (approx)\n"
184 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
185 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
186 " -E|--seed <uint> Manually set srand(3) seed\n"
187 " -u|--user <userid> Drop privileges and change to userid\n"
188 " -g|--group <groupid> Drop privileges and change to groupid\n"
189 " -V|--verbose Be more verbose\n"
190 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
191 " -v|--version Show version and exit\n"
192 " -e|--example Show built-in packet config example\n"
193 " -h|--help Guess what?!\n\n"
194 "Examples:\n"
195 " See trafgen.txf for configuration file examples.\n"
196 " trafgen --dev eth0 --conf trafgen.cfg\n"
197 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
198 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
199 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
200 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
201 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
202 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
203 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
204 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
205 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
206 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
207 "Note:\n"
208 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
209 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
210 " we assume the kernel crashed, thus we print the packet and quit.\n"
211 " In case you find a ping-of-death, please mention trafgen in your\n"
212 " commit message of the fix!\n\n"
213 " For introducing bit errors, delays with random variation and more,\n"
214 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
215 " For generating different package distributions, you can use scripting\n"
216 " to generate a trafgen config file with packet ratios as:\n\n"
217 " IMIX 64:7, 570:4, 1518:1\n"
218 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
219 " Cisco 64:7, 594:4, 1518:1\n"
220 " RPR Trimodal 64:60, 512:20, 1518:20\n"
221 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
222 "Please report bugs to <bugs@netsniff-ng.org>\n"
223 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
224 "Swiss federal institute of technology (ETH Zurich)\n"
225 "License: GNU GPL version 2.0\n"
226 "This is free software: you are free to change and redistribute it.\n"
227 "There is NO WARRANTY, to the extent permitted by law.\n");
228 die();
231 static void __noreturn example(void)
233 const char *e =
234 "/* Note: dynamic elements make trafgen slower! */\n"
235 "#include <stddef.h>\n\n"
236 "{\n"
237 " /* MAC Destination */\n"
238 " fill(0xff, ETH_ALEN),\n"
239 " /* MAC Source */\n"
240 " 0x00, 0x02, 0xb3, drnd(3),\n"
241 " /* IPv4 Protocol */\n"
242 " c16(ETH_P_IP),\n"
243 " /* IPv4 Version, IHL, TOS */\n"
244 " 0b01000101, 0,\n"
245 " /* IPv4 Total Len */\n"
246 " c16(59),\n"
247 " /* IPv4 Ident */\n"
248 " drnd(2),\n"
249 " /* IPv4 Flags, Frag Off */\n"
250 " 0b01000000, 0,\n"
251 " /* IPv4 TTL */\n"
252 " 64,\n"
253 " /* Proto TCP */\n"
254 " 0x06,\n"
255 " /* IPv4 Checksum (IP header from, to) */\n"
256 " csumip(14, 33),\n"
257 " /* Source IP */\n"
258 " drnd(4),\n"
259 " /* Dest IP */\n"
260 " drnd(4),\n"
261 " /* TCP Source Port */\n"
262 " drnd(2),\n"
263 " /* TCP Dest Port */\n"
264 " c16(80),\n"
265 " /* TCP Sequence Number */\n"
266 " drnd(4),\n"
267 " /* TCP Ackn. Number */\n"
268 " c32(0),\n"
269 " /* TCP Header length + TCP SYN/ECN Flag */\n"
270 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
271 " /* Window Size */\n"
272 " c16(16),\n"
273 " /* TCP Checksum (offset IP, offset TCP) */\n"
274 " csumtcp(14, 34),\n"
275 " /* TCP Options */\n"
276 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
277 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
278 " /* Data blob */\n"
279 " \"gotcha!\",\n"
280 "}";
281 puts(e);
282 die();
285 static void __noreturn version(void)
287 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
288 puts("multithreaded zero-copy network packet generator\n"
289 "http://www.netsniff-ng.org\n\n"
290 "Please report bugs to <bugs@netsniff-ng.org>\n"
291 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
292 "Swiss federal institute of technology (ETH Zurich)\n"
293 "License: GNU GPL version 2.0\n"
294 "This is free software: you are free to change and redistribute it.\n"
295 "There is NO WARRANTY, to the extent permitted by law.\n");
296 die();
299 static void apply_counter(int id)
301 size_t j, counter_max = packet_dyn[id].clen;
303 for (j = 0; j < counter_max; ++j) {
304 uint8_t val;
305 struct counter *counter = &packet_dyn[id].cnt[j];
307 val = counter->val - counter->min;
309 switch (counter->type) {
310 case TYPE_INC:
311 val = (val + counter->inc) % (counter->max - counter->min + 1);
312 break;
313 case TYPE_DEC:
314 val = (val - counter->inc) % (counter->min - counter->max + 1);
315 break;
316 default:
317 bug();
320 counter->val = val + counter->min;
321 packets[id].payload[counter->off] = val;
325 static void apply_randomizer(int id)
327 size_t j, rand_max = packet_dyn[id].rlen;
329 for (j = 0; j < rand_max; ++j) {
330 uint8_t val = (uint8_t) rand();
331 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
333 packets[id].payload[randomizer->off] = val;
337 static void apply_csum16(int id)
339 size_t j, csum_max = packet_dyn[id].slen;
341 for (j = 0; j < csum_max; ++j) {
342 uint16_t sum = 0;
343 struct csum16 *csum = &packet_dyn[id].csum[j];
345 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
346 if (unlikely(csum->to >= packets[id].len))
347 csum->to = packets[id].len - 1;
349 switch (csum->which) {
350 case CSUM_IP:
351 sum = calc_csum(packets[id].payload + csum->from,
352 csum->to - csum->from + 1, 0);
353 break;
354 case CSUM_UDP:
355 sum = p4_csum((void *) packets[id].payload + csum->from,
356 packets[id].payload + csum->to,
357 (packets[id].len - csum->to),
358 IPPROTO_UDP);
359 break;
360 case CSUM_TCP:
361 sum = p4_csum((void *) packets[id].payload + csum->from,
362 packets[id].payload + csum->to,
363 (packets[id].len - csum->to),
364 IPPROTO_TCP);
365 break;
366 default:
367 bug();
368 break;
371 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
375 static struct cpu_stats *setup_shared_var(unsigned long cpus)
377 int fd;
378 size_t len = cpus * sizeof(struct cpu_stats);
379 char zbuff[len], file[256];
380 struct cpu_stats *buff;
382 fmemset(zbuff, 0, len);
383 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
385 fd = creat(file, S_IRUSR | S_IWUSR);
386 bug_on(fd < 0);
387 close(fd);
389 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
390 S_IRUSR | S_IWUSR);
391 write_or_die(fd, zbuff, len);
393 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
394 MAP_SHARED, fd, 0);
395 if (buff == MAP_FAILED)
396 panic("Cannot setup shared variable!\n");
398 close(fd);
399 unlink(file);
401 memset(buff, 0, len);
402 return buff;
405 static void destroy_shared_var(void *buff, unsigned long cpus)
407 munmap(buff, cpus * sizeof(struct cpu_stats));
410 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
412 int i;
414 printf("{");
415 for (i = 0; i < len; ++i) {
416 if (i % 15 == 0)
417 printf("\n ");
418 printf("0x%02x, ", payload[i]);
420 printf("\n}\n");
421 fflush(stdout);
424 static int xmit_smoke_setup(struct ctx *ctx)
426 int icmp_sock, ret, ttl = 64;
427 struct icmp_filter filter;
429 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
430 if (icmp_sock < 0)
431 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
433 filter.data = ~(1 << ICMP_ECHOREPLY);
435 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
436 if (ret < 0)
437 panic("Cannot install filter!\n");
439 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
440 if (ret < 0)
441 panic("Cannot set TTL!\n");
443 memset(&ctx->dest, 0, sizeof(ctx->dest));
444 ctx->dest.sin_family = AF_INET;
445 ctx->dest.sin_port = 0;
447 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
448 if (ret < 0)
449 panic("Cannot resolv address!\n");
451 return icmp_sock;
454 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
456 int ret, i, j = 0, probes = 100;
457 short ident, cnt = 1, idstore[probes];
458 uint8_t outpack[512], *data;
459 struct icmphdr *icmp;
460 struct iphdr *ip;
461 size_t len = sizeof(*icmp) + 56;
462 struct sockaddr_in from;
463 socklen_t from_len;
464 struct pollfd fds = {
465 .fd = icmp_sock,
466 .events = POLLIN,
469 fmemset(idstore, 0, sizeof(idstore));
470 while (probes-- > 0) {
471 while ((ident = htons((short) rand())) == 0)
472 sleep(0);
473 idstore[j++] = ident;
475 memset(outpack, 0, sizeof(outpack));
476 icmp = (void *) outpack;
477 icmp->type = ICMP_ECHO;
478 icmp->un.echo.id = ident;
479 icmp->un.echo.sequence = htons(cnt++);
481 data = ((uint8_t *) outpack + sizeof(*icmp));
482 for (i = 0; i < 56; ++i)
483 data[i] = (uint8_t) rand();
485 icmp->checksum = csum((unsigned short *) outpack,
486 len / sizeof(unsigned short));
488 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
489 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
490 if (unlikely(ret != len))
491 panic("Cannot send out probe: %s!\n", strerror(errno));
493 ret = poll(&fds, 1, 50);
494 if (ret < 0)
495 panic("Poll failed!\n");
497 if (fds.revents & POLLIN) {
498 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
499 (struct sockaddr *) &from, &from_len);
500 if (unlikely(ret <= 0))
501 panic("Probe receive failed!\n");
502 if (unlikely(from_len != sizeof(ctx->dest)))
503 continue;
504 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
505 continue;
506 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
507 continue;
508 ip = (void *) outpack;
509 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
510 continue;
511 icmp = (void *) outpack + ip->ihl * 4;
512 for (i = 0; i < array_size(idstore); ++i) {
513 if (unlikely(icmp->un.echo.id != idstore[i]))
514 continue;
515 return 0;
520 return -1;
523 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
525 int ret, icmp_sock = -1;
526 unsigned long num = 1, i = 0;
527 struct timeval start, end, diff;
528 unsigned long long tx_bytes = 0, tx_packets = 0;
529 struct packet_dyn *pktd;
530 struct sockaddr_ll saddr = {
531 .sll_family = PF_PACKET,
532 .sll_halen = ETH_ALEN,
533 .sll_ifindex = device_ifindex(ctx->device),
536 if (ctx->num > 0)
537 num = ctx->num;
538 if (ctx->num == 0 && orig_num > 0)
539 num = 0;
541 if (ctx->smoke_test)
542 icmp_sock = xmit_smoke_setup(ctx);
544 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
546 bug_on(gettimeofday(&start, NULL));
548 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
549 pktd = &packet_dyn[i];
550 if (pktd->clen + pktd->rlen + pktd->slen) {
551 apply_counter(i);
552 apply_randomizer(i);
553 apply_csum16(i);
555 retry:
556 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
557 (struct sockaddr *) &saddr, sizeof(saddr));
558 if (unlikely(ret < 0)) {
559 if (errno == ENOBUFS) {
560 sched_yield();
561 goto retry;
564 panic("Sendto error: %s!\n", strerror(errno));
567 tx_bytes += packets[i].len;
568 tx_packets++;
570 if (ctx->smoke_test) {
571 ret = xmit_smoke_probe(icmp_sock, ctx);
572 if (unlikely(ret < 0)) {
573 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
574 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
575 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
576 i, seed);
578 dump_trafgen_snippet(packets[i].payload, packets[i].len);
579 break;
583 if (!ctx->rand) {
584 i++;
585 if (i >= plen)
586 i = 0;
587 } else
588 i = rand() % plen;
590 if (ctx->num > 0)
591 num--;
593 if (ctx->gap > 0)
594 usleep(ctx->gap);
597 bug_on(gettimeofday(&end, NULL));
598 timersub(&end, &start, &diff);
600 if (ctx->smoke_test)
601 close(icmp_sock);
603 stats[cpu].tx_packets = tx_packets;
604 stats[cpu].tx_bytes = tx_bytes;
605 stats[cpu].tv_sec = diff.tv_sec;
606 stats[cpu].tv_usec = diff.tv_usec;
608 stats[cpu].state |= CPU_STATS_STATE_RES;
611 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
613 int ifindex = device_ifindex(ctx->device);
614 uint8_t *out = NULL;
615 unsigned int it = 0;
616 unsigned long num = 1, i = 0, size;
617 struct ring tx_ring;
618 struct frame_map *hdr;
619 struct timeval start, end, diff;
620 struct packet_dyn *pktd;
621 unsigned long long tx_bytes = 0, tx_packets = 0;
623 fmemset(&tx_ring, 0, sizeof(tx_ring));
625 size = ring_size(ctx->device, ctx->reserve_size);
627 set_sock_prio(sock, 512);
628 set_packet_loss_discard(sock);
630 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
631 create_tx_ring(sock, &tx_ring, ctx->verbose);
632 mmap_tx_ring(sock, &tx_ring);
633 alloc_tx_ring_frames(sock, &tx_ring);
634 bind_tx_ring(sock, &tx_ring, ifindex);
636 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
638 if (ctx->kpull)
639 interval = ctx->kpull;
640 if (ctx->num > 0)
641 num = ctx->num;
642 if (ctx->num == 0 && orig_num > 0)
643 num = 0;
645 set_itimer_interval_value(&itimer, 0, interval);
646 setitimer(ITIMER_REAL, &itimer, NULL);
648 bug_on(gettimeofday(&start, NULL));
650 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
651 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
652 hdr = tx_ring.frames[it].iov_base;
653 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
655 hdr->tp_h.tp_snaplen = packets[i].len;
656 hdr->tp_h.tp_len = packets[i].len;
658 pktd = &packet_dyn[i];
659 if (pktd->clen + pktd->rlen + pktd->slen) {
660 apply_counter(i);
661 apply_randomizer(i);
662 apply_csum16(i);
665 fmemcpy(out, packets[i].payload, packets[i].len);
667 tx_bytes += packets[i].len;
668 tx_packets++;
670 if (!ctx->rand) {
671 i++;
672 if (i >= plen)
673 i = 0;
674 } else
675 i = rand() % plen;
677 kernel_may_pull_from_tx(&hdr->tp_h);
679 it++;
680 if (it >= tx_ring.layout.tp_frame_nr)
681 it = 0;
683 if (ctx->num > 0)
684 num--;
686 if (unlikely(sigint == 1))
687 break;
691 bug_on(gettimeofday(&end, NULL));
692 timersub(&end, &start, &diff);
694 timer_purge();
696 destroy_tx_ring(sock, &tx_ring);
698 stats[cpu].tx_packets = tx_packets;
699 stats[cpu].tx_bytes = tx_bytes;
700 stats[cpu].tv_sec = diff.tv_sec;
701 stats[cpu].tv_usec = diff.tv_usec;
703 stats[cpu].state |= CPU_STATS_STATE_RES;
706 static inline void __set_state(int cpu, sig_atomic_t s)
708 stats[cpu].state = s;
711 static inline sig_atomic_t __get_state(int cpu)
713 return stats[cpu].state;
716 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
718 int i;
719 unsigned long total;
721 for (i = 0, total = plen; i < ctx->cpus; i++) {
722 if (i == cpu)
723 continue;
725 while ((__get_state(i) &
726 (CPU_STATS_STATE_CFG |
727 CPU_STATS_STATE_RES)) == 0 &&
728 sigint == 0)
729 sched_yield();
731 total += stats[i].cf_packets;
734 return total;
737 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
739 int i, cpu_sel;
740 unsigned long total;
741 long long delta_correction = 0;
743 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
744 if (i == cpu)
745 continue;
747 while ((__get_state(i) &
748 (CPU_STATS_STATE_CHK |
749 CPU_STATS_STATE_RES)) == 0 &&
750 sigint == 0)
751 sched_yield();
753 total += stats[i].cd_packets;
756 if (total > orig)
757 delta_correction = -1 * ((long long) total - orig);
758 if (total < orig)
759 delta_correction = +1 * ((long long) orig - total);
761 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
762 if (stats[i].cd_packets > 0) {
763 if ((long long) stats[i].cd_packets +
764 delta_correction >= 0) {
765 cpu_sel = i;
766 break;
771 if (cpu == cpu_sel)
772 ctx->num += delta_correction;
775 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
776 sig_atomic_t s)
778 stats[cpu].cf_packets = p;
779 stats[cpu].cf_bytes = b;
780 stats[cpu].state = s;
783 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
785 stats[cpu].cd_packets = p;
786 stats[cpu].state = s;
789 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
791 int i;
792 unsigned long plen_total, orig = ctx->num;
793 size_t mtu, total_len = 0;
795 bug_on(plen != dlen);
797 for (i = 0; i < plen; ++i)
798 total_len += packets[i].len;
800 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
801 plen_total = __wait_and_sum_others(ctx, cpu);
803 if (orig > 0) {
804 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
806 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
807 CPU_STATS_STATE_CFG);
808 __correct_global_delta(ctx, cpu, orig);
811 if (plen == 0) {
812 __set_state(cpu, CPU_STATS_STATE_RES);
813 return 0;
816 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
817 if (packets[i].len > mtu + 14)
818 panic("Device MTU < than packet%d's size!\n", i);
819 if (packets[i].len <= 14)
820 panic("Packet%d's size too short!\n", i);
823 return 0;
826 static void main_loop(struct ctx *ctx, char *confname, bool slow,
827 int cpu, bool invoke_cpp, unsigned long orig_num)
829 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
830 if (xmit_packet_precheck(ctx, cpu) < 0)
831 return;
833 if (cpu == 0) {
834 int i;
835 size_t total_len = 0, total_pkts = 0;
837 for (i = 0; i < ctx->cpus; ++i) {
838 total_len += stats[i].cf_bytes;
839 total_pkts += stats[i].cf_packets;
842 printf("%6zu packets to schedule\n", total_pkts);
843 printf("%6zu bytes in total\n", total_len);
844 printf("Running! Hang up with ^C!\n\n");
845 fflush(stdout);
848 sock = pf_socket();
850 if (slow)
851 xmit_slowpath_or_die(ctx, cpu, orig_num);
852 else
853 xmit_fastpath_or_die(ctx, cpu, orig_num);
855 close(sock);
857 cleanup_packets();
860 static unsigned int generate_srand_seed(void)
862 int fd;
863 unsigned int _seed;
865 fd = open("/dev/urandom", O_RDONLY);
866 if (fd < 0)
867 return time(NULL);
869 read_or_die(fd, &_seed, sizeof(_seed));
871 close(fd);
872 return _seed;
875 int main(int argc, char **argv)
877 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
878 int c, opt_index, i, j, vals[4] = {0}, irq;
879 char *confname = NULL, *ptr;
880 unsigned long cpus_tmp, orig_num = 0;
881 unsigned long long tx_packets, tx_bytes;
882 struct ctx ctx;
884 fmemset(&ctx, 0, sizeof(ctx));
885 ctx.cpus = get_number_cpus_online();
886 ctx.uid = getuid();
887 ctx.gid = getgid();
889 while ((c = getopt_long(argc, argv, short_options, long_options,
890 &opt_index)) != EOF) {
891 switch (c) {
892 case 'h':
893 help();
894 break;
895 case 'v':
896 version();
897 break;
898 case 'C':
899 cpustats = false;
900 break;
901 case 'e':
902 example();
903 break;
904 case 'p':
905 invoke_cpp = true;
906 break;
907 case 'V':
908 ctx.verbose = true;
909 break;
910 case 'P':
911 cpus_tmp = strtoul(optarg, NULL, 0);
912 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
913 ctx.cpus = cpus_tmp;
914 break;
915 case 'd':
916 case 'o':
917 ctx.device = xstrndup(optarg, IFNAMSIZ);
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 ctx.kpull = strtoul(optarg, NULL, 0);
950 break;
951 case 'E':
952 seed = strtoul(optarg, NULL, 0);
953 reseed = false;
954 break;
955 case 'n':
956 orig_num = strtoul(optarg, NULL, 0);
957 ctx.num = orig_num;
958 break;
959 case 't':
960 slow = true;
961 ctx.gap = strtoul(optarg, NULL, 0);
962 if (ctx.gap > 0)
963 /* Fall back to single core to not
964 * mess up correct timing. We are slow
965 * anyway!
967 ctx.cpus = 1;
968 break;
969 case 'S':
970 ptr = optarg;
971 ctx.reserve_size = 0;
973 for (j = i = strlen(optarg); i > 0; --i) {
974 if (!isdigit(optarg[j - i]))
975 break;
976 ptr++;
979 if (!strncmp(ptr, "KiB", strlen("KiB")))
980 ctx.reserve_size = 1 << 10;
981 else if (!strncmp(ptr, "MiB", strlen("MiB")))
982 ctx.reserve_size = 1 << 20;
983 else if (!strncmp(ptr, "GiB", strlen("GiB")))
984 ctx.reserve_size = 1 << 30;
985 else
986 panic("Syntax error in ring size param!\n");
987 *ptr = 0;
989 ctx.reserve_size *= strtol(optarg, NULL, 0);
990 break;
991 case '?':
992 switch (optopt) {
993 case 'd':
994 case 'c':
995 case 'n':
996 case 'S':
997 case 's':
998 case 'P':
999 case 'o':
1000 case 'E':
1001 case 'i':
1002 case 'k':
1003 case 'u':
1004 case 'g':
1005 case 't':
1006 panic("Option -%c requires an argument!\n",
1007 optopt);
1008 default:
1009 if (isprint(optopt))
1010 printf("Unknown option character `0x%X\'!\n", optopt);
1011 die();
1013 default:
1014 break;
1018 if (argc < 5)
1019 help();
1020 if (ctx.device == NULL)
1021 panic("No networking device given!\n");
1022 if (confname == NULL)
1023 panic("No configuration file given!\n");
1024 if (device_mtu(ctx.device) == 0)
1025 panic("This is no networking device!\n");
1027 register_signal(SIGINT, signal_handler);
1028 register_signal(SIGHUP, signal_handler);
1029 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1031 set_system_socket_memory(vals, array_size(vals));
1032 xlockme();
1034 if (ctx.rfraw) {
1035 ctx.device_trans = xstrdup(ctx.device);
1036 xfree(ctx.device);
1038 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1039 sleep(0);
1042 irq = device_irq_number(ctx.device);
1043 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1045 stats = setup_shared_var(ctx.cpus);
1047 for (i = 0; i < ctx.cpus; i++) {
1048 pid_t pid = fork();
1050 switch (pid) {
1051 case 0:
1052 if (reseed)
1053 seed = generate_srand_seed();
1054 srand(seed);
1056 cpu_affinity(i);
1057 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1059 goto thread_out;
1060 case -1:
1061 panic("Cannot fork processes!\n");
1065 for (i = 0; i < ctx.cpus; i++) {
1066 int status;
1068 wait(&status);
1069 if (WEXITSTATUS(status) == EXIT_FAILURE)
1070 die();
1073 if (ctx.rfraw)
1074 leave_rfmon_mac80211(ctx.device);
1076 reset_system_socket_memory(vals, array_size(vals));
1078 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1079 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1080 sched_yield();
1082 tx_packets += stats[i].tx_packets;
1083 tx_bytes += stats[i].tx_bytes;
1086 fflush(stdout);
1087 printf("\n");
1088 printf("\r%12llu packets outgoing\n", tx_packets);
1089 printf("\r%12llu bytes outgoing\n", tx_bytes);
1090 for (i = 0; cpustats && i < ctx.cpus; i++) {
1091 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1092 stats[i].tv_sec, stats[i].tv_usec, i,
1093 stats[i].tx_packets);
1096 thread_out:
1097 xunlockme();
1098 destroy_shared_var(stats, ctx.cpus);
1099 device_restore_irq_affinity_list();
1101 free(ctx.device);
1102 free(ctx.device_trans);
1103 free(ctx.rhost);
1104 free(confname);
1106 return 0;