build: Use -n option to head command
[netsniff-ng.git] / trafgen.c
blob735cdcbfe2e04f76f73a77e5edb49d4e71117e85
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 counter_id)
301 int j, i = counter_id;
302 size_t counter_max = packet_dyn[i].clen;
304 for (j = 0; j < counter_max; ++j) {
305 uint8_t val;
306 struct counter *counter = &packet_dyn[i].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[i].payload[counter->off] = val;
326 static void apply_randomizer(int rand_id)
328 int j, i = rand_id;
329 size_t rand_max = packet_dyn[i].rlen;
331 for (j = 0; j < rand_max; ++j) {
332 uint8_t val = (uint8_t) rand();
333 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
335 packets[i].payload[randomizer->off] = val;
339 static void apply_csum16(int csum_id)
341 int j, i = csum_id;
342 size_t csum_max = packet_dyn[i].slen;
344 for (j = 0; j < csum_max; ++j) {
345 uint16_t sum = 0;
346 struct csum16 *csum = &packet_dyn[i].csum[j];
348 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
349 if (unlikely(csum->to >= packets[i].len))
350 csum->to = packets[i].len - 1;
352 switch (csum->which) {
353 case CSUM_IP:
354 sum = calc_csum(packets[i].payload + csum->from,
355 csum->to - csum->from + 1, 0);
356 break;
357 case CSUM_UDP:
358 sum = p4_csum((void *) packets[i].payload + csum->from,
359 packets[i].payload + csum->to,
360 (packets[i].len - csum->to),
361 IPPROTO_UDP);
362 break;
363 case CSUM_TCP:
364 sum = p4_csum((void *) packets[i].payload + csum->from,
365 packets[i].payload + csum->to,
366 (packets[i].len - csum->to),
367 IPPROTO_TCP);
368 break;
369 default:
370 bug();
371 break;
374 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
378 static struct cpu_stats *setup_shared_var(unsigned long cpus)
380 int fd;
381 size_t len = cpus * sizeof(struct cpu_stats);
382 char zbuff[len], file[256];
383 struct cpu_stats *buff;
385 fmemset(zbuff, 0, len);
386 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
388 fd = creat(file, S_IRUSR | S_IWUSR);
389 bug_on(fd < 0);
390 close(fd);
392 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
393 S_IRUSR | S_IWUSR);
394 write_or_die(fd, zbuff, len);
396 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
397 MAP_SHARED, fd, 0);
398 if (buff == MAP_FAILED)
399 panic("Cannot setup shared variable!\n");
401 close(fd);
402 unlink(file);
404 memset(buff, 0, len);
405 return buff;
408 static void destroy_shared_var(void *buff, unsigned long cpus)
410 munmap(buff, cpus * sizeof(struct cpu_stats));
413 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
415 int i;
417 printf("{");
418 for (i = 0; i < len; ++i) {
419 if (i % 15 == 0)
420 printf("\n ");
421 printf("0x%02x, ", payload[i]);
423 printf("\n}\n");
424 fflush(stdout);
427 static int xmit_smoke_setup(struct ctx *ctx)
429 int icmp_sock, ret, ttl = 64;
430 struct icmp_filter filter;
432 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
433 if (icmp_sock < 0)
434 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
436 filter.data = ~(1 << ICMP_ECHOREPLY);
438 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
439 if (ret < 0)
440 panic("Cannot install filter!\n");
442 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
443 if (ret < 0)
444 panic("Cannot set TTL!\n");
446 memset(&ctx->dest, 0, sizeof(ctx->dest));
447 ctx->dest.sin_family = AF_INET;
448 ctx->dest.sin_port = 0;
450 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
451 if (ret < 0)
452 panic("Cannot resolv address!\n");
454 return icmp_sock;
457 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
459 int ret, i, j = 0, probes = 100;
460 short ident, cnt = 1, idstore[probes];
461 uint8_t outpack[512], *data;
462 struct icmphdr *icmp;
463 struct iphdr *ip;
464 size_t len = sizeof(*icmp) + 56;
465 struct sockaddr_in from;
466 socklen_t from_len;
467 struct pollfd fds = {
468 .fd = icmp_sock,
469 .events = POLLIN,
472 fmemset(idstore, 0, sizeof(idstore));
473 while (probes-- > 0) {
474 while ((ident = htons((short) rand())) == 0)
475 sleep(0);
476 idstore[j++] = ident;
478 memset(outpack, 0, sizeof(outpack));
479 icmp = (void *) outpack;
480 icmp->type = ICMP_ECHO;
481 icmp->un.echo.id = ident;
482 icmp->un.echo.sequence = htons(cnt++);
484 data = ((uint8_t *) outpack + sizeof(*icmp));
485 for (i = 0; i < 56; ++i)
486 data[i] = (uint8_t) rand();
488 icmp->checksum = csum((unsigned short *) outpack,
489 len / sizeof(unsigned short));
491 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
492 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
493 if (unlikely(ret != len))
494 panic("Cannot send out probe: %s!\n", strerror(errno));
496 ret = poll(&fds, 1, 50);
497 if (ret < 0)
498 panic("Poll failed!\n");
500 if (fds.revents & POLLIN) {
501 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
502 (struct sockaddr *) &from, &from_len);
503 if (unlikely(ret <= 0))
504 panic("Probe receive failed!\n");
505 if (unlikely(from_len != sizeof(ctx->dest)))
506 continue;
507 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
508 continue;
509 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
510 continue;
511 ip = (void *) outpack;
512 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
513 continue;
514 icmp = (void *) outpack + ip->ihl * 4;
515 for (i = 0; i < array_size(idstore); ++i) {
516 if (unlikely(icmp->un.echo.id != idstore[i]))
517 continue;
518 return 0;
523 return -1;
526 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
528 int ret, icmp_sock = -1;
529 unsigned long num = 1, i = 0;
530 struct timeval start, end, diff;
531 unsigned long long tx_bytes = 0, tx_packets = 0;
532 struct packet_dyn *pktd;
533 struct sockaddr_ll saddr = {
534 .sll_family = PF_PACKET,
535 .sll_halen = ETH_ALEN,
536 .sll_ifindex = device_ifindex(ctx->device),
539 if (ctx->num > 0)
540 num = ctx->num;
541 if (ctx->num == 0 && orig_num > 0)
542 num = 0;
544 if (ctx->smoke_test)
545 icmp_sock = xmit_smoke_setup(ctx);
547 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
549 bug_on(gettimeofday(&start, NULL));
551 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
552 pktd = &packet_dyn[i];
553 if (pktd->clen + pktd->rlen + pktd->slen) {
554 apply_counter(i);
555 apply_randomizer(i);
556 apply_csum16(i);
558 retry:
559 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
560 (struct sockaddr *) &saddr, sizeof(saddr));
561 if (unlikely(ret < 0)) {
562 if (errno == ENOBUFS) {
563 sched_yield();
564 goto retry;
567 panic("Sendto error: %s!\n", strerror(errno));
570 tx_bytes += packets[i].len;
571 tx_packets++;
573 if (ctx->smoke_test) {
574 ret = xmit_smoke_probe(icmp_sock, ctx);
575 if (unlikely(ret < 0)) {
576 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
577 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
578 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
579 i, seed);
581 dump_trafgen_snippet(packets[i].payload, packets[i].len);
582 break;
586 if (!ctx->rand) {
587 i++;
588 if (i >= plen)
589 i = 0;
590 } else
591 i = rand() % plen;
593 if (ctx->num > 0)
594 num--;
596 if (ctx->gap > 0)
597 usleep(ctx->gap);
600 bug_on(gettimeofday(&end, NULL));
601 timersub(&end, &start, &diff);
603 if (ctx->smoke_test)
604 close(icmp_sock);
606 stats[cpu].tx_packets = tx_packets;
607 stats[cpu].tx_bytes = tx_bytes;
608 stats[cpu].tv_sec = diff.tv_sec;
609 stats[cpu].tv_usec = diff.tv_usec;
611 stats[cpu].state |= CPU_STATS_STATE_RES;
614 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
616 int ifindex = device_ifindex(ctx->device);
617 uint8_t *out = NULL;
618 unsigned int it = 0;
619 unsigned long num = 1, i = 0, size;
620 struct ring tx_ring;
621 struct frame_map *hdr;
622 struct timeval start, end, diff;
623 struct packet_dyn *pktd;
624 unsigned long long tx_bytes = 0, tx_packets = 0;
626 fmemset(&tx_ring, 0, sizeof(tx_ring));
628 size = ring_size(ctx->device, ctx->reserve_size);
630 set_sock_prio(sock, 512);
631 set_packet_loss_discard(sock);
633 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
634 create_tx_ring(sock, &tx_ring, ctx->verbose);
635 mmap_tx_ring(sock, &tx_ring);
636 alloc_tx_ring_frames(sock, &tx_ring);
637 bind_tx_ring(sock, &tx_ring, ifindex);
639 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
641 if (ctx->kpull)
642 interval = ctx->kpull;
643 if (ctx->num > 0)
644 num = ctx->num;
645 if (ctx->num == 0 && orig_num > 0)
646 num = 0;
648 set_itimer_interval_value(&itimer, 0, interval);
649 setitimer(ITIMER_REAL, &itimer, NULL);
651 bug_on(gettimeofday(&start, NULL));
653 while (likely(sigint == 0) && likely(num > 0) && likely(plen > 0)) {
654 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
655 hdr = tx_ring.frames[it].iov_base;
656 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
658 hdr->tp_h.tp_snaplen = packets[i].len;
659 hdr->tp_h.tp_len = packets[i].len;
661 pktd = &packet_dyn[i];
662 if (pktd->clen + pktd->rlen + pktd->slen) {
663 apply_counter(i);
664 apply_randomizer(i);
665 apply_csum16(i);
668 fmemcpy(out, packets[i].payload, packets[i].len);
670 tx_bytes += packets[i].len;
671 tx_packets++;
673 if (!ctx->rand) {
674 i++;
675 if (i >= plen)
676 i = 0;
677 } else
678 i = rand() % plen;
680 kernel_may_pull_from_tx(&hdr->tp_h);
682 it++;
683 if (it >= tx_ring.layout.tp_frame_nr)
684 it = 0;
686 if (ctx->num > 0)
687 num--;
689 if (unlikely(sigint == 1))
690 break;
694 bug_on(gettimeofday(&end, NULL));
695 timersub(&end, &start, &diff);
697 timer_purge();
699 destroy_tx_ring(sock, &tx_ring);
701 stats[cpu].tx_packets = tx_packets;
702 stats[cpu].tx_bytes = tx_bytes;
703 stats[cpu].tv_sec = diff.tv_sec;
704 stats[cpu].tv_usec = diff.tv_usec;
706 stats[cpu].state |= CPU_STATS_STATE_RES;
709 static inline void __set_state(int cpu, sig_atomic_t s)
711 stats[cpu].state = s;
714 static inline sig_atomic_t __get_state(int cpu)
716 return stats[cpu].state;
719 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
721 int i;
722 unsigned long total;
724 for (i = 0, total = plen; i < ctx->cpus; i++) {
725 if (i == cpu)
726 continue;
728 while ((__get_state(i) &
729 (CPU_STATS_STATE_CFG |
730 CPU_STATS_STATE_RES)) == 0 &&
731 sigint == 0)
732 sched_yield();
734 total += stats[i].cf_packets;
737 return total;
740 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
742 int i, cpu_sel;
743 unsigned long total;
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 (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 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 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 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, i, j, vals[4] = {0}, irq;
882 char *confname = NULL, *ptr;
883 unsigned long cpus_tmp, orig_num = 0;
884 unsigned long long tx_packets, tx_bytes;
885 struct ctx ctx;
887 fmemset(&ctx, 0, sizeof(ctx));
888 ctx.cpus = get_number_cpus_online();
889 ctx.uid = getuid();
890 ctx.gid = getgid();
892 while ((c = getopt_long(argc, argv, short_options, long_options,
893 &opt_index)) != EOF) {
894 switch (c) {
895 case 'h':
896 help();
897 break;
898 case 'v':
899 version();
900 break;
901 case 'C':
902 cpustats = false;
903 break;
904 case 'e':
905 example();
906 break;
907 case 'p':
908 invoke_cpp = true;
909 break;
910 case 'V':
911 ctx.verbose = true;
912 break;
913 case 'P':
914 cpus_tmp = strtoul(optarg, NULL, 0);
915 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
916 ctx.cpus = cpus_tmp;
917 break;
918 case 'd':
919 case 'o':
920 ctx.device = xstrndup(optarg, IFNAMSIZ);
921 break;
922 case 'r':
923 ctx.rand = true;
924 break;
925 case 's':
926 slow = true;
927 ctx.cpus = 1;
928 ctx.smoke_test = true;
929 ctx.rhost = xstrdup(optarg);
930 break;
931 case 'R':
932 ctx.rfraw = true;
933 break;
934 case 'J':
935 ctx.jumbo_support = true;
936 break;
937 case 'c':
938 case 'i':
939 confname = xstrdup(optarg);
940 if (!strncmp("-", confname, strlen("-")))
941 ctx.cpus = 1;
942 break;
943 case 'u':
944 ctx.uid = strtoul(optarg, NULL, 0);
945 ctx.enforce = true;
946 break;
947 case 'g':
948 ctx.gid = strtoul(optarg, NULL, 0);
949 ctx.enforce = true;
950 break;
951 case 'k':
952 ctx.kpull = strtoul(optarg, NULL, 0);
953 break;
954 case 'E':
955 seed = strtoul(optarg, NULL, 0);
956 reseed = false;
957 break;
958 case 'n':
959 orig_num = strtoul(optarg, NULL, 0);
960 ctx.num = orig_num;
961 break;
962 case 't':
963 slow = true;
964 ctx.gap = strtoul(optarg, NULL, 0);
965 if (ctx.gap > 0)
966 /* Fall back to single core to not
967 * mess up correct timing. We are slow
968 * anyway!
970 ctx.cpus = 1;
971 break;
972 case 'S':
973 ptr = optarg;
974 ctx.reserve_size = 0;
976 for (j = i = strlen(optarg); i > 0; --i) {
977 if (!isdigit(optarg[j - i]))
978 break;
979 ptr++;
982 if (!strncmp(ptr, "KiB", strlen("KiB")))
983 ctx.reserve_size = 1 << 10;
984 else if (!strncmp(ptr, "MiB", strlen("MiB")))
985 ctx.reserve_size = 1 << 20;
986 else if (!strncmp(ptr, "GiB", strlen("GiB")))
987 ctx.reserve_size = 1 << 30;
988 else
989 panic("Syntax error in ring size param!\n");
990 *ptr = 0;
992 ctx.reserve_size *= strtol(optarg, NULL, 0);
993 break;
994 case '?':
995 switch (optopt) {
996 case 'd':
997 case 'c':
998 case 'n':
999 case 'S':
1000 case 's':
1001 case 'P':
1002 case 'o':
1003 case 'E':
1004 case 'i':
1005 case 'k':
1006 case 'u':
1007 case 'g':
1008 case 't':
1009 panic("Option -%c requires an argument!\n",
1010 optopt);
1011 default:
1012 if (isprint(optopt))
1013 printf("Unknown option character `0x%X\'!\n", optopt);
1014 die();
1016 default:
1017 break;
1021 if (argc < 5)
1022 help();
1023 if (ctx.device == NULL)
1024 panic("No networking device given!\n");
1025 if (confname == NULL)
1026 panic("No configuration file given!\n");
1027 if (device_mtu(ctx.device) == 0)
1028 panic("This is no networking device!\n");
1030 register_signal(SIGINT, signal_handler);
1031 register_signal(SIGHUP, signal_handler);
1032 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1034 set_system_socket_memory(vals, array_size(vals));
1035 xlockme();
1037 if (ctx.rfraw) {
1038 ctx.device_trans = xstrdup(ctx.device);
1039 xfree(ctx.device);
1041 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1042 sleep(0);
1045 irq = device_irq_number(ctx.device);
1046 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1048 stats = setup_shared_var(ctx.cpus);
1050 for (i = 0; i < ctx.cpus; i++) {
1051 pid_t pid = fork();
1053 switch (pid) {
1054 case 0:
1055 if (reseed)
1056 seed = generate_srand_seed();
1057 srand(seed);
1059 cpu_affinity(i);
1060 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1062 goto thread_out;
1063 case -1:
1064 panic("Cannot fork processes!\n");
1068 for (i = 0; i < ctx.cpus; i++) {
1069 int status;
1071 wait(&status);
1072 if (WEXITSTATUS(status) == EXIT_FAILURE)
1073 die();
1076 if (ctx.rfraw)
1077 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1079 reset_system_socket_memory(vals, array_size(vals));
1081 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1082 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1083 sched_yield();
1085 tx_packets += stats[i].tx_packets;
1086 tx_bytes += stats[i].tx_bytes;
1089 fflush(stdout);
1090 printf("\n");
1091 printf("\r%12llu packets outgoing\n", tx_packets);
1092 printf("\r%12llu bytes outgoing\n", tx_bytes);
1093 for (i = 0; cpustats && i < ctx.cpus; i++) {
1094 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1095 stats[i].tv_sec, stats[i].tv_usec, i,
1096 stats[i].tx_packets);
1099 thread_out:
1100 xunlockme();
1101 destroy_shared_var(stats, ctx.cpus);
1102 device_restore_irq_affinity_list();
1104 free(ctx.device);
1105 free(ctx.device_trans);
1106 free(ctx.rhost);
1107 free(confname);
1109 return 0;