sock: add socket management functions
[netsniff-ng.git] / trafgen.c
blobc36a2d12b38a99acad9baf0a82cff48cbef0d232
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 "sock.h"
39 #include "cpus.h"
40 #include "lockme.h"
41 #include "privs.h"
42 #include "proc.h"
43 #include "mac80211.h"
44 #include "xutils.h"
45 #include "ioops.h"
46 #include "irq.h"
47 #include "built_in.h"
48 #include "trafgen_conf.h"
49 #include "tprintf.h"
50 #include "ring_tx.h"
51 #include "csum.h"
53 struct ctx {
54 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce;
55 unsigned long kpull, num, gap, reserve_size, cpus;
56 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
57 struct sockaddr_in dest;
60 struct cpu_stats {
61 unsigned long tv_sec, tv_usec;
62 unsigned long long tx_packets, tx_bytes;
63 unsigned long long cf_packets, cf_bytes;
64 unsigned long long cd_packets;
65 sig_atomic_t state;
68 static sig_atomic_t sigint = 0;
70 struct packet *packets = NULL;
71 size_t plen = 0;
73 struct packet_dyn *packet_dyn = NULL;
74 size_t dlen = 0;
76 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:";
77 static const struct option long_options[] = {
78 {"dev", required_argument, NULL, 'd'},
79 {"out", required_argument, NULL, 'o'},
80 {"in", required_argument, NULL, 'i'},
81 {"conf", required_argument, NULL, 'c'},
82 {"num", required_argument, NULL, 'n'},
83 {"gap", required_argument, NULL, 't'},
84 {"cpus", required_argument, NULL, 'P'},
85 {"ring-size", required_argument, NULL, 'S'},
86 {"kernel-pull", required_argument, NULL, 'k'},
87 {"smoke-test", required_argument, NULL, 's'},
88 {"seed", required_argument, NULL, 'E'},
89 {"user", required_argument, NULL, 'u'},
90 {"group", required_argument, NULL, 'g'},
91 {"jumbo-support", no_argument, NULL, 'J'},
92 {"cpp", no_argument, NULL, 'p'},
93 {"rfraw", no_argument, NULL, 'R'},
94 {"rand", no_argument, NULL, 'r'},
95 {"verbose", no_argument, NULL, 'V'},
96 {"version", no_argument, NULL, 'v'},
97 {"example", no_argument, NULL, 'e'},
98 {"help", no_argument, NULL, 'h'},
99 {NULL, 0, NULL, 0}
102 static int sock;
103 static struct itimerval itimer;
104 static unsigned long interval = TX_KERNEL_PULL_INT;
105 static struct cpu_stats *stats;
106 unsigned int seed;
108 #define CPU_STATS_STATE_CFG 1
109 #define CPU_STATS_STATE_CHK 2
110 #define CPU_STATS_STATE_RES 4
112 #ifndef ICMP_FILTER
113 # define ICMP_FILTER 1
115 struct icmp_filter {
116 __u32 data;
118 #endif
120 static void signal_handler(int number)
122 switch (number) {
123 case SIGINT:
124 sigint = 1;
125 case SIGHUP:
126 default:
127 break;
131 static void timer_elapsed(int number)
133 int ret = pull_and_flush_tx_ring(sock);
134 if (unlikely(ret < 0)) {
135 /* We could hit EBADF if the socket has been closed before
136 * the timer was triggered.
138 if (errno != EBADF && errno != ENOBUFS)
139 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
142 set_itimer_interval_value(&itimer, 0, interval);
143 setitimer(ITIMER_REAL, &itimer, NULL);
146 static void timer_purge(void)
148 int ret;
150 ret = pull_and_flush_tx_ring_wait(sock);
151 if (unlikely(ret < 0)) {
152 /* We could hit EBADF if the socket has been closed before
153 * the timer was triggered.
155 if (errno != EBADF && errno != ENOBUFS)
156 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
159 set_itimer_interval_value(&itimer, 0, 0);
160 setitimer(ITIMER_REAL, &itimer, NULL);
163 static void __noreturn help(void)
165 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
166 puts("http://www.netsniff-ng.org\n\n"
167 "Usage: trafgen [options]\n"
168 "Options:\n"
169 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
170 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
171 " -p|--cpp Run packet config through C preprocessor\n"
172 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
173 " -R|--rfraw Inject raw 802.11 frames\n"
174 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
175 " -n|--num <uint> Number of packets until exit (def: 0)\n"
176 " -r|--rand Randomize packet selection (def: round robin)\n"
177 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
178 " -t|--gap <uint> Interpacket gap in us (approx)\n"
179 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
180 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
181 " -E|--seed <uint> Manually set srand(3) seed\n"
182 " -u|--user <userid> Drop privileges and change to userid\n"
183 " -g|--group <groupid> Drop privileges and change to groupid\n"
184 " -V|--verbose Be more verbose\n"
185 " -v|--version Show version and exit\n"
186 " -e|--example Show built-in packet config example\n"
187 " -h|--help Guess what?!\n\n"
188 "Examples:\n"
189 " See trafgen.txf for configuration file examples.\n"
190 " trafgen --dev eth0 --conf trafgen.cfg\n"
191 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
192 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
193 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
194 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000\n"
195 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
196 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
197 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
198 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
199 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
200 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
201 "Note:\n"
202 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
203 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
204 " we assume the kernel crashed, thus we print the packet and quit.\n"
205 " In case you find a ping-of-death, please mention trafgen in your\n"
206 " commit message of the fix!\n\n"
207 " For introducing bit errors, delays with random variation and more,\n"
208 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
209 " For generating different package distributions, you can use scripting\n"
210 " to generate a trafgen config file with packet ratios as:\n\n"
211 " IMIX 64:7, 570:4, 1518:1\n"
212 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
213 " Cisco 64:7, 594:4, 1518:1\n"
214 " RPR Trimodal 64:60, 512:20, 1518:20\n"
215 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
216 "Please report bugs to <bugs@netsniff-ng.org>\n"
217 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
218 "Swiss federal institute of technology (ETH Zurich)\n"
219 "License: GNU GPL version 2.0\n"
220 "This is free software: you are free to change and redistribute it.\n"
221 "There is NO WARRANTY, to the extent permitted by law.\n");
222 die();
225 static void __noreturn example(void)
227 const char *e =
228 "/* Note: dynamic elements make trafgen slower! */\n"
229 "#include <stddef.h>\n\n"
230 "{\n"
231 " /* MAC Destination */\n"
232 " fill(0xff, ETH_ALEN),\n"
233 " /* MAC Source */\n"
234 " 0x00, 0x02, 0xb3, drnd(3),\n"
235 " /* IPv4 Protocol */\n"
236 " c16(ETH_P_IP),\n"
237 " /* IPv4 Version, IHL, TOS */\n"
238 " 0b01000101, 0,\n"
239 " /* IPv4 Total Len */\n"
240 " c16(58),\n"
241 " /* IPv4 Ident */\n"
242 " drnd(2),\n"
243 " /* IPv4 Flags, Frag Off */\n"
244 " 0b01000000, 0,\n"
245 " /* IPv4 TTL */\n"
246 " 64,\n"
247 " /* Proto TCP */\n"
248 " 0x06,\n"
249 " /* IPv4 Checksum (IP header from, to) */\n"
250 " csumip(14, 33),\n"
251 " /* Source IP */\n"
252 " drnd(4),\n"
253 " /* Dest IP */\n"
254 " drnd(4),\n"
255 " /* TCP Source Port */\n"
256 " drnd(2),\n"
257 " /* TCP Dest Port */\n"
258 " c16(80),\n"
259 " /* TCP Sequence Number */\n"
260 " drnd(4),\n"
261 " /* TCP Ackn. Number */\n"
262 " c32(0),\n"
263 " /* TCP Header length + TCP SYN/ECN Flag */\n"
264 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
265 " /* Window Size */\n"
266 " c16(16),\n"
267 " /* TCP Checksum (offset IP, offset TCP) */\n"
268 " csumtcp(14, 34),\n"
269 " /* TCP Options */\n"
270 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
271 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
272 " /* Data blob */\n"
273 " \"gotcha!\",\n"
274 "}";
275 puts(e);
276 die();
279 static void __noreturn version(void)
281 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_LONG);
282 puts("http://www.netsniff-ng.org\n\n"
283 "Please report bugs to <bugs@netsniff-ng.org>\n"
284 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
285 "Swiss federal institute of technology (ETH Zurich)\n"
286 "License: GNU GPL version 2.0\n"
287 "This is free software: you are free to change and redistribute it.\n"
288 "There is NO WARRANTY, to the extent permitted by law.\n");
289 die();
292 static void apply_counter(int counter_id)
294 int j, i = counter_id;
295 size_t counter_max = packet_dyn[i].clen;
297 for (j = 0; j < counter_max; ++j) {
298 uint8_t val;
299 struct counter *counter = &packet_dyn[i].cnt[j];
301 val = counter->val - counter->min;
303 switch (counter->type) {
304 case TYPE_INC:
305 val = (val + counter->inc) % (counter->max - counter->min + 1);
306 break;
307 case TYPE_DEC:
308 val = (val - counter->inc) % (counter->min - counter->max + 1);
309 break;
310 default:
311 bug();
314 counter->val = val + counter->min;
315 packets[i].payload[counter->off] = val;
319 static void apply_randomizer(int rand_id)
321 int j, i = rand_id;
322 size_t rand_max = packet_dyn[i].rlen;
324 for (j = 0; j < rand_max; ++j) {
325 uint8_t val = (uint8_t) rand();
326 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
328 packets[i].payload[randomizer->off] = val;
332 static void apply_csum16(int csum_id)
334 int j, i = csum_id;
335 size_t csum_max = packet_dyn[i].slen;
337 for (j = 0; j < csum_max; ++j) {
338 uint16_t sum = 0;
339 struct csum16 *csum = &packet_dyn[i].csum[j];
341 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
343 switch (csum->which) {
344 case CSUM_IP:
345 if (csum->to >= packets[i].len)
346 csum->to = packets[i].len - 1;
347 sum = calc_csum(packets[i].payload + csum->from,
348 csum->to - csum->from + 1, 0);
349 break;
350 case CSUM_UDP:
351 sum = p4_csum((void *) packets[i].payload + csum->from,
352 packets[i].payload + csum->to,
353 (packets[i].len - csum->to),
354 IPPROTO_UDP);
355 break;
356 case CSUM_TCP:
357 sum = p4_csum((void *) packets[i].payload + csum->from,
358 packets[i].payload + csum->to,
359 (packets[i].len - csum->to),
360 IPPROTO_TCP);
361 break;
364 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
368 static struct cpu_stats *setup_shared_var(unsigned long cpus)
370 int fd;
371 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
372 struct cpu_stats *buff;
374 fmemset(zbuff, 0, sizeof(zbuff));
375 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
377 fd = creat(file, S_IRUSR | S_IWUSR);
378 bug_on(fd < 0);
379 close(fd);
381 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
382 S_IRUSR | S_IWUSR);
383 write_or_die(fd, zbuff, sizeof(zbuff));
385 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
386 MAP_SHARED, fd, 0);
387 if (buff == (void *) -1)
388 panic("Cannot setup shared variable!\n");
390 close(fd);
391 unlink(file);
393 memset(buff, 0, sizeof(zbuff));
395 return buff;
398 static void destroy_shared_var(void *buff, unsigned long cpus)
400 munmap(buff, cpus * sizeof(struct cpu_stats));
403 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
405 int i;
407 printf("{");
408 for (i = 0; i < len; ++i) {
409 if (i % 15 == 0)
410 printf("\n ");
411 printf("0x%02x, ", payload[i]);
413 printf("\n}\n");
414 fflush(stdout);
417 static int xmit_smoke_setup(struct ctx *ctx)
419 int icmp_sock, ret, ttl = 64;
420 struct icmp_filter filter;
422 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
423 if (icmp_sock < 0)
424 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
426 filter.data = ~(1 << ICMP_ECHOREPLY);
428 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
429 if (ret < 0)
430 panic("Cannot install filter!\n");
432 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
433 if (ret < 0)
434 panic("Cannot set TTL!\n");
436 memset(&ctx->dest, 0, sizeof(ctx->dest));
437 ctx->dest.sin_family = AF_INET;
438 ctx->dest.sin_port = 0;
440 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
441 if (ret < 0)
442 panic("Cannot resolv address!\n");
444 return icmp_sock;
447 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
449 int ret, i, j = 0, probes = 100;
450 short ident, cnt = 1, idstore[probes];
451 uint8_t outpack[512], *data;
452 struct icmphdr *icmp;
453 struct iphdr *ip;
454 size_t len = sizeof(*icmp) + 56;
455 struct sockaddr_in from;
456 socklen_t from_len;
457 struct pollfd fds = {
458 .fd = icmp_sock,
459 .events = POLLIN,
462 fmemset(idstore, 0, sizeof(idstore));
463 while (probes-- > 0) {
464 while ((ident = htons((short) rand())) == 0)
465 sleep(0);
466 idstore[j++] = ident;
468 memset(outpack, 0, sizeof(outpack));
469 icmp = (void *) outpack;
470 icmp->type = ICMP_ECHO;
471 icmp->un.echo.id = ident;
472 icmp->un.echo.sequence = htons(cnt++);
474 data = ((uint8_t *) outpack + sizeof(*icmp));
475 for (i = 0; i < 56; ++i)
476 data[i] = (uint8_t) rand();
478 icmp->checksum = csum((unsigned short *) outpack,
479 len / sizeof(unsigned short));
481 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
482 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
483 if (unlikely(ret != len))
484 panic("Cannot send out probe: %s!\n", strerror(errno));
486 ret = poll(&fds, 1, 50);
487 if (ret < 0)
488 panic("Poll failed!\n");
490 if (fds.revents & POLLIN) {
491 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
492 (struct sockaddr *) &from, &from_len);
493 if (unlikely(ret <= 0))
494 panic("Probe receive failed!\n");
495 if (unlikely(from_len != sizeof(ctx->dest)))
496 continue;
497 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
498 continue;
499 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
500 continue;
501 ip = (void *) outpack;
502 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
503 continue;
504 icmp = (void *) outpack + ip->ihl * 4;
505 for (i = 0; i < array_size(idstore); ++i) {
506 if (unlikely(icmp->un.echo.id != idstore[i]))
507 continue;
508 return 0;
513 return -1;
516 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
518 int ret, icmp_sock = -1;
519 unsigned long num = 1, i = 0;
520 struct timeval start, end, diff;
521 unsigned long long tx_bytes = 0, tx_packets = 0;
522 struct packet_dyn *pktd;
523 struct sockaddr_ll saddr = {
524 .sll_family = PF_PACKET,
525 .sll_halen = ETH_ALEN,
526 .sll_ifindex = device_ifindex(ctx->device),
529 if (ctx->num > 0)
530 num = ctx->num;
531 if (ctx->num == 0 && orig_num > 0)
532 num = 0;
534 if (ctx->smoke_test)
535 icmp_sock = xmit_smoke_setup(ctx);
537 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
539 bug_on(gettimeofday(&start, NULL));
541 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
542 pktd = &packet_dyn[i];
543 if (pktd->clen + pktd->rlen + pktd->slen) {
544 apply_counter(i);
545 apply_randomizer(i);
546 apply_csum16(i);
548 retry:
549 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
550 (struct sockaddr *) &saddr, sizeof(saddr));
551 if (unlikely(ret < 0)) {
552 if (errno == ENOBUFS) {
553 sched_yield();
554 goto retry;
557 panic("Sendto error: %s!\n", strerror(errno));
560 tx_bytes += packets[i].len;
561 tx_packets++;
563 if (ctx->smoke_test) {
564 ret = xmit_smoke_probe(icmp_sock, ctx);
565 if (unlikely(ret < 0)) {
566 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
567 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
568 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
569 i, seed);
571 dump_trafgen_snippet(packets[i].payload, packets[i].len);
572 break;
576 if (!ctx->rand) {
577 i++;
578 if (i >= plen)
579 i = 0;
580 } else
581 i = rand() % plen;
583 if (ctx->num > 0)
584 num--;
586 if (ctx->gap > 0)
587 usleep(ctx->gap);
590 bug_on(gettimeofday(&end, NULL));
591 timersub(&end, &start, &diff);
593 if (ctx->smoke_test)
594 close(icmp_sock);
596 stats[cpu].tx_packets = tx_packets;
597 stats[cpu].tx_bytes = tx_bytes;
598 stats[cpu].tv_sec = diff.tv_sec;
599 stats[cpu].tv_usec = diff.tv_usec;
601 stats[cpu].state |= CPU_STATS_STATE_RES;
604 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
606 int ifindex = device_ifindex(ctx->device);
607 uint8_t *out = NULL;
608 unsigned int it = 0;
609 unsigned long num = 1, i = 0, size;
610 struct ring tx_ring;
611 struct frame_map *hdr;
612 struct timeval start, end, diff;
613 struct packet_dyn *pktd;
614 unsigned long long tx_bytes = 0, tx_packets = 0;
616 fmemset(&tx_ring, 0, sizeof(tx_ring));
618 size = ring_size(ctx->device, ctx->reserve_size);
620 set_sock_prio(sock, 512);
621 set_packet_loss_discard(sock);
623 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
624 create_tx_ring(sock, &tx_ring, ctx->verbose);
625 mmap_tx_ring(sock, &tx_ring);
626 alloc_tx_ring_frames(sock, &tx_ring);
627 bind_tx_ring(sock, &tx_ring, ifindex);
629 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
631 if (ctx->kpull)
632 interval = ctx->kpull;
633 if (ctx->num > 0)
634 num = ctx->num;
635 if (ctx->num == 0 && orig_num > 0)
636 num = 0;
638 set_itimer_interval_value(&itimer, 0, interval);
639 setitimer(ITIMER_REAL, &itimer, NULL);
641 bug_on(gettimeofday(&start, NULL));
643 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
644 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
645 hdr = tx_ring.frames[it].iov_base;
646 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
648 hdr->tp_h.tp_snaplen = packets[i].len;
649 hdr->tp_h.tp_len = packets[i].len;
651 pktd = &packet_dyn[i];
652 if (pktd->clen + pktd->rlen + pktd->slen) {
653 apply_counter(i);
654 apply_randomizer(i);
655 apply_csum16(i);
658 fmemcpy(out, packets[i].payload, packets[i].len);
660 tx_bytes += packets[i].len;
661 tx_packets++;
663 if (!ctx->rand) {
664 i++;
665 if (i >= plen)
666 i = 0;
667 } else
668 i = rand() % plen;
670 kernel_may_pull_from_tx(&hdr->tp_h);
672 it++;
673 if (it >= tx_ring.layout.tp_frame_nr)
674 it = 0;
676 if (ctx->num > 0)
677 num--;
679 if (unlikely(sigint == 1))
680 break;
684 bug_on(gettimeofday(&end, NULL));
685 timersub(&end, &start, &diff);
687 timer_purge();
689 destroy_tx_ring(sock, &tx_ring);
691 stats[cpu].tx_packets = tx_packets;
692 stats[cpu].tx_bytes = tx_bytes;
693 stats[cpu].tv_sec = diff.tv_sec;
694 stats[cpu].tv_usec = diff.tv_usec;
696 stats[cpu].state |= CPU_STATS_STATE_RES;
699 static inline void __set_state(int cpu, sig_atomic_t s)
701 stats[cpu].state = s;
704 static inline sig_atomic_t __get_state(int cpu)
706 return stats[cpu].state;
709 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
711 int i;
712 unsigned long total;
714 for (i = 0, total = plen; i < ctx->cpus; i++) {
715 if (i == cpu)
716 continue;
718 while ((__get_state(i) &
719 (CPU_STATS_STATE_CFG |
720 CPU_STATS_STATE_RES)) == 0 &&
721 sigint == 0)
722 sched_yield();
724 total += stats[i].cf_packets;
727 return total;
730 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
732 int i, cpu_sel;
733 unsigned long total;
734 long long delta_correction = 0;
736 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
737 if (i == cpu)
738 continue;
740 while ((__get_state(i) &
741 (CPU_STATS_STATE_CHK |
742 CPU_STATS_STATE_RES)) == 0 &&
743 sigint == 0)
744 sched_yield();
746 total += stats[i].cd_packets;
749 if (total > orig)
750 delta_correction = -1 * ((long long) total - orig);
751 if (total < orig)
752 delta_correction = +1 * ((long long) orig - total);
754 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
755 if (stats[i].cd_packets > 0) {
756 if ((long long) stats[i].cd_packets +
757 delta_correction > 0) {
758 cpu_sel = i;
759 break;
764 if (cpu == cpu_sel)
765 ctx->num += delta_correction;
768 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
769 sig_atomic_t s)
771 stats[cpu].cf_packets = p;
772 stats[cpu].cf_bytes = b;
773 stats[cpu].state = s;
776 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
778 stats[cpu].cd_packets = p;
779 stats[cpu].state = s;
782 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
784 int i;
785 unsigned long plen_total, orig = ctx->num;
786 size_t mtu, total_len = 0;
788 bug_on(plen != dlen);
790 for (i = 0; i < plen; ++i)
791 total_len += packets[i].len;
793 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
794 plen_total = __wait_and_sum_others(ctx, cpu);
796 if (orig > 0) {
797 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
799 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
800 CPU_STATS_STATE_CFG);
801 __correct_global_delta(ctx, cpu, orig);
804 if (plen == 0) {
805 __set_state(cpu, CPU_STATS_STATE_RES);
806 return 0;
809 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
810 if (packets[i].len > mtu + 14)
811 panic("Device MTU < than packet%d's size!\n", i);
812 if (packets[i].len <= 14)
813 panic("Packet%d's size too short!\n", i);
816 return 0;
819 static void main_loop(struct ctx *ctx, char *confname, bool slow,
820 int cpu, bool invoke_cpp, unsigned long orig_num)
822 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
823 if (xmit_packet_precheck(ctx, cpu) < 0)
824 return;
826 if (cpu == 0) {
827 int i;
828 size_t total_len = 0, total_pkts = 0;
830 for (i = 0; i < ctx->cpus; ++i) {
831 total_len += stats[i].cf_bytes;
832 total_pkts += stats[i].cf_packets;
835 printf("%6zu packets to schedule\n", total_pkts);
836 printf("%6zu bytes in total\n", total_len);
837 printf("Running! Hang up with ^C!\n\n");
838 fflush(stdout);
841 sock = pf_socket();
843 if (slow)
844 xmit_slowpath_or_die(ctx, cpu, orig_num);
845 else
846 xmit_fastpath_or_die(ctx, cpu, orig_num);
848 close(sock);
850 cleanup_packets();
853 static unsigned int generate_srand_seed(void)
855 int fd;
856 unsigned int seed;
858 fd = open("/dev/urandom", O_RDONLY);
859 if (fd < 0)
860 return time(0);
862 read_or_die(fd, &seed, sizeof(seed));
864 close(fd);
865 return seed;
868 int main(int argc, char **argv)
870 bool slow = false, invoke_cpp = false, reseed = true;
871 int c, opt_index, i, j, vals[4] = {0}, irq;
872 char *confname = NULL, *ptr;
873 unsigned long cpus_tmp, orig_num = 0;
874 unsigned long long tx_packets, tx_bytes;
875 struct ctx ctx;
877 fmemset(&ctx, 0, sizeof(ctx));
878 ctx.cpus = get_number_cpus_online();
879 ctx.uid = getuid();
880 ctx.gid = getgid();
882 while ((c = getopt_long(argc, argv, short_options, long_options,
883 &opt_index)) != EOF) {
884 switch (c) {
885 case 'h':
886 help();
887 break;
888 case 'v':
889 version();
890 break;
891 case 'e':
892 example();
893 break;
894 case 'p':
895 invoke_cpp = true;
896 break;
897 case 'V':
898 ctx.verbose = true;
899 break;
900 case 'P':
901 cpus_tmp = strtoul(optarg, NULL, 0);
902 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
903 ctx.cpus = cpus_tmp;
904 break;
905 case 'd':
906 case 'o':
907 ctx.device = xstrndup(optarg, IFNAMSIZ);
908 break;
909 case 'r':
910 ctx.rand = true;
911 break;
912 case 's':
913 slow = true;
914 ctx.cpus = 1;
915 ctx.smoke_test = true;
916 ctx.rhost = xstrdup(optarg);
917 break;
918 case 'R':
919 ctx.rfraw = true;
920 break;
921 case 'J':
922 ctx.jumbo_support = true;
923 break;
924 case 'c':
925 case 'i':
926 confname = xstrdup(optarg);
927 if (!strncmp("-", confname, strlen("-")))
928 ctx.cpus = 1;
929 break;
930 case 'u':
931 ctx.uid = strtoul(optarg, NULL, 0);
932 ctx.enforce = true;
933 break;
934 case 'g':
935 ctx.gid = strtoul(optarg, NULL, 0);
936 ctx.enforce = true;
937 break;
938 case 'k':
939 ctx.kpull = strtoul(optarg, NULL, 0);
940 break;
941 case 'E':
942 seed = strtoul(optarg, NULL, 0);
943 reseed = false;
944 break;
945 case 'n':
946 orig_num = strtoul(optarg, NULL, 0);
947 ctx.num = orig_num;
948 break;
949 case 't':
950 slow = true;
951 ctx.gap = strtoul(optarg, NULL, 0);
952 if (ctx.gap > 0)
953 /* Fall back to single core to not
954 * mess up correct timing. We are slow
955 * anyway!
957 ctx.cpus = 1;
958 break;
959 case 'S':
960 ptr = optarg;
961 ctx.reserve_size = 0;
963 for (j = i = strlen(optarg); i > 0; --i) {
964 if (!isdigit(optarg[j - i]))
965 break;
966 ptr++;
969 if (!strncmp(ptr, "KiB", strlen("KiB")))
970 ctx.reserve_size = 1 << 10;
971 else if (!strncmp(ptr, "MiB", strlen("MiB")))
972 ctx.reserve_size = 1 << 20;
973 else if (!strncmp(ptr, "GiB", strlen("GiB")))
974 ctx.reserve_size = 1 << 30;
975 else
976 panic("Syntax error in ring size param!\n");
977 *ptr = 0;
979 ctx.reserve_size *= strtol(optarg, NULL, 0);
980 break;
981 case '?':
982 switch (optopt) {
983 case 'd':
984 case 'c':
985 case 'n':
986 case 'S':
987 case 's':
988 case 'P':
989 case 'o':
990 case 'E':
991 case 'i':
992 case 'k':
993 case 'u':
994 case 'g':
995 case 't':
996 panic("Option -%c requires an argument!\n",
997 optopt);
998 default:
999 if (isprint(optopt))
1000 printf("Unknown option character `0x%X\'!\n", optopt);
1001 die();
1003 default:
1004 break;
1008 if (argc < 5)
1009 help();
1010 if (ctx.device == NULL)
1011 panic("No networking device given!\n");
1012 if (confname == NULL)
1013 panic("No configuration file given!\n");
1014 if (device_mtu(ctx.device) == 0)
1015 panic("This is no networking device!\n");
1017 register_signal(SIGINT, signal_handler);
1018 register_signal(SIGHUP, signal_handler);
1019 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1021 set_system_socket_memory(vals, array_size(vals));
1022 xlockme();
1024 if (ctx.rfraw) {
1025 ctx.device_trans = xstrdup(ctx.device);
1026 xfree(ctx.device);
1028 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1029 sleep(0);
1032 irq = device_irq_number(ctx.device);
1033 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1035 stats = setup_shared_var(ctx.cpus);
1037 for (i = 0; i < ctx.cpus; i++) {
1038 pid_t pid = fork();
1040 switch (pid) {
1041 case 0:
1042 if (reseed)
1043 seed = generate_srand_seed();
1044 srand(seed);
1046 cpu_affinity(i);
1047 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1049 goto thread_out;
1050 case -1:
1051 panic("Cannot fork processes!\n");
1055 for (i = 0; i < ctx.cpus; i++) {
1056 int status;
1058 wait(&status);
1059 if (WEXITSTATUS(status) == EXIT_FAILURE)
1060 die();
1063 if (ctx.rfraw)
1064 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1066 reset_system_socket_memory(vals, array_size(vals));
1068 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1069 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1070 sched_yield();
1072 tx_packets += stats[i].tx_packets;
1073 tx_bytes += stats[i].tx_bytes;
1076 fflush(stdout);
1077 printf("\n");
1078 printf("\r%12llu packets outgoing\n", tx_packets);
1079 printf("\r%12llu bytes outgoing\n", tx_bytes);
1080 for (i = 0; i < ctx.cpus; i++) {
1081 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1082 stats[i].tv_sec, stats[i].tv_usec, i,
1083 stats[i].tx_packets);
1086 thread_out:
1087 xunlockme();
1088 destroy_shared_var(stats, ctx.cpus);
1089 device_restore_irq_affinity_list();
1091 free(ctx.device);
1092 free(ctx.device_trans);
1093 free(ctx.rhost);
1094 free(confname);
1096 return 0;