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.
14 #include <sys/socket.h>
15 #include <sys/types.h>
16 #include <sys/fsuid.h>
17 #include <sys/prctl.h>
22 #include <net/ethernet.h>
23 #include <netinet/in.h>
24 #include <netinet/ip.h>
25 #include <linux/icmp.h>
27 #include <arpa/inet.h>
52 #include "trafgen_conf.h"
58 #ifndef timeval_to_timespec
59 #define timeval_to_timespec(tv, ts) { \
60 (ts)->tv_sec = (tv)->tv_sec; \
61 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
72 enum shaper_type type
;
73 unsigned long long sent
;
74 unsigned long long rate
;
77 struct timespec delay
;
81 bool rand
, rfraw
, jumbo_support
, verbose
, smoke_test
, enforce
, qdisc_path
;
86 char *device
, *device_trans
, *rhost
;
87 struct sockaddr_in dest
;
93 unsigned long tv_sec
, tv_usec
;
94 unsigned long long tx_packets
, tx_bytes
;
95 unsigned long long cf_packets
, cf_bytes
;
96 unsigned long long cd_packets
;
100 static sig_atomic_t sigint
= 0;
102 struct packet
*packets
= NULL
;
105 struct packet_dyn
*packet_dyn
= NULL
;
108 static const char *short_options
= "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQqD:b:";
109 static const struct option long_options
[] = {
110 {"dev", required_argument
, NULL
, 'd'},
111 {"out", required_argument
, NULL
, 'o'},
112 {"in", required_argument
, NULL
, 'i'},
113 {"conf", required_argument
, NULL
, 'c'},
114 {"num", required_argument
, NULL
, 'n'},
115 {"gap", required_argument
, NULL
, 't'},
116 {"rate", required_argument
, NULL
, 'b'},
117 {"cpus", required_argument
, NULL
, 'P'},
118 {"ring-size", required_argument
, NULL
, 'S'},
119 {"kernel-pull", required_argument
, NULL
, 'k'},
120 {"smoke-test", required_argument
, NULL
, 's'},
121 {"seed", required_argument
, NULL
, 'E'},
122 {"user", required_argument
, NULL
, 'u'},
123 {"group", required_argument
, NULL
, 'g'},
124 {"prio-high", no_argument
, NULL
, 'H'},
125 {"notouch-irq", no_argument
, NULL
, 'Q'},
126 {"no-sock-mem", no_argument
, NULL
, 'A'},
127 {"qdisc-path", no_argument
, NULL
, 'q'},
128 {"jumbo-support", no_argument
, NULL
, 'J'},
129 {"no-cpu-stats", no_argument
, NULL
, 'C'},
130 {"cpp", no_argument
, NULL
, 'p'},
131 {"define", required_argument
, NULL
, 'D'},
132 {"rfraw", no_argument
, NULL
, 'R'},
133 {"rand", no_argument
, NULL
, 'r'},
134 {"verbose", no_argument
, NULL
, 'V'},
135 {"version", no_argument
, NULL
, 'v'},
136 {"example", no_argument
, NULL
, 'e'},
137 {"help", no_argument
, NULL
, 'h'},
141 static const char *copyright
= "Please report bugs to <netsniff-ng@googlegroups.com>\n"
142 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
143 "Swiss federal institute of technology (ETH Zurich)\n"
144 "License: GNU GPL version 2.0\n"
145 "This is free software: you are free to change and redistribute it.\n"
146 "There is NO WARRANTY, to the extent permitted by law.";
149 static struct cpu_stats
*stats
;
150 static unsigned int seed
;
152 #define CPU_STATS_STATE_CFG 1
153 #define CPU_STATS_STATE_CHK 2
154 #define CPU_STATS_STATE_RES 4
157 # define ICMP_FILTER 1
164 #define SMOKE_N_PROBES 100
166 #define PKT_MIN_LEN 14
168 static void signal_handler(int number
)
181 static void __noreturn
help(void)
183 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING
);
184 puts("http://www.netsniff-ng.org\n\n"
185 "Usage: trafgen [options] [packet]\n"
187 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
188 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
189 " -p|--cpp Run packet config through C preprocessor\n"
190 " -D|--define Add macro/define for C preprocessor\n"
191 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
192 " -R|--rfraw Inject raw 802.11 frames\n"
193 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
194 " -n|--num <uint> Number of packets until exit (def: 0)\n"
195 " -r|--rand Randomize packet selection (def: round robin)\n"
196 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
197 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
198 " -b|--rate <rate> Send traffic at specified rate (pps/B/kB/MB/GB/kbit/Mbit/Gbit/KiB/MiB/GiB)\n"
199 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
200 " -E|--seed <uint> Manually set srand(3) seed\n"
201 " -u|--user <userid> Drop privileges and change to userid\n"
202 " -g|--group <groupid> Drop privileges and change to groupid\n"
203 " -H|--prio-high Make this high priority process\n"
204 " -A|--no-sock-mem Don't tune core socket memory\n"
205 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
206 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
207 " -V|--verbose Be more verbose\n"
208 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
209 " -v|--version Show version and exit\n"
210 " -e|--example Show built-in packet config example\n"
211 " -h|--help Guess what?!\n\n"
213 " trafgen --dev eth0 --conf trafgen.cfg\n"
214 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
215 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
216 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
217 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
218 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
219 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
220 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
221 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
222 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
223 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
224 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
225 "Generate config files from existing pcap using netsniff-ng:\n"
226 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
228 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
229 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
230 " we assume the kernel crashed, thus we print the packet and quit.\n"
231 " In case you find a ping-of-death, please mention trafgen in your\n"
232 " commit message of the fix!\n\n"
233 " For introducing bit errors, delays with random variation and more,\n"
234 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
235 " For generating different package distributions, you can use scripting\n"
236 " to generate a trafgen config file with packet ratios as:\n\n"
237 " IMIX 64:7, 570:4, 1518:1\n"
238 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
239 " Cisco 64:7, 594:4, 1518:1\n"
240 " RPR Trimodal 64:60, 512:20, 1518:20\n"
241 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
246 static void __noreturn
example(void)
249 "/* Note: dynamic elements make trafgen slower! */\n"
250 "#include <stddef.h>\n\n"
252 " /* MAC Destination */\n"
253 " fill(0xff, ETH_ALEN),\n"
254 " /* MAC Source */\n"
255 " 0x00, 0x02, 0xb3, drnd(3),\n"
256 " /* IPv4 Protocol */\n"
258 " /* IPv4 Version, IHL, TOS */\n"
260 " /* IPv4 Total Len */\n"
262 " /* IPv4 Ident */\n"
264 " /* IPv4 Flags, Frag Off */\n"
270 " /* IPv4 Checksum (IP header from, to) */\n"
276 " /* TCP Source Port */\n"
278 " /* TCP Dest Port */\n"
280 " /* TCP Sequence Number */\n"
282 " /* TCP Ackn. Number */\n"
284 " /* TCP Header length + TCP SYN/ECN Flag */\n"
285 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
286 " /* Window Size */\n"
288 " /* TCP Checksum (offset IP, offset TCP) */\n"
289 " csumtcp(14, 34),\n"
290 " /* TCP Options */\n"
291 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
292 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
300 static void __noreturn
version(void)
302 printf("trafgen %s, Git id: %s\n", VERSION_LONG
, GITVERSION
);
303 puts("multithreaded zero-copy network packet generator\n"
304 "http://www.netsniff-ng.org\n");
309 static void apply_counter(int id
)
311 size_t j
, counter_max
= packet_dyn
[id
].clen
;
313 for (j
= 0; j
< counter_max
; ++j
) {
315 struct counter
*counter
= &packet_dyn
[id
].cnt
[j
];
317 val
= counter
->val
- counter
->min
;
319 switch (counter
->type
) {
321 val
= (val
+ counter
->inc
) % (counter
->max
- counter
->min
+ 1);
324 val
= (val
- counter
->inc
) % (counter
->min
- counter
->max
+ 1);
330 counter
->val
= val
+ counter
->min
;
331 packets
[id
].payload
[counter
->off
] = val
;
335 static void apply_randomizer(int id
)
337 size_t j
, rand_max
= packet_dyn
[id
].rlen
;
339 for (j
= 0; j
< rand_max
; ++j
) {
340 uint8_t val
= (uint8_t) rand();
341 struct randomizer
*randomizer
= &packet_dyn
[id
].rnd
[j
];
343 packets
[id
].payload
[randomizer
->off
] = val
;
347 static void apply_csum16(int id
)
349 size_t j
, csum_max
= packet_dyn
[id
].slen
;
351 for (j
= 0; j
< csum_max
; ++j
) {
353 struct csum16
*csum
= &packet_dyn
[id
].csum
[j
];
355 fmemset(&packets
[id
].payload
[csum
->off
], 0, sizeof(sum
));
356 if (unlikely((size_t) csum
->to
>= packets
[id
].len
))
357 csum
->to
= packets
[id
].len
- 1;
359 switch (csum
->which
) {
361 sum
= calc_csum(packets
[id
].payload
+ csum
->from
,
362 csum
->to
- csum
->from
+ 1);
365 sum
= p4_csum((void *) packets
[id
].payload
+ csum
->from
,
366 packets
[id
].payload
+ csum
->to
,
367 (packets
[id
].len
- csum
->to
),
371 sum
= p4_csum((void *) packets
[id
].payload
+ csum
->from
,
372 packets
[id
].payload
+ csum
->to
,
373 (packets
[id
].len
- csum
->to
),
377 sum
= p6_csum((void *) packets
[id
].payload
+ csum
->from
,
378 packets
[id
].payload
+ csum
->to
,
379 (packets
[id
].len
- csum
->to
),
383 sum
= p6_csum((void *) packets
[id
].payload
+ csum
->from
,
384 packets
[id
].payload
+ csum
->to
,
385 (packets
[id
].len
- csum
->to
),
393 fmemcpy(&packets
[id
].payload
[csum
->off
], &sum
, sizeof(sum
));
397 static void preprocess_packets(void)
401 for (i
= 0; i
< plen
; i
++) {
402 struct packet_dyn
*pktd
= &packet_dyn
[i
];
404 if (packet_dyn_has_only_csums(pktd
)) {
412 static struct cpu_stats
*setup_shared_var(unsigned int cpus
)
415 size_t len
= cpus
* sizeof(struct cpu_stats
);
416 char *zbuff
, file
[256];
417 struct cpu_stats
*buff
;
419 zbuff
= xzmalloc(len
);
420 slprintf(file
, sizeof(file
), ".tmp_mmap.%u", (unsigned int) rand());
422 fd
= creat(file
, S_IRUSR
| S_IWUSR
);
426 fd
= open_or_die_m(file
, O_RDWR
| O_CREAT
| O_TRUNC
,
428 write_or_die(fd
, zbuff
, len
);
431 buff
= mmap(NULL
, len
, PROT_READ
| PROT_WRITE
,
433 if (buff
== MAP_FAILED
)
434 panic("Cannot setup shared variable!\n");
439 memset(buff
, 0, len
);
443 static void destroy_shared_var(void *buff
, unsigned int cpus
)
445 munmap(buff
, cpus
* sizeof(struct cpu_stats
));
448 static void dump_trafgen_snippet(uint8_t *payload
, size_t len
)
453 for (i
= 0; i
< len
; ++i
) {
456 printf("0x%02x, ", payload
[i
]);
462 static int xmit_smoke_setup(struct ctx
*ctx
)
464 int icmp_sock
, ret
, ttl
= 64;
465 struct icmp_filter filter
;
467 icmp_sock
= socket(AF_INET
, SOCK_RAW
, IPPROTO_ICMP
);
469 panic("Cannot get a ICMP socket: %s!\n", strerror(errno
));
471 filter
.data
= ~(1 << ICMP_ECHOREPLY
);
473 ret
= setsockopt(icmp_sock
, SOL_RAW
, ICMP_FILTER
, &filter
, sizeof(filter
));
475 panic("Cannot install filter!\n");
477 ret
= setsockopt(icmp_sock
, SOL_IP
, IP_TTL
, &ttl
, sizeof(ttl
));
479 panic("Cannot set TTL!\n");
481 memset(&ctx
->dest
, 0, sizeof(ctx
->dest
));
482 ctx
->dest
.sin_family
= AF_INET
;
483 ctx
->dest
.sin_port
= 0;
485 ret
= inet_aton(ctx
->rhost
, &ctx
->dest
.sin_addr
);
487 panic("Cannot resolve address!\n");
492 static int xmit_smoke_probe(int icmp_sock
, struct ctx
*ctx
)
496 short ident
, cnt
= 1, idstore
[SMOKE_N_PROBES
];
497 uint8_t outpack
[512], *data
;
498 struct icmphdr
*icmp
;
500 size_t len
= sizeof(*icmp
) + 56;
501 struct sockaddr_in from
;
503 struct pollfd fds
= {
508 fmemset(idstore
, 0, sizeof(idstore
));
509 for (j
= 0; j
< SMOKE_N_PROBES
; j
++) {
510 while ((ident
= htons((short) rand())) == 0)
514 memset(outpack
, 0, sizeof(outpack
));
515 icmp
= (void *) outpack
;
516 icmp
->type
= ICMP_ECHO
;
517 icmp
->un
.echo
.id
= ident
;
518 icmp
->un
.echo
.sequence
= htons(cnt
++);
520 data
= ((uint8_t *) outpack
+ sizeof(*icmp
));
521 for (i
= 0; i
< 56; ++i
)
522 data
[i
] = (uint8_t) rand();
524 icmp
->checksum
= csum((unsigned short *) outpack
,
525 len
/ sizeof(unsigned short));
527 ret
= sendto(icmp_sock
, outpack
, len
, MSG_DONTWAIT
,
528 (struct sockaddr
*) &ctx
->dest
, sizeof(ctx
->dest
));
529 if (unlikely(ret
!= (int) len
))
530 panic("Cannot send out probe: %s!\n", strerror(errno
));
532 ret
= poll(&fds
, 1, 50);
534 panic("Poll failed!\n");
536 if (fds
.revents
& POLLIN
) {
537 ret
= recvfrom(icmp_sock
, outpack
, sizeof(outpack
), 0,
538 (struct sockaddr
*) &from
, &from_len
);
539 if (unlikely(ret
<= 0))
540 panic("Probe receive failed!\n");
541 if (unlikely(from_len
!= sizeof(ctx
->dest
)))
543 if (unlikely(memcmp(&from
, &ctx
->dest
, sizeof(ctx
->dest
))))
545 if (unlikely((size_t) ret
< sizeof(*ip
) + sizeof(*icmp
)))
547 ip
= (void *) outpack
;
548 if (unlikely(ip
->ihl
* 4 + sizeof(*icmp
) > (size_t) ret
))
550 icmp
= (void *) outpack
+ ip
->ihl
* 4;
551 for (i
= 0; i
< array_size(idstore
); ++i
) {
552 if (unlikely(icmp
->un
.echo
.id
!= idstore
[i
]))
562 static bool shaper_is_set(struct shaper
*sh
)
564 if ((sh
->delay
.tv_sec
| sh
->delay
.tv_nsec
) > 0)
567 return sh
->type
!= SHAPER_NONE
;
570 static void shaper_init(struct shaper
*sh
)
572 if (sh
->type
== SHAPER_NONE
)
575 memset(&sh
->delay
, 0, sizeof(struct timespec
));
576 bug_on(gettimeofday(&sh
->start
, NULL
));
580 static void shaper_set_delay(struct shaper
*sh
, time_t sec
, long int ns
)
582 sh
->delay
.tv_sec
= sec
;
583 sh
->delay
.tv_nsec
= ns
;
586 static void shaper_set_rate(struct shaper
*sh
, unsigned long long rate
,
587 enum shaper_type type
)
589 memset(sh
, 0, sizeof(struct shaper
));
594 static void shaper_delay(struct shaper
*sh
, unsigned long pkt_len
)
596 if (sh
->type
!= SHAPER_NONE
)
597 sh
->sent
+= sh
->type
== SHAPER_BYTES
? pkt_len
: 1;
599 if (sh
->sent
>= sh
->rate
&& sh
->rate
> 0) {
600 struct timeval delay_us
;
601 struct timeval time_sent
;
602 struct timeval time_1s
= { .tv_sec
= 1 };
604 bug_on(gettimeofday(&sh
->end
, NULL
));
605 timersub(&sh
->end
, &sh
->start
, &time_sent
);
607 if (timercmp(&time_1s
, &time_sent
, > )) {
608 timersub(&time_1s
, &time_sent
, &delay_us
);
609 timeval_to_timespec(&delay_us
, &sh
->delay
);
613 if ((sh
->delay
.tv_sec
| sh
->delay
.tv_nsec
) > 0) {
614 nanosleep(&sh
->delay
, NULL
);
620 static void xmit_slowpath_or_die(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig_num
)
622 int ret
, icmp_sock
= -1;
623 unsigned long num
= 1, i
= 0;
624 struct timeval start
, end
, diff
;
625 unsigned long long tx_bytes
= 0, tx_packets
= 0;
626 struct packet_dyn
*pktd
;
627 struct sockaddr_ll saddr
= {
628 .sll_family
= PF_PACKET
,
629 .sll_halen
= ETH_ALEN
,
630 .sll_ifindex
= device_ifindex(ctx
->device
),
635 if (ctx
->num
== 0 && orig_num
> 0)
639 icmp_sock
= xmit_smoke_setup(ctx
);
641 drop_privileges(ctx
->enforce
, ctx
->uid
, ctx
->gid
);
643 bug_on(gettimeofday(&start
, NULL
));
645 if (shaper_is_set(&ctx
->sh
))
646 shaper_init(&ctx
->sh
);
648 while (likely(sigint
== 0 && num
> 0 && plen
> 0)) {
649 pktd
= &packet_dyn
[i
];
650 if (packet_dyn_has_elems(pktd
)) {
656 ret
= sendto(sock
, packets
[i
].payload
, packets
[i
].len
, 0,
657 (struct sockaddr
*) &saddr
, sizeof(saddr
));
658 if (unlikely(ret
< 0)) {
659 if (errno
== ENOBUFS
) {
664 panic("Sendto error: %s!\n", strerror(errno
));
667 tx_bytes
+= packets
[i
].len
;
670 if (ctx
->smoke_test
) {
671 ret
= xmit_smoke_probe(icmp_sock
, ctx
);
672 if (unlikely(ret
< 0)) {
673 printf("%sSmoke test alert:%s\n", colorize_start(bold
), colorize_end());
674 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
675 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
678 dump_trafgen_snippet(packets
[i
].payload
, packets
[i
].len
);
693 if (shaper_is_set(&ctx
->sh
))
694 shaper_delay(&ctx
->sh
, packets
[i
].len
);
697 bug_on(gettimeofday(&end
, NULL
));
698 timersub(&end
, &start
, &diff
);
703 stats
[cpu
].tx_packets
= tx_packets
;
704 stats
[cpu
].tx_bytes
= tx_bytes
;
705 stats
[cpu
].tv_sec
= diff
.tv_sec
;
706 stats
[cpu
].tv_usec
= diff
.tv_usec
;
708 stats
[cpu
].state
|= CPU_STATS_STATE_RES
;
711 static void xmit_fastpath_or_die(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig_num
)
713 int ifindex
= device_ifindex(ctx
->device
);
716 unsigned long num
= 1, i
= 0;
717 size_t size
= ring_size(ctx
->device
, ctx
->reserve_size
);
719 struct frame_map
*hdr
;
720 struct timeval start
, end
, diff
;
721 struct packet_dyn
*pktd
;
722 unsigned long long tx_bytes
= 0, tx_packets
= 0;
724 set_sock_prio(sock
, 512);
726 ring_tx_setup(&tx_ring
, sock
, size
, ifindex
, ctx
->jumbo_support
, ctx
->verbose
);
728 drop_privileges(ctx
->enforce
, ctx
->uid
, ctx
->gid
);
732 if (ctx
->num
== 0 && orig_num
> 0)
735 bug_on(gettimeofday(&start
, NULL
));
737 while (likely(sigint
== 0 && num
> 0 && plen
> 0)) {
738 if (!user_may_pull_from_tx(tx_ring
.frames
[it
].iov_base
)) {
739 int ret
= pull_and_flush_tx_ring(sock
);
740 if (unlikely(ret
< 0)) {
741 /* We could hit EBADF if the socket has been closed before
742 * the timer was triggered.
744 if (errno
!= EBADF
&& errno
!= ENOBUFS
)
745 panic("Flushing TX_RING failed: %s!\n", strerror(errno
));
751 hdr
= tx_ring
.frames
[it
].iov_base
;
752 out
= ((uint8_t *) hdr
) + TPACKET2_HDRLEN
- sizeof(struct sockaddr_ll
);
754 hdr
->tp_h
.tp_snaplen
= packets
[i
].len
;
755 hdr
->tp_h
.tp_len
= packets
[i
].len
;
757 pktd
= &packet_dyn
[i
];
758 if (packet_dyn_has_elems(pktd
)) {
764 fmemcpy(out
, packets
[i
].payload
, packets
[i
].len
);
766 tx_bytes
+= packets
[i
].len
;
776 kernel_may_pull_from_tx(&hdr
->tp_h
);
779 if (it
>= tx_ring
.layout
.tp_frame_nr
)
786 bug_on(gettimeofday(&end
, NULL
));
787 timersub(&end
, &start
, &diff
);
789 pull_and_flush_tx_ring_wait(sock
);
790 destroy_tx_ring(sock
, &tx_ring
);
792 stats
[cpu
].tx_packets
= tx_packets
;
793 stats
[cpu
].tx_bytes
= tx_bytes
;
794 stats
[cpu
].tv_sec
= diff
.tv_sec
;
795 stats
[cpu
].tv_usec
= diff
.tv_usec
;
797 stats
[cpu
].state
|= CPU_STATS_STATE_RES
;
800 static inline void __set_state(unsigned int cpu
, sig_atomic_t s
)
802 stats
[cpu
].state
= s
;
805 static inline sig_atomic_t __get_state(unsigned int cpu
)
807 return stats
[cpu
].state
;
810 static unsigned long __wait_and_sum_others(struct ctx
*ctx
, unsigned int cpu
)
815 for (i
= 0, total
= plen
; i
< ctx
->cpus
; i
++) {
819 while ((__get_state(i
) &
820 (CPU_STATS_STATE_CFG
|
821 CPU_STATS_STATE_RES
)) == 0 &&
825 total
+= stats
[i
].cf_packets
;
831 static void __correct_global_delta(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig
)
836 long long delta_correction
= 0;
838 for (i
= 0, total
= ctx
->num
; i
< ctx
->cpus
; i
++) {
842 while ((__get_state(i
) &
843 (CPU_STATS_STATE_CHK
|
844 CPU_STATS_STATE_RES
)) == 0 &&
848 total
+= stats
[i
].cd_packets
;
852 delta_correction
= -1 * ((long long) total
- orig
);
854 delta_correction
= +1 * ((long long) orig
- total
);
856 for (cpu_sel
= -1, i
= 0; i
< ctx
->cpus
; i
++) {
857 if (stats
[i
].cd_packets
> 0) {
858 if ((long long) stats
[i
].cd_packets
+
859 delta_correction
>= 0) {
866 if ((int) cpu
== cpu_sel
)
867 ctx
->num
+= delta_correction
;
870 static void __set_state_cf(unsigned int cpu
, unsigned long p
, unsigned long b
,
873 stats
[cpu
].cf_packets
= p
;
874 stats
[cpu
].cf_bytes
= b
;
875 stats
[cpu
].state
= s
;
878 static void __set_state_cd(unsigned int cpu
, unsigned long p
, sig_atomic_t s
)
880 stats
[cpu
].cd_packets
= p
;
881 stats
[cpu
].state
= s
;
884 static void xmit_packet_precheck(struct ctx
*ctx
, unsigned int cpu
)
886 unsigned long plen_total
, orig
= ctx
->num
;
887 size_t total_len
= 0;
890 bug_on(plen
!= dlen
);
892 for (i
= 0; i
< plen
; ++i
)
893 total_len
+= packets
[i
].len
;
895 __set_state_cf(cpu
, plen
, total_len
, CPU_STATS_STATE_CFG
);
896 plen_total
= __wait_and_sum_others(ctx
, cpu
);
899 ctx
->num
= (unsigned long) round((1.0 * plen
/ plen_total
) * orig
);
901 __set_state_cd(cpu
, ctx
->num
, CPU_STATS_STATE_CHK
|
902 CPU_STATS_STATE_CFG
);
903 __correct_global_delta(ctx
, cpu
, orig
);
907 __set_state(cpu
, CPU_STATS_STATE_RES
);
912 static void main_loop(struct ctx
*ctx
, char *confname
, bool slow
,
913 unsigned int cpu
, bool invoke_cpp
, char **cpp_argv
,
914 unsigned long orig_num
)
917 compile_packets_str(ctx
->packet_str
, ctx
->verbose
, cpu
);
919 compile_packets(confname
, ctx
->verbose
, cpu
, invoke_cpp
, cpp_argv
);
921 preprocess_packets();
923 xmit_packet_precheck(ctx
, cpu
);
927 size_t total_len
= 0, total_pkts
= 0;
929 for (i
= 0; i
< ctx
->cpus
; ++i
) {
930 total_len
+= stats
[i
].cf_bytes
;
931 total_pkts
+= stats
[i
].cf_packets
;
934 printf("%6zu packets to schedule\n", total_pkts
);
935 printf("%6zu bytes in total\n", total_len
);
936 printf("Running! Hang up with ^C!\n\n");
942 if (ctx
->qdisc_path
== false)
943 set_sock_qdisc_bypass(sock
, ctx
->verbose
);
946 xmit_slowpath_or_die(ctx
, cpu
, orig_num
);
948 xmit_fastpath_or_die(ctx
, cpu
, orig_num
);
955 static unsigned int generate_srand_seed(void)
960 fd
= open("/dev/urandom", O_RDONLY
);
964 read_or_die(fd
, &_seed
, sizeof(_seed
));
970 static void on_panic_del_rfmon(void *arg
)
972 leave_rfmon_mac80211(arg
);
975 int main(int argc
, char **argv
)
977 bool slow
= false, invoke_cpp
= false, reseed
= true, cpustats
= true;
978 bool prio_high
= false, set_irq_aff
= true, set_sock_mem
= true;
979 int c
, opt_index
, vals
[4] = {0}, irq
;
982 char *confname
= NULL
, *ptr
;
983 unsigned long cpus_tmp
, orig_num
= 0;
984 unsigned long long tx_packets
, tx_bytes
;
987 char **cpp_argv
= NULL
;
989 unsigned long long rate
;
990 enum shaper_type shape_type
;
991 struct timespec delay
;
993 fmemset(&ctx
, 0, sizeof(ctx
));
994 ctx
.cpus
= get_number_cpus_online();
997 ctx
.qdisc_path
= false;
999 /* Keep an initial small default size to reduce cache-misses. */
1000 ctx
.reserve_size
= 512 * (1 << 10);
1002 while ((c
= getopt_long(argc
, argv
, short_options
, long_options
,
1003 &opt_index
)) != EOF
) {
1021 cpp_argv
= argv_insert(cpp_argv
, &cpp_argc
, "-D");
1022 cpp_argv
= argv_insert(cpp_argv
, &cpp_argc
, optarg
);
1028 cpus_tmp
= strtoul(optarg
, NULL
, 0);
1029 if (cpus_tmp
> 0 && cpus_tmp
< ctx
.cpus
)
1030 ctx
.cpus
= cpus_tmp
;
1034 ctx
.device
= xstrndup(optarg
, IFNAMSIZ
);
1040 set_sock_mem
= false;
1043 set_irq_aff
= false;
1046 ctx
.qdisc_path
= true;
1054 ctx
.smoke_test
= true;
1055 ctx
.rhost
= xstrdup(optarg
);
1061 ctx
.jumbo_support
= true;
1065 confname
= xstrdup(optarg
);
1066 if (!strncmp("-", confname
, strlen("-")))
1070 ctx
.uid
= strtoul(optarg
, NULL
, 0);
1074 ctx
.gid
= strtoul(optarg
, NULL
, 0);
1078 printf("Option -k/--kernel-pull is no longer used and "
1079 "will be removed in a future release!\n");
1082 seed
= strtoul(optarg
, NULL
, 0);
1086 orig_num
= strtoul(optarg
, NULL
, 0);
1090 gap
= strtoul(optarg
, &ptr
, 0);
1091 if (!gap
&& optarg
== ptr
)
1092 panic("Invalid gap param\n");
1094 if (!strncmp(ptr
, "ns", strlen("ns"))) {
1095 delay
.tv_sec
= gap
/ 1000000000;
1096 delay
.tv_nsec
= gap
% 1000000000;
1097 } else if (*ptr
== '\0' || !strncmp(ptr
, "us", strlen("us"))) {
1098 /* Default to microseconds for backwards
1099 * compatibility if no postfix is given.
1101 delay
.tv_sec
= gap
/ 1000000;
1102 delay
.tv_nsec
= (gap
% 1000000) * 1000;
1103 } else if (!strncmp(ptr
, "ms", strlen("ms"))) {
1104 delay
.tv_sec
= gap
/ 1000;
1105 delay
.tv_nsec
= (gap
% 1000) * 1000000;
1106 } else if (!strncmp(ptr
, "s", strlen("s"))) {
1110 panic("Syntax error in time param!\n");
1113 shaper_set_delay(&ctx
.sh
, delay
.tv_sec
, delay
.tv_nsec
);
1116 rate
= strtoul(optarg
, &ptr
, 0);
1117 if (!rate
|| optarg
== ptr
)
1118 panic("Invalid rate param\n");
1120 if (strncmp(ptr
, "pps", strlen("pps")) == 0) {
1121 shape_type
= SHAPER_PKTS
;
1122 } else if (strncmp(ptr
, "B", strlen("B")) == 0) {
1123 shape_type
= SHAPER_BYTES
;
1124 } else if (strncmp(ptr
, "kB", strlen("kB")) == 0) {
1125 shape_type
= SHAPER_BYTES
;
1127 } else if (strncmp(ptr
, "MB", strlen("MB")) == 0) {
1128 shape_type
= SHAPER_BYTES
;
1129 rate
*= 1000 * 1000;
1130 } else if (strncmp(ptr
, "GB", strlen("GB")) == 0) {
1131 shape_type
= SHAPER_BYTES
;
1132 rate
*= 1000 * 1000 * 1000;
1133 } else if (strncmp(ptr
, "kbit", strlen("kbit")) == 0) {
1134 shape_type
= SHAPER_BYTES
;
1136 } else if (strncmp(ptr
, "Mbit", strlen("Mbit")) == 0) {
1137 shape_type
= SHAPER_BYTES
;
1138 rate
*= 1000 * 1000 / 8;
1139 } else if (strncmp(ptr
, "Gbit", strlen("Gbit")) == 0) {
1140 shape_type
= SHAPER_BYTES
;
1141 rate
*= 1000 * 1000 * 1000 / 8;
1142 } else if (strncmp(ptr
, "KiB", strlen("KiB")) == 0) {
1143 shape_type
= SHAPER_BYTES
;
1145 } else if (strncmp(ptr
, "MiB", strlen("MiB")) == 0) {
1146 shape_type
= SHAPER_BYTES
;
1148 } else if (strncmp(ptr
, "GiB", strlen("GiB")) == 0) {
1149 shape_type
= SHAPER_BYTES
;
1152 panic("Invalid unit type for rate\n");
1155 shaper_set_rate(&ctx
.sh
, rate
, shape_type
);
1158 ctx
.reserve_size
= strtoul(optarg
, &ptr
, 0);
1159 if (ctx
.reserve_size
== 0 && ptr
== optarg
)
1160 panic("Invalid ring size param\n");
1162 if (!strncmp(ptr
, "KiB", strlen("KiB")))
1163 ctx
.reserve_size
*= 1 << 10;
1164 else if (!strncmp(ptr
, "MiB", strlen("MiB")))
1165 ctx
.reserve_size
= 1 << 20;
1166 else if (!strncmp(ptr
, "GiB", strlen("GiB")))
1167 ctx
.reserve_size
*= 1 << 30;
1169 panic("Invalid ring size unit type\n");
1187 panic("Option -%c requires an argument!\n",
1190 if (isprint(optopt
))
1191 printf("Unknown option character `0x%X\'!\n", optopt
);
1199 if (argc
>= optind
) {
1201 ctx
.packet_str
= argv2str(optind
, argc
, argv
);
1204 if (argc
< min_opts
)
1206 if (ctx
.device
== NULL
)
1207 panic("No networking device given!\n");
1208 if (confname
== NULL
&& !ctx
.packet_str
)
1209 panic("No configuration file or packet string given!\n");
1210 if (device_mtu(ctx
.device
) == 0)
1211 panic("This is no networking device!\n");
1213 register_signal(SIGINT
, signal_handler
);
1214 register_signal(SIGQUIT
, signal_handler
);
1215 register_signal(SIGTERM
, signal_handler
);
1216 register_signal(SIGHUP
, signal_handler
);
1220 set_sched_status(SCHED_FIFO
, sched_get_priority_max(SCHED_FIFO
));
1224 set_system_socket_memory(vals
, array_size(vals
));
1228 ctx
.device_trans
= xstrdup(ctx
.device
);
1231 enter_rfmon_mac80211(ctx
.device_trans
, &ctx
.device
);
1232 panic_handler_add(on_panic_del_rfmon
, ctx
.device
);
1236 if (shaper_is_set(&ctx
.sh
)) {
1237 prctl(PR_SET_TIMERSLACK
, 1UL);
1238 /* Fall back to single core to not mess up correct timing.
1239 * We are slow anyway!
1246 * If number of packets is smaller than number of CPUs use only as
1247 * many CPUs as there are packets. Otherwise we end up sending more
1248 * packets than intended or none at all.
1251 ctx
.cpus
= min_t(unsigned int, ctx
.num
, ctx
.cpus
);
1253 irq
= device_irq_number(ctx
.device
);
1255 device_set_irq_affinity_list(irq
, 0, ctx
.cpus
- 1);
1257 stats
= setup_shared_var(ctx
.cpus
);
1259 for (i
= 0; i
< ctx
.cpus
; i
++) {
1265 seed
= generate_srand_seed();
1269 main_loop(&ctx
, confname
, slow
, i
, invoke_cpp
,
1270 cpp_argv
, orig_num
);
1274 panic("Cannot fork processes!\n");
1278 for (i
= 0; i
< ctx
.cpus
; i
++) {
1282 if (WEXITSTATUS(status
) == EXIT_FAILURE
)
1287 leave_rfmon_mac80211(ctx
.device
);
1290 reset_system_socket_memory(vals
, array_size(vals
));
1292 for (i
= 0, tx_packets
= tx_bytes
= 0; i
< ctx
.cpus
; i
++) {
1293 while ((__get_state(i
) & CPU_STATS_STATE_RES
) == 0)
1296 tx_packets
+= stats
[i
].tx_packets
;
1297 tx_bytes
+= stats
[i
].tx_bytes
;
1302 printf("\r%12llu packets outgoing\n", tx_packets
);
1303 printf("\r%12llu bytes outgoing\n", tx_bytes
);
1304 for (i
= 0; cpustats
&& i
< ctx
.cpus
; i
++) {
1305 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1306 stats
[i
].tv_sec
, stats
[i
].tv_usec
, i
,
1307 stats
[i
].tx_packets
);
1312 destroy_shared_var(stats
, ctx
.cpus
);
1314 device_restore_irq_affinity_list();
1316 argv_free(cpp_argv
);
1318 free(ctx
.device_trans
);
1321 free(ctx
.packet_str
);