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.
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/fsuid.h>
19 #include <sys/prctl.h>
23 #include <net/ethernet.h>
24 #include <netinet/in.h>
25 #include <netinet/ip.h>
26 #include <linux/icmp.h>
28 #include <arpa/inet.h>
53 #include "trafgen_conf.h"
58 #include "trafgen_proto.h"
70 enum shaper_type type
;
71 unsigned long long sent
;
72 unsigned long long rate
;
73 struct timeval tstamp
;
74 struct timespec delay
;
80 bool rand
, rfraw
, jumbo_support
, verbose
, smoke_test
, enforce
, qdisc_path
;
85 char *device
, *device_trans
, *rhost
;
86 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 Enable 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 slprintf(file
, sizeof(file
), ".tmp_mmap.XXXXXX");
420 fd
= mkostemp_or_die(file
, O_RDWR
| O_CREAT
| O_TRUNC
);
421 zbuff
= xzmalloc(len
);
422 write_or_die(fd
, zbuff
, len
);
425 buff
= mmap(NULL
, len
, PROT_READ
| PROT_WRITE
,
427 if (buff
== MAP_FAILED
)
428 panic("Cannot setup shared variable!\n");
433 memset(buff
, 0, len
);
437 static void destroy_shared_var(void *buff
, unsigned int cpus
)
439 munmap(buff
, cpus
* sizeof(struct cpu_stats
));
442 static void dump_trafgen_snippet(uint8_t *payload
, size_t len
)
447 for (i
= 0; i
< len
; ++i
) {
450 printf("0x%02x, ", payload
[i
]);
456 static int xmit_smoke_setup(struct ctx
*ctx
)
458 int icmp_sock
, ret
, ttl
= 64;
459 struct icmp_filter filter
;
461 icmp_sock
= socket(AF_INET
, SOCK_RAW
, IPPROTO_ICMP
);
463 panic("Cannot get a ICMP socket: %s!\n", strerror(errno
));
465 filter
.data
= ~(1 << ICMP_ECHOREPLY
);
467 ret
= setsockopt(icmp_sock
, SOL_RAW
, ICMP_FILTER
, &filter
, sizeof(filter
));
469 panic("Cannot install filter!\n");
471 ret
= setsockopt(icmp_sock
, SOL_IP
, IP_TTL
, &ttl
, sizeof(ttl
));
473 panic("Cannot set TTL!\n");
475 memset(&ctx
->dest
, 0, sizeof(ctx
->dest
));
476 ctx
->dest
.sin_family
= AF_INET
;
477 ctx
->dest
.sin_port
= 0;
479 ret
= inet_aton(ctx
->rhost
, &ctx
->dest
.sin_addr
);
481 panic("Cannot resolve address!\n");
486 static int xmit_smoke_probe(int icmp_sock
, struct ctx
*ctx
)
490 short ident
, cnt
= 1, idstore
[SMOKE_N_PROBES
];
491 uint8_t outpack
[512], *data
;
492 struct icmphdr
*icmp
;
494 size_t len
= sizeof(*icmp
) + 56;
495 struct sockaddr_in from
;
497 struct pollfd fds
= {
502 fmemset(idstore
, 0, sizeof(idstore
));
503 for (j
= 0; j
< SMOKE_N_PROBES
; j
++) {
504 while ((ident
= htons((short) rand())) == 0)
508 memset(outpack
, 0, sizeof(outpack
));
509 icmp
= (void *) outpack
;
510 icmp
->type
= ICMP_ECHO
;
511 icmp
->un
.echo
.id
= ident
;
512 icmp
->un
.echo
.sequence
= htons(cnt
++);
514 data
= ((uint8_t *) outpack
+ sizeof(*icmp
));
515 for (i
= 0; i
< 56; ++i
)
516 data
[i
] = (uint8_t) rand();
518 icmp
->checksum
= csum((unsigned short *) outpack
,
519 len
/ sizeof(unsigned short));
521 ret
= sendto(icmp_sock
, outpack
, len
, MSG_DONTWAIT
,
522 (struct sockaddr
*) &ctx
->dest
, sizeof(ctx
->dest
));
523 if (unlikely(ret
!= (int) len
))
524 panic("Cannot send out probe: %s!\n", strerror(errno
));
526 ret
= poll(&fds
, 1, 50);
528 panic("Poll failed!\n");
530 if (fds
.revents
& POLLIN
) {
531 ret
= recvfrom(icmp_sock
, outpack
, sizeof(outpack
), 0,
532 (struct sockaddr
*) &from
, &from_len
);
533 if (unlikely(ret
<= 0))
534 panic("Probe receive failed!\n");
535 if (unlikely(from_len
!= sizeof(ctx
->dest
)))
537 if (unlikely(memcmp(&from
, &ctx
->dest
, sizeof(ctx
->dest
))))
539 if (unlikely((size_t) ret
< sizeof(*ip
) + sizeof(*icmp
)))
541 ip
= (void *) outpack
;
542 if (unlikely(ip
->ihl
* 4 + sizeof(*icmp
) > (size_t) ret
))
544 icmp
= (void *) outpack
+ ip
->ihl
* 4;
545 for (i
= 0; i
< array_size(idstore
); ++i
) {
546 if (unlikely(icmp
->un
.echo
.id
!= idstore
[i
]))
556 static bool shaper_is_set(struct shaper
*sh
)
558 return sh
->type
!= SHAPER_NONE
;
561 static void shaper_init(struct shaper
*sh
)
563 if (sh
->type
== SHAPER_NONE
|| sh
->type
== SHAPER_DELAY
)
566 memset(&sh
->delay
, 0, sizeof(struct timespec
));
567 bug_on(gettimeofday(&sh
->start
, NULL
));
571 static void shaper_set_delay(struct shaper
*sh
, time_t sec
, long int ns
)
574 sh
->type
= SHAPER_NONE
;
578 sh
->type
= SHAPER_DELAY
;
579 sh
->delay
.tv_sec
= sec
;
580 sh
->delay
.tv_nsec
= ns
;
583 static void shaper_set_rate(struct shaper
*sh
, unsigned long long rate
,
584 enum shaper_type type
)
586 memset(sh
, 0, sizeof(struct shaper
));
591 static void shaper_set_tstamp(struct shaper
*sh
, struct timespec
*ts
)
593 TIMESPEC_TO_TIMEVAL(&sh
->tstamp
, ts
);
596 static void shaper_delay(struct shaper
*sh
, struct packet
*pkt
)
598 if (sh
->type
== SHAPER_BYTES
|| sh
->type
== SHAPER_PKTS
) {
599 unsigned long pkt_len
= pkt
->len
;
601 sh
->sent
+= sh
->type
== SHAPER_BYTES
? pkt_len
: 1;
603 if (sh
->sent
>= sh
->rate
&& sh
->rate
> 0) {
604 struct timeval delay_us
;
605 struct timeval time_sent
;
606 struct timeval time_1s
= { .tv_sec
= 1 };
608 bug_on(gettimeofday(&sh
->end
, NULL
));
609 timersub(&sh
->end
, &sh
->start
, &time_sent
);
611 if (timercmp(&time_1s
, &time_sent
, > )) {
612 timersub(&time_1s
, &time_sent
, &delay_us
);
613 TIMEVAL_TO_TIMESPEC(&delay_us
, &sh
->delay
);
616 } else if (sh
->type
== SHAPER_TSTAMP
) {
617 struct timeval tstamp
;
618 struct timeval pkt_diff
;
621 bug_on(gettimeofday(&sh
->end
, NULL
));
622 TIMESPEC_TO_TIMEVAL(&tstamp
, &pkt
->tstamp
);
623 timersub(&sh
->end
, &sh
->start
, &diff
);
624 timersub(&tstamp
, &sh
->tstamp
, &pkt_diff
);
626 if (timercmp(&diff
, &pkt_diff
, <)) {
627 struct timeval delay
;
629 timersub(&pkt_diff
, &diff
, &delay
);
630 TIMEVAL_TO_TIMESPEC(&delay
, &sh
->delay
);
633 memcpy(&sh
->tstamp
, &tstamp
, sizeof(sh
->tstamp
));
636 if ((sh
->delay
.tv_sec
| sh
->delay
.tv_nsec
) > 0) {
637 nanosleep(&sh
->delay
, NULL
);
643 static inline void packet_apply_dyn_elements(int idx
)
645 if (packet_dyn_has_elems(&packet_dyn
[idx
])) {
647 apply_randomizer(idx
);
651 if (packet_dyn_has_fields(&packet_dyn
[idx
])) {
654 for (i
= 0; i
< packet_dyn
[idx
].flen
; i
++)
655 proto_field_dyn_apply(packet_dyn
[idx
].fields
[i
]);
657 proto_packet_update(idx
);
661 static void xmit_slowpath_or_die(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig_num
)
663 int ret
, icmp_sock
= -1;
664 unsigned long num
= 1, i
= 0;
665 struct timeval start
, end
, diff
;
666 unsigned long long tx_bytes
= 0, tx_packets
= 0;
667 struct sockaddr_ll saddr
= {
668 .sll_family
= PF_PACKET
,
669 .sll_halen
= ETH_ALEN
,
670 .sll_ifindex
= device_ifindex(ctx
->device
),
675 if (ctx
->num
== 0 && orig_num
> 0)
679 icmp_sock
= xmit_smoke_setup(ctx
);
681 drop_privileges(ctx
->enforce
, ctx
->uid
, ctx
->gid
);
683 bug_on(gettimeofday(&start
, NULL
));
685 if (shaper_is_set(&ctx
->sh
))
686 shaper_init(&ctx
->sh
);
688 while (likely(sigint
== 0 && num
> 0 && plen
> 0)) {
689 packet_apply_dyn_elements(i
);
691 ret
= sendto(sock
, packets
[i
].payload
, packets
[i
].len
, 0,
692 (struct sockaddr
*) &saddr
, sizeof(saddr
));
693 if (unlikely(ret
< 0)) {
694 if (errno
== ENOBUFS
) {
699 panic("Sendto error: %s!\n", strerror(errno
));
702 tx_bytes
+= packets
[i
].len
;
705 if (ctx
->smoke_test
) {
706 ret
= xmit_smoke_probe(icmp_sock
, ctx
);
707 if (unlikely(ret
< 0)) {
708 printf("%sSmoke test alert:%s\n", colorize_start(bold
), colorize_end());
709 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
710 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
713 dump_trafgen_snippet(packets
[i
].payload
, packets
[i
].len
);
728 if (shaper_is_set(&ctx
->sh
))
729 shaper_delay(&ctx
->sh
, &packets
[i
]);
732 bug_on(gettimeofday(&end
, NULL
));
733 timersub(&end
, &start
, &diff
);
738 stats
[cpu
].tx_packets
= tx_packets
;
739 stats
[cpu
].tx_bytes
= tx_bytes
;
740 stats
[cpu
].tv_sec
= diff
.tv_sec
;
741 stats
[cpu
].tv_usec
= diff
.tv_usec
;
743 stats
[cpu
].state
|= CPU_STATS_STATE_RES
;
746 static void xmit_fastpath_or_die(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig_num
)
748 int ifindex
= device_ifindex(ctx
->device
);
751 unsigned long num
= 1, i
= 0;
752 size_t size
= ring_size(ctx
->device
, ctx
->reserve_size
);
754 struct frame_map
*hdr
;
755 struct timeval start
, end
, diff
;
756 unsigned long long tx_bytes
= 0, tx_packets
= 0;
758 set_sock_prio(sock
, 512);
760 ring_tx_setup(&tx_ring
, sock
, size
, ifindex
, ctx
->jumbo_support
, ctx
->verbose
);
762 drop_privileges(ctx
->enforce
, ctx
->uid
, ctx
->gid
);
766 if (ctx
->num
== 0 && orig_num
> 0)
769 bug_on(gettimeofday(&start
, NULL
));
771 while (likely(sigint
== 0 && num
> 0 && plen
> 0)) {
772 if (!user_may_pull_from_tx(tx_ring
.frames
[it
].iov_base
)) {
773 int ret
= pull_and_flush_tx_ring(sock
);
774 if (unlikely(ret
< 0)) {
775 /* We could hit EBADF if the socket has been closed before
776 * the timer was triggered.
778 if (errno
!= EBADF
&& errno
!= ENOBUFS
)
779 panic("Flushing TX_RING failed: %s!\n", strerror(errno
));
785 hdr
= tx_ring
.frames
[it
].iov_base
;
786 out
= ((uint8_t *) hdr
) + TPACKET2_HDRLEN
- sizeof(struct sockaddr_ll
);
788 hdr
->tp_h
.tp_snaplen
= packets
[i
].len
;
789 hdr
->tp_h
.tp_len
= packets
[i
].len
;
791 packet_apply_dyn_elements(i
);
793 fmemcpy(out
, packets
[i
].payload
, packets
[i
].len
);
795 tx_bytes
+= packets
[i
].len
;
805 kernel_may_pull_from_tx(&hdr
->tp_h
);
808 if (it
>= tx_ring
.layout
.tp_frame_nr
)
815 bug_on(gettimeofday(&end
, NULL
));
816 timersub(&end
, &start
, &diff
);
818 pull_and_flush_tx_ring_wait(sock
);
819 destroy_tx_ring(sock
, &tx_ring
);
821 stats
[cpu
].tx_packets
= tx_packets
;
822 stats
[cpu
].tx_bytes
= tx_bytes
;
823 stats
[cpu
].tv_sec
= diff
.tv_sec
;
824 stats
[cpu
].tv_usec
= diff
.tv_usec
;
826 stats
[cpu
].state
|= CPU_STATS_STATE_RES
;
829 static inline void __set_state(unsigned int cpu
, sig_atomic_t s
)
831 stats
[cpu
].state
= s
;
834 static inline sig_atomic_t __get_state(unsigned int cpu
)
836 return stats
[cpu
].state
;
839 static unsigned long __wait_and_sum_others(struct ctx
*ctx
, unsigned int cpu
)
844 for (i
= 0, total
= plen
; i
< ctx
->cpus
; i
++) {
848 while ((__get_state(i
) &
849 (CPU_STATS_STATE_CFG
|
850 CPU_STATS_STATE_RES
)) == 0 &&
854 total
+= stats
[i
].cf_packets
;
860 static void __correct_global_delta(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig
)
865 long long delta_correction
= 0;
867 for (i
= 0, total
= ctx
->num
; i
< ctx
->cpus
; i
++) {
871 while ((__get_state(i
) &
872 (CPU_STATS_STATE_CHK
|
873 CPU_STATS_STATE_RES
)) == 0 &&
877 total
+= stats
[i
].cd_packets
;
881 delta_correction
= -1 * ((long long) total
- orig
);
883 delta_correction
= +1 * ((long long) orig
- total
);
885 for (cpu_sel
= -1, i
= 0; i
< ctx
->cpus
; i
++) {
886 if (stats
[i
].cd_packets
> 0) {
887 if ((long long) stats
[i
].cd_packets
+
888 delta_correction
>= 0) {
895 if ((int) cpu
== cpu_sel
)
896 ctx
->num
+= delta_correction
;
899 static void __set_state_cf(unsigned int cpu
, unsigned long p
, unsigned long b
,
902 stats
[cpu
].cf_packets
= p
;
903 stats
[cpu
].cf_bytes
= b
;
904 stats
[cpu
].state
= s
;
907 static void __set_state_cd(unsigned int cpu
, unsigned long p
, sig_atomic_t s
)
909 stats
[cpu
].cd_packets
= p
;
910 stats
[cpu
].state
= s
;
913 static void xmit_packet_precheck(struct ctx
*ctx
, unsigned int cpu
)
915 unsigned long plen_total
, orig
= ctx
->num
;
916 size_t total_len
= 0;
919 bug_on(plen
!= dlen
);
921 for (i
= 0; i
< plen
; ++i
)
922 total_len
+= packets
[i
].len
;
924 __set_state_cf(cpu
, plen
, total_len
, CPU_STATS_STATE_CFG
);
925 plen_total
= __wait_and_sum_others(ctx
, cpu
);
928 ctx
->num
= (unsigned long) round((1.0 * plen
/ plen_total
) * orig
);
930 __set_state_cd(cpu
, ctx
->num
, CPU_STATS_STATE_CHK
|
931 CPU_STATS_STATE_CFG
);
932 __correct_global_delta(ctx
, cpu
, orig
);
936 __set_state(cpu
, CPU_STATS_STATE_RES
);
941 static void pcap_load_packets(const char *path
)
943 const struct pcap_file_ops
*pcap_io
= pcap_ops
[PCAP_OPS_SG
];
944 uint32_t link_type
, magic
;
951 fd
= open(path
, O_RDONLY
| O_LARGEFILE
| O_NOATIME
);
952 if (fd
< 0 && errno
== EPERM
)
953 fd
= open_or_die(path
, O_RDONLY
| O_LARGEFILE
);
955 panic("Cannot open file %s! %s.\n", path
, strerror(errno
));
957 if (pcap_io
->init_once_pcap
)
958 pcap_io
->init_once_pcap(false);
960 ret
= pcap_io
->pull_fhdr_pcap(fd
, &magic
, &link_type
);
962 panic("Error reading pcap header!\n");
964 if (pcap_io
->prepare_access_pcap
) {
965 ret
= pcap_io
->prepare_access_pcap(fd
, PCAP_MODE_RD
, false);
967 panic("Error prepare reading pcap!\n");
970 buf_len
= round_up(1024 * 1024, RUNTIME_PAGE_SIZE
);
971 buf
= xmalloc_aligned(buf_len
, CO_CACHE_LINE_SIZE
);
973 while (pcap_io
->read_pcap(fd
, &phdr
, magic
, buf
, buf_len
) > 0) {
977 pkt_len
= pcap_get_length(&phdr
, magic
);
983 pkt
= current_packet();
986 pkt
->payload
= xzmalloc(pkt_len
);
987 memcpy(pkt
->payload
, buf
, pkt_len
);
988 pcap_get_tstamp(&phdr
, magic
, &pkt
->tstamp
);
991 if (pcap_io
->prepare_close_pcap
)
992 pcap_io
->prepare_close_pcap(fd
, PCAP_MODE_RD
);
998 static void main_loop(struct ctx
*ctx
, char *confname
, bool slow
,
999 unsigned int cpu
, bool invoke_cpp
, char **cpp_argv
,
1000 unsigned long orig_num
)
1003 pcap_load_packets(ctx
->pcap_in
);
1004 shaper_set_tstamp(&ctx
->sh
, &packets
[0].tstamp
);
1007 if (ctx
->packet_str
)
1008 compile_packets_str(ctx
->packet_str
, ctx
->verbose
, cpu
);
1010 compile_packets(confname
, ctx
->verbose
, cpu
, invoke_cpp
, cpp_argv
);
1012 preprocess_packets();
1015 xmit_packet_precheck(ctx
, cpu
);
1019 size_t total_len
= 0, total_pkts
= 0;
1021 for (i
= 0; i
< ctx
->cpus
; ++i
) {
1022 total_len
+= stats
[i
].cf_bytes
;
1023 total_pkts
+= stats
[i
].cf_packets
;
1026 printf("%6zu packets to schedule\n", total_pkts
);
1027 printf("%6zu bytes in total\n", total_len
);
1028 printf("Running! Hang up with ^C!\n\n");
1034 if (ctx
->qdisc_path
== false)
1035 set_sock_qdisc_bypass(sock
, ctx
->verbose
);
1038 xmit_slowpath_or_die(ctx
, cpu
, orig_num
);
1040 xmit_fastpath_or_die(ctx
, cpu
, orig_num
);
1047 static unsigned int generate_srand_seed(void)
1052 fd
= open("/dev/urandom", O_RDONLY
);
1056 read_or_die(fd
, &_seed
, sizeof(_seed
));
1062 static void on_panic_del_rfmon(void *arg
)
1064 leave_rfmon_mac80211(arg
);
1067 int main(int argc
, char **argv
)
1069 bool slow
= false, invoke_cpp
= false, reseed
= true, cpustats
= true;
1070 bool prio_high
= false, set_irq_aff
= true, set_sock_mem
= true;
1071 int c
, vals
[4] = {0}, irq
;
1074 char *confname
= NULL
, *ptr
;
1075 unsigned long cpus_tmp
, orig_num
= 0;
1076 unsigned long long tx_packets
, tx_bytes
;
1079 char **cpp_argv
= NULL
;
1080 size_t cpp_argc
= 0;
1081 unsigned long long rate
;
1082 enum shaper_type shape_type
;
1083 struct timespec delay
;
1085 fmemset(&ctx
, 0, sizeof(ctx
));
1086 ctx
.cpus
= get_number_cpus_online();
1089 ctx
.qdisc_path
= false;
1091 /* Keep an initial small default size to reduce cache-misses. */
1092 ctx
.reserve_size
= 512 * (1 << 10);
1094 while ((c
= getopt_long(argc
, argv
, short_options
, long_options
,
1113 cpp_argv
= argv_insert(cpp_argv
, &cpp_argc
, "-D");
1114 cpp_argv
= argv_insert(cpp_argv
, &cpp_argc
, optarg
);
1120 cpus_tmp
= strtoul(optarg
, NULL
, 0);
1121 if (cpus_tmp
> 0 && cpus_tmp
< ctx
.cpus
)
1122 ctx
.cpus
= cpus_tmp
;
1126 ctx
.device
= xstrndup(optarg
, IFNAMSIZ
);
1132 set_sock_mem
= false;
1135 set_irq_aff
= false;
1138 ctx
.qdisc_path
= true;
1146 ctx
.smoke_test
= true;
1147 ctx
.rhost
= xstrdup(optarg
);
1153 ctx
.jumbo_support
= true;
1156 confname
= xstrdup(optarg
);
1157 if (strstr(confname
, ".pcap")) {
1158 ctx
.sh
.type
= SHAPER_TSTAMP
;
1159 ctx
.pcap_in
= confname
;
1163 if (!strncmp("-", confname
, strlen("-")))
1167 ctx
.uid
= strtoul(optarg
, NULL
, 0);
1171 ctx
.gid
= strtoul(optarg
, NULL
, 0);
1175 printf("Option -k/--kernel-pull is no longer used and "
1176 "will be removed in a future release!\n");
1179 seed
= strtoul(optarg
, NULL
, 0);
1183 orig_num
= strtoul(optarg
, NULL
, 0);
1187 gap
= strtoul(optarg
, &ptr
, 0);
1188 if (!gap
&& optarg
== ptr
)
1189 panic("Invalid gap param\n");
1191 if (!strncmp(ptr
, "ns", strlen("ns"))) {
1192 delay
.tv_sec
= gap
/ 1000000000;
1193 delay
.tv_nsec
= gap
% 1000000000;
1194 } else if (*ptr
== '\0' || !strncmp(ptr
, "us", strlen("us"))) {
1195 /* Default to microseconds for backwards
1196 * compatibility if no postfix is given.
1198 delay
.tv_sec
= gap
/ 1000000;
1199 delay
.tv_nsec
= (gap
% 1000000) * 1000;
1200 } else if (!strncmp(ptr
, "ms", strlen("ms"))) {
1201 delay
.tv_sec
= gap
/ 1000;
1202 delay
.tv_nsec
= (gap
% 1000) * 1000000;
1203 } else if (!strncmp(ptr
, "s", strlen("s"))) {
1207 panic("Syntax error in time param!\n");
1210 shaper_set_delay(&ctx
.sh
, delay
.tv_sec
, delay
.tv_nsec
);
1213 rate
= strtoul(optarg
, &ptr
, 0);
1214 if (!rate
&& optarg
== ptr
)
1215 panic("Invalid rate param\n");
1217 if (strncmp(ptr
, "pps", strlen("pps")) == 0) {
1218 shape_type
= SHAPER_PKTS
;
1219 } else if (strncmp(ptr
, "B", strlen("B")) == 0) {
1220 shape_type
= SHAPER_BYTES
;
1221 } else if (strncmp(ptr
, "kB", strlen("kB")) == 0) {
1222 shape_type
= SHAPER_BYTES
;
1224 } else if (strncmp(ptr
, "MB", strlen("MB")) == 0) {
1225 shape_type
= SHAPER_BYTES
;
1226 rate
*= 1000 * 1000;
1227 } else if (strncmp(ptr
, "GB", strlen("GB")) == 0) {
1228 shape_type
= SHAPER_BYTES
;
1229 rate
*= 1000 * 1000 * 1000;
1230 } else if (strncmp(ptr
, "kbit", strlen("kbit")) == 0) {
1231 shape_type
= SHAPER_BYTES
;
1233 } else if (strncmp(ptr
, "Mbit", strlen("Mbit")) == 0) {
1234 shape_type
= SHAPER_BYTES
;
1235 rate
*= 1000 * 1000 / 8;
1236 } else if (strncmp(ptr
, "Gbit", strlen("Gbit")) == 0) {
1237 shape_type
= SHAPER_BYTES
;
1238 rate
*= 1000 * 1000 * 1000 / 8;
1239 } else if (strncmp(ptr
, "KiB", strlen("KiB")) == 0) {
1240 shape_type
= SHAPER_BYTES
;
1242 } else if (strncmp(ptr
, "MiB", strlen("MiB")) == 0) {
1243 shape_type
= SHAPER_BYTES
;
1245 } else if (strncmp(ptr
, "GiB", strlen("GiB")) == 0) {
1246 shape_type
= SHAPER_BYTES
;
1249 shape_type
= SHAPER_NONE
;
1251 panic("Invalid unit type for rate\n");
1254 shaper_set_rate(&ctx
.sh
, rate
, shape_type
);
1257 ctx
.reserve_size
= strtoul(optarg
, &ptr
, 0);
1258 if (ctx
.reserve_size
== 0 && ptr
== optarg
)
1259 panic("Invalid ring size param\n");
1261 if (!strncmp(ptr
, "KiB", strlen("KiB")))
1262 ctx
.reserve_size
*= 1 << 10;
1263 else if (!strncmp(ptr
, "MiB", strlen("MiB")))
1264 ctx
.reserve_size
= 1 << 20;
1265 else if (!strncmp(ptr
, "GiB", strlen("GiB")))
1266 ctx
.reserve_size
*= 1 << 30;
1268 panic("Invalid ring size unit type\n");
1286 panic("Option -%c requires an argument!\n",
1289 if (isprint(optopt
))
1290 printf("Unknown option character `0x%X\'!\n", optopt
);
1298 if (argc
>= optind
) {
1300 ctx
.packet_str
= argv2str(optind
, argc
, argv
);
1303 if (argc
< min_opts
)
1305 if (ctx
.device
== NULL
)
1306 panic("No networking device given!\n");
1307 if (confname
== NULL
&& !ctx
.packet_str
)
1308 panic("No configuration file or packet string given!\n");
1309 if (device_mtu(ctx
.device
) == 0)
1310 panic("This is no networking device!\n");
1312 register_signal(SIGINT
, signal_handler
);
1313 register_signal(SIGQUIT
, signal_handler
);
1314 register_signal(SIGTERM
, signal_handler
);
1315 register_signal(SIGHUP
, signal_handler
);
1317 protos_init(ctx
.device
);
1321 set_sched_status(SCHED_FIFO
, sched_get_priority_max(SCHED_FIFO
));
1325 set_system_socket_memory(vals
, array_size(vals
));
1329 ctx
.device_trans
= xstrdup(ctx
.device
);
1332 enter_rfmon_mac80211(ctx
.device_trans
, &ctx
.device
);
1333 panic_handler_add(on_panic_del_rfmon
, ctx
.device
);
1337 if (shaper_is_set(&ctx
.sh
) || (ctx
.pcap_in
)) {
1338 prctl(PR_SET_TIMERSLACK
, 1UL);
1339 /* Fall back to single core to not mess up correct timing.
1340 * We are slow anyway!
1347 * If number of packets is smaller than number of CPUs use only as
1348 * many CPUs as there are packets. Otherwise we end up sending more
1349 * packets than intended or none at all.
1352 ctx
.cpus
= min_t(unsigned int, ctx
.num
, ctx
.cpus
);
1354 irq
= device_irq_number(ctx
.device
);
1356 device_set_irq_affinity_list(irq
, 0, ctx
.cpus
- 1);
1358 stats
= setup_shared_var(ctx
.cpus
);
1360 for (i
= 0; i
< ctx
.cpus
; i
++) {
1366 seed
= generate_srand_seed();
1370 main_loop(&ctx
, confname
, slow
, i
, invoke_cpp
,
1371 cpp_argv
, orig_num
);
1375 panic("Cannot fork processes!\n");
1379 for (i
= 0; i
< ctx
.cpus
; i
++) {
1383 if (WEXITSTATUS(status
) == EXIT_FAILURE
)
1388 leave_rfmon_mac80211(ctx
.device
);
1391 reset_system_socket_memory(vals
, array_size(vals
));
1393 for (i
= 0, tx_packets
= tx_bytes
= 0; i
< ctx
.cpus
; i
++) {
1394 while ((__get_state(i
) & CPU_STATS_STATE_RES
) == 0)
1397 tx_packets
+= stats
[i
].tx_packets
;
1398 tx_bytes
+= stats
[i
].tx_bytes
;
1403 printf("\r%12llu packets outgoing\n", tx_packets
);
1404 printf("\r%12llu bytes outgoing\n", tx_bytes
);
1405 for (i
= 0; cpustats
&& i
< ctx
.cpus
; i
++) {
1406 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1407 stats
[i
].tv_sec
, stats
[i
].tv_usec
, i
,
1408 stats
[i
].tx_packets
);
1413 destroy_shared_var(stats
, ctx
.cpus
);
1415 device_restore_irq_affinity_list();
1417 argv_free(cpp_argv
);
1419 free(ctx
.device_trans
);
1422 free(ctx
.packet_str
);