ifpps: minor: Add parentheses to do {} while in padding_from_num()
[netsniff-ng.git] / trafgen.c
blobe140479b2633399b1857adbed81445b6ecb6bc39
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;
60 unsigned int cpus;
61 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
62 struct sockaddr_in dest;
65 struct cpu_stats {
66 unsigned long tv_sec, tv_usec;
67 unsigned long long tx_packets, tx_bytes;
68 unsigned long long cf_packets, cf_bytes;
69 unsigned long long cd_packets;
70 sig_atomic_t state;
73 static sig_atomic_t sigint = 0;
75 struct packet *packets = NULL;
76 size_t plen = 0;
78 struct packet_dyn *packet_dyn = NULL;
79 size_t dlen = 0;
81 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:C";
82 static const struct option long_options[] = {
83 {"dev", required_argument, NULL, 'd'},
84 {"out", required_argument, NULL, 'o'},
85 {"in", required_argument, NULL, 'i'},
86 {"conf", required_argument, NULL, 'c'},
87 {"num", required_argument, NULL, 'n'},
88 {"gap", required_argument, NULL, 't'},
89 {"cpus", required_argument, NULL, 'P'},
90 {"ring-size", required_argument, NULL, 'S'},
91 {"kernel-pull", required_argument, NULL, 'k'},
92 {"smoke-test", required_argument, NULL, 's'},
93 {"seed", required_argument, NULL, 'E'},
94 {"user", required_argument, NULL, 'u'},
95 {"group", required_argument, NULL, 'g'},
96 {"jumbo-support", no_argument, NULL, 'J'},
97 {"no-cpu-stats", no_argument, NULL, 'C'},
98 {"cpp", no_argument, NULL, 'p'},
99 {"rfraw", no_argument, NULL, 'R'},
100 {"rand", no_argument, NULL, 'r'},
101 {"verbose", no_argument, NULL, 'V'},
102 {"version", no_argument, NULL, 'v'},
103 {"example", no_argument, NULL, 'e'},
104 {"help", no_argument, NULL, 'h'},
105 {NULL, 0, NULL, 0}
108 static int sock;
109 static struct itimerval itimer;
110 static unsigned long interval = TX_KERNEL_PULL_INT;
111 static struct cpu_stats *stats;
112 static unsigned int seed;
114 #define CPU_STATS_STATE_CFG 1
115 #define CPU_STATS_STATE_CHK 2
116 #define CPU_STATS_STATE_RES 4
118 #ifndef ICMP_FILTER
119 # define ICMP_FILTER 1
121 struct icmp_filter {
122 __u32 data;
124 #endif
126 static void signal_handler(int number)
128 switch (number) {
129 case SIGINT:
130 sigint = 1;
131 case SIGHUP:
132 default:
133 break;
137 static void timer_elapsed(int unused __maybe_unused)
139 int ret = pull_and_flush_tx_ring(sock);
140 if (unlikely(ret < 0)) {
141 /* We could hit EBADF if the socket has been closed before
142 * the timer was triggered.
144 if (errno != EBADF && errno != ENOBUFS)
145 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
148 set_itimer_interval_value(&itimer, 0, interval);
149 setitimer(ITIMER_REAL, &itimer, NULL);
152 static void timer_purge(void)
154 int ret;
156 ret = pull_and_flush_tx_ring_wait(sock);
157 if (unlikely(ret < 0)) {
158 /* We could hit EBADF if the socket has been closed before
159 * the timer was triggered.
161 if (errno != EBADF && errno != ENOBUFS)
162 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
165 set_itimer_interval_value(&itimer, 0, 0);
166 setitimer(ITIMER_REAL, &itimer, NULL);
169 static void __noreturn help(void)
171 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
172 puts("http://www.netsniff-ng.org\n\n"
173 "Usage: trafgen [options]\n"
174 "Options:\n"
175 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
176 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
177 " -p|--cpp Run packet config through C preprocessor\n"
178 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
179 " -R|--rfraw Inject raw 802.11 frames\n"
180 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
181 " -n|--num <uint> Number of packets until exit (def: 0)\n"
182 " -r|--rand Randomize packet selection (def: round robin)\n"
183 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
184 " -t|--gap <uint> Interpacket gap in us (approx)\n"
185 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
186 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
187 " -E|--seed <uint> Manually set srand(3) seed\n"
188 " -u|--user <userid> Drop privileges and change to userid\n"
189 " -g|--group <groupid> Drop privileges and change to groupid\n"
190 " -V|--verbose Be more verbose\n"
191 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
192 " -v|--version Show version and exit\n"
193 " -e|--example Show built-in packet config example\n"
194 " -h|--help Guess what?!\n\n"
195 "Examples:\n"
196 " See trafgen.txf for configuration file examples.\n"
197 " trafgen --dev eth0 --conf trafgen.cfg\n"
198 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
199 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
200 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
201 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
202 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
203 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
204 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
205 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
206 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
207 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
208 "Note:\n"
209 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
210 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
211 " we assume the kernel crashed, thus we print the packet and quit.\n"
212 " In case you find a ping-of-death, please mention trafgen in your\n"
213 " commit message of the fix!\n\n"
214 " For introducing bit errors, delays with random variation and more,\n"
215 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
216 " For generating different package distributions, you can use scripting\n"
217 " to generate a trafgen config file with packet ratios as:\n\n"
218 " IMIX 64:7, 570:4, 1518:1\n"
219 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
220 " Cisco 64:7, 594:4, 1518:1\n"
221 " RPR Trimodal 64:60, 512:20, 1518:20\n"
222 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
223 "Please report bugs to <bugs@netsniff-ng.org>\n"
224 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
225 "Swiss federal institute of technology (ETH Zurich)\n"
226 "License: GNU GPL version 2.0\n"
227 "This is free software: you are free to change and redistribute it.\n"
228 "There is NO WARRANTY, to the extent permitted by law.\n");
229 die();
232 static void __noreturn example(void)
234 const char *e =
235 "/* Note: dynamic elements make trafgen slower! */\n"
236 "#include <stddef.h>\n\n"
237 "{\n"
238 " /* MAC Destination */\n"
239 " fill(0xff, ETH_ALEN),\n"
240 " /* MAC Source */\n"
241 " 0x00, 0x02, 0xb3, drnd(3),\n"
242 " /* IPv4 Protocol */\n"
243 " c16(ETH_P_IP),\n"
244 " /* IPv4 Version, IHL, TOS */\n"
245 " 0b01000101, 0,\n"
246 " /* IPv4 Total Len */\n"
247 " c16(59),\n"
248 " /* IPv4 Ident */\n"
249 " drnd(2),\n"
250 " /* IPv4 Flags, Frag Off */\n"
251 " 0b01000000, 0,\n"
252 " /* IPv4 TTL */\n"
253 " 64,\n"
254 " /* Proto TCP */\n"
255 " 0x06,\n"
256 " /* IPv4 Checksum (IP header from, to) */\n"
257 " csumip(14, 33),\n"
258 " /* Source IP */\n"
259 " drnd(4),\n"
260 " /* Dest IP */\n"
261 " drnd(4),\n"
262 " /* TCP Source Port */\n"
263 " drnd(2),\n"
264 " /* TCP Dest Port */\n"
265 " c16(80),\n"
266 " /* TCP Sequence Number */\n"
267 " drnd(4),\n"
268 " /* TCP Ackn. Number */\n"
269 " c32(0),\n"
270 " /* TCP Header length + TCP SYN/ECN Flag */\n"
271 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
272 " /* Window Size */\n"
273 " c16(16),\n"
274 " /* TCP Checksum (offset IP, offset TCP) */\n"
275 " csumtcp(14, 34),\n"
276 " /* TCP Options */\n"
277 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
278 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
279 " /* Data blob */\n"
280 " \"gotcha!\",\n"
281 "}";
282 puts(e);
283 die();
286 static void __noreturn version(void)
288 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
289 puts("multithreaded zero-copy network packet generator\n"
290 "http://www.netsniff-ng.org\n\n"
291 "Please report bugs to <bugs@netsniff-ng.org>\n"
292 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
293 "Swiss federal institute of technology (ETH Zurich)\n"
294 "License: GNU GPL version 2.0\n"
295 "This is free software: you are free to change and redistribute it.\n"
296 "There is NO WARRANTY, to the extent permitted by law.\n");
297 die();
300 static void apply_counter(int id)
302 size_t j, counter_max = packet_dyn[id].clen;
304 for (j = 0; j < counter_max; ++j) {
305 uint8_t val;
306 struct counter *counter = &packet_dyn[id].cnt[j];
308 val = counter->val - counter->min;
310 switch (counter->type) {
311 case TYPE_INC:
312 val = (val + counter->inc) % (counter->max - counter->min + 1);
313 break;
314 case TYPE_DEC:
315 val = (val - counter->inc) % (counter->min - counter->max + 1);
316 break;
317 default:
318 bug();
321 counter->val = val + counter->min;
322 packets[id].payload[counter->off] = val;
326 static void apply_randomizer(int id)
328 size_t j, rand_max = packet_dyn[id].rlen;
330 for (j = 0; j < rand_max; ++j) {
331 uint8_t val = (uint8_t) rand();
332 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
334 packets[id].payload[randomizer->off] = val;
338 static void apply_csum16(int id)
340 size_t j, csum_max = packet_dyn[id].slen;
342 for (j = 0; j < csum_max; ++j) {
343 uint16_t sum = 0;
344 struct csum16 *csum = &packet_dyn[id].csum[j];
346 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
347 if (unlikely((size_t) csum->to >= packets[id].len))
348 csum->to = packets[id].len - 1;
350 switch (csum->which) {
351 case CSUM_IP:
352 sum = calc_csum(packets[id].payload + csum->from,
353 csum->to - csum->from + 1, 0);
354 break;
355 case CSUM_UDP:
356 sum = p4_csum((void *) packets[id].payload + csum->from,
357 packets[id].payload + csum->to,
358 (packets[id].len - csum->to),
359 IPPROTO_UDP);
360 break;
361 case CSUM_TCP:
362 sum = p4_csum((void *) packets[id].payload + csum->from,
363 packets[id].payload + csum->to,
364 (packets[id].len - csum->to),
365 IPPROTO_TCP);
366 break;
367 default:
368 bug();
369 break;
372 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
376 static struct cpu_stats *setup_shared_var(unsigned long cpus)
378 int fd;
379 size_t len = cpus * sizeof(struct cpu_stats);
380 char zbuff[len], file[256];
381 struct cpu_stats *buff;
383 fmemset(zbuff, 0, len);
384 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
386 fd = creat(file, S_IRUSR | S_IWUSR);
387 bug_on(fd < 0);
388 close(fd);
390 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
391 S_IRUSR | S_IWUSR);
392 write_or_die(fd, zbuff, len);
394 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
395 MAP_SHARED, fd, 0);
396 if (buff == MAP_FAILED)
397 panic("Cannot setup shared variable!\n");
399 close(fd);
400 unlink(file);
402 memset(buff, 0, len);
403 return buff;
406 static void destroy_shared_var(void *buff, unsigned long cpus)
408 munmap(buff, cpus * sizeof(struct cpu_stats));
411 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
413 size_t i;
415 printf("{");
416 for (i = 0; i < len; ++i) {
417 if (i % 15 == 0)
418 printf("\n ");
419 printf("0x%02x, ", payload[i]);
421 printf("\n}\n");
422 fflush(stdout);
425 static int xmit_smoke_setup(struct ctx *ctx)
427 int icmp_sock, ret, ttl = 64;
428 struct icmp_filter filter;
430 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
431 if (icmp_sock < 0)
432 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
434 filter.data = ~(1 << ICMP_ECHOREPLY);
436 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
437 if (ret < 0)
438 panic("Cannot install filter!\n");
440 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
441 if (ret < 0)
442 panic("Cannot set TTL!\n");
444 memset(&ctx->dest, 0, sizeof(ctx->dest));
445 ctx->dest.sin_family = AF_INET;
446 ctx->dest.sin_port = 0;
448 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
449 if (ret < 0)
450 panic("Cannot resolv address!\n");
452 return icmp_sock;
455 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
457 int ret;
458 unsigned int i, j = 0, probes = 100;
459 short ident, cnt = 1, idstore[probes];
460 uint8_t outpack[512], *data;
461 struct icmphdr *icmp;
462 struct iphdr *ip;
463 size_t len = sizeof(*icmp) + 56;
464 struct sockaddr_in from;
465 socklen_t from_len;
466 struct pollfd fds = {
467 .fd = icmp_sock,
468 .events = POLLIN,
471 fmemset(idstore, 0, sizeof(idstore));
472 while (probes-- > 0) {
473 while ((ident = htons((short) rand())) == 0)
474 sleep(0);
475 idstore[j++] = ident;
477 memset(outpack, 0, sizeof(outpack));
478 icmp = (void *) outpack;
479 icmp->type = ICMP_ECHO;
480 icmp->un.echo.id = ident;
481 icmp->un.echo.sequence = htons(cnt++);
483 data = ((uint8_t *) outpack + sizeof(*icmp));
484 for (i = 0; i < 56; ++i)
485 data[i] = (uint8_t) rand();
487 icmp->checksum = csum((unsigned short *) outpack,
488 len / sizeof(unsigned short));
490 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
491 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
492 if (unlikely(ret != (int) len))
493 panic("Cannot send out probe: %s!\n", strerror(errno));
495 ret = poll(&fds, 1, 50);
496 if (ret < 0)
497 panic("Poll failed!\n");
499 if (fds.revents & POLLIN) {
500 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
501 (struct sockaddr *) &from, &from_len);
502 if (unlikely(ret <= 0))
503 panic("Probe receive failed!\n");
504 if (unlikely(from_len != sizeof(ctx->dest)))
505 continue;
506 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
507 continue;
508 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
509 continue;
510 ip = (void *) outpack;
511 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
512 continue;
513 icmp = (void *) outpack + ip->ihl * 4;
514 for (i = 0; i < array_size(idstore); ++i) {
515 if (unlikely(icmp->un.echo.id != idstore[i]))
516 continue;
517 return 0;
522 return -1;
525 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
527 int ret, icmp_sock = -1;
528 unsigned long num = 1, i = 0;
529 struct timeval start, end, diff;
530 unsigned long long tx_bytes = 0, tx_packets = 0;
531 struct packet_dyn *pktd;
532 struct sockaddr_ll saddr = {
533 .sll_family = PF_PACKET,
534 .sll_halen = ETH_ALEN,
535 .sll_ifindex = device_ifindex(ctx->device),
538 if (ctx->num > 0)
539 num = ctx->num;
540 if (ctx->num == 0 && orig_num > 0)
541 num = 0;
543 if (ctx->smoke_test)
544 icmp_sock = xmit_smoke_setup(ctx);
546 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
548 bug_on(gettimeofday(&start, NULL));
550 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
551 pktd = &packet_dyn[i];
552 if (pktd->clen + pktd->rlen + pktd->slen) {
553 apply_counter(i);
554 apply_randomizer(i);
555 apply_csum16(i);
557 retry:
558 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
559 (struct sockaddr *) &saddr, sizeof(saddr));
560 if (unlikely(ret < 0)) {
561 if (errno == ENOBUFS) {
562 sched_yield();
563 goto retry;
566 panic("Sendto error: %s!\n", strerror(errno));
569 tx_bytes += packets[i].len;
570 tx_packets++;
572 if (ctx->smoke_test) {
573 ret = xmit_smoke_probe(icmp_sock, ctx);
574 if (unlikely(ret < 0)) {
575 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
576 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
577 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
578 i, seed);
580 dump_trafgen_snippet(packets[i].payload, packets[i].len);
581 break;
585 if (!ctx->rand) {
586 i++;
587 if (i >= plen)
588 i = 0;
589 } else
590 i = rand() % plen;
592 if (ctx->num > 0)
593 num--;
595 if (ctx->gap > 0)
596 usleep(ctx->gap);
599 bug_on(gettimeofday(&end, NULL));
600 timersub(&end, &start, &diff);
602 if (ctx->smoke_test)
603 close(icmp_sock);
605 stats[cpu].tx_packets = tx_packets;
606 stats[cpu].tx_bytes = tx_bytes;
607 stats[cpu].tv_sec = diff.tv_sec;
608 stats[cpu].tv_usec = diff.tv_usec;
610 stats[cpu].state |= CPU_STATS_STATE_RES;
613 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
615 int ifindex = device_ifindex(ctx->device);
616 uint8_t *out = NULL;
617 unsigned int it = 0;
618 unsigned long num = 1, i = 0, size;
619 struct ring tx_ring;
620 struct frame_map *hdr;
621 struct timeval start, end, diff;
622 struct packet_dyn *pktd;
623 unsigned long long tx_bytes = 0, tx_packets = 0;
625 fmemset(&tx_ring, 0, sizeof(tx_ring));
627 size = ring_size(ctx->device, ctx->reserve_size);
629 set_sock_prio(sock, 512);
630 set_packet_loss_discard(sock);
632 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
633 create_tx_ring(sock, &tx_ring, ctx->verbose);
634 mmap_tx_ring(sock, &tx_ring);
635 alloc_tx_ring_frames(sock, &tx_ring);
636 bind_tx_ring(sock, &tx_ring, ifindex);
638 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
640 if (ctx->kpull)
641 interval = ctx->kpull;
642 if (ctx->num > 0)
643 num = ctx->num;
644 if (ctx->num == 0 && orig_num > 0)
645 num = 0;
647 set_itimer_interval_value(&itimer, 0, interval);
648 setitimer(ITIMER_REAL, &itimer, NULL);
650 bug_on(gettimeofday(&start, NULL));
652 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
653 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
654 hdr = tx_ring.frames[it].iov_base;
655 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
657 hdr->tp_h.tp_snaplen = packets[i].len;
658 hdr->tp_h.tp_len = packets[i].len;
660 pktd = &packet_dyn[i];
661 if (pktd->clen + pktd->rlen + pktd->slen) {
662 apply_counter(i);
663 apply_randomizer(i);
664 apply_csum16(i);
667 fmemcpy(out, packets[i].payload, packets[i].len);
669 tx_bytes += packets[i].len;
670 tx_packets++;
672 if (!ctx->rand) {
673 i++;
674 if (i >= plen)
675 i = 0;
676 } else
677 i = rand() % plen;
679 kernel_may_pull_from_tx(&hdr->tp_h);
681 it++;
682 if (it >= tx_ring.layout.tp_frame_nr)
683 it = 0;
685 if (ctx->num > 0)
686 num--;
688 if (unlikely(sigint == 1))
689 break;
693 bug_on(gettimeofday(&end, NULL));
694 timersub(&end, &start, &diff);
696 timer_purge();
698 destroy_tx_ring(sock, &tx_ring);
700 stats[cpu].tx_packets = tx_packets;
701 stats[cpu].tx_bytes = tx_bytes;
702 stats[cpu].tv_sec = diff.tv_sec;
703 stats[cpu].tv_usec = diff.tv_usec;
705 stats[cpu].state |= CPU_STATS_STATE_RES;
708 static inline void __set_state(int cpu, sig_atomic_t s)
710 stats[cpu].state = s;
713 static inline sig_atomic_t __get_state(int cpu)
715 return stats[cpu].state;
718 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
720 unsigned int i;
721 unsigned long total;
723 for (i = 0, total = plen; i < ctx->cpus; i++) {
724 if (i == cpu)
725 continue;
727 while ((__get_state(i) &
728 (CPU_STATS_STATE_CFG |
729 CPU_STATS_STATE_RES)) == 0 &&
730 sigint == 0)
731 sched_yield();
733 total += stats[i].cf_packets;
736 return total;
739 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
741 unsigned int i;
742 unsigned long total;
743 int cpu_sel;
744 long long delta_correction = 0;
746 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
747 if (i == cpu)
748 continue;
750 while ((__get_state(i) &
751 (CPU_STATS_STATE_CHK |
752 CPU_STATS_STATE_RES)) == 0 &&
753 sigint == 0)
754 sched_yield();
756 total += stats[i].cd_packets;
759 if (total > orig)
760 delta_correction = -1 * ((long long) total - orig);
761 if (total < orig)
762 delta_correction = +1 * ((long long) orig - total);
764 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
765 if (stats[i].cd_packets > 0) {
766 if ((long long) stats[i].cd_packets +
767 delta_correction >= 0) {
768 cpu_sel = i;
769 break;
774 if ((int) cpu == cpu_sel)
775 ctx->num += delta_correction;
778 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
779 sig_atomic_t s)
781 stats[cpu].cf_packets = p;
782 stats[cpu].cf_bytes = b;
783 stats[cpu].state = s;
786 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
788 stats[cpu].cd_packets = p;
789 stats[cpu].state = s;
792 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
794 unsigned int i;
795 unsigned long plen_total, orig = ctx->num;
796 size_t mtu, total_len = 0;
798 bug_on(plen != dlen);
800 for (i = 0; i < plen; ++i)
801 total_len += packets[i].len;
803 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
804 plen_total = __wait_and_sum_others(ctx, cpu);
806 if (orig > 0) {
807 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
809 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
810 CPU_STATS_STATE_CFG);
811 __correct_global_delta(ctx, cpu, orig);
814 if (plen == 0) {
815 __set_state(cpu, CPU_STATS_STATE_RES);
816 return 0;
819 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
820 if (packets[i].len > mtu + 14)
821 panic("Device MTU < than packet%d's size!\n", i);
822 if (packets[i].len <= 14)
823 panic("Packet%d's size too short!\n", i);
826 return 0;
829 static void main_loop(struct ctx *ctx, char *confname, bool slow,
830 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
832 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
833 if (xmit_packet_precheck(ctx, cpu) < 0)
834 return;
836 if (cpu == 0) {
837 unsigned int i;
838 size_t total_len = 0, total_pkts = 0;
840 for (i = 0; i < ctx->cpus; ++i) {
841 total_len += stats[i].cf_bytes;
842 total_pkts += stats[i].cf_packets;
845 printf("%6zu packets to schedule\n", total_pkts);
846 printf("%6zu bytes in total\n", total_len);
847 printf("Running! Hang up with ^C!\n\n");
848 fflush(stdout);
851 sock = pf_socket();
853 if (slow)
854 xmit_slowpath_or_die(ctx, cpu, orig_num);
855 else
856 xmit_fastpath_or_die(ctx, cpu, orig_num);
858 close(sock);
860 cleanup_packets();
863 static unsigned int generate_srand_seed(void)
865 int fd;
866 unsigned int _seed;
868 fd = open("/dev/urandom", O_RDONLY);
869 if (fd < 0)
870 return time(NULL);
872 read_or_die(fd, &_seed, sizeof(_seed));
874 close(fd);
875 return _seed;
878 int main(int argc, char **argv)
880 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
881 int c, opt_index, vals[4] = {0}, irq;
882 unsigned int i, j;
883 char *confname = NULL, *ptr;
884 unsigned long cpus_tmp, orig_num = 0;
885 unsigned long long tx_packets, tx_bytes;
886 struct ctx ctx;
888 fmemset(&ctx, 0, sizeof(ctx));
889 ctx.cpus = get_number_cpus_online();
890 ctx.uid = getuid();
891 ctx.gid = getgid();
893 while ((c = getopt_long(argc, argv, short_options, long_options,
894 &opt_index)) != EOF) {
895 switch (c) {
896 case 'h':
897 help();
898 break;
899 case 'v':
900 version();
901 break;
902 case 'C':
903 cpustats = false;
904 break;
905 case 'e':
906 example();
907 break;
908 case 'p':
909 invoke_cpp = true;
910 break;
911 case 'V':
912 ctx.verbose = true;
913 break;
914 case 'P':
915 cpus_tmp = strtoul(optarg, NULL, 0);
916 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
917 ctx.cpus = cpus_tmp;
918 break;
919 case 'd':
920 case 'o':
921 ctx.device = xstrndup(optarg, IFNAMSIZ);
922 break;
923 case 'r':
924 ctx.rand = true;
925 break;
926 case 's':
927 slow = true;
928 ctx.cpus = 1;
929 ctx.smoke_test = true;
930 ctx.rhost = xstrdup(optarg);
931 break;
932 case 'R':
933 ctx.rfraw = true;
934 break;
935 case 'J':
936 ctx.jumbo_support = true;
937 break;
938 case 'c':
939 case 'i':
940 confname = xstrdup(optarg);
941 if (!strncmp("-", confname, strlen("-")))
942 ctx.cpus = 1;
943 break;
944 case 'u':
945 ctx.uid = strtoul(optarg, NULL, 0);
946 ctx.enforce = true;
947 break;
948 case 'g':
949 ctx.gid = strtoul(optarg, NULL, 0);
950 ctx.enforce = true;
951 break;
952 case 'k':
953 ctx.kpull = strtoul(optarg, NULL, 0);
954 break;
955 case 'E':
956 seed = strtoul(optarg, NULL, 0);
957 reseed = false;
958 break;
959 case 'n':
960 orig_num = strtoul(optarg, NULL, 0);
961 ctx.num = orig_num;
962 break;
963 case 't':
964 slow = true;
965 ctx.gap = strtoul(optarg, NULL, 0);
966 if (ctx.gap > 0)
967 /* Fall back to single core to not
968 * mess up correct timing. We are slow
969 * anyway!
971 ctx.cpus = 1;
972 break;
973 case 'S':
974 ptr = optarg;
975 ctx.reserve_size = 0;
977 for (j = i = strlen(optarg); i > 0; --i) {
978 if (!isdigit(optarg[j - i]))
979 break;
980 ptr++;
983 if (!strncmp(ptr, "KiB", strlen("KiB")))
984 ctx.reserve_size = 1 << 10;
985 else if (!strncmp(ptr, "MiB", strlen("MiB")))
986 ctx.reserve_size = 1 << 20;
987 else if (!strncmp(ptr, "GiB", strlen("GiB")))
988 ctx.reserve_size = 1 << 30;
989 else
990 panic("Syntax error in ring size param!\n");
991 *ptr = 0;
993 ctx.reserve_size *= strtol(optarg, NULL, 0);
994 break;
995 case '?':
996 switch (optopt) {
997 case 'd':
998 case 'c':
999 case 'n':
1000 case 'S':
1001 case 's':
1002 case 'P':
1003 case 'o':
1004 case 'E':
1005 case 'i':
1006 case 'k':
1007 case 'u':
1008 case 'g':
1009 case 't':
1010 panic("Option -%c requires an argument!\n",
1011 optopt);
1012 default:
1013 if (isprint(optopt))
1014 printf("Unknown option character `0x%X\'!\n", optopt);
1015 die();
1017 default:
1018 break;
1022 if (argc < 5)
1023 help();
1024 if (ctx.device == NULL)
1025 panic("No networking device given!\n");
1026 if (confname == NULL)
1027 panic("No configuration file given!\n");
1028 if (device_mtu(ctx.device) == 0)
1029 panic("This is no networking device!\n");
1031 register_signal(SIGINT, signal_handler);
1032 register_signal(SIGHUP, signal_handler);
1033 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1035 set_system_socket_memory(vals, array_size(vals));
1036 xlockme();
1038 if (ctx.rfraw) {
1039 ctx.device_trans = xstrdup(ctx.device);
1040 xfree(ctx.device);
1042 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1043 sleep(0);
1046 irq = device_irq_number(ctx.device);
1047 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1049 stats = setup_shared_var(ctx.cpus);
1051 for (i = 0; i < ctx.cpus; i++) {
1052 pid_t pid = fork();
1054 switch (pid) {
1055 case 0:
1056 if (reseed)
1057 seed = generate_srand_seed();
1058 srand(seed);
1060 cpu_affinity(i);
1061 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1063 goto thread_out;
1064 case -1:
1065 panic("Cannot fork processes!\n");
1069 for (i = 0; i < ctx.cpus; i++) {
1070 int status;
1072 wait(&status);
1073 if (WEXITSTATUS(status) == EXIT_FAILURE)
1074 die();
1077 if (ctx.rfraw)
1078 leave_rfmon_mac80211(ctx.device);
1080 reset_system_socket_memory(vals, array_size(vals));
1082 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1083 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1084 sched_yield();
1086 tx_packets += stats[i].tx_packets;
1087 tx_bytes += stats[i].tx_bytes;
1090 fflush(stdout);
1091 printf("\n");
1092 printf("\r%12llu packets outgoing\n", tx_packets);
1093 printf("\r%12llu bytes outgoing\n", tx_bytes);
1094 for (i = 0; cpustats && i < ctx.cpus; i++) {
1095 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1096 stats[i].tv_sec, stats[i].tv_usec, i,
1097 stats[i].tx_packets);
1100 thread_out:
1101 xunlockme();
1102 destroy_shared_var(stats, ctx.cpus);
1103 device_restore_irq_affinity_list();
1105 free(ctx.device);
1106 free(ctx.device_trans);
1107 free(ctx.rhost);
1108 free(confname);
1110 return 0;