xref: /linux/tools/testing/selftests/net/lib/csum.c (revision 8342c68435dd34b1ecd65b02fff9745cadab2616)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /* Test hardware checksum offload: Rx + Tx, IPv4 + IPv6, TCP + UDP.
4  *
5  * The test runs on two machines to exercise the NIC.
6  *
7  *     CMD=$((./csum -[46] -[tu] -S $SADDR -D $DADDR -[RT] -r 1 $EXTRA_ARGS))
8  *
9  * Rx:
10  *
11  * The sender sends packets with a known checksum field using PF_INET(6)
12  * SOCK_RAW sockets.
13  *
14  * good packet: $CMD [-t]
15  * bad packet:  $CMD [-t] -E
16  *
17  * The receiver reads UDP packets with a UDP socket. This is not an
18  * option for TCP packets ('-t'). Optionally insert an iptables filter
19  * to avoid these entering the real protocol stack.
20  *
21  * The receiver also reads all packets with a PF_PACKET socket, to
22  * observe whether both good and bad packets arrive on the host. And to
23  * read the optional TP_STATUS_CSUM_VALID bit. This requires setting
24  * option PACKET_AUXDATA, and works only for CHECKSUM_UNNECESSARY.
25  *
26  * Tx:
27  *
28  * The sender needs to build CHECKSUM_PARTIAL packets to exercise tx
29  * checksum offload.
30  *
31  * The sender can sends packets with a UDP socket.
32  *
33  * Optionally crafts a packet that sums up to zero to verify that the
34  * device writes negative zero 0xFFFF in this case to distinguish from
35  * 0x0000 (checksum disabled), as required by RFC 768. Hit this case
36  * by choosing a specific source port.
37  *
38  * good packet: $CMD -U
39  * zero csum:   $CMD -U -Z
40  *
41  * The sender can also build packets with PF_PACKET with PACKET_VNET_HDR,
42  * to cover more protocols. PF_PACKET requires passing src and dst mac
43  * addresses.
44  *
45  * good packet: $CMD -s $smac -d $dmac -p [-t]
46  *
47  * Argument '-z' sends UDP packets with a 0x000 checksum disabled field,
48  * to verify that the NIC passes these packets unmodified.
49  *
50  * Argument '-e' adds a transport mode encapsulation header between
51  * network and transport header. This will fail for devices that parse
52  *  headers. Should work on devices that implement protocol agnostic tx
53  * checksum offload (NETIF_F_HW_CSUM).
54  *
55  * Argument '-r $SEED' optionally randomizes header, payload and length
56  * to increase coverage between packets sent. SEED 1 further chooses a
57  * different seed for each run (and logs this for reproducibility). It
58  * is advised to enable this for extra coverage in continuous testing.
59  */
60 
61 #define _GNU_SOURCE
62 
63 #include <arpa/inet.h>
64 #include <asm/byteorder.h>
65 #include <errno.h>
66 #include <error.h>
67 #include <linux/filter.h>
68 #include <linux/if_packet.h>
69 #include <linux/ipv6.h>
70 #include <linux/virtio_net.h>
71 #include <net/ethernet.h>
72 #include <net/if.h>
73 #include <netinet/if_ether.h>
74 #include <netinet/in.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip6.h>
77 #include <netinet/tcp.h>
78 #include <netinet/udp.h>
79 #include <poll.h>
80 #include <sched.h>
81 #include <stdbool.h>
82 #include <stddef.h>
83 #include <stdint.h>
84 #include <stdio.h>
85 #include <stdlib.h>
86 #include <string.h>
87 #include <sys/socket.h>
88 #include <sys/stat.h>
89 #include <sys/time.h>
90 #include <sys/types.h>
91 #include <unistd.h>
92 
93 #include "kselftest.h"
94 
95 static bool cfg_bad_csum;
96 static int cfg_family = PF_INET6;
97 static int cfg_num_pkt = 4;
98 static bool cfg_do_rx = true;
99 static bool cfg_do_tx = true;
100 static bool cfg_encap;
101 static char *cfg_ifname = "eth0";
102 static char *cfg_mac_dst;
103 static char *cfg_mac_src;
104 static int cfg_proto = IPPROTO_UDP;
105 static int cfg_payload_char = 'a';
106 static int cfg_payload_len = 100;
107 static uint16_t cfg_port_dst = 34000;
108 static uint16_t cfg_port_src = 33000;
109 static uint16_t cfg_port_src_encap = 33001;
110 static unsigned int cfg_random_seed;
111 static int cfg_rcvbuf = 1 << 22;	/* be able to queue large cfg_num_pkt */
112 static bool cfg_send_pfpacket;
113 static bool cfg_send_udp;
114 static int cfg_timeout_ms = 2000;
115 static bool cfg_zero_disable; /* skip checksum: set to zero (udp only) */
116 static bool cfg_zero_sum;     /* create packet that adds up to zero */
117 
118 static struct sockaddr_in cfg_daddr4 = {.sin_family = AF_INET};
119 static struct sockaddr_in cfg_saddr4 = {.sin_family = AF_INET};
120 static struct sockaddr_in6 cfg_daddr6 = {.sin6_family = AF_INET6};
121 static struct sockaddr_in6 cfg_saddr6 = {.sin6_family = AF_INET6};
122 
123 #define ENC_HEADER_LEN	(sizeof(struct udphdr) + sizeof(struct udp_encap_hdr))
124 #define MAX_HEADER_LEN	(sizeof(struct ipv6hdr) + ENC_HEADER_LEN + sizeof(struct tcphdr))
125 #define MAX_PAYLOAD_LEN 1024
126 
127 /* Trivial demo encap. Stand-in for transport layer protocols like ESP or PSP */
128 struct udp_encap_hdr {
129 	uint8_t nexthdr;
130 	uint8_t padding[3];
131 };
132 
133 /* Ipaddrs, for pseudo csum. Global var is ugly, pass through funcs was worse */
134 static void *iph_addr_p;
135 
136 static unsigned long gettimeofday_ms(void)
137 {
138 	struct timeval tv;
139 
140 	gettimeofday(&tv, NULL);
141 	return (tv.tv_sec * 1000UL) + (tv.tv_usec / 1000UL);
142 }
143 
144 static uint32_t checksum_nofold(char *data, size_t len, uint32_t sum)
145 {
146 	uint16_t *words = (uint16_t *)data;
147 	int i;
148 
149 	for (i = 0; i < len / 2; i++)
150 		sum += words[i];
151 
152 	if (len & 1)
153 		sum += ((unsigned char *)data)[len - 1];
154 
155 	return sum;
156 }
157 
158 static uint16_t checksum_fold(void *data, size_t len, uint32_t sum)
159 {
160 	sum = checksum_nofold(data, len, sum);
161 
162 	while (sum > 0xFFFF)
163 		sum = (sum & 0xFFFF) + (sum >> 16);
164 
165 	return ~sum;
166 }
167 
168 static uint16_t checksum(void *th, uint16_t proto, size_t len)
169 {
170 	uint32_t sum;
171 	int alen;
172 
173 	alen = cfg_family == PF_INET6 ? 32 : 8;
174 
175 	sum = checksum_nofold(iph_addr_p, alen, 0);
176 	sum += htons(proto);
177 	sum += htons(len);
178 
179 	/* With CHECKSUM_PARTIAL kernel expects non-inverted pseudo csum */
180 	if (cfg_do_tx && cfg_send_pfpacket)
181 		return ~checksum_fold(NULL, 0, sum);
182 	else
183 		return checksum_fold(th, len, sum);
184 }
185 
186 static void *build_packet_ipv4(void *_iph, uint8_t proto, unsigned int len)
187 {
188 	struct iphdr *iph = _iph;
189 
190 	memset(iph, 0, sizeof(*iph));
191 
192 	iph->version = 4;
193 	iph->ihl = 5;
194 	iph->ttl = 8;
195 	iph->protocol = proto;
196 	iph->saddr = cfg_saddr4.sin_addr.s_addr;
197 	iph->daddr = cfg_daddr4.sin_addr.s_addr;
198 	iph->tot_len = htons(sizeof(*iph) + len);
199 	iph->check = checksum_fold(iph, sizeof(*iph), 0);
200 
201 	iph_addr_p = &iph->saddr;
202 
203 	return iph + 1;
204 }
205 
206 static void *build_packet_ipv6(void *_ip6h, uint8_t proto, unsigned int len)
207 {
208 	struct ipv6hdr *ip6h = _ip6h;
209 
210 	memset(ip6h, 0, sizeof(*ip6h));
211 
212 	ip6h->version = 6;
213 	ip6h->payload_len = htons(len);
214 	ip6h->nexthdr = proto;
215 	ip6h->hop_limit = 64;
216 	ip6h->saddr = cfg_saddr6.sin6_addr;
217 	ip6h->daddr = cfg_daddr6.sin6_addr;
218 
219 	iph_addr_p = &ip6h->saddr;
220 
221 	return ip6h + 1;
222 }
223 
224 static void *build_packet_udp(void *_uh)
225 {
226 	struct udphdr *uh = _uh;
227 
228 	uh->source = htons(cfg_port_src);
229 	uh->dest = htons(cfg_port_dst);
230 	uh->len = htons(sizeof(*uh) + cfg_payload_len);
231 	uh->check = 0;
232 
233 	/* choose source port so that uh->check adds up to zero */
234 	if (cfg_zero_sum) {
235 		uh->source = 0;
236 		uh->source = checksum(uh, IPPROTO_UDP, sizeof(*uh) + cfg_payload_len);
237 
238 		fprintf(stderr, "%s: changing sport: %hu -> %hu\n",
239 			cfg_do_tx ? "tx" : "rx",
240 			cfg_port_src, ntohs(uh->source));
241 		cfg_port_src = ntohs(uh->source);
242 	}
243 
244 	if (cfg_zero_disable)
245 		uh->check = 0;
246 	else
247 		uh->check = checksum(uh, IPPROTO_UDP, sizeof(*uh) + cfg_payload_len);
248 
249 	if (cfg_bad_csum)
250 		uh->check = ~uh->check;
251 
252 	if (cfg_do_tx)
253 		fprintf(stderr, "tx: sending checksum: 0x%x\n", uh->check);
254 	return uh + 1;
255 }
256 
257 static void *build_packet_tcp(void *_th)
258 {
259 	struct tcphdr *th = _th;
260 
261 	th->source = htons(cfg_port_src);
262 	th->dest = htons(cfg_port_dst);
263 	th->doff = 5;
264 	th->check = 0;
265 
266 	th->check = checksum(th, IPPROTO_TCP, sizeof(*th) + cfg_payload_len);
267 
268 	if (cfg_bad_csum)
269 		th->check = ~th->check;
270 
271 	fprintf(stderr, "tx: sending checksum: 0x%x\n", th->check);
272 	return th + 1;
273 }
274 
275 static char *build_packet_udp_encap(void *_uh)
276 {
277 	struct udphdr *uh = _uh;
278 	struct udp_encap_hdr *eh = _uh + sizeof(*uh);
279 
280 	/* outer dst == inner dst, to simplify BPF filter
281 	 * outer src != inner src, to demultiplex on recv
282 	 */
283 	uh->dest = htons(cfg_port_dst);
284 	uh->source = htons(cfg_port_src_encap);
285 	uh->check = 0;
286 	uh->len = htons(sizeof(*uh) +
287 			sizeof(*eh) +
288 			sizeof(struct tcphdr) +
289 			cfg_payload_len);
290 
291 	eh->nexthdr = IPPROTO_TCP;
292 
293 	return build_packet_tcp(eh + 1);
294 }
295 
296 static char *build_packet(char *buf, int max_len, int *len)
297 {
298 	uint8_t proto;
299 	char *off;
300 	int tlen;
301 
302 	if (cfg_random_seed) {
303 		int *buf32 = (void *)buf;
304 		int i;
305 
306 		for (i = 0; i < (max_len / sizeof(int)); i++)
307 			buf32[i] = rand();
308 	} else {
309 		memset(buf, cfg_payload_char, max_len);
310 	}
311 
312 	if (cfg_proto == IPPROTO_UDP)
313 		tlen = sizeof(struct udphdr) + cfg_payload_len;
314 	else
315 		tlen = sizeof(struct tcphdr) + cfg_payload_len;
316 
317 	if (cfg_encap) {
318 		proto = IPPROTO_UDP;
319 		tlen += ENC_HEADER_LEN;
320 	} else {
321 		proto = cfg_proto;
322 	}
323 
324 	if (cfg_family == PF_INET)
325 		off = build_packet_ipv4(buf, proto, tlen);
326 	else
327 		off = build_packet_ipv6(buf, proto, tlen);
328 
329 	if (cfg_encap)
330 		off = build_packet_udp_encap(off);
331 	else if (cfg_proto == IPPROTO_UDP)
332 		off = build_packet_udp(off);
333 	else
334 		off = build_packet_tcp(off);
335 
336 	/* only pass the payload, but still compute headers for cfg_zero_sum */
337 	if (cfg_send_udp) {
338 		*len = cfg_payload_len;
339 		return off;
340 	}
341 
342 	*len = off - buf + cfg_payload_len;
343 	return buf;
344 }
345 
346 static int open_inet(int ipproto, int protocol)
347 {
348 	int fd;
349 
350 	fd = socket(cfg_family, ipproto, protocol);
351 	if (fd == -1)
352 		error(1, errno, "socket inet");
353 
354 	if (cfg_family == PF_INET6) {
355 		/* may have been updated by cfg_zero_sum */
356 		cfg_saddr6.sin6_port = htons(cfg_port_src);
357 
358 		if (bind(fd, (void *)&cfg_saddr6, sizeof(cfg_saddr6)))
359 			error(1, errno, "bind dgram 6");
360 		if (connect(fd, (void *)&cfg_daddr6, sizeof(cfg_daddr6)))
361 			error(1, errno, "connect dgram 6");
362 	} else {
363 		/* may have been updated by cfg_zero_sum */
364 		cfg_saddr4.sin_port = htons(cfg_port_src);
365 
366 		if (bind(fd, (void *)&cfg_saddr4, sizeof(cfg_saddr4)))
367 			error(1, errno, "bind dgram 4");
368 		if (connect(fd, (void *)&cfg_daddr4, sizeof(cfg_daddr4)))
369 			error(1, errno, "connect dgram 4");
370 	}
371 
372 	return fd;
373 }
374 
375 static int open_packet(void)
376 {
377 	int fd, one = 1;
378 
379 	fd = socket(PF_PACKET, SOCK_RAW, 0);
380 	if (fd == -1)
381 		error(1, errno, "socket packet");
382 
383 	if (setsockopt(fd, SOL_PACKET, PACKET_VNET_HDR, &one, sizeof(one)))
384 		error(1, errno, "setsockopt packet_vnet_ndr");
385 
386 	return fd;
387 }
388 
389 static void send_inet(int fd, const char *buf, int len)
390 {
391 	int ret;
392 
393 	ret = write(fd, buf, len);
394 	if (ret == -1)
395 		error(1, errno, "write");
396 	if (ret != len)
397 		error(1, 0, "write: %d", ret);
398 }
399 
400 static void eth_str_to_addr(const char *str, unsigned char *eth)
401 {
402 	if (sscanf(str, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
403 		   &eth[0], &eth[1], &eth[2], &eth[3], &eth[4], &eth[5]) != 6)
404 		error(1, 0, "cannot parse mac addr %s", str);
405 }
406 
407 static void send_packet(int fd, const char *buf, int len)
408 {
409 	struct virtio_net_hdr vh = {0};
410 	struct sockaddr_ll addr = {0};
411 	struct msghdr msg = {0};
412 	struct ethhdr eth;
413 	struct iovec iov[3];
414 	int ret;
415 
416 	addr.sll_family = AF_PACKET;
417 	addr.sll_halen = ETH_ALEN;
418 	addr.sll_ifindex = if_nametoindex(cfg_ifname);
419 	if (!addr.sll_ifindex)
420 		error(1, errno, "if_nametoindex %s", cfg_ifname);
421 
422 	vh.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
423 	if (cfg_family == PF_INET6) {
424 		vh.csum_start = sizeof(struct ethhdr) + sizeof(struct ipv6hdr);
425 		addr.sll_protocol = htons(ETH_P_IPV6);
426 	} else {
427 		vh.csum_start = sizeof(struct ethhdr) + sizeof(struct iphdr);
428 		addr.sll_protocol = htons(ETH_P_IP);
429 	}
430 
431 	if (cfg_encap)
432 		vh.csum_start += ENC_HEADER_LEN;
433 
434 	if (cfg_proto == IPPROTO_TCP) {
435 		vh.csum_offset = __builtin_offsetof(struct tcphdr, check);
436 		vh.hdr_len = vh.csum_start + sizeof(struct tcphdr);
437 	} else {
438 		vh.csum_offset = __builtin_offsetof(struct udphdr, check);
439 		vh.hdr_len = vh.csum_start + sizeof(struct udphdr);
440 	}
441 
442 	eth_str_to_addr(cfg_mac_src, eth.h_source);
443 	eth_str_to_addr(cfg_mac_dst, eth.h_dest);
444 	eth.h_proto = addr.sll_protocol;
445 
446 	iov[0].iov_base = &vh;
447 	iov[0].iov_len = sizeof(vh);
448 
449 	iov[1].iov_base = &eth;
450 	iov[1].iov_len = sizeof(eth);
451 
452 	iov[2].iov_base = (void *)buf;
453 	iov[2].iov_len = len;
454 
455 	msg.msg_iov = iov;
456 	msg.msg_iovlen = ARRAY_SIZE(iov);
457 
458 	msg.msg_name = &addr;
459 	msg.msg_namelen = sizeof(addr);
460 
461 	ret = sendmsg(fd, &msg, 0);
462 	if (ret == -1)
463 		error(1, errno, "sendmsg packet");
464 	if (ret != sizeof(vh) + sizeof(eth) + len)
465 		error(1, errno, "sendmsg packet: %u", ret);
466 }
467 
468 static int recv_prepare_udp(void)
469 {
470 	int fd;
471 
472 	fd = socket(cfg_family, SOCK_DGRAM, 0);
473 	if (fd == -1)
474 		error(1, errno, "socket r");
475 
476 	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
477 		       &cfg_rcvbuf, sizeof(cfg_rcvbuf)))
478 		error(1, errno, "setsockopt SO_RCVBUF r");
479 
480 	if (cfg_family == PF_INET6) {
481 		if (bind(fd, (void *)&cfg_daddr6, sizeof(cfg_daddr6)))
482 			error(1, errno, "bind r");
483 	} else {
484 		if (bind(fd, (void *)&cfg_daddr4, sizeof(cfg_daddr4)))
485 			error(1, errno, "bind r");
486 	}
487 
488 	return fd;
489 }
490 
491 /* Filter out all traffic that is not cfg_proto with our destination port.
492  *
493  * Otherwise background noise may cause PF_PACKET receive queue overflow,
494  * dropping the expected packets and failing the test.
495  */
496 static void __recv_prepare_packet_filter(int fd, int off_nexthdr, int off_dport)
497 {
498 	struct sock_filter filter[] = {
499 		BPF_STMT(BPF_LD + BPF_B + BPF_ABS, SKF_AD_OFF + SKF_AD_PKTTYPE),
500 		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, PACKET_HOST, 0, 4),
501 		BPF_STMT(BPF_LD + BPF_B + BPF_ABS, off_nexthdr),
502 		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, cfg_encap ? IPPROTO_UDP : cfg_proto, 0, 2),
503 		BPF_STMT(BPF_LD + BPF_H + BPF_ABS, off_dport),
504 		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, cfg_port_dst, 1, 0),
505 		BPF_STMT(BPF_RET + BPF_K, 0),
506 		BPF_STMT(BPF_RET + BPF_K, 0xFFFF),
507 	};
508 	struct sock_fprog prog = {};
509 
510 	prog.filter = filter;
511 	prog.len = ARRAY_SIZE(filter);
512 	if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog)))
513 		error(1, errno, "setsockopt filter");
514 }
515 
516 static void recv_prepare_packet_filter(int fd)
517 {
518 	const int off_dport = offsetof(struct tcphdr, dest); /* same for udp */
519 
520 	if (cfg_family == AF_INET)
521 		__recv_prepare_packet_filter(fd, offsetof(struct iphdr, protocol),
522 					     sizeof(struct iphdr) + off_dport);
523 	else
524 		__recv_prepare_packet_filter(fd, offsetof(struct ipv6hdr, nexthdr),
525 					     sizeof(struct ipv6hdr) + off_dport);
526 }
527 
528 static void recv_prepare_packet_bind(int fd)
529 {
530 	struct sockaddr_ll laddr = {0};
531 
532 	laddr.sll_family = AF_PACKET;
533 
534 	if (cfg_family == PF_INET)
535 		laddr.sll_protocol = htons(ETH_P_IP);
536 	else
537 		laddr.sll_protocol = htons(ETH_P_IPV6);
538 
539 	laddr.sll_ifindex = if_nametoindex(cfg_ifname);
540 	if (!laddr.sll_ifindex)
541 		error(1, 0, "if_nametoindex %s", cfg_ifname);
542 
543 	if (bind(fd, (void *)&laddr, sizeof(laddr)))
544 		error(1, errno, "bind pf_packet");
545 }
546 
547 static int recv_prepare_packet(void)
548 {
549 	int fd, one = 1;
550 
551 	fd = socket(PF_PACKET, SOCK_DGRAM, 0);
552 	if (fd == -1)
553 		error(1, errno, "socket p");
554 
555 	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
556 		       &cfg_rcvbuf, sizeof(cfg_rcvbuf)))
557 		error(1, errno, "setsockopt SO_RCVBUF p");
558 
559 	/* enable auxdata to recv checksum status (valid vs unknown) */
560 	if (setsockopt(fd, SOL_PACKET, PACKET_AUXDATA, &one, sizeof(one)))
561 		error(1, errno, "setsockopt auxdata");
562 
563 	/* install filter to restrict packet flow to match */
564 	recv_prepare_packet_filter(fd);
565 
566 	/* bind to address family to start packet flow */
567 	recv_prepare_packet_bind(fd);
568 
569 	return fd;
570 }
571 
572 static int recv_udp(int fd)
573 {
574 	static char buf[MAX_PAYLOAD_LEN];
575 	struct sockaddr_storage addr;
576 	socklen_t addrlen;
577 	int ret, count = 0;
578 
579 	while (1) {
580 		addrlen = sizeof(addr);
581 		ret = recvfrom(fd, buf, sizeof(buf), MSG_DONTWAIT,
582 			       (struct sockaddr *)&addr, &addrlen);
583 		if (ret == -1 && errno == EAGAIN)
584 			break;
585 		if (ret == -1)
586 			error(1, errno, "recv r");
587 
588 		if (cfg_family == PF_INET) {
589 			struct sockaddr_in *sin = (void *)&addr;
590 
591 			if (sin->sin_addr.s_addr != cfg_saddr4.sin_addr.s_addr)
592 				continue;
593 			if (sin->sin_port != htons(cfg_port_src))
594 				continue;
595 		} else {
596 			struct sockaddr_in6 *sin6 = (void *)&addr;
597 
598 			if (memcmp(&sin6->sin6_addr, &cfg_saddr6.sin6_addr,
599 				   sizeof(sin6->sin6_addr)))
600 				continue;
601 			if (sin6->sin6_port != htons(cfg_port_src))
602 				continue;
603 		}
604 
605 		fprintf(stderr, "rx: udp: len=%u\n", ret);
606 		count++;
607 	}
608 
609 	return count;
610 }
611 
612 static int recv_verify_csum(void *th, int len, uint16_t sport, uint16_t csum_field)
613 {
614 	uint16_t csum;
615 
616 	csum = checksum(th, cfg_proto, len);
617 
618 	fprintf(stderr, "rx: pkt: sport=%hu len=%u csum=0x%hx verify=0x%hx\n",
619 		sport, len, csum_field, csum);
620 
621 	/* csum must be zero unless cfg_bad_csum indicates bad csum */
622 	if (csum && !cfg_bad_csum) {
623 		fprintf(stderr, "pkt: bad csum\n");
624 		return 1;
625 	} else if (cfg_bad_csum && !csum) {
626 		fprintf(stderr, "pkt: good csum, while bad expected\n");
627 		return 1;
628 	}
629 
630 	if (cfg_zero_sum && csum_field != 0xFFFF) {
631 		fprintf(stderr, "pkt: zero csum: field should be 0xFFFF, is 0x%hx\n", csum_field);
632 		return 1;
633 	}
634 
635 	return 0;
636 }
637 
638 static int recv_verify_packet_tcp(void *th, int len)
639 {
640 	struct tcphdr *tcph = th;
641 
642 	if (len < sizeof(*tcph) || tcph->dest != htons(cfg_port_dst))
643 		return -1;
644 
645 	if (tcph->source != htons(cfg_port_src))
646 		return -1;
647 
648 	return recv_verify_csum(th, len, ntohs(tcph->source), tcph->check);
649 }
650 
651 static int recv_verify_packet_udp_encap(void *th, int len)
652 {
653 	struct udp_encap_hdr *eh = th;
654 
655 	if (len < sizeof(*eh) || eh->nexthdr != IPPROTO_TCP)
656 		return -1;
657 
658 	return recv_verify_packet_tcp(eh + 1, len - sizeof(*eh));
659 }
660 
661 static int recv_verify_packet_udp(void *th, int len)
662 {
663 	struct udphdr *udph = th;
664 
665 	if (len < sizeof(*udph))
666 		return -1;
667 
668 	if (udph->dest != htons(cfg_port_dst))
669 		return -1;
670 
671 	if (udph->source == htons(cfg_port_src_encap))
672 		return recv_verify_packet_udp_encap(udph + 1,
673 						    len - sizeof(*udph));
674 
675 	if (udph->source != htons(cfg_port_src))
676 		return -1;
677 
678 	return recv_verify_csum(th, len, ntohs(udph->source), udph->check);
679 }
680 
681 static int recv_verify_packet_ipv4(void *nh, int len)
682 {
683 	struct iphdr *iph = nh;
684 	uint16_t proto = cfg_encap ? IPPROTO_UDP : cfg_proto;
685 	uint16_t ip_len;
686 
687 	if (len < sizeof(*iph) || iph->protocol != proto)
688 		return -1;
689 
690 	if (iph->saddr != cfg_saddr4.sin_addr.s_addr)
691 		return -1;
692 
693 	ip_len = ntohs(iph->tot_len);
694 	if (ip_len > len || ip_len < sizeof(*iph))
695 		return -1;
696 
697 	len = ip_len;
698 	iph_addr_p = &iph->saddr;
699 	if (proto == IPPROTO_TCP)
700 		return recv_verify_packet_tcp(iph + 1, len - sizeof(*iph));
701 	else
702 		return recv_verify_packet_udp(iph + 1, len - sizeof(*iph));
703 }
704 
705 static int recv_verify_packet_ipv6(void *nh, int len)
706 {
707 	struct ipv6hdr *ip6h = nh;
708 	uint16_t proto = cfg_encap ? IPPROTO_UDP : cfg_proto;
709 	uint16_t payload_len;
710 
711 	if (len < sizeof(*ip6h) || ip6h->nexthdr != proto)
712 		return -1;
713 
714 	if (memcmp(&ip6h->saddr, &cfg_saddr6.sin6_addr, sizeof(ip6h->saddr)))
715 		return -1;
716 
717 	payload_len = ntohs(ip6h->payload_len);
718 	if (payload_len > len - sizeof(*ip6h))
719 		return -1;
720 
721 	iph_addr_p = &ip6h->saddr;
722 	if (proto == IPPROTO_TCP)
723 		return recv_verify_packet_tcp(ip6h + 1, payload_len);
724 	else
725 		return recv_verify_packet_udp(ip6h + 1, payload_len);
726 }
727 
728 /* return whether auxdata includes TP_STATUS_CSUM_VALID */
729 static uint32_t recv_get_packet_csum_status(struct msghdr *msg)
730 {
731 	struct tpacket_auxdata *aux = NULL;
732 	struct cmsghdr *cm;
733 
734 	if (msg->msg_flags & MSG_CTRUNC)
735 		error(1, 0, "cmsg: truncated");
736 
737 	for (cm = CMSG_FIRSTHDR(msg); cm; cm = CMSG_NXTHDR(msg, cm)) {
738 		if (cm->cmsg_level != SOL_PACKET ||
739 		    cm->cmsg_type != PACKET_AUXDATA)
740 			error(1, 0, "cmsg: level=%d type=%d\n",
741 			      cm->cmsg_level, cm->cmsg_type);
742 
743 		if (cm->cmsg_len != CMSG_LEN(sizeof(struct tpacket_auxdata)))
744 			error(1, 0, "cmsg: len=%zu expected=%zu",
745 			      cm->cmsg_len, CMSG_LEN(sizeof(struct tpacket_auxdata)));
746 
747 		aux = (void *)CMSG_DATA(cm);
748 	}
749 
750 	if (!aux)
751 		error(1, 0, "cmsg: no auxdata");
752 
753 	return aux->tp_status;
754 }
755 
756 static int recv_packet(int fd)
757 {
758 	static char _buf[MAX_HEADER_LEN + MAX_PAYLOAD_LEN];
759 	unsigned long total = 0, bad_csums = 0, bad_validations = 0;
760 	char ctrl[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
761 	struct pkt *buf = (void *)_buf;
762 	struct msghdr msg = {0};
763 	uint32_t tp_status;
764 	struct iovec iov;
765 	int len, ret;
766 
767 	iov.iov_base = _buf;
768 	iov.iov_len = sizeof(_buf);
769 
770 	msg.msg_iov = &iov;
771 	msg.msg_iovlen = 1;
772 
773 	msg.msg_control = ctrl;
774 	msg.msg_controllen = sizeof(ctrl);
775 
776 	while (1) {
777 		msg.msg_flags = 0;
778 
779 		len = recvmsg(fd, &msg, MSG_DONTWAIT);
780 		if (len == -1 && errno == EAGAIN)
781 			break;
782 		if (len == -1)
783 			error(1, errno, "recv p");
784 
785 		tp_status = recv_get_packet_csum_status(&msg);
786 
787 		/* GRO might coalesce randomized packets. Such GSO packets are
788 		 * then reinitialized for csum offload (CHECKSUM_PARTIAL), with
789 		 * a pseudo csum. Do not try to validate these checksums.
790 		 */
791 		if (tp_status & TP_STATUS_CSUMNOTREADY) {
792 			fprintf(stderr, "cmsg: GSO packet has partial csum: skip\n");
793 			continue;
794 		}
795 
796 		if (cfg_family == PF_INET6)
797 			ret = recv_verify_packet_ipv6(buf, len);
798 		else
799 			ret = recv_verify_packet_ipv4(buf, len);
800 
801 		if (ret == -1 /* skip: non-matching */)
802 			continue;
803 
804 		total++;
805 		if (ret == 1)
806 			bad_csums++;
807 
808 		/* Fail if kernel returns valid for known bad csum.
809 		 * Do not fail if kernel does not validate a good csum:
810 		 * Absence of validation does not imply invalid.
811 		 */
812 		if (tp_status & TP_STATUS_CSUM_VALID && cfg_bad_csum) {
813 			fprintf(stderr, "cmsg: expected bad csum, pf_packet returns valid\n");
814 			bad_validations++;
815 		}
816 	}
817 
818 	if (bad_csums || bad_validations)
819 		error(1, 0, "rx: errors at pf_packet: total=%lu bad_csums=%lu bad_valids=%lu\n",
820 		      total, bad_csums, bad_validations);
821 
822 	return total;
823 }
824 
825 static void parse_args(int argc, char *const argv[])
826 {
827 	const char *daddr = NULL, *saddr = NULL;
828 	int c;
829 
830 	while ((c = getopt(argc, argv, "46d:D:eEi:l:L:n:r:PRs:S:tTuUzZ")) != -1) {
831 		switch (c) {
832 		case '4':
833 			cfg_family = PF_INET;
834 			break;
835 		case '6':
836 			cfg_family = PF_INET6;
837 			break;
838 		case 'd':
839 			cfg_mac_dst = optarg;
840 			break;
841 		case 'D':
842 			daddr = optarg;
843 			break;
844 		case 'e':
845 			cfg_encap = true;
846 			break;
847 		case 'E':
848 			cfg_bad_csum = true;
849 			break;
850 		case 'i':
851 			cfg_ifname = optarg;
852 			break;
853 		case 'l':
854 			cfg_payload_len = strtol(optarg, NULL, 0);
855 			break;
856 		case 'L':
857 			cfg_timeout_ms = strtol(optarg, NULL, 0) * 1000;
858 			break;
859 		case 'n':
860 			cfg_num_pkt = strtol(optarg, NULL, 0);
861 			break;
862 		case 'r':
863 			cfg_random_seed = strtol(optarg, NULL, 0);
864 			break;
865 		case 'P':
866 			cfg_send_pfpacket = true;
867 			break;
868 		case 'R':
869 			/* only Rx: used with two machine tests */
870 			cfg_do_tx = false;
871 			break;
872 		case 's':
873 			cfg_mac_src = optarg;
874 			break;
875 		case 'S':
876 			saddr = optarg;
877 			break;
878 		case 't':
879 			cfg_proto = IPPROTO_TCP;
880 			break;
881 		case 'T':
882 			/* only Tx: used with two machine tests */
883 			cfg_do_rx = false;
884 			break;
885 		case 'u':
886 			cfg_proto = IPPROTO_UDP;
887 			break;
888 		case 'U':
889 			/* send using real udp socket,
890 			 * to exercise tx checksum offload
891 			 */
892 			cfg_send_udp = true;
893 			break;
894 		case 'z':
895 			cfg_zero_disable = true;
896 			break;
897 		case 'Z':
898 			cfg_zero_sum = true;
899 			break;
900 		default:
901 			error(1, 0, "unknown arg %c", c);
902 		}
903 	}
904 
905 	if (!daddr || !saddr)
906 		error(1, 0, "Must pass -D <daddr> and -S <saddr>");
907 
908 	if (cfg_do_tx && cfg_send_pfpacket && (!cfg_mac_src || !cfg_mac_dst))
909 		error(1, 0, "Transmit with pf_packet requires mac addresses");
910 
911 	if (cfg_payload_len > MAX_PAYLOAD_LEN)
912 		error(1, 0, "Payload length exceeds max");
913 
914 	if (cfg_proto != IPPROTO_UDP && (cfg_zero_sum || cfg_zero_disable))
915 		error(1, 0, "Only UDP supports zero csum");
916 
917 	if (cfg_zero_sum && !cfg_send_udp)
918 		error(1, 0, "Zero checksum conversion requires -U for tx csum offload");
919 	if (cfg_zero_sum && cfg_bad_csum)
920 		error(1, 0, "Cannot combine zero checksum conversion and invalid checksum");
921 	if (cfg_zero_sum && cfg_random_seed)
922 		error(1, 0, "Cannot combine zero checksum conversion with randomization");
923 
924 	if (cfg_family == PF_INET6) {
925 		cfg_saddr6.sin6_port = htons(cfg_port_src);
926 		cfg_daddr6.sin6_port = htons(cfg_port_dst);
927 
928 		if (inet_pton(cfg_family, daddr, &cfg_daddr6.sin6_addr) != 1)
929 			error(1, errno, "Cannot parse ipv6 -D");
930 		if (inet_pton(cfg_family, saddr, &cfg_saddr6.sin6_addr) != 1)
931 			error(1, errno, "Cannot parse ipv6 -S");
932 	} else {
933 		cfg_saddr4.sin_port = htons(cfg_port_src);
934 		cfg_daddr4.sin_port = htons(cfg_port_dst);
935 
936 		if (inet_pton(cfg_family, daddr, &cfg_daddr4.sin_addr) != 1)
937 			error(1, errno, "Cannot parse ipv4 -D");
938 		if (inet_pton(cfg_family, saddr, &cfg_saddr4.sin_addr) != 1)
939 			error(1, errno, "Cannot parse ipv4 -S");
940 	}
941 
942 	if (cfg_do_tx && cfg_random_seed) {
943 		/* special case: time-based seed */
944 		if (cfg_random_seed == 1)
945 			cfg_random_seed = (unsigned int)gettimeofday_ms();
946 		srand(cfg_random_seed);
947 		fprintf(stderr, "randomization seed: %u\n", cfg_random_seed);
948 	}
949 }
950 
951 static void do_tx(void)
952 {
953 	static char _buf[MAX_HEADER_LEN + MAX_PAYLOAD_LEN];
954 	char *buf;
955 	int fd, len, i;
956 
957 	buf = build_packet(_buf, sizeof(_buf), &len);
958 
959 	if (cfg_send_pfpacket)
960 		fd = open_packet();
961 	else if (cfg_send_udp)
962 		fd = open_inet(SOCK_DGRAM, 0);
963 	else
964 		fd = open_inet(SOCK_RAW, IPPROTO_RAW);
965 
966 	for (i = 0; i < cfg_num_pkt; i++) {
967 		if (cfg_send_pfpacket)
968 			send_packet(fd, buf, len);
969 		else
970 			send_inet(fd, buf, len);
971 
972 		/* randomize each packet individually to increase coverage */
973 		if (cfg_random_seed) {
974 			cfg_payload_len = rand() % MAX_PAYLOAD_LEN;
975 			buf = build_packet(_buf, sizeof(_buf), &len);
976 		}
977 
978 		/* avoid bursting */
979 		usleep(20);
980 	}
981 
982 	if (close(fd))
983 		error(1, errno, "close tx");
984 }
985 
986 static void do_rx(int fdp, int fdr)
987 {
988 	unsigned long count_udp = 0, count_pkt = 0;
989 	long tleft, tstop;
990 	struct pollfd pfd;
991 
992 	if (!cfg_do_tx && cfg_zero_sum) {
993 		static char _buf[MAX_HEADER_LEN + MAX_PAYLOAD_LEN];
994 		int len;
995 
996 		/* calculate source port that causes csum to add up to zero */
997 		build_packet(_buf, sizeof(_buf), &len);
998 	}
999 
1000 	tstop = gettimeofday_ms() + cfg_timeout_ms;
1001 	tleft = cfg_timeout_ms;
1002 
1003 	do {
1004 		pfd.events = POLLIN;
1005 		pfd.fd = fdp;
1006 		if (poll(&pfd, 1, tleft) == -1)
1007 			error(1, errno, "poll");
1008 
1009 		if (pfd.revents & POLLIN)
1010 			count_pkt += recv_packet(fdp);
1011 
1012 		if (cfg_proto == IPPROTO_UDP)
1013 			count_udp += recv_udp(fdr);
1014 
1015 		tleft = tstop - gettimeofday_ms();
1016 	} while (tleft > 0);
1017 
1018 	if (close(fdr))
1019 		error(1, errno, "close r");
1020 	if (close(fdp))
1021 		error(1, errno, "close p");
1022 
1023 	if (count_pkt < cfg_num_pkt)
1024 		error(1, 0, "rx: missing packets at pf_packet: %lu < %u",
1025 		      count_pkt, cfg_num_pkt);
1026 
1027 	if (cfg_proto == IPPROTO_UDP) {
1028 		if (cfg_bad_csum && count_udp)
1029 			error(1, 0, "rx: unexpected packets at udp");
1030 		if (!cfg_bad_csum && !count_udp)
1031 			error(1, 0, "rx: missing packets at udp");
1032 	}
1033 }
1034 
1035 int main(int argc, char *const argv[])
1036 {
1037 	int fdp = -1, fdr = -1;		/* -1 to silence -Wmaybe-uninitialized */
1038 
1039 	parse_args(argc, argv);
1040 
1041 	/* open receive sockets before transmitting */
1042 	if (cfg_do_rx) {
1043 		fdp = recv_prepare_packet();
1044 		fdr = recv_prepare_udp();
1045 	}
1046 
1047 	if (cfg_do_tx)
1048 		do_tx();
1049 
1050 	if (cfg_do_rx)
1051 		do_rx(fdp, fdr);
1052 
1053 	fprintf(stderr, "OK\n");
1054 	return 0;
1055 }
1056