• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2020 Intel Corporation. */
3 
4 /*
5  * Some functions in this program are taken from
6  * Linux kernel samples/bpf/xdpsock* and modified
7  * for use.
8  *
9  * See test_xsk.sh for detailed information on test topology
10  * and prerequisite network setup.
11  *
12  * This test program contains two threads, each thread is single socket with
13  * a unique UMEM. It validates in-order packet delivery and packet content
14  * by sending packets to each other.
15  *
16  * Tests Information:
17  * ------------------
18  * These selftests test AF_XDP SKB and Native/DRV modes using veth
19  * Virtual Ethernet interfaces.
20  *
21  * For each mode, the following tests are run:
22  *    a. nopoll - soft-irq processing in run-to-completion mode
23  *    b. poll - using poll() syscall
24  *    c. Socket Teardown
25  *       Create a Tx and a Rx socket, Tx from one socket, Rx on another. Destroy
26  *       both sockets, then repeat multiple times. Only nopoll mode is used
27  *    d. Bi-directional sockets
28  *       Configure sockets as bi-directional tx/rx sockets, sets up fill and
29  *       completion rings on each socket, tx/rx in both directions. Only nopoll
30  *       mode is used
31  *    e. Statistics
32  *       Trigger some error conditions and ensure that the appropriate statistics
33  *       are incremented. Within this test, the following statistics are tested:
34  *       i.   rx dropped
35  *            Increase the UMEM frame headroom to a value which results in
36  *            insufficient space in the rx buffer for both the packet and the headroom.
37  *       ii.  tx invalid
38  *            Set the 'len' field of tx descriptors to an invalid value (umem frame
39  *            size + 1).
40  *       iii. rx ring full
41  *            Reduce the size of the RX ring to a fraction of the fill ring size.
42  *       iv.  fill queue empty
43  *            Do not populate the fill queue and then try to receive pkts.
44  *    f. bpf_link resource persistence
45  *       Configure sockets at indexes 0 and 1, run a traffic on queue ids 0,
46  *       then remove xsk sockets from queue 0 on both veth interfaces and
47  *       finally run a traffic on queues ids 1
48  *    g. unaligned mode
49  *    h. tests for invalid and corner case Tx descriptors so that the correct ones
50  *       are discarded and let through, respectively.
51  *    i. 2K frame size tests
52  *
53  * Total tests: 12
54  *
55  * Flow:
56  * -----
57  * - Single process spawns two threads: Tx and Rx
58  * - Each of these two threads attach to a veth interface within their assigned
59  *   namespaces
60  * - Each thread Creates one AF_XDP socket connected to a unique umem for each
61  *   veth interface
62  * - Tx thread Transmits 10k packets from veth<xxxx> to veth<yyyy>
63  * - Rx thread verifies if all 10k packets were received and delivered in-order,
64  *   and have the right content
65  *
66  * Enable/disable packet dump mode:
67  * --------------------------
68  * To enable L2 - L4 headers and payload dump of each packet on STDOUT, add
69  * parameter -D to params array in test_xsk.sh, i.e. params=("-S" "-D")
70  */
71 
72 #define _GNU_SOURCE
73 #include <fcntl.h>
74 #include <errno.h>
75 #include <getopt.h>
76 #include <asm/barrier.h>
77 #include <linux/if_link.h>
78 #include <linux/if_ether.h>
79 #include <linux/ip.h>
80 #include <linux/udp.h>
81 #include <arpa/inet.h>
82 #include <net/if.h>
83 #include <locale.h>
84 #include <poll.h>
85 #include <pthread.h>
86 #include <signal.h>
87 #include <stdbool.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <stddef.h>
92 #include <sys/mman.h>
93 #include <sys/socket.h>
94 #include <sys/time.h>
95 #include <sys/types.h>
96 #include <sys/queue.h>
97 #include <time.h>
98 #include <unistd.h>
99 #include <stdatomic.h>
100 #include "xsk.h"
101 #include "xskxceiver.h"
102 #include <bpf/bpf.h>
103 #include <linux/filter.h>
104 #include "../kselftest.h"
105 
106 /* AF_XDP APIs were moved into libxdp and marked as deprecated in libbpf.
107  * Until xskxceiver is either moved or re-writed into libxdp, suppress
108  * deprecation warnings in this file
109  */
110 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
111 
112 static const char *MAC1 = "\x00\x0A\x56\x9E\xEE\x62";
113 static const char *MAC2 = "\x00\x0A\x56\x9E\xEE\x61";
114 static const char *IP1 = "192.168.100.162";
115 static const char *IP2 = "192.168.100.161";
116 static const u16 UDP_PORT1 = 2020;
117 static const u16 UDP_PORT2 = 2121;
118 
__exit_with_error(int error,const char * file,const char * func,int line)119 static void __exit_with_error(int error, const char *file, const char *func, int line)
120 {
121 	ksft_test_result_fail("[%s:%s:%i]: ERROR: %d/\"%s\"\n", file, func, line, error,
122 			      strerror(error));
123 	ksft_exit_xfail();
124 }
125 
126 #define exit_with_error(error) __exit_with_error(error, __FILE__, __func__, __LINE__)
127 #define busy_poll_string(test) (test)->ifobj_tx->busy_poll ? "BUSY-POLL " : ""
mode_string(struct test_spec * test)128 static char *mode_string(struct test_spec *test)
129 {
130 	switch (test->mode) {
131 	case TEST_MODE_SKB:
132 		return "SKB";
133 	case TEST_MODE_DRV:
134 		return "DRV";
135 	case TEST_MODE_ZC:
136 		return "ZC";
137 	default:
138 		return "BOGUS";
139 	}
140 }
141 
report_failure(struct test_spec * test)142 static void report_failure(struct test_spec *test)
143 {
144 	if (test->fail)
145 		return;
146 
147 	ksft_test_result_fail("FAIL: %s %s%s\n", mode_string(test), busy_poll_string(test),
148 			      test->name);
149 	test->fail = true;
150 }
151 
memset32_htonl(void * dest,u32 val,u32 size)152 static void memset32_htonl(void *dest, u32 val, u32 size)
153 {
154 	u32 *ptr = (u32 *)dest;
155 	int i;
156 
157 	val = htonl(val);
158 
159 	for (i = 0; i < (size & (~0x3)); i += 4)
160 		ptr[i >> 2] = val;
161 }
162 
163 /*
164  * Fold a partial checksum
165  * This function code has been taken from
166  * Linux kernel include/asm-generic/checksum.h
167  */
csum_fold(__u32 csum)168 static __u16 csum_fold(__u32 csum)
169 {
170 	u32 sum = (__force u32)csum;
171 
172 	sum = (sum & 0xffff) + (sum >> 16);
173 	sum = (sum & 0xffff) + (sum >> 16);
174 	return (__force __u16)~sum;
175 }
176 
177 /*
178  * This function code has been taken from
179  * Linux kernel lib/checksum.c
180  */
from64to32(u64 x)181 static u32 from64to32(u64 x)
182 {
183 	/* add up 32-bit and 32-bit for 32+c bit */
184 	x = (x & 0xffffffff) + (x >> 32);
185 	/* add up carry.. */
186 	x = (x & 0xffffffff) + (x >> 32);
187 	return (u32)x;
188 }
189 
190 /*
191  * This function code has been taken from
192  * Linux kernel lib/checksum.c
193  */
csum_tcpudp_nofold(__be32 saddr,__be32 daddr,__u32 len,__u8 proto,__u32 sum)194 static __u32 csum_tcpudp_nofold(__be32 saddr, __be32 daddr, __u32 len, __u8 proto, __u32 sum)
195 {
196 	unsigned long long s = (__force u32)sum;
197 
198 	s += (__force u32)saddr;
199 	s += (__force u32)daddr;
200 #ifdef __BIG_ENDIAN__
201 	s += proto + len;
202 #else
203 	s += (proto + len) << 8;
204 #endif
205 	return (__force __u32)from64to32(s);
206 }
207 
208 /*
209  * This function has been taken from
210  * Linux kernel include/asm-generic/checksum.h
211  */
csum_tcpudp_magic(__be32 saddr,__be32 daddr,__u32 len,__u8 proto,__u32 sum)212 static __u16 csum_tcpudp_magic(__be32 saddr, __be32 daddr, __u32 len, __u8 proto, __u32 sum)
213 {
214 	return csum_fold(csum_tcpudp_nofold(saddr, daddr, len, proto, sum));
215 }
216 
udp_csum(u32 saddr,u32 daddr,u32 len,u8 proto,u16 * udp_pkt)217 static u16 udp_csum(u32 saddr, u32 daddr, u32 len, u8 proto, u16 *udp_pkt)
218 {
219 	u32 csum = 0;
220 	u32 cnt = 0;
221 
222 	/* udp hdr and data */
223 	for (; cnt < len; cnt += 2)
224 		csum += udp_pkt[cnt >> 1];
225 
226 	return csum_tcpudp_magic(saddr, daddr, len, proto, csum);
227 }
228 
gen_eth_hdr(struct ifobject * ifobject,struct ethhdr * eth_hdr)229 static void gen_eth_hdr(struct ifobject *ifobject, struct ethhdr *eth_hdr)
230 {
231 	memcpy(eth_hdr->h_dest, ifobject->dst_mac, ETH_ALEN);
232 	memcpy(eth_hdr->h_source, ifobject->src_mac, ETH_ALEN);
233 	eth_hdr->h_proto = htons(ETH_P_IP);
234 }
235 
gen_ip_hdr(struct ifobject * ifobject,struct iphdr * ip_hdr)236 static void gen_ip_hdr(struct ifobject *ifobject, struct iphdr *ip_hdr)
237 {
238 	ip_hdr->version = IP_PKT_VER;
239 	ip_hdr->ihl = 0x5;
240 	ip_hdr->tos = IP_PKT_TOS;
241 	ip_hdr->tot_len = htons(IP_PKT_SIZE);
242 	ip_hdr->id = 0;
243 	ip_hdr->frag_off = 0;
244 	ip_hdr->ttl = IPDEFTTL;
245 	ip_hdr->protocol = IPPROTO_UDP;
246 	ip_hdr->saddr = ifobject->src_ip;
247 	ip_hdr->daddr = ifobject->dst_ip;
248 	ip_hdr->check = 0;
249 }
250 
gen_udp_hdr(u32 payload,void * pkt,struct ifobject * ifobject,struct udphdr * udp_hdr)251 static void gen_udp_hdr(u32 payload, void *pkt, struct ifobject *ifobject,
252 			struct udphdr *udp_hdr)
253 {
254 	udp_hdr->source = htons(ifobject->src_port);
255 	udp_hdr->dest = htons(ifobject->dst_port);
256 	udp_hdr->len = htons(UDP_PKT_SIZE);
257 	memset32_htonl(pkt + PKT_HDR_SIZE, payload, UDP_PKT_DATA_SIZE);
258 }
259 
is_umem_valid(struct ifobject * ifobj)260 static bool is_umem_valid(struct ifobject *ifobj)
261 {
262 	return !!ifobj->umem->umem;
263 }
264 
gen_udp_csum(struct udphdr * udp_hdr,struct iphdr * ip_hdr)265 static void gen_udp_csum(struct udphdr *udp_hdr, struct iphdr *ip_hdr)
266 {
267 	udp_hdr->check = 0;
268 	udp_hdr->check =
269 	    udp_csum(ip_hdr->saddr, ip_hdr->daddr, UDP_PKT_SIZE, IPPROTO_UDP, (u16 *)udp_hdr);
270 }
271 
xsk_configure_umem(struct xsk_umem_info * umem,void * buffer,u64 size)272 static int xsk_configure_umem(struct xsk_umem_info *umem, void *buffer, u64 size)
273 {
274 	struct xsk_umem_config cfg = {
275 		.fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS,
276 		.comp_size = XSK_RING_CONS__DEFAULT_NUM_DESCS,
277 		.frame_size = umem->frame_size,
278 		.frame_headroom = umem->frame_headroom,
279 		.flags = XSK_UMEM__DEFAULT_FLAGS
280 	};
281 	int ret;
282 
283 	if (umem->unaligned_mode)
284 		cfg.flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
285 
286 	ret = xsk_umem__create(&umem->umem, buffer, size,
287 			       &umem->fq, &umem->cq, &cfg);
288 	if (ret)
289 		return ret;
290 
291 	umem->buffer = buffer;
292 	return 0;
293 }
294 
enable_busy_poll(struct xsk_socket_info * xsk)295 static void enable_busy_poll(struct xsk_socket_info *xsk)
296 {
297 	int sock_opt;
298 
299 	sock_opt = 1;
300 	if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_PREFER_BUSY_POLL,
301 		       (void *)&sock_opt, sizeof(sock_opt)) < 0)
302 		exit_with_error(errno);
303 
304 	sock_opt = 20;
305 	if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL,
306 		       (void *)&sock_opt, sizeof(sock_opt)) < 0)
307 		exit_with_error(errno);
308 
309 	sock_opt = BATCH_SIZE;
310 	if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL_BUDGET,
311 		       (void *)&sock_opt, sizeof(sock_opt)) < 0)
312 		exit_with_error(errno);
313 }
314 
__xsk_configure_socket(struct xsk_socket_info * xsk,struct xsk_umem_info * umem,struct ifobject * ifobject,bool shared)315 static int __xsk_configure_socket(struct xsk_socket_info *xsk, struct xsk_umem_info *umem,
316 				  struct ifobject *ifobject, bool shared)
317 {
318 	struct xsk_socket_config cfg = {};
319 	struct xsk_ring_cons *rxr;
320 	struct xsk_ring_prod *txr;
321 
322 	xsk->umem = umem;
323 	cfg.rx_size = xsk->rxqsize;
324 	cfg.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
325 	cfg.libbpf_flags = XSK_LIBBPF_FLAGS__INHIBIT_PROG_LOAD;
326 	cfg.xdp_flags = ifobject->xdp_flags;
327 	cfg.bind_flags = ifobject->bind_flags;
328 	if (shared)
329 		cfg.bind_flags |= XDP_SHARED_UMEM;
330 
331 	txr = ifobject->tx_on ? &xsk->tx : NULL;
332 	rxr = ifobject->rx_on ? &xsk->rx : NULL;
333 	return xsk_socket__create(&xsk->xsk, ifobject->ifname, 0, umem->umem, rxr, txr, &cfg);
334 }
335 
ifobj_zc_avail(struct ifobject * ifobject)336 static bool ifobj_zc_avail(struct ifobject *ifobject)
337 {
338 	size_t umem_sz = DEFAULT_UMEM_BUFFERS * XSK_UMEM__DEFAULT_FRAME_SIZE;
339 	int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
340 	struct xsk_socket_info *xsk;
341 	struct xsk_umem_info *umem;
342 	bool zc_avail = false;
343 	void *bufs;
344 	int ret;
345 
346 	bufs = mmap(NULL, umem_sz, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
347 	if (bufs == MAP_FAILED)
348 		exit_with_error(errno);
349 
350 	umem = calloc(1, sizeof(struct xsk_umem_info));
351 	if (!umem) {
352 		munmap(bufs, umem_sz);
353 		exit_with_error(ENOMEM);
354 	}
355 	umem->frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
356 	ret = xsk_configure_umem(umem, bufs, umem_sz);
357 	if (ret)
358 		exit_with_error(-ret);
359 
360 	xsk = calloc(1, sizeof(struct xsk_socket_info));
361 	if (!xsk)
362 		goto out;
363 	ifobject->xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
364 	ifobject->xdp_flags |= XDP_FLAGS_DRV_MODE;
365 	ifobject->bind_flags = XDP_USE_NEED_WAKEUP | XDP_ZEROCOPY;
366 	ifobject->rx_on = true;
367 	xsk->rxqsize = XSK_RING_CONS__DEFAULT_NUM_DESCS;
368 	ret = __xsk_configure_socket(xsk, umem, ifobject, false);
369 	if (!ret)
370 		zc_avail = true;
371 
372 	xsk_socket__delete(xsk->xsk);
373 	free(xsk);
374 out:
375 	munmap(umem->buffer, umem_sz);
376 	xsk_umem__delete(umem->umem);
377 	free(umem);
378 	return zc_avail;
379 }
380 
381 static struct option long_options[] = {
382 	{"interface", required_argument, 0, 'i'},
383 	{"busy-poll", no_argument, 0, 'b'},
384 	{"dump-pkts", no_argument, 0, 'D'},
385 	{"verbose", no_argument, 0, 'v'},
386 	{0, 0, 0, 0}
387 };
388 
usage(const char * prog)389 static void usage(const char *prog)
390 {
391 	const char *str =
392 		"  Usage: %s [OPTIONS]\n"
393 		"  Options:\n"
394 		"  -i, --interface      Use interface\n"
395 		"  -D, --dump-pkts      Dump packets L2 - L5\n"
396 		"  -v, --verbose        Verbose output\n"
397 		"  -b, --busy-poll      Enable busy poll\n";
398 
399 	ksft_print_msg(str, prog);
400 }
401 
switch_namespace(const char * nsname)402 static int switch_namespace(const char *nsname)
403 {
404 	char fqns[26] = "/var/run/netns/";
405 	int nsfd;
406 
407 	if (!nsname || strlen(nsname) == 0)
408 		return -1;
409 
410 	strncat(fqns, nsname, sizeof(fqns) - strlen(fqns) - 1);
411 	nsfd = open(fqns, O_RDONLY);
412 
413 	if (nsfd == -1)
414 		exit_with_error(errno);
415 
416 	if (setns(nsfd, 0) == -1)
417 		exit_with_error(errno);
418 
419 	print_verbose("NS switched: %s\n", nsname);
420 
421 	return nsfd;
422 }
423 
validate_interface(struct ifobject * ifobj)424 static bool validate_interface(struct ifobject *ifobj)
425 {
426 	if (!strcmp(ifobj->ifname, ""))
427 		return false;
428 	return true;
429 }
430 
parse_command_line(struct ifobject * ifobj_tx,struct ifobject * ifobj_rx,int argc,char ** argv)431 static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj_rx, int argc,
432 			       char **argv)
433 {
434 	struct ifobject *ifobj;
435 	u32 interface_nb = 0;
436 	int option_index, c;
437 
438 	opterr = 0;
439 
440 	for (;;) {
441 		char *sptr, *token;
442 
443 		c = getopt_long(argc, argv, "i:Dvb", long_options, &option_index);
444 		if (c == -1)
445 			break;
446 
447 		switch (c) {
448 		case 'i':
449 			if (interface_nb == 0)
450 				ifobj = ifobj_tx;
451 			else if (interface_nb == 1)
452 				ifobj = ifobj_rx;
453 			else
454 				break;
455 
456 			sptr = strndupa(optarg, strlen(optarg));
457 			memcpy(ifobj->ifname, strsep(&sptr, ","), MAX_INTERFACE_NAME_CHARS);
458 			token = strsep(&sptr, ",");
459 			if (token)
460 				memcpy(ifobj->nsname, token, MAX_INTERFACES_NAMESPACE_CHARS);
461 			interface_nb++;
462 			break;
463 		case 'D':
464 			opt_pkt_dump = true;
465 			break;
466 		case 'v':
467 			opt_verbose = true;
468 			break;
469 		case 'b':
470 			ifobj_tx->busy_poll = true;
471 			ifobj_rx->busy_poll = true;
472 			break;
473 		default:
474 			usage(basename(argv[0]));
475 			ksft_exit_xfail();
476 		}
477 	}
478 }
479 
__test_spec_init(struct test_spec * test,struct ifobject * ifobj_tx,struct ifobject * ifobj_rx)480 static void __test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
481 			     struct ifobject *ifobj_rx)
482 {
483 	u32 i, j;
484 
485 	for (i = 0; i < MAX_INTERFACES; i++) {
486 		struct ifobject *ifobj = i ? ifobj_rx : ifobj_tx;
487 
488 		ifobj->xsk = &ifobj->xsk_arr[0];
489 		ifobj->use_poll = false;
490 		ifobj->use_fill_ring = true;
491 		ifobj->release_rx = true;
492 		ifobj->validation_func = NULL;
493 
494 		if (i == 0) {
495 			ifobj->rx_on = false;
496 			ifobj->tx_on = true;
497 			ifobj->pkt_stream = test->tx_pkt_stream_default;
498 		} else {
499 			ifobj->rx_on = true;
500 			ifobj->tx_on = false;
501 			ifobj->pkt_stream = test->rx_pkt_stream_default;
502 		}
503 
504 		memset(ifobj->umem, 0, sizeof(*ifobj->umem));
505 		ifobj->umem->num_frames = DEFAULT_UMEM_BUFFERS;
506 		ifobj->umem->frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
507 		if (ifobj->shared_umem && ifobj->rx_on)
508 			ifobj->umem->base_addr = DEFAULT_UMEM_BUFFERS *
509 				XSK_UMEM__DEFAULT_FRAME_SIZE;
510 
511 		for (j = 0; j < MAX_SOCKETS; j++) {
512 			memset(&ifobj->xsk_arr[j], 0, sizeof(ifobj->xsk_arr[j]));
513 			ifobj->xsk_arr[j].rxqsize = XSK_RING_CONS__DEFAULT_NUM_DESCS;
514 		}
515 	}
516 
517 	test->ifobj_tx = ifobj_tx;
518 	test->ifobj_rx = ifobj_rx;
519 	test->current_step = 0;
520 	test->total_steps = 1;
521 	test->nb_sockets = 1;
522 	test->fail = false;
523 }
524 
test_spec_init(struct test_spec * test,struct ifobject * ifobj_tx,struct ifobject * ifobj_rx,enum test_mode mode)525 static void test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
526 			   struct ifobject *ifobj_rx, enum test_mode mode)
527 {
528 	struct pkt_stream *tx_pkt_stream;
529 	struct pkt_stream *rx_pkt_stream;
530 	u32 i;
531 
532 	tx_pkt_stream = test->tx_pkt_stream_default;
533 	rx_pkt_stream = test->rx_pkt_stream_default;
534 	memset(test, 0, sizeof(*test));
535 	test->tx_pkt_stream_default = tx_pkt_stream;
536 	test->rx_pkt_stream_default = rx_pkt_stream;
537 
538 	for (i = 0; i < MAX_INTERFACES; i++) {
539 		struct ifobject *ifobj = i ? ifobj_rx : ifobj_tx;
540 
541 		ifobj->xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
542 		if (mode == TEST_MODE_SKB)
543 			ifobj->xdp_flags |= XDP_FLAGS_SKB_MODE;
544 		else
545 			ifobj->xdp_flags |= XDP_FLAGS_DRV_MODE;
546 
547 		ifobj->bind_flags = XDP_USE_NEED_WAKEUP;
548 		if (mode == TEST_MODE_ZC)
549 			ifobj->bind_flags |= XDP_ZEROCOPY;
550 		else
551 			ifobj->bind_flags |= XDP_COPY;
552 	}
553 
554 	test->mode = mode;
555 	__test_spec_init(test, ifobj_tx, ifobj_rx);
556 }
557 
test_spec_reset(struct test_spec * test)558 static void test_spec_reset(struct test_spec *test)
559 {
560 	__test_spec_init(test, test->ifobj_tx, test->ifobj_rx);
561 }
562 
test_spec_set_name(struct test_spec * test,const char * name)563 static void test_spec_set_name(struct test_spec *test, const char *name)
564 {
565 	strncpy(test->name, name, MAX_TEST_NAME_SIZE);
566 }
567 
pkt_stream_reset(struct pkt_stream * pkt_stream)568 static void pkt_stream_reset(struct pkt_stream *pkt_stream)
569 {
570 	if (pkt_stream)
571 		pkt_stream->rx_pkt_nb = 0;
572 }
573 
pkt_stream_get_pkt(struct pkt_stream * pkt_stream,u32 pkt_nb)574 static struct pkt *pkt_stream_get_pkt(struct pkt_stream *pkt_stream, u32 pkt_nb)
575 {
576 	if (pkt_nb >= pkt_stream->nb_pkts)
577 		return NULL;
578 
579 	return &pkt_stream->pkts[pkt_nb];
580 }
581 
pkt_stream_get_next_rx_pkt(struct pkt_stream * pkt_stream,u32 * pkts_sent)582 static struct pkt *pkt_stream_get_next_rx_pkt(struct pkt_stream *pkt_stream, u32 *pkts_sent)
583 {
584 	while (pkt_stream->rx_pkt_nb < pkt_stream->nb_pkts) {
585 		(*pkts_sent)++;
586 		if (pkt_stream->pkts[pkt_stream->rx_pkt_nb].valid)
587 			return &pkt_stream->pkts[pkt_stream->rx_pkt_nb++];
588 		pkt_stream->rx_pkt_nb++;
589 	}
590 	return NULL;
591 }
592 
pkt_stream_delete(struct pkt_stream * pkt_stream)593 static void pkt_stream_delete(struct pkt_stream *pkt_stream)
594 {
595 	free(pkt_stream->pkts);
596 	free(pkt_stream);
597 }
598 
pkt_stream_restore_default(struct test_spec * test)599 static void pkt_stream_restore_default(struct test_spec *test)
600 {
601 	struct pkt_stream *tx_pkt_stream = test->ifobj_tx->pkt_stream;
602 	struct pkt_stream *rx_pkt_stream = test->ifobj_rx->pkt_stream;
603 
604 	if (tx_pkt_stream != test->tx_pkt_stream_default) {
605 		pkt_stream_delete(test->ifobj_tx->pkt_stream);
606 		test->ifobj_tx->pkt_stream = test->tx_pkt_stream_default;
607 	}
608 
609 	if (rx_pkt_stream != test->rx_pkt_stream_default) {
610 		pkt_stream_delete(test->ifobj_rx->pkt_stream);
611 		test->ifobj_rx->pkt_stream = test->rx_pkt_stream_default;
612 	}
613 }
614 
__pkt_stream_alloc(u32 nb_pkts)615 static struct pkt_stream *__pkt_stream_alloc(u32 nb_pkts)
616 {
617 	struct pkt_stream *pkt_stream;
618 
619 	pkt_stream = calloc(1, sizeof(*pkt_stream));
620 	if (!pkt_stream)
621 		return NULL;
622 
623 	pkt_stream->pkts = calloc(nb_pkts, sizeof(*pkt_stream->pkts));
624 	if (!pkt_stream->pkts) {
625 		free(pkt_stream);
626 		return NULL;
627 	}
628 
629 	pkt_stream->nb_pkts = nb_pkts;
630 	return pkt_stream;
631 }
632 
pkt_set(struct xsk_umem_info * umem,struct pkt * pkt,u64 addr,u32 len)633 static void pkt_set(struct xsk_umem_info *umem, struct pkt *pkt, u64 addr, u32 len)
634 {
635 	pkt->addr = addr + umem->base_addr;
636 	pkt->len = len;
637 	if (len > umem->frame_size - XDP_PACKET_HEADROOM - MIN_PKT_SIZE * 2 - umem->frame_headroom)
638 		pkt->valid = false;
639 	else
640 		pkt->valid = true;
641 }
642 
pkt_stream_generate(struct xsk_umem_info * umem,u32 nb_pkts,u32 pkt_len)643 static struct pkt_stream *pkt_stream_generate(struct xsk_umem_info *umem, u32 nb_pkts, u32 pkt_len)
644 {
645 	struct pkt_stream *pkt_stream;
646 	u32 i;
647 
648 	pkt_stream = __pkt_stream_alloc(nb_pkts);
649 	if (!pkt_stream)
650 		exit_with_error(ENOMEM);
651 
652 	for (i = 0; i < nb_pkts; i++) {
653 		pkt_set(umem, &pkt_stream->pkts[i], (i % umem->num_frames) * umem->frame_size,
654 			pkt_len);
655 		pkt_stream->pkts[i].payload = i;
656 	}
657 
658 	return pkt_stream;
659 }
660 
pkt_stream_clone(struct xsk_umem_info * umem,struct pkt_stream * pkt_stream)661 static struct pkt_stream *pkt_stream_clone(struct xsk_umem_info *umem,
662 					   struct pkt_stream *pkt_stream)
663 {
664 	return pkt_stream_generate(umem, pkt_stream->nb_pkts, pkt_stream->pkts[0].len);
665 }
666 
pkt_stream_replace(struct test_spec * test,u32 nb_pkts,u32 pkt_len)667 static void pkt_stream_replace(struct test_spec *test, u32 nb_pkts, u32 pkt_len)
668 {
669 	struct pkt_stream *pkt_stream;
670 
671 	pkt_stream = pkt_stream_generate(test->ifobj_tx->umem, nb_pkts, pkt_len);
672 	test->ifobj_tx->pkt_stream = pkt_stream;
673 	pkt_stream = pkt_stream_generate(test->ifobj_rx->umem, nb_pkts, pkt_len);
674 	test->ifobj_rx->pkt_stream = pkt_stream;
675 }
676 
__pkt_stream_replace_half(struct ifobject * ifobj,u32 pkt_len,int offset)677 static void __pkt_stream_replace_half(struct ifobject *ifobj, u32 pkt_len,
678 				      int offset)
679 {
680 	struct xsk_umem_info *umem = ifobj->umem;
681 	struct pkt_stream *pkt_stream;
682 	u32 i;
683 
684 	pkt_stream = pkt_stream_clone(umem, ifobj->pkt_stream);
685 	for (i = 1; i < ifobj->pkt_stream->nb_pkts; i += 2)
686 		pkt_set(umem, &pkt_stream->pkts[i],
687 			(i % umem->num_frames) * umem->frame_size + offset, pkt_len);
688 
689 	ifobj->pkt_stream = pkt_stream;
690 }
691 
pkt_stream_replace_half(struct test_spec * test,u32 pkt_len,int offset)692 static void pkt_stream_replace_half(struct test_spec *test, u32 pkt_len, int offset)
693 {
694 	__pkt_stream_replace_half(test->ifobj_tx, pkt_len, offset);
695 	__pkt_stream_replace_half(test->ifobj_rx, pkt_len, offset);
696 }
697 
pkt_stream_receive_half(struct test_spec * test)698 static void pkt_stream_receive_half(struct test_spec *test)
699 {
700 	struct xsk_umem_info *umem = test->ifobj_rx->umem;
701 	struct pkt_stream *pkt_stream = test->ifobj_tx->pkt_stream;
702 	u32 i;
703 
704 	test->ifobj_rx->pkt_stream = pkt_stream_generate(umem, pkt_stream->nb_pkts,
705 							 pkt_stream->pkts[0].len);
706 	pkt_stream = test->ifobj_rx->pkt_stream;
707 	for (i = 1; i < pkt_stream->nb_pkts; i += 2)
708 		pkt_stream->pkts[i].valid = false;
709 }
710 
pkt_generate(struct ifobject * ifobject,u32 pkt_nb)711 static struct pkt *pkt_generate(struct ifobject *ifobject, u32 pkt_nb)
712 {
713 	struct pkt *pkt = pkt_stream_get_pkt(ifobject->pkt_stream, pkt_nb);
714 	struct udphdr *udp_hdr;
715 	struct ethhdr *eth_hdr;
716 	struct iphdr *ip_hdr;
717 	void *data;
718 
719 	if (!pkt)
720 		return NULL;
721 	if (!pkt->valid || pkt->len < MIN_PKT_SIZE)
722 		return pkt;
723 
724 	data = xsk_umem__get_data(ifobject->umem->buffer, pkt->addr);
725 	udp_hdr = (struct udphdr *)(data + sizeof(struct ethhdr) + sizeof(struct iphdr));
726 	ip_hdr = (struct iphdr *)(data + sizeof(struct ethhdr));
727 	eth_hdr = (struct ethhdr *)data;
728 
729 	gen_udp_hdr(pkt_nb, data, ifobject, udp_hdr);
730 	gen_ip_hdr(ifobject, ip_hdr);
731 	gen_udp_csum(udp_hdr, ip_hdr);
732 	gen_eth_hdr(ifobject, eth_hdr);
733 
734 	return pkt;
735 }
736 
__pkt_stream_generate_custom(struct ifobject * ifobj,struct pkt * pkts,u32 nb_pkts)737 static void __pkt_stream_generate_custom(struct ifobject *ifobj,
738 					 struct pkt *pkts, u32 nb_pkts)
739 {
740 	struct pkt_stream *pkt_stream;
741 	u32 i;
742 
743 	pkt_stream = __pkt_stream_alloc(nb_pkts);
744 	if (!pkt_stream)
745 		exit_with_error(ENOMEM);
746 
747 	for (i = 0; i < nb_pkts; i++) {
748 		pkt_stream->pkts[i].addr = pkts[i].addr + ifobj->umem->base_addr;
749 		pkt_stream->pkts[i].len = pkts[i].len;
750 		pkt_stream->pkts[i].payload = i;
751 		pkt_stream->pkts[i].valid = pkts[i].valid;
752 	}
753 
754 	ifobj->pkt_stream = pkt_stream;
755 }
756 
pkt_stream_generate_custom(struct test_spec * test,struct pkt * pkts,u32 nb_pkts)757 static void pkt_stream_generate_custom(struct test_spec *test, struct pkt *pkts, u32 nb_pkts)
758 {
759 	__pkt_stream_generate_custom(test->ifobj_tx, pkts, nb_pkts);
760 	__pkt_stream_generate_custom(test->ifobj_rx, pkts, nb_pkts);
761 }
762 
pkt_dump(void * pkt,u32 len)763 static void pkt_dump(void *pkt, u32 len)
764 {
765 	char s[INET_ADDRSTRLEN];
766 	struct ethhdr *ethhdr;
767 	struct udphdr *udphdr;
768 	struct iphdr *iphdr;
769 	u32 payload, i;
770 
771 	ethhdr = pkt;
772 	iphdr = pkt + sizeof(*ethhdr);
773 	udphdr = pkt + sizeof(*ethhdr) + sizeof(*iphdr);
774 
775 	/*extract L2 frame */
776 	fprintf(stdout, "DEBUG>> L2: dst mac: ");
777 	for (i = 0; i < ETH_ALEN; i++)
778 		fprintf(stdout, "%02X", ethhdr->h_dest[i]);
779 
780 	fprintf(stdout, "\nDEBUG>> L2: src mac: ");
781 	for (i = 0; i < ETH_ALEN; i++)
782 		fprintf(stdout, "%02X", ethhdr->h_source[i]);
783 
784 	/*extract L3 frame */
785 	fprintf(stdout, "\nDEBUG>> L3: ip_hdr->ihl: %02X\n", iphdr->ihl);
786 	fprintf(stdout, "DEBUG>> L3: ip_hdr->saddr: %s\n",
787 		inet_ntop(AF_INET, &iphdr->saddr, s, sizeof(s)));
788 	fprintf(stdout, "DEBUG>> L3: ip_hdr->daddr: %s\n",
789 		inet_ntop(AF_INET, &iphdr->daddr, s, sizeof(s)));
790 	/*extract L4 frame */
791 	fprintf(stdout, "DEBUG>> L4: udp_hdr->src: %d\n", ntohs(udphdr->source));
792 	fprintf(stdout, "DEBUG>> L4: udp_hdr->dst: %d\n", ntohs(udphdr->dest));
793 	/*extract L5 frame */
794 	payload = ntohl(*((u32 *)(pkt + PKT_HDR_SIZE)));
795 
796 	fprintf(stdout, "DEBUG>> L5: payload: %d\n", payload);
797 	fprintf(stdout, "---------------------------------------\n");
798 }
799 
is_offset_correct(struct xsk_umem_info * umem,struct pkt_stream * pkt_stream,u64 addr,u64 pkt_stream_addr)800 static bool is_offset_correct(struct xsk_umem_info *umem, struct pkt_stream *pkt_stream, u64 addr,
801 			      u64 pkt_stream_addr)
802 {
803 	u32 headroom = umem->unaligned_mode ? 0 : umem->frame_headroom;
804 	u32 offset = addr % umem->frame_size, expected_offset = 0;
805 
806 	if (!pkt_stream->use_addr_for_fill)
807 		pkt_stream_addr = 0;
808 
809 	expected_offset += (pkt_stream_addr + headroom + XDP_PACKET_HEADROOM) % umem->frame_size;
810 
811 	if (offset == expected_offset)
812 		return true;
813 
814 	ksft_print_msg("[%s] expected [%u], got [%u]\n", __func__, expected_offset, offset);
815 	return false;
816 }
817 
is_pkt_valid(struct pkt * pkt,void * buffer,u64 addr,u32 len)818 static bool is_pkt_valid(struct pkt *pkt, void *buffer, u64 addr, u32 len)
819 {
820 	void *data = xsk_umem__get_data(buffer, addr);
821 	struct iphdr *iphdr = (struct iphdr *)(data + sizeof(struct ethhdr));
822 
823 	if (!pkt) {
824 		ksft_print_msg("[%s] too many packets received\n", __func__);
825 		return false;
826 	}
827 
828 	if (len < MIN_PKT_SIZE || pkt->len < MIN_PKT_SIZE) {
829 		/* Do not try to verify packets that are smaller than minimum size. */
830 		return true;
831 	}
832 
833 	if (pkt->len != len) {
834 		ksft_print_msg("[%s] expected length [%d], got length [%d]\n",
835 			       __func__, pkt->len, len);
836 		return false;
837 	}
838 
839 	if (iphdr->version == IP_PKT_VER && iphdr->tos == IP_PKT_TOS) {
840 		u32 seqnum = ntohl(*((u32 *)(data + PKT_HDR_SIZE)));
841 
842 		if (opt_pkt_dump)
843 			pkt_dump(data, PKT_SIZE);
844 
845 		if (pkt->payload != seqnum) {
846 			ksft_print_msg("[%s] expected seqnum [%d], got seqnum [%d]\n",
847 				       __func__, pkt->payload, seqnum);
848 			return false;
849 		}
850 	} else {
851 		ksft_print_msg("Invalid frame received: ");
852 		ksft_print_msg("[IP_PKT_VER: %02X], [IP_PKT_TOS: %02X]\n", iphdr->version,
853 			       iphdr->tos);
854 		return false;
855 	}
856 
857 	return true;
858 }
859 
kick_tx(struct xsk_socket_info * xsk)860 static void kick_tx(struct xsk_socket_info *xsk)
861 {
862 	int ret;
863 
864 	ret = sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
865 	if (ret >= 0)
866 		return;
867 	if (errno == ENOBUFS || errno == EAGAIN || errno == EBUSY || errno == ENETDOWN) {
868 		usleep(100);
869 		return;
870 	}
871 	exit_with_error(errno);
872 }
873 
kick_rx(struct xsk_socket_info * xsk)874 static void kick_rx(struct xsk_socket_info *xsk)
875 {
876 	int ret;
877 
878 	ret = recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
879 	if (ret < 0)
880 		exit_with_error(errno);
881 }
882 
complete_pkts(struct xsk_socket_info * xsk,int batch_size)883 static int complete_pkts(struct xsk_socket_info *xsk, int batch_size)
884 {
885 	unsigned int rcvd;
886 	u32 idx;
887 
888 	if (xsk_ring_prod__needs_wakeup(&xsk->tx))
889 		kick_tx(xsk);
890 
891 	rcvd = xsk_ring_cons__peek(&xsk->umem->cq, batch_size, &idx);
892 	if (rcvd) {
893 		if (rcvd > xsk->outstanding_tx) {
894 			u64 addr = *xsk_ring_cons__comp_addr(&xsk->umem->cq, idx + rcvd - 1);
895 
896 			ksft_print_msg("[%s] Too many packets completed\n", __func__);
897 			ksft_print_msg("Last completion address: %llx\n", addr);
898 			return TEST_FAILURE;
899 		}
900 
901 		xsk_ring_cons__release(&xsk->umem->cq, rcvd);
902 		xsk->outstanding_tx -= rcvd;
903 	}
904 
905 	return TEST_PASS;
906 }
907 
receive_pkts(struct test_spec * test,struct pollfd * fds)908 static int receive_pkts(struct test_spec *test, struct pollfd *fds)
909 {
910 	struct timeval tv_end, tv_now, tv_timeout = {THREAD_TMOUT, 0};
911 	struct pkt_stream *pkt_stream = test->ifobj_rx->pkt_stream;
912 	u32 idx_rx = 0, idx_fq = 0, rcvd, i, pkts_sent = 0;
913 	struct xsk_socket_info *xsk = test->ifobj_rx->xsk;
914 	struct ifobject *ifobj = test->ifobj_rx;
915 	struct xsk_umem_info *umem = xsk->umem;
916 	struct pkt *pkt;
917 	int ret;
918 
919 	ret = gettimeofday(&tv_now, NULL);
920 	if (ret)
921 		exit_with_error(errno);
922 	timeradd(&tv_now, &tv_timeout, &tv_end);
923 
924 	pkt = pkt_stream_get_next_rx_pkt(pkt_stream, &pkts_sent);
925 	while (pkt) {
926 		ret = gettimeofday(&tv_now, NULL);
927 		if (ret)
928 			exit_with_error(errno);
929 		if (timercmp(&tv_now, &tv_end, >)) {
930 			ksft_print_msg("ERROR: [%s] Receive loop timed out\n", __func__);
931 			return TEST_FAILURE;
932 		}
933 
934 		kick_rx(xsk);
935 		if (ifobj->use_poll) {
936 			ret = poll(fds, 1, POLL_TMOUT);
937 			if (ret < 0)
938 				exit_with_error(errno);
939 
940 			if (!ret) {
941 				if (!is_umem_valid(test->ifobj_tx))
942 					return TEST_PASS;
943 
944 				ksft_print_msg("ERROR: [%s] Poll timed out\n", __func__);
945 				return TEST_FAILURE;
946 
947 			}
948 
949 			if (!(fds->revents & POLLIN))
950 				continue;
951 		}
952 
953 		rcvd = xsk_ring_cons__peek(&xsk->rx, BATCH_SIZE, &idx_rx);
954 		if (!rcvd)
955 			continue;
956 
957 		if (ifobj->use_fill_ring) {
958 			ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
959 			while (ret != rcvd) {
960 				if (ret < 0)
961 					exit_with_error(-ret);
962 				if (xsk_ring_prod__needs_wakeup(&umem->fq)) {
963 					ret = poll(fds, 1, POLL_TMOUT);
964 					if (ret < 0)
965 						exit_with_error(errno);
966 				}
967 				ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
968 			}
969 		}
970 
971 		for (i = 0; i < rcvd; i++) {
972 			const struct xdp_desc *desc = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++);
973 			u64 addr = desc->addr, orig;
974 
975 			orig = xsk_umem__extract_addr(addr);
976 			addr = xsk_umem__add_offset_to_addr(addr);
977 
978 			if (!is_pkt_valid(pkt, umem->buffer, addr, desc->len) ||
979 			    !is_offset_correct(umem, pkt_stream, addr, pkt->addr))
980 				return TEST_FAILURE;
981 
982 			if (ifobj->use_fill_ring)
983 				*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) = orig;
984 			pkt = pkt_stream_get_next_rx_pkt(pkt_stream, &pkts_sent);
985 		}
986 
987 		if (ifobj->use_fill_ring)
988 			xsk_ring_prod__submit(&umem->fq, rcvd);
989 		if (ifobj->release_rx)
990 			xsk_ring_cons__release(&xsk->rx, rcvd);
991 
992 		pthread_mutex_lock(&pacing_mutex);
993 		pkts_in_flight -= pkts_sent;
994 		if (pkts_in_flight < umem->num_frames)
995 			pthread_cond_signal(&pacing_cond);
996 		pthread_mutex_unlock(&pacing_mutex);
997 		pkts_sent = 0;
998 	}
999 
1000 	return TEST_PASS;
1001 }
1002 
__send_pkts(struct ifobject * ifobject,u32 * pkt_nb,struct pollfd * fds,bool timeout)1003 static int __send_pkts(struct ifobject *ifobject, u32 *pkt_nb, struct pollfd *fds,
1004 		       bool timeout)
1005 {
1006 	struct xsk_socket_info *xsk = ifobject->xsk;
1007 	bool use_poll = ifobject->use_poll;
1008 	u32 i, idx = 0, ret, valid_pkts = 0;
1009 
1010 	while (xsk_ring_prod__reserve(&xsk->tx, BATCH_SIZE, &idx) < BATCH_SIZE) {
1011 		if (use_poll) {
1012 			ret = poll(fds, 1, POLL_TMOUT);
1013 			if (timeout) {
1014 				if (ret < 0) {
1015 					ksft_print_msg("ERROR: [%s] Poll error %d\n",
1016 						       __func__, errno);
1017 					return TEST_FAILURE;
1018 				}
1019 				if (ret == 0)
1020 					return TEST_PASS;
1021 				break;
1022 			}
1023 			if (ret <= 0) {
1024 				ksft_print_msg("ERROR: [%s] Poll error %d\n",
1025 					       __func__, errno);
1026 				return TEST_FAILURE;
1027 			}
1028 		}
1029 
1030 		complete_pkts(xsk, BATCH_SIZE);
1031 	}
1032 
1033 	for (i = 0; i < BATCH_SIZE; i++) {
1034 		struct xdp_desc *tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx + i);
1035 		struct pkt *pkt = pkt_generate(ifobject, *pkt_nb);
1036 
1037 		if (!pkt)
1038 			break;
1039 
1040 		tx_desc->addr = pkt->addr;
1041 		tx_desc->len = pkt->len;
1042 		(*pkt_nb)++;
1043 		if (pkt->valid)
1044 			valid_pkts++;
1045 	}
1046 
1047 	pthread_mutex_lock(&pacing_mutex);
1048 	pkts_in_flight += valid_pkts;
1049 	/* pkts_in_flight might be negative if many invalid packets are sent */
1050 	if (pkts_in_flight >= (int)(ifobject->umem->num_frames - BATCH_SIZE)) {
1051 		kick_tx(xsk);
1052 		pthread_cond_wait(&pacing_cond, &pacing_mutex);
1053 	}
1054 	pthread_mutex_unlock(&pacing_mutex);
1055 
1056 	xsk_ring_prod__submit(&xsk->tx, i);
1057 	xsk->outstanding_tx += valid_pkts;
1058 
1059 	if (use_poll) {
1060 		ret = poll(fds, 1, POLL_TMOUT);
1061 		if (ret <= 0) {
1062 			if (ret == 0 && timeout)
1063 				return TEST_PASS;
1064 
1065 			ksft_print_msg("ERROR: [%s] Poll error %d\n", __func__, ret);
1066 			return TEST_FAILURE;
1067 		}
1068 	}
1069 
1070 	if (!timeout) {
1071 		if (complete_pkts(xsk, i))
1072 			return TEST_FAILURE;
1073 
1074 		usleep(10);
1075 		return TEST_PASS;
1076 	}
1077 
1078 	return TEST_CONTINUE;
1079 }
1080 
wait_for_tx_completion(struct xsk_socket_info * xsk)1081 static void wait_for_tx_completion(struct xsk_socket_info *xsk)
1082 {
1083 	while (xsk->outstanding_tx)
1084 		complete_pkts(xsk, BATCH_SIZE);
1085 }
1086 
send_pkts(struct test_spec * test,struct ifobject * ifobject)1087 static int send_pkts(struct test_spec *test, struct ifobject *ifobject)
1088 {
1089 	bool timeout = !is_umem_valid(test->ifobj_rx);
1090 	struct pollfd fds = { };
1091 	u32 pkt_cnt = 0, ret;
1092 
1093 	fds.fd = xsk_socket__fd(ifobject->xsk->xsk);
1094 	fds.events = POLLOUT;
1095 
1096 	while (pkt_cnt < ifobject->pkt_stream->nb_pkts) {
1097 		ret = __send_pkts(ifobject, &pkt_cnt, &fds, timeout);
1098 		if ((ret || test->fail) && !timeout)
1099 			return TEST_FAILURE;
1100 		else if (ret == TEST_PASS && timeout)
1101 			return ret;
1102 	}
1103 
1104 	wait_for_tx_completion(ifobject->xsk);
1105 	return TEST_PASS;
1106 }
1107 
get_xsk_stats(struct xsk_socket * xsk,struct xdp_statistics * stats)1108 static int get_xsk_stats(struct xsk_socket *xsk, struct xdp_statistics *stats)
1109 {
1110 	int fd = xsk_socket__fd(xsk), err;
1111 	socklen_t optlen, expected_len;
1112 
1113 	optlen = sizeof(*stats);
1114 	err = getsockopt(fd, SOL_XDP, XDP_STATISTICS, stats, &optlen);
1115 	if (err) {
1116 		ksft_print_msg("[%s] getsockopt(XDP_STATISTICS) error %u %s\n",
1117 			       __func__, -err, strerror(-err));
1118 		return TEST_FAILURE;
1119 	}
1120 
1121 	expected_len = sizeof(struct xdp_statistics);
1122 	if (optlen != expected_len) {
1123 		ksft_print_msg("[%s] getsockopt optlen error. Expected: %u got: %u\n",
1124 			       __func__, expected_len, optlen);
1125 		return TEST_FAILURE;
1126 	}
1127 
1128 	return TEST_PASS;
1129 }
1130 
validate_rx_dropped(struct ifobject * ifobject)1131 static int validate_rx_dropped(struct ifobject *ifobject)
1132 {
1133 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1134 	struct xdp_statistics stats;
1135 	int err;
1136 
1137 	kick_rx(ifobject->xsk);
1138 
1139 	err = get_xsk_stats(xsk, &stats);
1140 	if (err)
1141 		return TEST_FAILURE;
1142 
1143 	/* The receiver calls getsockopt after receiving the last (valid)
1144 	 * packet which is not the final packet sent in this test (valid and
1145 	 * invalid packets are sent in alternating fashion with the final
1146 	 * packet being invalid). Since the last packet may or may not have
1147 	 * been dropped already, both outcomes must be allowed.
1148 	 */
1149 	if (stats.rx_dropped == ifobject->pkt_stream->nb_pkts / 2 ||
1150 	    stats.rx_dropped == ifobject->pkt_stream->nb_pkts / 2 - 1)
1151 		return TEST_PASS;
1152 
1153 	return TEST_FAILURE;
1154 }
1155 
validate_rx_full(struct ifobject * ifobject)1156 static int validate_rx_full(struct ifobject *ifobject)
1157 {
1158 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1159 	struct xdp_statistics stats;
1160 	int err;
1161 
1162 	usleep(1000);
1163 	kick_rx(ifobject->xsk);
1164 
1165 	err = get_xsk_stats(xsk, &stats);
1166 	if (err)
1167 		return TEST_FAILURE;
1168 
1169 	if (stats.rx_ring_full)
1170 		return TEST_PASS;
1171 
1172 	return TEST_FAILURE;
1173 }
1174 
validate_fill_empty(struct ifobject * ifobject)1175 static int validate_fill_empty(struct ifobject *ifobject)
1176 {
1177 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1178 	struct xdp_statistics stats;
1179 	int err;
1180 
1181 	usleep(1000);
1182 	kick_rx(ifobject->xsk);
1183 
1184 	err = get_xsk_stats(xsk, &stats);
1185 	if (err)
1186 		return TEST_FAILURE;
1187 
1188 	if (stats.rx_fill_ring_empty_descs)
1189 		return TEST_PASS;
1190 
1191 	return TEST_FAILURE;
1192 }
1193 
validate_tx_invalid_descs(struct ifobject * ifobject)1194 static int validate_tx_invalid_descs(struct ifobject *ifobject)
1195 {
1196 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1197 	int fd = xsk_socket__fd(xsk);
1198 	struct xdp_statistics stats;
1199 	socklen_t optlen;
1200 	int err;
1201 
1202 	optlen = sizeof(stats);
1203 	err = getsockopt(fd, SOL_XDP, XDP_STATISTICS, &stats, &optlen);
1204 	if (err) {
1205 		ksft_print_msg("[%s] getsockopt(XDP_STATISTICS) error %u %s\n",
1206 			       __func__, -err, strerror(-err));
1207 		return TEST_FAILURE;
1208 	}
1209 
1210 	if (stats.tx_invalid_descs != ifobject->pkt_stream->nb_pkts / 2) {
1211 		ksft_print_msg("[%s] tx_invalid_descs incorrect. Got [%u] expected [%u]\n",
1212 			       __func__, stats.tx_invalid_descs, ifobject->pkt_stream->nb_pkts);
1213 		return TEST_FAILURE;
1214 	}
1215 
1216 	return TEST_PASS;
1217 }
1218 
xsk_configure_socket(struct test_spec * test,struct ifobject * ifobject,struct xsk_umem_info * umem,bool tx)1219 static void xsk_configure_socket(struct test_spec *test, struct ifobject *ifobject,
1220 				 struct xsk_umem_info *umem, bool tx)
1221 {
1222 	int i, ret;
1223 
1224 	for (i = 0; i < test->nb_sockets; i++) {
1225 		bool shared = (ifobject->shared_umem && tx) ? true : !!i;
1226 		u32 ctr = 0;
1227 
1228 		while (ctr++ < SOCK_RECONF_CTR) {
1229 			ret = __xsk_configure_socket(&ifobject->xsk_arr[i], umem,
1230 						     ifobject, shared);
1231 			if (!ret)
1232 				break;
1233 
1234 			/* Retry if it fails as xsk_socket__create() is asynchronous */
1235 			if (ctr >= SOCK_RECONF_CTR)
1236 				exit_with_error(-ret);
1237 			usleep(USLEEP_MAX);
1238 		}
1239 		if (ifobject->busy_poll)
1240 			enable_busy_poll(&ifobject->xsk_arr[i]);
1241 	}
1242 }
1243 
thread_common_ops_tx(struct test_spec * test,struct ifobject * ifobject)1244 static void thread_common_ops_tx(struct test_spec *test, struct ifobject *ifobject)
1245 {
1246 	xsk_configure_socket(test, ifobject, test->ifobj_rx->umem, true);
1247 	ifobject->xsk = &ifobject->xsk_arr[0];
1248 	ifobject->xsk_map_fd = test->ifobj_rx->xsk_map_fd;
1249 	memcpy(ifobject->umem, test->ifobj_rx->umem, sizeof(struct xsk_umem_info));
1250 }
1251 
xsk_populate_fill_ring(struct xsk_umem_info * umem,struct pkt_stream * pkt_stream)1252 static void xsk_populate_fill_ring(struct xsk_umem_info *umem, struct pkt_stream *pkt_stream)
1253 {
1254 	u32 idx = 0, i, buffers_to_fill;
1255 	int ret;
1256 
1257 	if (umem->num_frames < XSK_RING_PROD__DEFAULT_NUM_DESCS)
1258 		buffers_to_fill = umem->num_frames;
1259 	else
1260 		buffers_to_fill = XSK_RING_PROD__DEFAULT_NUM_DESCS;
1261 
1262 	ret = xsk_ring_prod__reserve(&umem->fq, buffers_to_fill, &idx);
1263 	if (ret != buffers_to_fill)
1264 		exit_with_error(ENOSPC);
1265 	for (i = 0; i < buffers_to_fill; i++) {
1266 		u64 addr;
1267 
1268 		if (pkt_stream->use_addr_for_fill) {
1269 			struct pkt *pkt = pkt_stream_get_pkt(pkt_stream, i);
1270 
1271 			if (!pkt)
1272 				break;
1273 			addr = pkt->addr;
1274 		} else {
1275 			addr = i * umem->frame_size;
1276 		}
1277 
1278 		*xsk_ring_prod__fill_addr(&umem->fq, idx++) = addr;
1279 	}
1280 	xsk_ring_prod__submit(&umem->fq, buffers_to_fill);
1281 }
1282 
thread_common_ops(struct test_spec * test,struct ifobject * ifobject)1283 static void thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
1284 {
1285 	u64 umem_sz = ifobject->umem->num_frames * ifobject->umem->frame_size;
1286 	int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
1287 	LIBBPF_OPTS(bpf_xdp_query_opts, opts);
1288 	int ret, ifindex;
1289 	void *bufs;
1290 
1291 	ifobject->ns_fd = switch_namespace(ifobject->nsname);
1292 
1293 	if (ifobject->umem->unaligned_mode)
1294 		mmap_flags |= MAP_HUGETLB;
1295 
1296 	if (ifobject->shared_umem)
1297 		umem_sz *= 2;
1298 
1299 	bufs = mmap(NULL, umem_sz, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
1300 	if (bufs == MAP_FAILED)
1301 		exit_with_error(errno);
1302 
1303 	ret = xsk_configure_umem(ifobject->umem, bufs, umem_sz);
1304 	if (ret)
1305 		exit_with_error(-ret);
1306 
1307 	xsk_populate_fill_ring(ifobject->umem, ifobject->pkt_stream);
1308 
1309 	xsk_configure_socket(test, ifobject, ifobject->umem, false);
1310 
1311 	ifobject->xsk = &ifobject->xsk_arr[0];
1312 
1313 	if (!ifobject->rx_on)
1314 		return;
1315 
1316 	ifindex = if_nametoindex(ifobject->ifname);
1317 	if (!ifindex)
1318 		exit_with_error(errno);
1319 
1320 	ret = xsk_setup_xdp_prog_xsk(ifobject->xsk->xsk, &ifobject->xsk_map_fd);
1321 	if (ret)
1322 		exit_with_error(-ret);
1323 
1324 	ret = bpf_xdp_query(ifindex, ifobject->xdp_flags, &opts);
1325 	if (ret)
1326 		exit_with_error(-ret);
1327 
1328 	if (ifobject->xdp_flags & XDP_FLAGS_SKB_MODE) {
1329 		if (opts.attach_mode != XDP_ATTACHED_SKB) {
1330 			ksft_print_msg("ERROR: [%s] XDP prog not in SKB mode\n");
1331 			exit_with_error(EINVAL);
1332 		}
1333 	} else if (ifobject->xdp_flags & XDP_FLAGS_DRV_MODE) {
1334 		if (opts.attach_mode != XDP_ATTACHED_DRV) {
1335 			ksft_print_msg("ERROR: [%s] XDP prog not in DRV mode\n");
1336 			exit_with_error(EINVAL);
1337 		}
1338 	}
1339 
1340 	ret = xsk_socket__update_xskmap(ifobject->xsk->xsk, ifobject->xsk_map_fd);
1341 	if (ret)
1342 		exit_with_error(errno);
1343 }
1344 
worker_testapp_validate_tx(void * arg)1345 static void *worker_testapp_validate_tx(void *arg)
1346 {
1347 	struct test_spec *test = (struct test_spec *)arg;
1348 	struct ifobject *ifobject = test->ifobj_tx;
1349 	int err;
1350 
1351 	if (test->current_step == 1) {
1352 		if (!ifobject->shared_umem)
1353 			thread_common_ops(test, ifobject);
1354 		else
1355 			thread_common_ops_tx(test, ifobject);
1356 	}
1357 
1358 	print_verbose("Sending %d packets on interface %s\n", ifobject->pkt_stream->nb_pkts,
1359 		      ifobject->ifname);
1360 	err = send_pkts(test, ifobject);
1361 
1362 	if (!err && ifobject->validation_func)
1363 		err = ifobject->validation_func(ifobject);
1364 	if (err)
1365 		report_failure(test);
1366 
1367 	pthread_exit(NULL);
1368 }
1369 
worker_testapp_validate_rx(void * arg)1370 static void *worker_testapp_validate_rx(void *arg)
1371 {
1372 	struct test_spec *test = (struct test_spec *)arg;
1373 	struct ifobject *ifobject = test->ifobj_rx;
1374 	struct pollfd fds = { };
1375 	int id = 0;
1376 	int err;
1377 
1378 	if (test->current_step == 1) {
1379 		thread_common_ops(test, ifobject);
1380 	} else {
1381 		bpf_map_delete_elem(ifobject->xsk_map_fd, &id);
1382 		xsk_socket__update_xskmap(ifobject->xsk->xsk, ifobject->xsk_map_fd);
1383 	}
1384 
1385 	fds.fd = xsk_socket__fd(ifobject->xsk->xsk);
1386 	fds.events = POLLIN;
1387 
1388 	pthread_barrier_wait(&barr);
1389 
1390 	err = receive_pkts(test, &fds);
1391 
1392 	if (!err && ifobject->validation_func)
1393 		err = ifobject->validation_func(ifobject);
1394 	if (err) {
1395 		report_failure(test);
1396 		pthread_mutex_lock(&pacing_mutex);
1397 		pthread_cond_signal(&pacing_cond);
1398 		pthread_mutex_unlock(&pacing_mutex);
1399 	}
1400 
1401 	pthread_exit(NULL);
1402 }
1403 
testapp_clean_xsk_umem(struct ifobject * ifobj)1404 static void testapp_clean_xsk_umem(struct ifobject *ifobj)
1405 {
1406 	u64 umem_sz = ifobj->umem->num_frames * ifobj->umem->frame_size;
1407 
1408 	if (ifobj->shared_umem)
1409 		umem_sz *= 2;
1410 
1411 	xsk_umem__delete(ifobj->umem->umem);
1412 	munmap(ifobj->umem->buffer, umem_sz);
1413 }
1414 
handler(int signum)1415 static void handler(int signum)
1416 {
1417 	pthread_exit(NULL);
1418 }
1419 
testapp_validate_traffic_single_thread(struct test_spec * test,struct ifobject * ifobj,enum test_type type)1420 static int testapp_validate_traffic_single_thread(struct test_spec *test, struct ifobject *ifobj,
1421 						  enum test_type type)
1422 {
1423 	bool old_shared_umem = ifobj->shared_umem;
1424 	pthread_t t0;
1425 
1426 	if (pthread_barrier_init(&barr, NULL, 2))
1427 		exit_with_error(errno);
1428 
1429 	test->current_step++;
1430 	if (type == TEST_TYPE_POLL_RXQ_TMOUT)
1431 		pkt_stream_reset(ifobj->pkt_stream);
1432 	pkts_in_flight = 0;
1433 
1434 	test->ifobj_rx->shared_umem = false;
1435 	test->ifobj_tx->shared_umem = false;
1436 
1437 	signal(SIGUSR1, handler);
1438 	/* Spawn thread */
1439 	pthread_create(&t0, NULL, ifobj->func_ptr, test);
1440 
1441 	if (type != TEST_TYPE_POLL_TXQ_TMOUT)
1442 		pthread_barrier_wait(&barr);
1443 
1444 	if (pthread_barrier_destroy(&barr))
1445 		exit_with_error(errno);
1446 
1447 	pthread_kill(t0, SIGUSR1);
1448 	pthread_join(t0, NULL);
1449 
1450 	if (test->total_steps == test->current_step || test->fail) {
1451 		xsk_socket__delete(ifobj->xsk->xsk);
1452 		testapp_clean_xsk_umem(ifobj);
1453 	}
1454 
1455 	test->ifobj_rx->shared_umem = old_shared_umem;
1456 	test->ifobj_tx->shared_umem = old_shared_umem;
1457 
1458 	return !!test->fail;
1459 }
1460 
testapp_validate_traffic(struct test_spec * test)1461 static int testapp_validate_traffic(struct test_spec *test)
1462 {
1463 	struct ifobject *ifobj_tx = test->ifobj_tx;
1464 	struct ifobject *ifobj_rx = test->ifobj_rx;
1465 	pthread_t t0, t1;
1466 
1467 	if (pthread_barrier_init(&barr, NULL, 2))
1468 		exit_with_error(errno);
1469 
1470 	test->current_step++;
1471 	pkt_stream_reset(ifobj_rx->pkt_stream);
1472 	pkts_in_flight = 0;
1473 
1474 	/*Spawn RX thread */
1475 	pthread_create(&t0, NULL, ifobj_rx->func_ptr, test);
1476 
1477 	pthread_barrier_wait(&barr);
1478 	if (pthread_barrier_destroy(&barr))
1479 		exit_with_error(errno);
1480 
1481 	/*Spawn TX thread */
1482 	pthread_create(&t1, NULL, ifobj_tx->func_ptr, test);
1483 
1484 	pthread_join(t1, NULL);
1485 	pthread_join(t0, NULL);
1486 
1487 	if (test->total_steps == test->current_step || test->fail) {
1488 		xsk_socket__delete(ifobj_tx->xsk->xsk);
1489 		xsk_socket__delete(ifobj_rx->xsk->xsk);
1490 		testapp_clean_xsk_umem(ifobj_rx);
1491 		if (!ifobj_tx->shared_umem)
1492 			testapp_clean_xsk_umem(ifobj_tx);
1493 	}
1494 
1495 	return !!test->fail;
1496 }
1497 
testapp_teardown(struct test_spec * test)1498 static void testapp_teardown(struct test_spec *test)
1499 {
1500 	int i;
1501 
1502 	test_spec_set_name(test, "TEARDOWN");
1503 	for (i = 0; i < MAX_TEARDOWN_ITER; i++) {
1504 		if (testapp_validate_traffic(test))
1505 			return;
1506 		test_spec_reset(test);
1507 	}
1508 }
1509 
swap_directions(struct ifobject ** ifobj1,struct ifobject ** ifobj2)1510 static void swap_directions(struct ifobject **ifobj1, struct ifobject **ifobj2)
1511 {
1512 	thread_func_t tmp_func_ptr = (*ifobj1)->func_ptr;
1513 	struct ifobject *tmp_ifobj = (*ifobj1);
1514 
1515 	(*ifobj1)->func_ptr = (*ifobj2)->func_ptr;
1516 	(*ifobj2)->func_ptr = tmp_func_ptr;
1517 
1518 	*ifobj1 = *ifobj2;
1519 	*ifobj2 = tmp_ifobj;
1520 }
1521 
testapp_bidi(struct test_spec * test)1522 static void testapp_bidi(struct test_spec *test)
1523 {
1524 	test_spec_set_name(test, "BIDIRECTIONAL");
1525 	test->ifobj_tx->rx_on = true;
1526 	test->ifobj_rx->tx_on = true;
1527 	test->total_steps = 2;
1528 	if (testapp_validate_traffic(test))
1529 		return;
1530 
1531 	print_verbose("Switching Tx/Rx vectors\n");
1532 	swap_directions(&test->ifobj_rx, &test->ifobj_tx);
1533 	testapp_validate_traffic(test);
1534 
1535 	swap_directions(&test->ifobj_rx, &test->ifobj_tx);
1536 }
1537 
swap_xsk_resources(struct ifobject * ifobj_tx,struct ifobject * ifobj_rx)1538 static void swap_xsk_resources(struct ifobject *ifobj_tx, struct ifobject *ifobj_rx)
1539 {
1540 	int ret;
1541 
1542 	xsk_socket__delete(ifobj_tx->xsk->xsk);
1543 	xsk_socket__delete(ifobj_rx->xsk->xsk);
1544 	ifobj_tx->xsk = &ifobj_tx->xsk_arr[1];
1545 	ifobj_rx->xsk = &ifobj_rx->xsk_arr[1];
1546 
1547 	ret = xsk_socket__update_xskmap(ifobj_rx->xsk->xsk, ifobj_rx->xsk_map_fd);
1548 	if (ret)
1549 		exit_with_error(errno);
1550 }
1551 
testapp_bpf_res(struct test_spec * test)1552 static void testapp_bpf_res(struct test_spec *test)
1553 {
1554 	test_spec_set_name(test, "BPF_RES");
1555 	test->total_steps = 2;
1556 	test->nb_sockets = 2;
1557 	if (testapp_validate_traffic(test))
1558 		return;
1559 
1560 	swap_xsk_resources(test->ifobj_tx, test->ifobj_rx);
1561 	testapp_validate_traffic(test);
1562 }
1563 
testapp_headroom(struct test_spec * test)1564 static void testapp_headroom(struct test_spec *test)
1565 {
1566 	test_spec_set_name(test, "UMEM_HEADROOM");
1567 	test->ifobj_rx->umem->frame_headroom = UMEM_HEADROOM_TEST_SIZE;
1568 	testapp_validate_traffic(test);
1569 }
1570 
testapp_stats_rx_dropped(struct test_spec * test)1571 static void testapp_stats_rx_dropped(struct test_spec *test)
1572 {
1573 	test_spec_set_name(test, "STAT_RX_DROPPED");
1574 	pkt_stream_replace_half(test, MIN_PKT_SIZE * 4, 0);
1575 	test->ifobj_rx->umem->frame_headroom = test->ifobj_rx->umem->frame_size -
1576 		XDP_PACKET_HEADROOM - MIN_PKT_SIZE * 3;
1577 	pkt_stream_receive_half(test);
1578 	test->ifobj_rx->validation_func = validate_rx_dropped;
1579 	testapp_validate_traffic(test);
1580 }
1581 
testapp_stats_tx_invalid_descs(struct test_spec * test)1582 static void testapp_stats_tx_invalid_descs(struct test_spec *test)
1583 {
1584 	test_spec_set_name(test, "STAT_TX_INVALID");
1585 	pkt_stream_replace_half(test, XSK_UMEM__INVALID_FRAME_SIZE, 0);
1586 	test->ifobj_tx->validation_func = validate_tx_invalid_descs;
1587 	testapp_validate_traffic(test);
1588 
1589 	pkt_stream_restore_default(test);
1590 }
1591 
testapp_stats_rx_full(struct test_spec * test)1592 static void testapp_stats_rx_full(struct test_spec *test)
1593 {
1594 	test_spec_set_name(test, "STAT_RX_FULL");
1595 	pkt_stream_replace(test, DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, PKT_SIZE);
1596 	test->ifobj_rx->pkt_stream = pkt_stream_generate(test->ifobj_rx->umem,
1597 							 DEFAULT_UMEM_BUFFERS, PKT_SIZE);
1598 	if (!test->ifobj_rx->pkt_stream)
1599 		exit_with_error(ENOMEM);
1600 
1601 	test->ifobj_rx->xsk->rxqsize = DEFAULT_UMEM_BUFFERS;
1602 	test->ifobj_rx->release_rx = false;
1603 	test->ifobj_rx->validation_func = validate_rx_full;
1604 	testapp_validate_traffic(test);
1605 
1606 	pkt_stream_restore_default(test);
1607 }
1608 
testapp_stats_fill_empty(struct test_spec * test)1609 static void testapp_stats_fill_empty(struct test_spec *test)
1610 {
1611 	test_spec_set_name(test, "STAT_RX_FILL_EMPTY");
1612 	pkt_stream_replace(test, DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, PKT_SIZE);
1613 	test->ifobj_rx->pkt_stream = pkt_stream_generate(test->ifobj_rx->umem,
1614 							 DEFAULT_UMEM_BUFFERS, PKT_SIZE);
1615 	if (!test->ifobj_rx->pkt_stream)
1616 		exit_with_error(ENOMEM);
1617 
1618 	test->ifobj_rx->use_fill_ring = false;
1619 	test->ifobj_rx->validation_func = validate_fill_empty;
1620 	testapp_validate_traffic(test);
1621 
1622 	pkt_stream_restore_default(test);
1623 }
1624 
1625 /* Simple test */
hugepages_present(struct ifobject * ifobject)1626 static bool hugepages_present(struct ifobject *ifobject)
1627 {
1628 	const size_t mmap_sz = 2 * ifobject->umem->num_frames * ifobject->umem->frame_size;
1629 	void *bufs;
1630 
1631 	bufs = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1632 		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
1633 	if (bufs == MAP_FAILED)
1634 		return false;
1635 
1636 	munmap(bufs, mmap_sz);
1637 	return true;
1638 }
1639 
testapp_unaligned(struct test_spec * test)1640 static bool testapp_unaligned(struct test_spec *test)
1641 {
1642 	if (!hugepages_present(test->ifobj_tx)) {
1643 		ksft_test_result_skip("No 2M huge pages present.\n");
1644 		return false;
1645 	}
1646 
1647 	test_spec_set_name(test, "UNALIGNED_MODE");
1648 	test->ifobj_tx->umem->unaligned_mode = true;
1649 	test->ifobj_rx->umem->unaligned_mode = true;
1650 	/* Let half of the packets straddle a buffer boundrary */
1651 	pkt_stream_replace_half(test, PKT_SIZE, -PKT_SIZE / 2);
1652 	test->ifobj_rx->pkt_stream->use_addr_for_fill = true;
1653 	testapp_validate_traffic(test);
1654 
1655 	pkt_stream_restore_default(test);
1656 	return true;
1657 }
1658 
testapp_single_pkt(struct test_spec * test)1659 static void testapp_single_pkt(struct test_spec *test)
1660 {
1661 	struct pkt pkts[] = {{0x1000, PKT_SIZE, 0, true}};
1662 
1663 	pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts));
1664 	testapp_validate_traffic(test);
1665 	pkt_stream_restore_default(test);
1666 }
1667 
testapp_invalid_desc(struct test_spec * test)1668 static void testapp_invalid_desc(struct test_spec *test)
1669 {
1670 	u64 umem_size = test->ifobj_tx->umem->num_frames * test->ifobj_tx->umem->frame_size;
1671 	struct pkt pkts[] = {
1672 		/* Zero packet address allowed */
1673 		{0, PKT_SIZE, 0, true},
1674 		/* Allowed packet */
1675 		{0x1000, PKT_SIZE, 0, true},
1676 		/* Straddling the start of umem */
1677 		{-2, PKT_SIZE, 0, false},
1678 		/* Packet too large */
1679 		{0x2000, XSK_UMEM__INVALID_FRAME_SIZE, 0, false},
1680 		/* After umem ends */
1681 		{umem_size, PKT_SIZE, 0, false},
1682 		/* Straddle the end of umem */
1683 		{umem_size - PKT_SIZE / 2, PKT_SIZE, 0, false},
1684 		/* Straddle a page boundrary */
1685 		{0x3000 - PKT_SIZE / 2, PKT_SIZE, 0, false},
1686 		/* Straddle a 2K boundrary */
1687 		{0x3800 - PKT_SIZE / 2, PKT_SIZE, 0, true},
1688 		/* Valid packet for synch so that something is received */
1689 		{0x4000, PKT_SIZE, 0, true}};
1690 
1691 	if (test->ifobj_tx->umem->unaligned_mode) {
1692 		/* Crossing a page boundrary allowed */
1693 		pkts[6].valid = true;
1694 	}
1695 	if (test->ifobj_tx->umem->frame_size == XSK_UMEM__DEFAULT_FRAME_SIZE / 2) {
1696 		/* Crossing a 2K frame size boundrary not allowed */
1697 		pkts[7].valid = false;
1698 	}
1699 
1700 	if (test->ifobj_tx->shared_umem) {
1701 		pkts[4].addr += umem_size;
1702 		pkts[5].addr += umem_size;
1703 	}
1704 
1705 	pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts));
1706 	testapp_validate_traffic(test);
1707 	pkt_stream_restore_default(test);
1708 }
1709 
init_iface(struct ifobject * ifobj,const char * dst_mac,const char * src_mac,const char * dst_ip,const char * src_ip,const u16 dst_port,const u16 src_port,thread_func_t func_ptr)1710 static void init_iface(struct ifobject *ifobj, const char *dst_mac, const char *src_mac,
1711 		       const char *dst_ip, const char *src_ip, const u16 dst_port,
1712 		       const u16 src_port, thread_func_t func_ptr)
1713 {
1714 	struct in_addr ip;
1715 
1716 	memcpy(ifobj->dst_mac, dst_mac, ETH_ALEN);
1717 	memcpy(ifobj->src_mac, src_mac, ETH_ALEN);
1718 
1719 	inet_aton(dst_ip, &ip);
1720 	ifobj->dst_ip = ip.s_addr;
1721 
1722 	inet_aton(src_ip, &ip);
1723 	ifobj->src_ip = ip.s_addr;
1724 
1725 	ifobj->dst_port = dst_port;
1726 	ifobj->src_port = src_port;
1727 
1728 	ifobj->func_ptr = func_ptr;
1729 }
1730 
run_pkt_test(struct test_spec * test,enum test_mode mode,enum test_type type)1731 static void run_pkt_test(struct test_spec *test, enum test_mode mode, enum test_type type)
1732 {
1733 	switch (type) {
1734 	case TEST_TYPE_STATS_RX_DROPPED:
1735 		if (mode == TEST_MODE_ZC) {
1736 			ksft_test_result_skip("Can not run RX_DROPPED test for ZC mode\n");
1737 			return;
1738 		}
1739 		testapp_stats_rx_dropped(test);
1740 		break;
1741 	case TEST_TYPE_STATS_TX_INVALID_DESCS:
1742 		testapp_stats_tx_invalid_descs(test);
1743 		break;
1744 	case TEST_TYPE_STATS_RX_FULL:
1745 		testapp_stats_rx_full(test);
1746 		break;
1747 	case TEST_TYPE_STATS_FILL_EMPTY:
1748 		testapp_stats_fill_empty(test);
1749 		break;
1750 	case TEST_TYPE_TEARDOWN:
1751 		testapp_teardown(test);
1752 		break;
1753 	case TEST_TYPE_BIDI:
1754 		testapp_bidi(test);
1755 		break;
1756 	case TEST_TYPE_BPF_RES:
1757 		testapp_bpf_res(test);
1758 		break;
1759 	case TEST_TYPE_RUN_TO_COMPLETION:
1760 		test_spec_set_name(test, "RUN_TO_COMPLETION");
1761 		testapp_validate_traffic(test);
1762 		break;
1763 	case TEST_TYPE_RUN_TO_COMPLETION_SINGLE_PKT:
1764 		test_spec_set_name(test, "RUN_TO_COMPLETION_SINGLE_PKT");
1765 		testapp_single_pkt(test);
1766 		break;
1767 	case TEST_TYPE_RUN_TO_COMPLETION_2K_FRAME:
1768 		test_spec_set_name(test, "RUN_TO_COMPLETION_2K_FRAME_SIZE");
1769 		test->ifobj_tx->umem->frame_size = 2048;
1770 		test->ifobj_rx->umem->frame_size = 2048;
1771 		pkt_stream_replace(test, DEFAULT_PKT_CNT, PKT_SIZE);
1772 		testapp_validate_traffic(test);
1773 
1774 		pkt_stream_restore_default(test);
1775 		break;
1776 	case TEST_TYPE_RX_POLL:
1777 		test->ifobj_rx->use_poll = true;
1778 		test_spec_set_name(test, "POLL_RX");
1779 		testapp_validate_traffic(test);
1780 		break;
1781 	case TEST_TYPE_TX_POLL:
1782 		test->ifobj_tx->use_poll = true;
1783 		test_spec_set_name(test, "POLL_TX");
1784 		testapp_validate_traffic(test);
1785 		break;
1786 	case TEST_TYPE_POLL_TXQ_TMOUT:
1787 		test_spec_set_name(test, "POLL_TXQ_FULL");
1788 		test->ifobj_tx->use_poll = true;
1789 		/* create invalid frame by set umem frame_size and pkt length equal to 2048 */
1790 		test->ifobj_tx->umem->frame_size = 2048;
1791 		pkt_stream_replace(test, 2 * DEFAULT_PKT_CNT, 2048);
1792 		testapp_validate_traffic_single_thread(test, test->ifobj_tx, type);
1793 		pkt_stream_restore_default(test);
1794 		break;
1795 	case TEST_TYPE_POLL_RXQ_TMOUT:
1796 		test_spec_set_name(test, "POLL_RXQ_EMPTY");
1797 		test->ifobj_rx->use_poll = true;
1798 		testapp_validate_traffic_single_thread(test, test->ifobj_rx, type);
1799 		break;
1800 	case TEST_TYPE_ALIGNED_INV_DESC:
1801 		test_spec_set_name(test, "ALIGNED_INV_DESC");
1802 		testapp_invalid_desc(test);
1803 		break;
1804 	case TEST_TYPE_ALIGNED_INV_DESC_2K_FRAME:
1805 		test_spec_set_name(test, "ALIGNED_INV_DESC_2K_FRAME_SIZE");
1806 		test->ifobj_tx->umem->frame_size = 2048;
1807 		test->ifobj_rx->umem->frame_size = 2048;
1808 		testapp_invalid_desc(test);
1809 		break;
1810 	case TEST_TYPE_UNALIGNED_INV_DESC:
1811 		if (!hugepages_present(test->ifobj_tx)) {
1812 			ksft_test_result_skip("No 2M huge pages present.\n");
1813 			return;
1814 		}
1815 		test_spec_set_name(test, "UNALIGNED_INV_DESC");
1816 		test->ifobj_tx->umem->unaligned_mode = true;
1817 		test->ifobj_rx->umem->unaligned_mode = true;
1818 		testapp_invalid_desc(test);
1819 		break;
1820 	case TEST_TYPE_UNALIGNED:
1821 		if (!testapp_unaligned(test))
1822 			return;
1823 		break;
1824 	case TEST_TYPE_HEADROOM:
1825 		testapp_headroom(test);
1826 		break;
1827 	default:
1828 		break;
1829 	}
1830 
1831 	if (!test->fail)
1832 		ksft_test_result_pass("PASS: %s %s%s\n", mode_string(test), busy_poll_string(test),
1833 				      test->name);
1834 }
1835 
ifobject_create(void)1836 static struct ifobject *ifobject_create(void)
1837 {
1838 	struct ifobject *ifobj;
1839 
1840 	ifobj = calloc(1, sizeof(struct ifobject));
1841 	if (!ifobj)
1842 		return NULL;
1843 
1844 	ifobj->xsk_arr = calloc(MAX_SOCKETS, sizeof(*ifobj->xsk_arr));
1845 	if (!ifobj->xsk_arr)
1846 		goto out_xsk_arr;
1847 
1848 	ifobj->umem = calloc(1, sizeof(*ifobj->umem));
1849 	if (!ifobj->umem)
1850 		goto out_umem;
1851 
1852 	ifobj->ns_fd = -1;
1853 
1854 	return ifobj;
1855 
1856 out_umem:
1857 	free(ifobj->xsk_arr);
1858 out_xsk_arr:
1859 	free(ifobj);
1860 	return NULL;
1861 }
1862 
ifobject_delete(struct ifobject * ifobj)1863 static void ifobject_delete(struct ifobject *ifobj)
1864 {
1865 	if (ifobj->ns_fd != -1)
1866 		close(ifobj->ns_fd);
1867 	free(ifobj->umem);
1868 	free(ifobj->xsk_arr);
1869 	free(ifobj);
1870 }
1871 
is_xdp_supported(struct ifobject * ifobject)1872 static bool is_xdp_supported(struct ifobject *ifobject)
1873 {
1874 	int flags = XDP_FLAGS_DRV_MODE;
1875 
1876 	LIBBPF_OPTS(bpf_link_create_opts, opts, .flags = flags);
1877 	struct bpf_insn insns[2] = {
1878 		BPF_MOV64_IMM(BPF_REG_0, XDP_PASS),
1879 		BPF_EXIT_INSN()
1880 	};
1881 	int ifindex = if_nametoindex(ifobject->ifname);
1882 	int prog_fd, insn_cnt = ARRAY_SIZE(insns);
1883 	int err;
1884 
1885 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_XDP, NULL, "GPL", insns, insn_cnt, NULL);
1886 	if (prog_fd < 0)
1887 		return false;
1888 
1889 	err = bpf_xdp_attach(ifindex, prog_fd, flags, NULL);
1890 	if (err) {
1891 		close(prog_fd);
1892 		return false;
1893 	}
1894 
1895 	bpf_xdp_detach(ifindex, flags, NULL);
1896 	close(prog_fd);
1897 
1898 	return true;
1899 }
1900 
main(int argc,char ** argv)1901 int main(int argc, char **argv)
1902 {
1903 	struct pkt_stream *rx_pkt_stream_default;
1904 	struct pkt_stream *tx_pkt_stream_default;
1905 	struct ifobject *ifobj_tx, *ifobj_rx;
1906 	int modes = TEST_MODE_SKB + 1;
1907 	u32 i, j, failed_tests = 0;
1908 	struct test_spec test;
1909 	bool shared_umem;
1910 
1911 	/* Use libbpf 1.0 API mode */
1912 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
1913 
1914 	ifobj_tx = ifobject_create();
1915 	if (!ifobj_tx)
1916 		exit_with_error(ENOMEM);
1917 	ifobj_rx = ifobject_create();
1918 	if (!ifobj_rx)
1919 		exit_with_error(ENOMEM);
1920 
1921 	setlocale(LC_ALL, "");
1922 
1923 	parse_command_line(ifobj_tx, ifobj_rx, argc, argv);
1924 	shared_umem = !strcmp(ifobj_tx->ifname, ifobj_rx->ifname);
1925 
1926 	ifobj_tx->shared_umem = shared_umem;
1927 	ifobj_rx->shared_umem = shared_umem;
1928 
1929 	if (!validate_interface(ifobj_tx) || !validate_interface(ifobj_rx)) {
1930 		usage(basename(argv[0]));
1931 		ksft_exit_xfail();
1932 	}
1933 
1934 	init_iface(ifobj_tx, MAC1, MAC2, IP1, IP2, UDP_PORT1, UDP_PORT2,
1935 		   worker_testapp_validate_tx);
1936 	init_iface(ifobj_rx, MAC2, MAC1, IP2, IP1, UDP_PORT2, UDP_PORT1,
1937 		   worker_testapp_validate_rx);
1938 
1939 	if (is_xdp_supported(ifobj_tx)) {
1940 		modes++;
1941 		if (ifobj_zc_avail(ifobj_tx))
1942 			modes++;
1943 	}
1944 
1945 	test_spec_init(&test, ifobj_tx, ifobj_rx, 0);
1946 	tx_pkt_stream_default = pkt_stream_generate(ifobj_tx->umem, DEFAULT_PKT_CNT, PKT_SIZE);
1947 	rx_pkt_stream_default = pkt_stream_generate(ifobj_rx->umem, DEFAULT_PKT_CNT, PKT_SIZE);
1948 	if (!tx_pkt_stream_default || !rx_pkt_stream_default)
1949 		exit_with_error(ENOMEM);
1950 	test.tx_pkt_stream_default = tx_pkt_stream_default;
1951 	test.rx_pkt_stream_default = rx_pkt_stream_default;
1952 
1953 	ksft_set_plan(modes * TEST_TYPE_MAX);
1954 
1955 	for (i = 0; i < modes; i++)
1956 		for (j = 0; j < TEST_TYPE_MAX; j++) {
1957 			test_spec_init(&test, ifobj_tx, ifobj_rx, i);
1958 			run_pkt_test(&test, i, j);
1959 			usleep(USLEEP_MAX);
1960 
1961 			if (test.fail)
1962 				failed_tests++;
1963 		}
1964 
1965 	pkt_stream_delete(tx_pkt_stream_default);
1966 	pkt_stream_delete(rx_pkt_stream_default);
1967 	ifobject_delete(ifobj_tx);
1968 	ifobject_delete(ifobj_rx);
1969 
1970 	if (failed_tests)
1971 		ksft_exit_fail();
1972 	else
1973 		ksft_exit_pass();
1974 }
1975