xref: /linux/tools/testing/selftests/bpf/xskxceiver.c (revision 90d32e92011eaae8e70a9169b4e7acf4ca8f9d3a)
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  *    j. If multi-buffer is supported, send 9k packets divided into 3 frames
53  *    k. If multi-buffer and huge pages are supported, send 9k packets in a single frame
54  *       using unaligned mode
55  *    l. If multi-buffer is supported, try various nasty combinations of descriptors to
56  *       check if they pass the validation or not
57  *
58  * Flow:
59  * -----
60  * - Single process spawns two threads: Tx and Rx
61  * - Each of these two threads attach to a veth interface
62  * - Each thread creates one AF_XDP socket connected to a unique umem for each
63  *   veth interface
64  * - Tx thread Transmits a number of packets from veth<xxxx> to veth<yyyy>
65  * - Rx thread verifies if all packets were received and delivered in-order,
66  *   and have the right content
67  *
68  * Enable/disable packet dump mode:
69  * --------------------------
70  * To enable L2 - L4 headers and payload dump of each packet on STDOUT, add
71  * parameter -D to params array in test_xsk.sh, i.e. params=("-S" "-D")
72  */
73 
74 #define _GNU_SOURCE
75 #include <assert.h>
76 #include <fcntl.h>
77 #include <errno.h>
78 #include <getopt.h>
79 #include <linux/if_link.h>
80 #include <linux/if_ether.h>
81 #include <linux/mman.h>
82 #include <linux/netdev.h>
83 #include <linux/bitmap.h>
84 #include <linux/ethtool.h>
85 #include <arpa/inet.h>
86 #include <net/if.h>
87 #include <locale.h>
88 #include <poll.h>
89 #include <pthread.h>
90 #include <signal.h>
91 #include <stdio.h>
92 #include <stdlib.h>
93 #include <string.h>
94 #include <stddef.h>
95 #include <sys/mman.h>
96 #include <sys/socket.h>
97 #include <sys/time.h>
98 #include <sys/types.h>
99 #include <unistd.h>
100 
101 #include "xsk_xdp_progs.skel.h"
102 #include "xsk.h"
103 #include "xskxceiver.h"
104 #include <bpf/bpf.h>
105 #include <linux/filter.h>
106 #include "../kselftest.h"
107 #include "xsk_xdp_common.h"
108 
109 #include <network_helpers.h>
110 
111 static bool opt_verbose;
112 static bool opt_print_tests;
113 static enum test_mode opt_mode = TEST_MODE_ALL;
114 static u32 opt_run_test = RUN_ALL_TESTS;
115 
116 void test__fail(void) { /* for network_helpers.c */ }
117 
118 static void __exit_with_error(int error, const char *file, const char *func, int line)
119 {
120 	ksft_test_result_fail("[%s:%s:%i]: ERROR: %d/\"%s\"\n", file, func, line, error,
121 			      strerror(error));
122 	ksft_exit_xfail();
123 }
124 
125 #define exit_with_error(error) __exit_with_error(error, __FILE__, __func__, __LINE__)
126 #define busy_poll_string(test) (test)->ifobj_tx->busy_poll ? "BUSY-POLL " : ""
127 static char *mode_string(struct test_spec *test)
128 {
129 	switch (test->mode) {
130 	case TEST_MODE_SKB:
131 		return "SKB";
132 	case TEST_MODE_DRV:
133 		return "DRV";
134 	case TEST_MODE_ZC:
135 		return "ZC";
136 	default:
137 		return "BOGUS";
138 	}
139 }
140 
141 static void report_failure(struct test_spec *test)
142 {
143 	if (test->fail)
144 		return;
145 
146 	ksft_test_result_fail("FAIL: %s %s%s\n", mode_string(test), busy_poll_string(test),
147 			      test->name);
148 	test->fail = true;
149 }
150 
151 /* The payload is a word consisting of a packet sequence number in the upper
152  * 16-bits and a intra packet data sequence number in the lower 16 bits. So the 3rd packet's
153  * 5th word of data will contain the number (2<<16) | 4 as they are numbered from 0.
154  */
155 static void write_payload(void *dest, u32 pkt_nb, u32 start, u32 size)
156 {
157 	u32 *ptr = (u32 *)dest, i;
158 
159 	start /= sizeof(*ptr);
160 	size /= sizeof(*ptr);
161 	for (i = 0; i < size; i++)
162 		ptr[i] = htonl(pkt_nb << 16 | (i + start));
163 }
164 
165 static void gen_eth_hdr(struct xsk_socket_info *xsk, struct ethhdr *eth_hdr)
166 {
167 	memcpy(eth_hdr->h_dest, xsk->dst_mac, ETH_ALEN);
168 	memcpy(eth_hdr->h_source, xsk->src_mac, ETH_ALEN);
169 	eth_hdr->h_proto = htons(ETH_P_LOOPBACK);
170 }
171 
172 static bool is_umem_valid(struct ifobject *ifobj)
173 {
174 	return !!ifobj->umem->umem;
175 }
176 
177 static u32 mode_to_xdp_flags(enum test_mode mode)
178 {
179 	return (mode == TEST_MODE_SKB) ? XDP_FLAGS_SKB_MODE : XDP_FLAGS_DRV_MODE;
180 }
181 
182 static u64 umem_size(struct xsk_umem_info *umem)
183 {
184 	return umem->num_frames * umem->frame_size;
185 }
186 
187 static int xsk_configure_umem(struct ifobject *ifobj, struct xsk_umem_info *umem, void *buffer,
188 			      u64 size)
189 {
190 	struct xsk_umem_config cfg = {
191 		.fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS,
192 		.comp_size = XSK_RING_CONS__DEFAULT_NUM_DESCS,
193 		.frame_size = umem->frame_size,
194 		.frame_headroom = umem->frame_headroom,
195 		.flags = XSK_UMEM__DEFAULT_FLAGS
196 	};
197 	int ret;
198 
199 	if (umem->unaligned_mode)
200 		cfg.flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
201 
202 	ret = xsk_umem__create(&umem->umem, buffer, size,
203 			       &umem->fq, &umem->cq, &cfg);
204 	if (ret)
205 		return ret;
206 
207 	umem->buffer = buffer;
208 	if (ifobj->shared_umem && ifobj->rx_on) {
209 		umem->base_addr = umem_size(umem);
210 		umem->next_buffer = umem_size(umem);
211 	}
212 
213 	return 0;
214 }
215 
216 static u64 umem_alloc_buffer(struct xsk_umem_info *umem)
217 {
218 	u64 addr;
219 
220 	addr = umem->next_buffer;
221 	umem->next_buffer += umem->frame_size;
222 	if (umem->next_buffer >= umem->base_addr + umem_size(umem))
223 		umem->next_buffer = umem->base_addr;
224 
225 	return addr;
226 }
227 
228 static void umem_reset_alloc(struct xsk_umem_info *umem)
229 {
230 	umem->next_buffer = 0;
231 }
232 
233 static void enable_busy_poll(struct xsk_socket_info *xsk)
234 {
235 	int sock_opt;
236 
237 	sock_opt = 1;
238 	if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_PREFER_BUSY_POLL,
239 		       (void *)&sock_opt, sizeof(sock_opt)) < 0)
240 		exit_with_error(errno);
241 
242 	sock_opt = 20;
243 	if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL,
244 		       (void *)&sock_opt, sizeof(sock_opt)) < 0)
245 		exit_with_error(errno);
246 
247 	sock_opt = xsk->batch_size;
248 	if (setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL_BUDGET,
249 		       (void *)&sock_opt, sizeof(sock_opt)) < 0)
250 		exit_with_error(errno);
251 }
252 
253 static int __xsk_configure_socket(struct xsk_socket_info *xsk, struct xsk_umem_info *umem,
254 				  struct ifobject *ifobject, bool shared)
255 {
256 	struct xsk_socket_config cfg = {};
257 	struct xsk_ring_cons *rxr;
258 	struct xsk_ring_prod *txr;
259 
260 	xsk->umem = umem;
261 	cfg.rx_size = xsk->rxqsize;
262 	cfg.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
263 	cfg.bind_flags = ifobject->bind_flags;
264 	if (shared)
265 		cfg.bind_flags |= XDP_SHARED_UMEM;
266 	if (ifobject->mtu > MAX_ETH_PKT_SIZE)
267 		cfg.bind_flags |= XDP_USE_SG;
268 
269 	txr = ifobject->tx_on ? &xsk->tx : NULL;
270 	rxr = ifobject->rx_on ? &xsk->rx : NULL;
271 	return xsk_socket__create(&xsk->xsk, ifobject->ifindex, 0, umem->umem, rxr, txr, &cfg);
272 }
273 
274 static bool ifobj_zc_avail(struct ifobject *ifobject)
275 {
276 	size_t umem_sz = DEFAULT_UMEM_BUFFERS * XSK_UMEM__DEFAULT_FRAME_SIZE;
277 	int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
278 	struct xsk_socket_info *xsk;
279 	struct xsk_umem_info *umem;
280 	bool zc_avail = false;
281 	void *bufs;
282 	int ret;
283 
284 	bufs = mmap(NULL, umem_sz, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
285 	if (bufs == MAP_FAILED)
286 		exit_with_error(errno);
287 
288 	umem = calloc(1, sizeof(struct xsk_umem_info));
289 	if (!umem) {
290 		munmap(bufs, umem_sz);
291 		exit_with_error(ENOMEM);
292 	}
293 	umem->frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
294 	ret = xsk_configure_umem(ifobject, umem, bufs, umem_sz);
295 	if (ret)
296 		exit_with_error(-ret);
297 
298 	xsk = calloc(1, sizeof(struct xsk_socket_info));
299 	if (!xsk)
300 		goto out;
301 	ifobject->bind_flags = XDP_USE_NEED_WAKEUP | XDP_ZEROCOPY;
302 	ifobject->rx_on = true;
303 	xsk->rxqsize = XSK_RING_CONS__DEFAULT_NUM_DESCS;
304 	ret = __xsk_configure_socket(xsk, umem, ifobject, false);
305 	if (!ret)
306 		zc_avail = true;
307 
308 	xsk_socket__delete(xsk->xsk);
309 	free(xsk);
310 out:
311 	munmap(umem->buffer, umem_sz);
312 	xsk_umem__delete(umem->umem);
313 	free(umem);
314 	return zc_avail;
315 }
316 
317 static struct option long_options[] = {
318 	{"interface", required_argument, 0, 'i'},
319 	{"busy-poll", no_argument, 0, 'b'},
320 	{"verbose", no_argument, 0, 'v'},
321 	{"mode", required_argument, 0, 'm'},
322 	{"list", no_argument, 0, 'l'},
323 	{"test", required_argument, 0, 't'},
324 	{"help", no_argument, 0, 'h'},
325 	{0, 0, 0, 0}
326 };
327 
328 static void print_usage(char **argv)
329 {
330 	const char *str =
331 		"  Usage: xskxceiver [OPTIONS]\n"
332 		"  Options:\n"
333 		"  -i, --interface      Use interface\n"
334 		"  -v, --verbose        Verbose output\n"
335 		"  -b, --busy-poll      Enable busy poll\n"
336 		"  -m, --mode           Run only mode skb, drv, or zc\n"
337 		"  -l, --list           List all available tests\n"
338 		"  -t, --test           Run a specific test. Enter number from -l option.\n"
339 		"  -h, --help           Display this help and exit\n";
340 
341 	ksft_print_msg(str, basename(argv[0]));
342 	ksft_exit_xfail();
343 }
344 
345 static bool validate_interface(struct ifobject *ifobj)
346 {
347 	if (!strcmp(ifobj->ifname, ""))
348 		return false;
349 	return true;
350 }
351 
352 static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj_rx, int argc,
353 			       char **argv)
354 {
355 	struct ifobject *ifobj;
356 	u32 interface_nb = 0;
357 	int option_index, c;
358 
359 	opterr = 0;
360 
361 	for (;;) {
362 		c = getopt_long(argc, argv, "i:vbm:lt:", long_options, &option_index);
363 		if (c == -1)
364 			break;
365 
366 		switch (c) {
367 		case 'i':
368 			if (interface_nb == 0)
369 				ifobj = ifobj_tx;
370 			else if (interface_nb == 1)
371 				ifobj = ifobj_rx;
372 			else
373 				break;
374 
375 			memcpy(ifobj->ifname, optarg,
376 			       min_t(size_t, MAX_INTERFACE_NAME_CHARS, strlen(optarg)));
377 
378 			ifobj->ifindex = if_nametoindex(ifobj->ifname);
379 			if (!ifobj->ifindex)
380 				exit_with_error(errno);
381 
382 			interface_nb++;
383 			break;
384 		case 'v':
385 			opt_verbose = true;
386 			break;
387 		case 'b':
388 			ifobj_tx->busy_poll = true;
389 			ifobj_rx->busy_poll = true;
390 			break;
391 		case 'm':
392 			if (!strncmp("skb", optarg, strlen(optarg)))
393 				opt_mode = TEST_MODE_SKB;
394 			else if (!strncmp("drv", optarg, strlen(optarg)))
395 				opt_mode = TEST_MODE_DRV;
396 			else if (!strncmp("zc", optarg, strlen(optarg)))
397 				opt_mode = TEST_MODE_ZC;
398 			else
399 				print_usage(argv);
400 			break;
401 		case 'l':
402 			opt_print_tests = true;
403 			break;
404 		case 't':
405 			errno = 0;
406 			opt_run_test = strtol(optarg, NULL, 0);
407 			if (errno)
408 				print_usage(argv);
409 			break;
410 		case 'h':
411 		default:
412 			print_usage(argv);
413 		}
414 	}
415 }
416 
417 static int set_ring_size(struct ifobject *ifobj)
418 {
419 	int ret;
420 	u32 ctr = 0;
421 
422 	while (ctr++ < SOCK_RECONF_CTR) {
423 		ret = set_hw_ring_size(ifobj->ifname, &ifobj->ring);
424 		if (!ret)
425 			break;
426 
427 		/* Retry if it fails */
428 		if (ctr >= SOCK_RECONF_CTR || errno != EBUSY)
429 			return -errno;
430 
431 		usleep(USLEEP_MAX);
432 	}
433 
434 	return ret;
435 }
436 
437 static int hw_ring_size_reset(struct ifobject *ifobj)
438 {
439 	ifobj->ring.tx_pending = ifobj->set_ring.default_tx;
440 	ifobj->ring.rx_pending = ifobj->set_ring.default_rx;
441 	return set_ring_size(ifobj);
442 }
443 
444 static void __test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
445 			     struct ifobject *ifobj_rx)
446 {
447 	u32 i, j;
448 
449 	for (i = 0; i < MAX_INTERFACES; i++) {
450 		struct ifobject *ifobj = i ? ifobj_rx : ifobj_tx;
451 
452 		ifobj->xsk = &ifobj->xsk_arr[0];
453 		ifobj->use_poll = false;
454 		ifobj->use_fill_ring = true;
455 		ifobj->release_rx = true;
456 		ifobj->validation_func = NULL;
457 		ifobj->use_metadata = false;
458 
459 		if (i == 0) {
460 			ifobj->rx_on = false;
461 			ifobj->tx_on = true;
462 		} else {
463 			ifobj->rx_on = true;
464 			ifobj->tx_on = false;
465 		}
466 
467 		memset(ifobj->umem, 0, sizeof(*ifobj->umem));
468 		ifobj->umem->num_frames = DEFAULT_UMEM_BUFFERS;
469 		ifobj->umem->frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
470 
471 		for (j = 0; j < MAX_SOCKETS; j++) {
472 			memset(&ifobj->xsk_arr[j], 0, sizeof(ifobj->xsk_arr[j]));
473 			ifobj->xsk_arr[j].rxqsize = XSK_RING_CONS__DEFAULT_NUM_DESCS;
474 			ifobj->xsk_arr[j].batch_size = DEFAULT_BATCH_SIZE;
475 			if (i == 0)
476 				ifobj->xsk_arr[j].pkt_stream = test->tx_pkt_stream_default;
477 			else
478 				ifobj->xsk_arr[j].pkt_stream = test->rx_pkt_stream_default;
479 
480 			memcpy(ifobj->xsk_arr[j].src_mac, g_mac, ETH_ALEN);
481 			memcpy(ifobj->xsk_arr[j].dst_mac, g_mac, ETH_ALEN);
482 			ifobj->xsk_arr[j].src_mac[5] += ((j * 2) + 0);
483 			ifobj->xsk_arr[j].dst_mac[5] += ((j * 2) + 1);
484 		}
485 	}
486 
487 	if (ifobj_tx->hw_ring_size_supp)
488 		hw_ring_size_reset(ifobj_tx);
489 
490 	test->ifobj_tx = ifobj_tx;
491 	test->ifobj_rx = ifobj_rx;
492 	test->current_step = 0;
493 	test->total_steps = 1;
494 	test->nb_sockets = 1;
495 	test->fail = false;
496 	test->set_ring = false;
497 	test->mtu = MAX_ETH_PKT_SIZE;
498 	test->xdp_prog_rx = ifobj_rx->xdp_progs->progs.xsk_def_prog;
499 	test->xskmap_rx = ifobj_rx->xdp_progs->maps.xsk;
500 	test->xdp_prog_tx = ifobj_tx->xdp_progs->progs.xsk_def_prog;
501 	test->xskmap_tx = ifobj_tx->xdp_progs->maps.xsk;
502 }
503 
504 static void test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
505 			   struct ifobject *ifobj_rx, enum test_mode mode,
506 			   const struct test_spec *test_to_run)
507 {
508 	struct pkt_stream *tx_pkt_stream;
509 	struct pkt_stream *rx_pkt_stream;
510 	u32 i;
511 
512 	tx_pkt_stream = test->tx_pkt_stream_default;
513 	rx_pkt_stream = test->rx_pkt_stream_default;
514 	memset(test, 0, sizeof(*test));
515 	test->tx_pkt_stream_default = tx_pkt_stream;
516 	test->rx_pkt_stream_default = rx_pkt_stream;
517 
518 	for (i = 0; i < MAX_INTERFACES; i++) {
519 		struct ifobject *ifobj = i ? ifobj_rx : ifobj_tx;
520 
521 		ifobj->bind_flags = XDP_USE_NEED_WAKEUP;
522 		if (mode == TEST_MODE_ZC)
523 			ifobj->bind_flags |= XDP_ZEROCOPY;
524 		else
525 			ifobj->bind_flags |= XDP_COPY;
526 	}
527 
528 	strncpy(test->name, test_to_run->name, MAX_TEST_NAME_SIZE);
529 	test->test_func = test_to_run->test_func;
530 	test->mode = mode;
531 	__test_spec_init(test, ifobj_tx, ifobj_rx);
532 }
533 
534 static void test_spec_reset(struct test_spec *test)
535 {
536 	__test_spec_init(test, test->ifobj_tx, test->ifobj_rx);
537 }
538 
539 static void test_spec_set_xdp_prog(struct test_spec *test, struct bpf_program *xdp_prog_rx,
540 				   struct bpf_program *xdp_prog_tx, struct bpf_map *xskmap_rx,
541 				   struct bpf_map *xskmap_tx)
542 {
543 	test->xdp_prog_rx = xdp_prog_rx;
544 	test->xdp_prog_tx = xdp_prog_tx;
545 	test->xskmap_rx = xskmap_rx;
546 	test->xskmap_tx = xskmap_tx;
547 }
548 
549 static int test_spec_set_mtu(struct test_spec *test, int mtu)
550 {
551 	int err;
552 
553 	if (test->ifobj_rx->mtu != mtu) {
554 		err = xsk_set_mtu(test->ifobj_rx->ifindex, mtu);
555 		if (err)
556 			return err;
557 		test->ifobj_rx->mtu = mtu;
558 	}
559 	if (test->ifobj_tx->mtu != mtu) {
560 		err = xsk_set_mtu(test->ifobj_tx->ifindex, mtu);
561 		if (err)
562 			return err;
563 		test->ifobj_tx->mtu = mtu;
564 	}
565 
566 	return 0;
567 }
568 
569 static void pkt_stream_reset(struct pkt_stream *pkt_stream)
570 {
571 	if (pkt_stream) {
572 		pkt_stream->current_pkt_nb = 0;
573 		pkt_stream->nb_rx_pkts = 0;
574 	}
575 }
576 
577 static struct pkt *pkt_stream_get_next_tx_pkt(struct pkt_stream *pkt_stream)
578 {
579 	if (pkt_stream->current_pkt_nb >= pkt_stream->nb_pkts)
580 		return NULL;
581 
582 	return &pkt_stream->pkts[pkt_stream->current_pkt_nb++];
583 }
584 
585 static struct pkt *pkt_stream_get_next_rx_pkt(struct pkt_stream *pkt_stream, u32 *pkts_sent)
586 {
587 	while (pkt_stream->current_pkt_nb < pkt_stream->nb_pkts) {
588 		(*pkts_sent)++;
589 		if (pkt_stream->pkts[pkt_stream->current_pkt_nb].valid)
590 			return &pkt_stream->pkts[pkt_stream->current_pkt_nb++];
591 		pkt_stream->current_pkt_nb++;
592 	}
593 	return NULL;
594 }
595 
596 static void pkt_stream_delete(struct pkt_stream *pkt_stream)
597 {
598 	free(pkt_stream->pkts);
599 	free(pkt_stream);
600 }
601 
602 static void pkt_stream_restore_default(struct test_spec *test)
603 {
604 	struct pkt_stream *tx_pkt_stream = test->ifobj_tx->xsk->pkt_stream;
605 	struct pkt_stream *rx_pkt_stream = test->ifobj_rx->xsk->pkt_stream;
606 
607 	if (tx_pkt_stream != test->tx_pkt_stream_default) {
608 		pkt_stream_delete(test->ifobj_tx->xsk->pkt_stream);
609 		test->ifobj_tx->xsk->pkt_stream = test->tx_pkt_stream_default;
610 	}
611 
612 	if (rx_pkt_stream != test->rx_pkt_stream_default) {
613 		pkt_stream_delete(test->ifobj_rx->xsk->pkt_stream);
614 		test->ifobj_rx->xsk->pkt_stream = test->rx_pkt_stream_default;
615 	}
616 }
617 
618 static struct pkt_stream *__pkt_stream_alloc(u32 nb_pkts)
619 {
620 	struct pkt_stream *pkt_stream;
621 
622 	pkt_stream = calloc(1, sizeof(*pkt_stream));
623 	if (!pkt_stream)
624 		return NULL;
625 
626 	pkt_stream->pkts = calloc(nb_pkts, sizeof(*pkt_stream->pkts));
627 	if (!pkt_stream->pkts) {
628 		free(pkt_stream);
629 		return NULL;
630 	}
631 
632 	pkt_stream->nb_pkts = nb_pkts;
633 	return pkt_stream;
634 }
635 
636 static bool pkt_continues(u32 options)
637 {
638 	return options & XDP_PKT_CONTD;
639 }
640 
641 static u32 ceil_u32(u32 a, u32 b)
642 {
643 	return (a + b - 1) / b;
644 }
645 
646 static u32 pkt_nb_frags(u32 frame_size, struct pkt_stream *pkt_stream, struct pkt *pkt)
647 {
648 	u32 nb_frags = 1, next_frag;
649 
650 	if (!pkt)
651 		return 1;
652 
653 	if (!pkt_stream->verbatim) {
654 		if (!pkt->valid || !pkt->len)
655 			return 1;
656 		return ceil_u32(pkt->len, frame_size);
657 	}
658 
659 	/* Search for the end of the packet in verbatim mode */
660 	if (!pkt_continues(pkt->options))
661 		return nb_frags;
662 
663 	next_frag = pkt_stream->current_pkt_nb;
664 	pkt++;
665 	while (next_frag++ < pkt_stream->nb_pkts) {
666 		nb_frags++;
667 		if (!pkt_continues(pkt->options) || !pkt->valid)
668 			break;
669 		pkt++;
670 	}
671 	return nb_frags;
672 }
673 
674 static bool set_pkt_valid(int offset, u32 len)
675 {
676 	return len <= MAX_ETH_JUMBO_SIZE;
677 }
678 
679 static void pkt_set(struct pkt_stream *pkt_stream, struct pkt *pkt, int offset, u32 len)
680 {
681 	pkt->offset = offset;
682 	pkt->len = len;
683 	pkt->valid = set_pkt_valid(offset, len);
684 }
685 
686 static void pkt_stream_pkt_set(struct pkt_stream *pkt_stream, struct pkt *pkt, int offset, u32 len)
687 {
688 	bool prev_pkt_valid = pkt->valid;
689 
690 	pkt_set(pkt_stream, pkt, offset, len);
691 	pkt_stream->nb_valid_entries += pkt->valid - prev_pkt_valid;
692 }
693 
694 static u32 pkt_get_buffer_len(struct xsk_umem_info *umem, u32 len)
695 {
696 	return ceil_u32(len, umem->frame_size) * umem->frame_size;
697 }
698 
699 static struct pkt_stream *__pkt_stream_generate(u32 nb_pkts, u32 pkt_len, u32 nb_start, u32 nb_off)
700 {
701 	struct pkt_stream *pkt_stream;
702 	u32 i;
703 
704 	pkt_stream = __pkt_stream_alloc(nb_pkts);
705 	if (!pkt_stream)
706 		exit_with_error(ENOMEM);
707 
708 	pkt_stream->nb_pkts = nb_pkts;
709 	pkt_stream->max_pkt_len = pkt_len;
710 	for (i = 0; i < nb_pkts; i++) {
711 		struct pkt *pkt = &pkt_stream->pkts[i];
712 
713 		pkt_stream_pkt_set(pkt_stream, pkt, 0, pkt_len);
714 		pkt->pkt_nb = nb_start + i * nb_off;
715 	}
716 
717 	return pkt_stream;
718 }
719 
720 static struct pkt_stream *pkt_stream_generate(u32 nb_pkts, u32 pkt_len)
721 {
722 	return __pkt_stream_generate(nb_pkts, pkt_len, 0, 1);
723 }
724 
725 static struct pkt_stream *pkt_stream_clone(struct pkt_stream *pkt_stream)
726 {
727 	return pkt_stream_generate(pkt_stream->nb_pkts, pkt_stream->pkts[0].len);
728 }
729 
730 static void pkt_stream_replace(struct test_spec *test, u32 nb_pkts, u32 pkt_len)
731 {
732 	struct pkt_stream *pkt_stream;
733 
734 	pkt_stream = pkt_stream_generate(nb_pkts, pkt_len);
735 	test->ifobj_tx->xsk->pkt_stream = pkt_stream;
736 	pkt_stream = pkt_stream_generate(nb_pkts, pkt_len);
737 	test->ifobj_rx->xsk->pkt_stream = pkt_stream;
738 }
739 
740 static void __pkt_stream_replace_half(struct ifobject *ifobj, u32 pkt_len,
741 				      int offset)
742 {
743 	struct pkt_stream *pkt_stream;
744 	u32 i;
745 
746 	pkt_stream = pkt_stream_clone(ifobj->xsk->pkt_stream);
747 	for (i = 1; i < ifobj->xsk->pkt_stream->nb_pkts; i += 2)
748 		pkt_stream_pkt_set(pkt_stream, &pkt_stream->pkts[i], offset, pkt_len);
749 
750 	ifobj->xsk->pkt_stream = pkt_stream;
751 }
752 
753 static void pkt_stream_replace_half(struct test_spec *test, u32 pkt_len, int offset)
754 {
755 	__pkt_stream_replace_half(test->ifobj_tx, pkt_len, offset);
756 	__pkt_stream_replace_half(test->ifobj_rx, pkt_len, offset);
757 }
758 
759 static void pkt_stream_receive_half(struct test_spec *test)
760 {
761 	struct pkt_stream *pkt_stream = test->ifobj_tx->xsk->pkt_stream;
762 	u32 i;
763 
764 	test->ifobj_rx->xsk->pkt_stream = pkt_stream_generate(pkt_stream->nb_pkts,
765 							      pkt_stream->pkts[0].len);
766 	pkt_stream = test->ifobj_rx->xsk->pkt_stream;
767 	for (i = 1; i < pkt_stream->nb_pkts; i += 2)
768 		pkt_stream->pkts[i].valid = false;
769 
770 	pkt_stream->nb_valid_entries /= 2;
771 }
772 
773 static void pkt_stream_even_odd_sequence(struct test_spec *test)
774 {
775 	struct pkt_stream *pkt_stream;
776 	u32 i;
777 
778 	for (i = 0; i < test->nb_sockets; i++) {
779 		pkt_stream = test->ifobj_tx->xsk_arr[i].pkt_stream;
780 		pkt_stream = __pkt_stream_generate(pkt_stream->nb_pkts / 2,
781 						   pkt_stream->pkts[0].len, i, 2);
782 		test->ifobj_tx->xsk_arr[i].pkt_stream = pkt_stream;
783 
784 		pkt_stream = test->ifobj_rx->xsk_arr[i].pkt_stream;
785 		pkt_stream = __pkt_stream_generate(pkt_stream->nb_pkts / 2,
786 						   pkt_stream->pkts[0].len, i, 2);
787 		test->ifobj_rx->xsk_arr[i].pkt_stream = pkt_stream;
788 	}
789 }
790 
791 static u64 pkt_get_addr(struct pkt *pkt, struct xsk_umem_info *umem)
792 {
793 	if (!pkt->valid)
794 		return pkt->offset;
795 	return pkt->offset + umem_alloc_buffer(umem);
796 }
797 
798 static void pkt_stream_cancel(struct pkt_stream *pkt_stream)
799 {
800 	pkt_stream->current_pkt_nb--;
801 }
802 
803 static void pkt_generate(struct xsk_socket_info *xsk, struct xsk_umem_info *umem, u64 addr, u32 len,
804 			 u32 pkt_nb, u32 bytes_written)
805 {
806 	void *data = xsk_umem__get_data(umem->buffer, addr);
807 
808 	if (len < MIN_PKT_SIZE)
809 		return;
810 
811 	if (!bytes_written) {
812 		gen_eth_hdr(xsk, data);
813 
814 		len -= PKT_HDR_SIZE;
815 		data += PKT_HDR_SIZE;
816 	} else {
817 		bytes_written -= PKT_HDR_SIZE;
818 	}
819 
820 	write_payload(data, pkt_nb, bytes_written, len);
821 }
822 
823 static struct pkt_stream *__pkt_stream_generate_custom(struct ifobject *ifobj, struct pkt *frames,
824 						       u32 nb_frames, bool verbatim)
825 {
826 	u32 i, len = 0, pkt_nb = 0, payload = 0;
827 	struct pkt_stream *pkt_stream;
828 
829 	pkt_stream = __pkt_stream_alloc(nb_frames);
830 	if (!pkt_stream)
831 		exit_with_error(ENOMEM);
832 
833 	for (i = 0; i < nb_frames; i++) {
834 		struct pkt *pkt = &pkt_stream->pkts[pkt_nb];
835 		struct pkt *frame = &frames[i];
836 
837 		pkt->offset = frame->offset;
838 		if (verbatim) {
839 			*pkt = *frame;
840 			pkt->pkt_nb = payload;
841 			if (!frame->valid || !pkt_continues(frame->options))
842 				payload++;
843 		} else {
844 			if (frame->valid)
845 				len += frame->len;
846 			if (frame->valid && pkt_continues(frame->options))
847 				continue;
848 
849 			pkt->pkt_nb = pkt_nb;
850 			pkt->len = len;
851 			pkt->valid = frame->valid;
852 			pkt->options = 0;
853 
854 			len = 0;
855 		}
856 
857 		print_verbose("offset: %d len: %u valid: %u options: %u pkt_nb: %u\n",
858 			      pkt->offset, pkt->len, pkt->valid, pkt->options, pkt->pkt_nb);
859 
860 		if (pkt->valid && pkt->len > pkt_stream->max_pkt_len)
861 			pkt_stream->max_pkt_len = pkt->len;
862 
863 		if (pkt->valid)
864 			pkt_stream->nb_valid_entries++;
865 
866 		pkt_nb++;
867 	}
868 
869 	pkt_stream->nb_pkts = pkt_nb;
870 	pkt_stream->verbatim = verbatim;
871 	return pkt_stream;
872 }
873 
874 static void pkt_stream_generate_custom(struct test_spec *test, struct pkt *pkts, u32 nb_pkts)
875 {
876 	struct pkt_stream *pkt_stream;
877 
878 	pkt_stream = __pkt_stream_generate_custom(test->ifobj_tx, pkts, nb_pkts, true);
879 	test->ifobj_tx->xsk->pkt_stream = pkt_stream;
880 
881 	pkt_stream = __pkt_stream_generate_custom(test->ifobj_rx, pkts, nb_pkts, false);
882 	test->ifobj_rx->xsk->pkt_stream = pkt_stream;
883 }
884 
885 static void pkt_print_data(u32 *data, u32 cnt)
886 {
887 	u32 i;
888 
889 	for (i = 0; i < cnt; i++) {
890 		u32 seqnum, pkt_nb;
891 
892 		seqnum = ntohl(*data) & 0xffff;
893 		pkt_nb = ntohl(*data) >> 16;
894 		ksft_print_msg("%u:%u ", pkt_nb, seqnum);
895 		data++;
896 	}
897 }
898 
899 static void pkt_dump(void *pkt, u32 len, bool eth_header)
900 {
901 	struct ethhdr *ethhdr = pkt;
902 	u32 i, *data;
903 
904 	if (eth_header) {
905 		/*extract L2 frame */
906 		ksft_print_msg("DEBUG>> L2: dst mac: ");
907 		for (i = 0; i < ETH_ALEN; i++)
908 			ksft_print_msg("%02X", ethhdr->h_dest[i]);
909 
910 		ksft_print_msg("\nDEBUG>> L2: src mac: ");
911 		for (i = 0; i < ETH_ALEN; i++)
912 			ksft_print_msg("%02X", ethhdr->h_source[i]);
913 
914 		data = pkt + PKT_HDR_SIZE;
915 	} else {
916 		data = pkt;
917 	}
918 
919 	/*extract L5 frame */
920 	ksft_print_msg("\nDEBUG>> L5: seqnum: ");
921 	pkt_print_data(data, PKT_DUMP_NB_TO_PRINT);
922 	ksft_print_msg("....");
923 	if (len > PKT_DUMP_NB_TO_PRINT * sizeof(u32)) {
924 		ksft_print_msg("\n.... ");
925 		pkt_print_data(data + len / sizeof(u32) - PKT_DUMP_NB_TO_PRINT,
926 			       PKT_DUMP_NB_TO_PRINT);
927 	}
928 	ksft_print_msg("\n---------------------------------------\n");
929 }
930 
931 static bool is_offset_correct(struct xsk_umem_info *umem, struct pkt *pkt, u64 addr)
932 {
933 	u32 headroom = umem->unaligned_mode ? 0 : umem->frame_headroom;
934 	u32 offset = addr % umem->frame_size, expected_offset;
935 	int pkt_offset = pkt->valid ? pkt->offset : 0;
936 
937 	if (!umem->unaligned_mode)
938 		pkt_offset = 0;
939 
940 	expected_offset = (pkt_offset + headroom + XDP_PACKET_HEADROOM) % umem->frame_size;
941 
942 	if (offset == expected_offset)
943 		return true;
944 
945 	ksft_print_msg("[%s] expected [%u], got [%u]\n", __func__, expected_offset, offset);
946 	return false;
947 }
948 
949 static bool is_metadata_correct(struct pkt *pkt, void *buffer, u64 addr)
950 {
951 	void *data = xsk_umem__get_data(buffer, addr);
952 	struct xdp_info *meta = data - sizeof(struct xdp_info);
953 
954 	if (meta->count != pkt->pkt_nb) {
955 		ksft_print_msg("[%s] expected meta_count [%d], got meta_count [%llu]\n",
956 			       __func__, pkt->pkt_nb,
957 			       (unsigned long long)meta->count);
958 		return false;
959 	}
960 
961 	return true;
962 }
963 
964 static bool is_frag_valid(struct xsk_umem_info *umem, u64 addr, u32 len, u32 expected_pkt_nb,
965 			  u32 bytes_processed)
966 {
967 	u32 seqnum, pkt_nb, *pkt_data, words_to_end, expected_seqnum;
968 	void *data = xsk_umem__get_data(umem->buffer, addr);
969 
970 	addr -= umem->base_addr;
971 
972 	if (addr >= umem->num_frames * umem->frame_size ||
973 	    addr + len > umem->num_frames * umem->frame_size) {
974 		ksft_print_msg("Frag invalid addr: %llx len: %u\n",
975 			       (unsigned long long)addr, len);
976 		return false;
977 	}
978 	if (!umem->unaligned_mode && addr % umem->frame_size + len > umem->frame_size) {
979 		ksft_print_msg("Frag crosses frame boundary addr: %llx len: %u\n",
980 			       (unsigned long long)addr, len);
981 		return false;
982 	}
983 
984 	pkt_data = data;
985 	if (!bytes_processed) {
986 		pkt_data += PKT_HDR_SIZE / sizeof(*pkt_data);
987 		len -= PKT_HDR_SIZE;
988 	} else {
989 		bytes_processed -= PKT_HDR_SIZE;
990 	}
991 
992 	expected_seqnum = bytes_processed / sizeof(*pkt_data);
993 	seqnum = ntohl(*pkt_data) & 0xffff;
994 	pkt_nb = ntohl(*pkt_data) >> 16;
995 
996 	if (expected_pkt_nb != pkt_nb) {
997 		ksft_print_msg("[%s] expected pkt_nb [%u], got pkt_nb [%u]\n",
998 			       __func__, expected_pkt_nb, pkt_nb);
999 		goto error;
1000 	}
1001 	if (expected_seqnum != seqnum) {
1002 		ksft_print_msg("[%s] expected seqnum at start [%u], got seqnum [%u]\n",
1003 			       __func__, expected_seqnum, seqnum);
1004 		goto error;
1005 	}
1006 
1007 	words_to_end = len / sizeof(*pkt_data) - 1;
1008 	pkt_data += words_to_end;
1009 	seqnum = ntohl(*pkt_data) & 0xffff;
1010 	expected_seqnum += words_to_end;
1011 	if (expected_seqnum != seqnum) {
1012 		ksft_print_msg("[%s] expected seqnum at end [%u], got seqnum [%u]\n",
1013 			       __func__, expected_seqnum, seqnum);
1014 		goto error;
1015 	}
1016 
1017 	return true;
1018 
1019 error:
1020 	pkt_dump(data, len, !bytes_processed);
1021 	return false;
1022 }
1023 
1024 static bool is_pkt_valid(struct pkt *pkt, void *buffer, u64 addr, u32 len)
1025 {
1026 	if (pkt->len != len) {
1027 		ksft_print_msg("[%s] expected packet length [%d], got length [%d]\n",
1028 			       __func__, pkt->len, len);
1029 		pkt_dump(xsk_umem__get_data(buffer, addr), len, true);
1030 		return false;
1031 	}
1032 
1033 	return true;
1034 }
1035 
1036 static int kick_tx(struct xsk_socket_info *xsk)
1037 {
1038 	int ret;
1039 
1040 	ret = sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
1041 	if (ret >= 0)
1042 		return TEST_PASS;
1043 	if (errno == ENOBUFS || errno == EAGAIN || errno == EBUSY || errno == ENETDOWN) {
1044 		usleep(100);
1045 		return TEST_PASS;
1046 	}
1047 	return TEST_FAILURE;
1048 }
1049 
1050 static int kick_rx(struct xsk_socket_info *xsk)
1051 {
1052 	int ret;
1053 
1054 	ret = recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
1055 	if (ret < 0)
1056 		return TEST_FAILURE;
1057 
1058 	return TEST_PASS;
1059 }
1060 
1061 static int complete_pkts(struct xsk_socket_info *xsk, int batch_size)
1062 {
1063 	unsigned int rcvd;
1064 	u32 idx;
1065 	int ret;
1066 
1067 	if (xsk_ring_prod__needs_wakeup(&xsk->tx)) {
1068 		ret = kick_tx(xsk);
1069 		if (ret)
1070 			return TEST_FAILURE;
1071 	}
1072 
1073 	rcvd = xsk_ring_cons__peek(&xsk->umem->cq, batch_size, &idx);
1074 	if (rcvd) {
1075 		if (rcvd > xsk->outstanding_tx) {
1076 			u64 addr = *xsk_ring_cons__comp_addr(&xsk->umem->cq, idx + rcvd - 1);
1077 
1078 			ksft_print_msg("[%s] Too many packets completed\n", __func__);
1079 			ksft_print_msg("Last completion address: %llx\n",
1080 				       (unsigned long long)addr);
1081 			return TEST_FAILURE;
1082 		}
1083 
1084 		xsk_ring_cons__release(&xsk->umem->cq, rcvd);
1085 		xsk->outstanding_tx -= rcvd;
1086 	}
1087 
1088 	return TEST_PASS;
1089 }
1090 
1091 static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
1092 {
1093 	u32 frags_processed = 0, nb_frags = 0, pkt_len = 0;
1094 	u32 idx_rx = 0, idx_fq = 0, rcvd, pkts_sent = 0;
1095 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
1096 	struct ifobject *ifobj = test->ifobj_rx;
1097 	struct xsk_umem_info *umem = xsk->umem;
1098 	struct pollfd fds = { };
1099 	struct pkt *pkt;
1100 	u64 first_addr = 0;
1101 	int ret;
1102 
1103 	fds.fd = xsk_socket__fd(xsk->xsk);
1104 	fds.events = POLLIN;
1105 
1106 	ret = kick_rx(xsk);
1107 	if (ret)
1108 		return TEST_FAILURE;
1109 
1110 	if (ifobj->use_poll) {
1111 		ret = poll(&fds, 1, POLL_TMOUT);
1112 		if (ret < 0)
1113 			return TEST_FAILURE;
1114 
1115 		if (!ret) {
1116 			if (!is_umem_valid(test->ifobj_tx))
1117 				return TEST_PASS;
1118 
1119 			ksft_print_msg("ERROR: [%s] Poll timed out\n", __func__);
1120 			return TEST_CONTINUE;
1121 		}
1122 
1123 		if (!(fds.revents & POLLIN))
1124 			return TEST_CONTINUE;
1125 	}
1126 
1127 	rcvd = xsk_ring_cons__peek(&xsk->rx, xsk->batch_size, &idx_rx);
1128 	if (!rcvd)
1129 		return TEST_CONTINUE;
1130 
1131 	if (ifobj->use_fill_ring) {
1132 		ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
1133 		while (ret != rcvd) {
1134 			if (xsk_ring_prod__needs_wakeup(&umem->fq)) {
1135 				ret = poll(&fds, 1, POLL_TMOUT);
1136 				if (ret < 0)
1137 					return TEST_FAILURE;
1138 			}
1139 			ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
1140 		}
1141 	}
1142 
1143 	while (frags_processed < rcvd) {
1144 		const struct xdp_desc *desc = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++);
1145 		u64 addr = desc->addr, orig;
1146 
1147 		orig = xsk_umem__extract_addr(addr);
1148 		addr = xsk_umem__add_offset_to_addr(addr);
1149 
1150 		if (!nb_frags) {
1151 			pkt = pkt_stream_get_next_rx_pkt(pkt_stream, &pkts_sent);
1152 			if (!pkt) {
1153 				ksft_print_msg("[%s] received too many packets addr: %lx len %u\n",
1154 					       __func__, addr, desc->len);
1155 				return TEST_FAILURE;
1156 			}
1157 		}
1158 
1159 		print_verbose("Rx: addr: %lx len: %u options: %u pkt_nb: %u valid: %u\n",
1160 			      addr, desc->len, desc->options, pkt->pkt_nb, pkt->valid);
1161 
1162 		if (!is_frag_valid(umem, addr, desc->len, pkt->pkt_nb, pkt_len) ||
1163 		    !is_offset_correct(umem, pkt, addr) || (ifobj->use_metadata &&
1164 		    !is_metadata_correct(pkt, umem->buffer, addr)))
1165 			return TEST_FAILURE;
1166 
1167 		if (!nb_frags++)
1168 			first_addr = addr;
1169 		frags_processed++;
1170 		pkt_len += desc->len;
1171 		if (ifobj->use_fill_ring)
1172 			*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) = orig;
1173 
1174 		if (pkt_continues(desc->options))
1175 			continue;
1176 
1177 		/* The complete packet has been received */
1178 		if (!is_pkt_valid(pkt, umem->buffer, first_addr, pkt_len) ||
1179 		    !is_offset_correct(umem, pkt, addr))
1180 			return TEST_FAILURE;
1181 
1182 		pkt_stream->nb_rx_pkts++;
1183 		nb_frags = 0;
1184 		pkt_len = 0;
1185 	}
1186 
1187 	if (nb_frags) {
1188 		/* In the middle of a packet. Start over from beginning of packet. */
1189 		idx_rx -= nb_frags;
1190 		xsk_ring_cons__cancel(&xsk->rx, nb_frags);
1191 		if (ifobj->use_fill_ring) {
1192 			idx_fq -= nb_frags;
1193 			xsk_ring_prod__cancel(&umem->fq, nb_frags);
1194 		}
1195 		frags_processed -= nb_frags;
1196 	}
1197 
1198 	if (ifobj->use_fill_ring)
1199 		xsk_ring_prod__submit(&umem->fq, frags_processed);
1200 	if (ifobj->release_rx)
1201 		xsk_ring_cons__release(&xsk->rx, frags_processed);
1202 
1203 	pthread_mutex_lock(&pacing_mutex);
1204 	pkts_in_flight -= pkts_sent;
1205 	pthread_mutex_unlock(&pacing_mutex);
1206 	pkts_sent = 0;
1207 
1208 return TEST_CONTINUE;
1209 }
1210 
1211 bool all_packets_received(struct test_spec *test, struct xsk_socket_info *xsk, u32 sock_num,
1212 			  unsigned long *bitmap)
1213 {
1214 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
1215 
1216 	if (!pkt_stream) {
1217 		__set_bit(sock_num, bitmap);
1218 		return false;
1219 	}
1220 
1221 	if (pkt_stream->nb_rx_pkts == pkt_stream->nb_valid_entries) {
1222 		__set_bit(sock_num, bitmap);
1223 		if (bitmap_full(bitmap, test->nb_sockets))
1224 			return true;
1225 	}
1226 
1227 	return false;
1228 }
1229 
1230 static int receive_pkts(struct test_spec *test)
1231 {
1232 	struct timeval tv_end, tv_now, tv_timeout = {THREAD_TMOUT, 0};
1233 	DECLARE_BITMAP(bitmap, test->nb_sockets);
1234 	struct xsk_socket_info *xsk;
1235 	u32 sock_num = 0;
1236 	int res, ret;
1237 
1238 	ret = gettimeofday(&tv_now, NULL);
1239 	if (ret)
1240 		exit_with_error(errno);
1241 
1242 	timeradd(&tv_now, &tv_timeout, &tv_end);
1243 
1244 	while (1) {
1245 		xsk = &test->ifobj_rx->xsk_arr[sock_num];
1246 
1247 		if ((all_packets_received(test, xsk, sock_num, bitmap)))
1248 			break;
1249 
1250 		res = __receive_pkts(test, xsk);
1251 		if (!(res == TEST_PASS || res == TEST_CONTINUE))
1252 			return res;
1253 
1254 		ret = gettimeofday(&tv_now, NULL);
1255 		if (ret)
1256 			exit_with_error(errno);
1257 
1258 		if (timercmp(&tv_now, &tv_end, >)) {
1259 			ksft_print_msg("ERROR: [%s] Receive loop timed out\n", __func__);
1260 			return TEST_FAILURE;
1261 		}
1262 		sock_num = (sock_num + 1) % test->nb_sockets;
1263 	}
1264 
1265 	return TEST_PASS;
1266 }
1267 
1268 static int __send_pkts(struct ifobject *ifobject, struct xsk_socket_info *xsk, bool timeout)
1269 {
1270 	u32 i, idx = 0, valid_pkts = 0, valid_frags = 0, buffer_len;
1271 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
1272 	struct xsk_umem_info *umem = ifobject->umem;
1273 	bool use_poll = ifobject->use_poll;
1274 	struct pollfd fds = { };
1275 	int ret;
1276 
1277 	buffer_len = pkt_get_buffer_len(umem, pkt_stream->max_pkt_len);
1278 	/* pkts_in_flight might be negative if many invalid packets are sent */
1279 	if (pkts_in_flight >= (int)((umem_size(umem) - xsk->batch_size * buffer_len) /
1280 	    buffer_len)) {
1281 		ret = kick_tx(xsk);
1282 		if (ret)
1283 			return TEST_FAILURE;
1284 		return TEST_CONTINUE;
1285 	}
1286 
1287 	fds.fd = xsk_socket__fd(xsk->xsk);
1288 	fds.events = POLLOUT;
1289 
1290 	while (xsk_ring_prod__reserve(&xsk->tx, xsk->batch_size, &idx) < xsk->batch_size) {
1291 		if (use_poll) {
1292 			ret = poll(&fds, 1, POLL_TMOUT);
1293 			if (timeout) {
1294 				if (ret < 0) {
1295 					ksft_print_msg("ERROR: [%s] Poll error %d\n",
1296 						       __func__, errno);
1297 					return TEST_FAILURE;
1298 				}
1299 				if (ret == 0)
1300 					return TEST_PASS;
1301 				break;
1302 			}
1303 			if (ret <= 0) {
1304 				ksft_print_msg("ERROR: [%s] Poll error %d\n",
1305 					       __func__, errno);
1306 				return TEST_FAILURE;
1307 			}
1308 		}
1309 
1310 		complete_pkts(xsk, xsk->batch_size);
1311 	}
1312 
1313 	for (i = 0; i < xsk->batch_size; i++) {
1314 		struct pkt *pkt = pkt_stream_get_next_tx_pkt(pkt_stream);
1315 		u32 nb_frags_left, nb_frags, bytes_written = 0;
1316 
1317 		if (!pkt)
1318 			break;
1319 
1320 		nb_frags = pkt_nb_frags(umem->frame_size, pkt_stream, pkt);
1321 		if (nb_frags > xsk->batch_size - i) {
1322 			pkt_stream_cancel(pkt_stream);
1323 			xsk_ring_prod__cancel(&xsk->tx, xsk->batch_size - i);
1324 			break;
1325 		}
1326 		nb_frags_left = nb_frags;
1327 
1328 		while (nb_frags_left--) {
1329 			struct xdp_desc *tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx + i);
1330 
1331 			tx_desc->addr = pkt_get_addr(pkt, ifobject->umem);
1332 			if (pkt_stream->verbatim) {
1333 				tx_desc->len = pkt->len;
1334 				tx_desc->options = pkt->options;
1335 			} else if (nb_frags_left) {
1336 				tx_desc->len = umem->frame_size;
1337 				tx_desc->options = XDP_PKT_CONTD;
1338 			} else {
1339 				tx_desc->len = pkt->len - bytes_written;
1340 				tx_desc->options = 0;
1341 			}
1342 			if (pkt->valid)
1343 				pkt_generate(xsk, umem, tx_desc->addr, tx_desc->len, pkt->pkt_nb,
1344 					     bytes_written);
1345 			bytes_written += tx_desc->len;
1346 
1347 			print_verbose("Tx addr: %llx len: %u options: %u pkt_nb: %u\n",
1348 				      tx_desc->addr, tx_desc->len, tx_desc->options, pkt->pkt_nb);
1349 
1350 			if (nb_frags_left) {
1351 				i++;
1352 				if (pkt_stream->verbatim)
1353 					pkt = pkt_stream_get_next_tx_pkt(pkt_stream);
1354 			}
1355 		}
1356 
1357 		if (pkt && pkt->valid) {
1358 			valid_pkts++;
1359 			valid_frags += nb_frags;
1360 		}
1361 	}
1362 
1363 	pthread_mutex_lock(&pacing_mutex);
1364 	pkts_in_flight += valid_pkts;
1365 	pthread_mutex_unlock(&pacing_mutex);
1366 
1367 	xsk_ring_prod__submit(&xsk->tx, i);
1368 	xsk->outstanding_tx += valid_frags;
1369 
1370 	if (use_poll) {
1371 		ret = poll(&fds, 1, POLL_TMOUT);
1372 		if (ret <= 0) {
1373 			if (ret == 0 && timeout)
1374 				return TEST_PASS;
1375 
1376 			ksft_print_msg("ERROR: [%s] Poll error %d\n", __func__, ret);
1377 			return TEST_FAILURE;
1378 		}
1379 	}
1380 
1381 	if (!timeout) {
1382 		if (complete_pkts(xsk, i))
1383 			return TEST_FAILURE;
1384 
1385 		usleep(10);
1386 		return TEST_PASS;
1387 	}
1388 
1389 	return TEST_CONTINUE;
1390 }
1391 
1392 static int wait_for_tx_completion(struct xsk_socket_info *xsk)
1393 {
1394 	struct timeval tv_end, tv_now, tv_timeout = {THREAD_TMOUT, 0};
1395 	int ret;
1396 
1397 	ret = gettimeofday(&tv_now, NULL);
1398 	if (ret)
1399 		exit_with_error(errno);
1400 	timeradd(&tv_now, &tv_timeout, &tv_end);
1401 
1402 	while (xsk->outstanding_tx) {
1403 		ret = gettimeofday(&tv_now, NULL);
1404 		if (ret)
1405 			exit_with_error(errno);
1406 		if (timercmp(&tv_now, &tv_end, >)) {
1407 			ksft_print_msg("ERROR: [%s] Transmission loop timed out\n", __func__);
1408 			return TEST_FAILURE;
1409 		}
1410 
1411 		complete_pkts(xsk, xsk->batch_size);
1412 	}
1413 
1414 	return TEST_PASS;
1415 }
1416 
1417 bool all_packets_sent(struct test_spec *test, unsigned long *bitmap)
1418 {
1419 	return bitmap_full(bitmap, test->nb_sockets);
1420 }
1421 
1422 static int send_pkts(struct test_spec *test, struct ifobject *ifobject)
1423 {
1424 	bool timeout = !is_umem_valid(test->ifobj_rx);
1425 	DECLARE_BITMAP(bitmap, test->nb_sockets);
1426 	u32 i, ret;
1427 
1428 	while (!(all_packets_sent(test, bitmap))) {
1429 		for (i = 0; i < test->nb_sockets; i++) {
1430 			struct pkt_stream *pkt_stream;
1431 
1432 			pkt_stream = ifobject->xsk_arr[i].pkt_stream;
1433 			if (!pkt_stream || pkt_stream->current_pkt_nb >= pkt_stream->nb_pkts) {
1434 				__set_bit(i, bitmap);
1435 				continue;
1436 			}
1437 			ret = __send_pkts(ifobject, &ifobject->xsk_arr[i], timeout);
1438 			if (ret == TEST_CONTINUE && !test->fail)
1439 				continue;
1440 
1441 			if ((ret || test->fail) && !timeout)
1442 				return TEST_FAILURE;
1443 
1444 			if (ret == TEST_PASS && timeout)
1445 				return ret;
1446 
1447 			ret = wait_for_tx_completion(&ifobject->xsk_arr[i]);
1448 			if (ret)
1449 				return TEST_FAILURE;
1450 		}
1451 	}
1452 
1453 	return TEST_PASS;
1454 }
1455 
1456 static int get_xsk_stats(struct xsk_socket *xsk, struct xdp_statistics *stats)
1457 {
1458 	int fd = xsk_socket__fd(xsk), err;
1459 	socklen_t optlen, expected_len;
1460 
1461 	optlen = sizeof(*stats);
1462 	err = getsockopt(fd, SOL_XDP, XDP_STATISTICS, stats, &optlen);
1463 	if (err) {
1464 		ksft_print_msg("[%s] getsockopt(XDP_STATISTICS) error %u %s\n",
1465 			       __func__, -err, strerror(-err));
1466 		return TEST_FAILURE;
1467 	}
1468 
1469 	expected_len = sizeof(struct xdp_statistics);
1470 	if (optlen != expected_len) {
1471 		ksft_print_msg("[%s] getsockopt optlen error. Expected: %u got: %u\n",
1472 			       __func__, expected_len, optlen);
1473 		return TEST_FAILURE;
1474 	}
1475 
1476 	return TEST_PASS;
1477 }
1478 
1479 static int validate_rx_dropped(struct ifobject *ifobject)
1480 {
1481 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1482 	struct xdp_statistics stats;
1483 	int err;
1484 
1485 	err = kick_rx(ifobject->xsk);
1486 	if (err)
1487 		return TEST_FAILURE;
1488 
1489 	err = get_xsk_stats(xsk, &stats);
1490 	if (err)
1491 		return TEST_FAILURE;
1492 
1493 	/* The receiver calls getsockopt after receiving the last (valid)
1494 	 * packet which is not the final packet sent in this test (valid and
1495 	 * invalid packets are sent in alternating fashion with the final
1496 	 * packet being invalid). Since the last packet may or may not have
1497 	 * been dropped already, both outcomes must be allowed.
1498 	 */
1499 	if (stats.rx_dropped == ifobject->xsk->pkt_stream->nb_pkts / 2 ||
1500 	    stats.rx_dropped == ifobject->xsk->pkt_stream->nb_pkts / 2 - 1)
1501 		return TEST_PASS;
1502 
1503 	return TEST_FAILURE;
1504 }
1505 
1506 static int validate_rx_full(struct ifobject *ifobject)
1507 {
1508 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1509 	struct xdp_statistics stats;
1510 	int err;
1511 
1512 	usleep(1000);
1513 	err = kick_rx(ifobject->xsk);
1514 	if (err)
1515 		return TEST_FAILURE;
1516 
1517 	err = get_xsk_stats(xsk, &stats);
1518 	if (err)
1519 		return TEST_FAILURE;
1520 
1521 	if (stats.rx_ring_full)
1522 		return TEST_PASS;
1523 
1524 	return TEST_FAILURE;
1525 }
1526 
1527 static int validate_fill_empty(struct ifobject *ifobject)
1528 {
1529 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1530 	struct xdp_statistics stats;
1531 	int err;
1532 
1533 	usleep(1000);
1534 	err = kick_rx(ifobject->xsk);
1535 	if (err)
1536 		return TEST_FAILURE;
1537 
1538 	err = get_xsk_stats(xsk, &stats);
1539 	if (err)
1540 		return TEST_FAILURE;
1541 
1542 	if (stats.rx_fill_ring_empty_descs)
1543 		return TEST_PASS;
1544 
1545 	return TEST_FAILURE;
1546 }
1547 
1548 static int validate_tx_invalid_descs(struct ifobject *ifobject)
1549 {
1550 	struct xsk_socket *xsk = ifobject->xsk->xsk;
1551 	int fd = xsk_socket__fd(xsk);
1552 	struct xdp_statistics stats;
1553 	socklen_t optlen;
1554 	int err;
1555 
1556 	optlen = sizeof(stats);
1557 	err = getsockopt(fd, SOL_XDP, XDP_STATISTICS, &stats, &optlen);
1558 	if (err) {
1559 		ksft_print_msg("[%s] getsockopt(XDP_STATISTICS) error %u %s\n",
1560 			       __func__, -err, strerror(-err));
1561 		return TEST_FAILURE;
1562 	}
1563 
1564 	if (stats.tx_invalid_descs != ifobject->xsk->pkt_stream->nb_pkts / 2) {
1565 		ksft_print_msg("[%s] tx_invalid_descs incorrect. Got [%llu] expected [%u]\n",
1566 			       __func__,
1567 			       (unsigned long long)stats.tx_invalid_descs,
1568 			       ifobject->xsk->pkt_stream->nb_pkts);
1569 		return TEST_FAILURE;
1570 	}
1571 
1572 	return TEST_PASS;
1573 }
1574 
1575 static void xsk_configure_socket(struct test_spec *test, struct ifobject *ifobject,
1576 				 struct xsk_umem_info *umem, bool tx)
1577 {
1578 	int i, ret;
1579 
1580 	for (i = 0; i < test->nb_sockets; i++) {
1581 		bool shared = (ifobject->shared_umem && tx) ? true : !!i;
1582 		u32 ctr = 0;
1583 
1584 		while (ctr++ < SOCK_RECONF_CTR) {
1585 			ret = __xsk_configure_socket(&ifobject->xsk_arr[i], umem,
1586 						     ifobject, shared);
1587 			if (!ret)
1588 				break;
1589 
1590 			/* Retry if it fails as xsk_socket__create() is asynchronous */
1591 			if (ctr >= SOCK_RECONF_CTR)
1592 				exit_with_error(-ret);
1593 			usleep(USLEEP_MAX);
1594 		}
1595 		if (ifobject->busy_poll)
1596 			enable_busy_poll(&ifobject->xsk_arr[i]);
1597 	}
1598 }
1599 
1600 static void thread_common_ops_tx(struct test_spec *test, struct ifobject *ifobject)
1601 {
1602 	xsk_configure_socket(test, ifobject, test->ifobj_rx->umem, true);
1603 	ifobject->xsk = &ifobject->xsk_arr[0];
1604 	ifobject->xskmap = test->ifobj_rx->xskmap;
1605 	memcpy(ifobject->umem, test->ifobj_rx->umem, sizeof(struct xsk_umem_info));
1606 	ifobject->umem->base_addr = 0;
1607 }
1608 
1609 static void xsk_populate_fill_ring(struct xsk_umem_info *umem, struct pkt_stream *pkt_stream,
1610 				   bool fill_up)
1611 {
1612 	u32 rx_frame_size = umem->frame_size - XDP_PACKET_HEADROOM;
1613 	u32 idx = 0, filled = 0, buffers_to_fill, nb_pkts;
1614 	int ret;
1615 
1616 	if (umem->num_frames < XSK_RING_PROD__DEFAULT_NUM_DESCS)
1617 		buffers_to_fill = umem->num_frames;
1618 	else
1619 		buffers_to_fill = XSK_RING_PROD__DEFAULT_NUM_DESCS;
1620 
1621 	ret = xsk_ring_prod__reserve(&umem->fq, buffers_to_fill, &idx);
1622 	if (ret != buffers_to_fill)
1623 		exit_with_error(ENOSPC);
1624 
1625 	while (filled < buffers_to_fill) {
1626 		struct pkt *pkt = pkt_stream_get_next_rx_pkt(pkt_stream, &nb_pkts);
1627 		u64 addr;
1628 		u32 i;
1629 
1630 		for (i = 0; i < pkt_nb_frags(rx_frame_size, pkt_stream, pkt); i++) {
1631 			if (!pkt) {
1632 				if (!fill_up)
1633 					break;
1634 				addr = filled * umem->frame_size + umem->base_addr;
1635 			} else if (pkt->offset >= 0) {
1636 				addr = pkt->offset % umem->frame_size + umem_alloc_buffer(umem);
1637 			} else {
1638 				addr = pkt->offset + umem_alloc_buffer(umem);
1639 			}
1640 
1641 			*xsk_ring_prod__fill_addr(&umem->fq, idx++) = addr;
1642 			if (++filled >= buffers_to_fill)
1643 				break;
1644 		}
1645 	}
1646 	xsk_ring_prod__submit(&umem->fq, filled);
1647 	xsk_ring_prod__cancel(&umem->fq, buffers_to_fill - filled);
1648 
1649 	pkt_stream_reset(pkt_stream);
1650 	umem_reset_alloc(umem);
1651 }
1652 
1653 static void thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
1654 {
1655 	u64 umem_sz = ifobject->umem->num_frames * ifobject->umem->frame_size;
1656 	int mmap_flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE;
1657 	LIBBPF_OPTS(bpf_xdp_query_opts, opts);
1658 	void *bufs;
1659 	int ret;
1660 	u32 i;
1661 
1662 	if (ifobject->umem->unaligned_mode)
1663 		mmap_flags |= MAP_HUGETLB | MAP_HUGE_2MB;
1664 
1665 	if (ifobject->shared_umem)
1666 		umem_sz *= 2;
1667 
1668 	bufs = mmap(NULL, umem_sz, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
1669 	if (bufs == MAP_FAILED)
1670 		exit_with_error(errno);
1671 
1672 	ret = xsk_configure_umem(ifobject, ifobject->umem, bufs, umem_sz);
1673 	if (ret)
1674 		exit_with_error(-ret);
1675 
1676 	xsk_configure_socket(test, ifobject, ifobject->umem, false);
1677 
1678 	ifobject->xsk = &ifobject->xsk_arr[0];
1679 
1680 	if (!ifobject->rx_on)
1681 		return;
1682 
1683 	xsk_populate_fill_ring(ifobject->umem, ifobject->xsk->pkt_stream, ifobject->use_fill_ring);
1684 
1685 	for (i = 0; i < test->nb_sockets; i++) {
1686 		ifobject->xsk = &ifobject->xsk_arr[i];
1687 		ret = xsk_update_xskmap(ifobject->xskmap, ifobject->xsk->xsk, i);
1688 		if (ret)
1689 			exit_with_error(errno);
1690 	}
1691 }
1692 
1693 static void *worker_testapp_validate_tx(void *arg)
1694 {
1695 	struct test_spec *test = (struct test_spec *)arg;
1696 	struct ifobject *ifobject = test->ifobj_tx;
1697 	int err;
1698 
1699 	if (test->current_step == 1) {
1700 		if (!ifobject->shared_umem)
1701 			thread_common_ops(test, ifobject);
1702 		else
1703 			thread_common_ops_tx(test, ifobject);
1704 	}
1705 
1706 	err = send_pkts(test, ifobject);
1707 
1708 	if (!err && ifobject->validation_func)
1709 		err = ifobject->validation_func(ifobject);
1710 	if (err)
1711 		report_failure(test);
1712 
1713 	pthread_exit(NULL);
1714 }
1715 
1716 static void *worker_testapp_validate_rx(void *arg)
1717 {
1718 	struct test_spec *test = (struct test_spec *)arg;
1719 	struct ifobject *ifobject = test->ifobj_rx;
1720 	int err;
1721 
1722 	if (test->current_step == 1) {
1723 		thread_common_ops(test, ifobject);
1724 	} else {
1725 		xsk_clear_xskmap(ifobject->xskmap);
1726 		err = xsk_update_xskmap(ifobject->xskmap, ifobject->xsk->xsk, 0);
1727 		if (err) {
1728 			ksft_print_msg("Error: Failed to update xskmap, error %s\n",
1729 				       strerror(-err));
1730 			exit_with_error(-err);
1731 		}
1732 	}
1733 
1734 	pthread_barrier_wait(&barr);
1735 
1736 	err = receive_pkts(test);
1737 
1738 	if (!err && ifobject->validation_func)
1739 		err = ifobject->validation_func(ifobject);
1740 	if (err)
1741 		report_failure(test);
1742 
1743 	pthread_exit(NULL);
1744 }
1745 
1746 static u64 ceil_u64(u64 a, u64 b)
1747 {
1748 	return (a + b - 1) / b;
1749 }
1750 
1751 static void testapp_clean_xsk_umem(struct ifobject *ifobj)
1752 {
1753 	u64 umem_sz = ifobj->umem->num_frames * ifobj->umem->frame_size;
1754 
1755 	if (ifobj->shared_umem)
1756 		umem_sz *= 2;
1757 
1758 	umem_sz = ceil_u64(umem_sz, HUGEPAGE_SIZE) * HUGEPAGE_SIZE;
1759 	xsk_umem__delete(ifobj->umem->umem);
1760 	munmap(ifobj->umem->buffer, umem_sz);
1761 }
1762 
1763 static void handler(int signum)
1764 {
1765 	pthread_exit(NULL);
1766 }
1767 
1768 static bool xdp_prog_changed_rx(struct test_spec *test)
1769 {
1770 	struct ifobject *ifobj = test->ifobj_rx;
1771 
1772 	return ifobj->xdp_prog != test->xdp_prog_rx || ifobj->mode != test->mode;
1773 }
1774 
1775 static bool xdp_prog_changed_tx(struct test_spec *test)
1776 {
1777 	struct ifobject *ifobj = test->ifobj_tx;
1778 
1779 	return ifobj->xdp_prog != test->xdp_prog_tx || ifobj->mode != test->mode;
1780 }
1781 
1782 static void xsk_reattach_xdp(struct ifobject *ifobj, struct bpf_program *xdp_prog,
1783 			     struct bpf_map *xskmap, enum test_mode mode)
1784 {
1785 	int err;
1786 
1787 	xsk_detach_xdp_program(ifobj->ifindex, mode_to_xdp_flags(ifobj->mode));
1788 	err = xsk_attach_xdp_program(xdp_prog, ifobj->ifindex, mode_to_xdp_flags(mode));
1789 	if (err) {
1790 		ksft_print_msg("Error attaching XDP program\n");
1791 		exit_with_error(-err);
1792 	}
1793 
1794 	if (ifobj->mode != mode && (mode == TEST_MODE_DRV || mode == TEST_MODE_ZC))
1795 		if (!xsk_is_in_mode(ifobj->ifindex, XDP_FLAGS_DRV_MODE)) {
1796 			ksft_print_msg("ERROR: XDP prog not in DRV mode\n");
1797 			exit_with_error(EINVAL);
1798 		}
1799 
1800 	ifobj->xdp_prog = xdp_prog;
1801 	ifobj->xskmap = xskmap;
1802 	ifobj->mode = mode;
1803 }
1804 
1805 static void xsk_attach_xdp_progs(struct test_spec *test, struct ifobject *ifobj_rx,
1806 				 struct ifobject *ifobj_tx)
1807 {
1808 	if (xdp_prog_changed_rx(test))
1809 		xsk_reattach_xdp(ifobj_rx, test->xdp_prog_rx, test->xskmap_rx, test->mode);
1810 
1811 	if (!ifobj_tx || ifobj_tx->shared_umem)
1812 		return;
1813 
1814 	if (xdp_prog_changed_tx(test))
1815 		xsk_reattach_xdp(ifobj_tx, test->xdp_prog_tx, test->xskmap_tx, test->mode);
1816 }
1817 
1818 static int __testapp_validate_traffic(struct test_spec *test, struct ifobject *ifobj1,
1819 				      struct ifobject *ifobj2)
1820 {
1821 	pthread_t t0, t1;
1822 	int err;
1823 
1824 	if (test->mtu > MAX_ETH_PKT_SIZE) {
1825 		if (test->mode == TEST_MODE_ZC && (!ifobj1->multi_buff_zc_supp ||
1826 						   (ifobj2 && !ifobj2->multi_buff_zc_supp))) {
1827 			ksft_test_result_skip("Multi buffer for zero-copy not supported.\n");
1828 			return TEST_SKIP;
1829 		}
1830 		if (test->mode != TEST_MODE_ZC && (!ifobj1->multi_buff_supp ||
1831 						   (ifobj2 && !ifobj2->multi_buff_supp))) {
1832 			ksft_test_result_skip("Multi buffer not supported.\n");
1833 			return TEST_SKIP;
1834 		}
1835 	}
1836 	err = test_spec_set_mtu(test, test->mtu);
1837 	if (err) {
1838 		ksft_print_msg("Error, could not set mtu.\n");
1839 		exit_with_error(err);
1840 	}
1841 
1842 	if (ifobj2) {
1843 		if (pthread_barrier_init(&barr, NULL, 2))
1844 			exit_with_error(errno);
1845 		pkt_stream_reset(ifobj2->xsk->pkt_stream);
1846 	}
1847 
1848 	test->current_step++;
1849 	pkt_stream_reset(ifobj1->xsk->pkt_stream);
1850 	pkts_in_flight = 0;
1851 
1852 	signal(SIGUSR1, handler);
1853 	/*Spawn RX thread */
1854 	pthread_create(&t0, NULL, ifobj1->func_ptr, test);
1855 
1856 	if (ifobj2) {
1857 		pthread_barrier_wait(&barr);
1858 		if (pthread_barrier_destroy(&barr))
1859 			exit_with_error(errno);
1860 
1861 		/*Spawn TX thread */
1862 		pthread_create(&t1, NULL, ifobj2->func_ptr, test);
1863 
1864 		pthread_join(t1, NULL);
1865 	}
1866 
1867 	if (!ifobj2)
1868 		pthread_kill(t0, SIGUSR1);
1869 	else
1870 		pthread_join(t0, NULL);
1871 
1872 	if (test->total_steps == test->current_step || test->fail) {
1873 		u32 i;
1874 
1875 		if (ifobj2)
1876 			for (i = 0; i < test->nb_sockets; i++)
1877 				xsk_socket__delete(ifobj2->xsk_arr[i].xsk);
1878 
1879 		for (i = 0; i < test->nb_sockets; i++)
1880 			xsk_socket__delete(ifobj1->xsk_arr[i].xsk);
1881 
1882 		testapp_clean_xsk_umem(ifobj1);
1883 		if (ifobj2 && !ifobj2->shared_umem)
1884 			testapp_clean_xsk_umem(ifobj2);
1885 	}
1886 
1887 	return !!test->fail;
1888 }
1889 
1890 static int testapp_validate_traffic(struct test_spec *test)
1891 {
1892 	struct ifobject *ifobj_rx = test->ifobj_rx;
1893 	struct ifobject *ifobj_tx = test->ifobj_tx;
1894 
1895 	if ((ifobj_rx->umem->unaligned_mode && !ifobj_rx->unaligned_supp) ||
1896 	    (ifobj_tx->umem->unaligned_mode && !ifobj_tx->unaligned_supp)) {
1897 		ksft_test_result_skip("No huge pages present.\n");
1898 		return TEST_SKIP;
1899 	}
1900 
1901 	if (test->set_ring) {
1902 		if (ifobj_tx->hw_ring_size_supp)
1903 			return set_ring_size(ifobj_tx);
1904 
1905 	ksft_test_result_skip("Changing HW ring size not supported.\n");
1906 	return TEST_SKIP;
1907 	}
1908 
1909 	xsk_attach_xdp_progs(test, ifobj_rx, ifobj_tx);
1910 	return __testapp_validate_traffic(test, ifobj_rx, ifobj_tx);
1911 }
1912 
1913 static int testapp_validate_traffic_single_thread(struct test_spec *test, struct ifobject *ifobj)
1914 {
1915 	return __testapp_validate_traffic(test, ifobj, NULL);
1916 }
1917 
1918 static int testapp_teardown(struct test_spec *test)
1919 {
1920 	int i;
1921 
1922 	for (i = 0; i < MAX_TEARDOWN_ITER; i++) {
1923 		if (testapp_validate_traffic(test))
1924 			return TEST_FAILURE;
1925 		test_spec_reset(test);
1926 	}
1927 
1928 	return TEST_PASS;
1929 }
1930 
1931 static void swap_directions(struct ifobject **ifobj1, struct ifobject **ifobj2)
1932 {
1933 	thread_func_t tmp_func_ptr = (*ifobj1)->func_ptr;
1934 	struct ifobject *tmp_ifobj = (*ifobj1);
1935 
1936 	(*ifobj1)->func_ptr = (*ifobj2)->func_ptr;
1937 	(*ifobj2)->func_ptr = tmp_func_ptr;
1938 
1939 	*ifobj1 = *ifobj2;
1940 	*ifobj2 = tmp_ifobj;
1941 }
1942 
1943 static int testapp_bidirectional(struct test_spec *test)
1944 {
1945 	int res;
1946 
1947 	test->ifobj_tx->rx_on = true;
1948 	test->ifobj_rx->tx_on = true;
1949 	test->total_steps = 2;
1950 	if (testapp_validate_traffic(test))
1951 		return TEST_FAILURE;
1952 
1953 	print_verbose("Switching Tx/Rx direction\n");
1954 	swap_directions(&test->ifobj_rx, &test->ifobj_tx);
1955 	res = __testapp_validate_traffic(test, test->ifobj_rx, test->ifobj_tx);
1956 
1957 	swap_directions(&test->ifobj_rx, &test->ifobj_tx);
1958 	return res;
1959 }
1960 
1961 static int swap_xsk_resources(struct test_spec *test)
1962 {
1963 	int ret;
1964 
1965 	test->ifobj_tx->xsk_arr[0].pkt_stream = NULL;
1966 	test->ifobj_rx->xsk_arr[0].pkt_stream = NULL;
1967 	test->ifobj_tx->xsk_arr[1].pkt_stream = test->tx_pkt_stream_default;
1968 	test->ifobj_rx->xsk_arr[1].pkt_stream = test->rx_pkt_stream_default;
1969 	test->ifobj_tx->xsk = &test->ifobj_tx->xsk_arr[1];
1970 	test->ifobj_rx->xsk = &test->ifobj_rx->xsk_arr[1];
1971 
1972 	ret = xsk_update_xskmap(test->ifobj_rx->xskmap, test->ifobj_rx->xsk->xsk, 0);
1973 	if (ret)
1974 		return TEST_FAILURE;
1975 
1976 	return TEST_PASS;
1977 }
1978 
1979 static int testapp_xdp_prog_cleanup(struct test_spec *test)
1980 {
1981 	test->total_steps = 2;
1982 	test->nb_sockets = 2;
1983 	if (testapp_validate_traffic(test))
1984 		return TEST_FAILURE;
1985 
1986 	if (swap_xsk_resources(test))
1987 		return TEST_FAILURE;
1988 	return testapp_validate_traffic(test);
1989 }
1990 
1991 static int testapp_headroom(struct test_spec *test)
1992 {
1993 	test->ifobj_rx->umem->frame_headroom = UMEM_HEADROOM_TEST_SIZE;
1994 	return testapp_validate_traffic(test);
1995 }
1996 
1997 static int testapp_stats_rx_dropped(struct test_spec *test)
1998 {
1999 	if (test->mode == TEST_MODE_ZC) {
2000 		ksft_test_result_skip("Can not run RX_DROPPED test for ZC mode\n");
2001 		return TEST_SKIP;
2002 	}
2003 
2004 	pkt_stream_replace_half(test, MIN_PKT_SIZE * 4, 0);
2005 	test->ifobj_rx->umem->frame_headroom = test->ifobj_rx->umem->frame_size -
2006 		XDP_PACKET_HEADROOM - MIN_PKT_SIZE * 3;
2007 	pkt_stream_receive_half(test);
2008 	test->ifobj_rx->validation_func = validate_rx_dropped;
2009 	return testapp_validate_traffic(test);
2010 }
2011 
2012 static int testapp_stats_tx_invalid_descs(struct test_spec *test)
2013 {
2014 	pkt_stream_replace_half(test, XSK_UMEM__INVALID_FRAME_SIZE, 0);
2015 	test->ifobj_tx->validation_func = validate_tx_invalid_descs;
2016 	return testapp_validate_traffic(test);
2017 }
2018 
2019 static int testapp_stats_rx_full(struct test_spec *test)
2020 {
2021 	pkt_stream_replace(test, DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, MIN_PKT_SIZE);
2022 	test->ifobj_rx->xsk->pkt_stream = pkt_stream_generate(DEFAULT_UMEM_BUFFERS, MIN_PKT_SIZE);
2023 
2024 	test->ifobj_rx->xsk->rxqsize = DEFAULT_UMEM_BUFFERS;
2025 	test->ifobj_rx->release_rx = false;
2026 	test->ifobj_rx->validation_func = validate_rx_full;
2027 	return testapp_validate_traffic(test);
2028 }
2029 
2030 static int testapp_stats_fill_empty(struct test_spec *test)
2031 {
2032 	pkt_stream_replace(test, DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, MIN_PKT_SIZE);
2033 	test->ifobj_rx->xsk->pkt_stream = pkt_stream_generate(DEFAULT_UMEM_BUFFERS, MIN_PKT_SIZE);
2034 
2035 	test->ifobj_rx->use_fill_ring = false;
2036 	test->ifobj_rx->validation_func = validate_fill_empty;
2037 	return testapp_validate_traffic(test);
2038 }
2039 
2040 static int testapp_send_receive_unaligned(struct test_spec *test)
2041 {
2042 	test->ifobj_tx->umem->unaligned_mode = true;
2043 	test->ifobj_rx->umem->unaligned_mode = true;
2044 	/* Let half of the packets straddle a 4K buffer boundary */
2045 	pkt_stream_replace_half(test, MIN_PKT_SIZE, -MIN_PKT_SIZE / 2);
2046 
2047 	return testapp_validate_traffic(test);
2048 }
2049 
2050 static int testapp_send_receive_unaligned_mb(struct test_spec *test)
2051 {
2052 	test->mtu = MAX_ETH_JUMBO_SIZE;
2053 	test->ifobj_tx->umem->unaligned_mode = true;
2054 	test->ifobj_rx->umem->unaligned_mode = true;
2055 	pkt_stream_replace(test, DEFAULT_PKT_CNT, MAX_ETH_JUMBO_SIZE);
2056 	return testapp_validate_traffic(test);
2057 }
2058 
2059 static int testapp_single_pkt(struct test_spec *test)
2060 {
2061 	struct pkt pkts[] = {{0, MIN_PKT_SIZE, 0, true}};
2062 
2063 	pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts));
2064 	return testapp_validate_traffic(test);
2065 }
2066 
2067 static int testapp_send_receive_mb(struct test_spec *test)
2068 {
2069 	test->mtu = MAX_ETH_JUMBO_SIZE;
2070 	pkt_stream_replace(test, DEFAULT_PKT_CNT, MAX_ETH_JUMBO_SIZE);
2071 
2072 	return testapp_validate_traffic(test);
2073 }
2074 
2075 static int testapp_invalid_desc_mb(struct test_spec *test)
2076 {
2077 	struct xsk_umem_info *umem = test->ifobj_tx->umem;
2078 	u64 umem_size = umem->num_frames * umem->frame_size;
2079 	struct pkt pkts[] = {
2080 		/* Valid packet for synch to start with */
2081 		{0, MIN_PKT_SIZE, 0, true, 0},
2082 		/* Zero frame len is not legal */
2083 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2084 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2085 		{0, 0, 0, false, 0},
2086 		/* Invalid address in the second frame */
2087 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2088 		{umem_size, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2089 		/* Invalid len in the middle */
2090 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2091 		{0, XSK_UMEM__INVALID_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2092 		/* Invalid options in the middle */
2093 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2094 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XSK_DESC__INVALID_OPTION},
2095 		/* Transmit 2 frags, receive 3 */
2096 		{0, XSK_UMEM__MAX_FRAME_SIZE, 0, true, XDP_PKT_CONTD},
2097 		{0, XSK_UMEM__MAX_FRAME_SIZE, 0, true, 0},
2098 		/* Middle frame crosses chunk boundary with small length */
2099 		{0, XSK_UMEM__LARGE_FRAME_SIZE, 0, false, XDP_PKT_CONTD},
2100 		{-MIN_PKT_SIZE / 2, MIN_PKT_SIZE, 0, false, 0},
2101 		/* Valid packet for synch so that something is received */
2102 		{0, MIN_PKT_SIZE, 0, true, 0}};
2103 
2104 	if (umem->unaligned_mode) {
2105 		/* Crossing a chunk boundary allowed */
2106 		pkts[12].valid = true;
2107 		pkts[13].valid = true;
2108 	}
2109 
2110 	test->mtu = MAX_ETH_JUMBO_SIZE;
2111 	pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts));
2112 	return testapp_validate_traffic(test);
2113 }
2114 
2115 static int testapp_invalid_desc(struct test_spec *test)
2116 {
2117 	struct xsk_umem_info *umem = test->ifobj_tx->umem;
2118 	u64 umem_size = umem->num_frames * umem->frame_size;
2119 	struct pkt pkts[] = {
2120 		/* Zero packet address allowed */
2121 		{0, MIN_PKT_SIZE, 0, true},
2122 		/* Allowed packet */
2123 		{0, MIN_PKT_SIZE, 0, true},
2124 		/* Straddling the start of umem */
2125 		{-2, MIN_PKT_SIZE, 0, false},
2126 		/* Packet too large */
2127 		{0, XSK_UMEM__INVALID_FRAME_SIZE, 0, false},
2128 		/* Up to end of umem allowed */
2129 		{umem_size - MIN_PKT_SIZE - 2 * umem->frame_size, MIN_PKT_SIZE, 0, true},
2130 		/* After umem ends */
2131 		{umem_size, MIN_PKT_SIZE, 0, false},
2132 		/* Straddle the end of umem */
2133 		{umem_size - MIN_PKT_SIZE / 2, MIN_PKT_SIZE, 0, false},
2134 		/* Straddle a 4K boundary */
2135 		{0x1000 - MIN_PKT_SIZE / 2, MIN_PKT_SIZE, 0, false},
2136 		/* Straddle a 2K boundary */
2137 		{0x800 - MIN_PKT_SIZE / 2, MIN_PKT_SIZE, 0, true},
2138 		/* Valid packet for synch so that something is received */
2139 		{0, MIN_PKT_SIZE, 0, true}};
2140 
2141 	if (umem->unaligned_mode) {
2142 		/* Crossing a page boundary allowed */
2143 		pkts[7].valid = true;
2144 	}
2145 	if (umem->frame_size == XSK_UMEM__DEFAULT_FRAME_SIZE / 2) {
2146 		/* Crossing a 2K frame size boundary not allowed */
2147 		pkts[8].valid = false;
2148 	}
2149 
2150 	if (test->ifobj_tx->shared_umem) {
2151 		pkts[4].offset += umem_size;
2152 		pkts[5].offset += umem_size;
2153 		pkts[6].offset += umem_size;
2154 	}
2155 
2156 	pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts));
2157 	return testapp_validate_traffic(test);
2158 }
2159 
2160 static int testapp_xdp_drop(struct test_spec *test)
2161 {
2162 	struct xsk_xdp_progs *skel_rx = test->ifobj_rx->xdp_progs;
2163 	struct xsk_xdp_progs *skel_tx = test->ifobj_tx->xdp_progs;
2164 
2165 	test_spec_set_xdp_prog(test, skel_rx->progs.xsk_xdp_drop, skel_tx->progs.xsk_xdp_drop,
2166 			       skel_rx->maps.xsk, skel_tx->maps.xsk);
2167 
2168 	pkt_stream_receive_half(test);
2169 	return testapp_validate_traffic(test);
2170 }
2171 
2172 static int testapp_xdp_metadata_copy(struct test_spec *test)
2173 {
2174 	struct xsk_xdp_progs *skel_rx = test->ifobj_rx->xdp_progs;
2175 	struct xsk_xdp_progs *skel_tx = test->ifobj_tx->xdp_progs;
2176 	struct bpf_map *data_map;
2177 	int count = 0;
2178 	int key = 0;
2179 
2180 	test_spec_set_xdp_prog(test, skel_rx->progs.xsk_xdp_populate_metadata,
2181 			       skel_tx->progs.xsk_xdp_populate_metadata,
2182 			       skel_rx->maps.xsk, skel_tx->maps.xsk);
2183 	test->ifobj_rx->use_metadata = true;
2184 
2185 	data_map = bpf_object__find_map_by_name(skel_rx->obj, "xsk_xdp_.bss");
2186 	if (!data_map || !bpf_map__is_internal(data_map)) {
2187 		ksft_print_msg("Error: could not find bss section of XDP program\n");
2188 		return TEST_FAILURE;
2189 	}
2190 
2191 	if (bpf_map_update_elem(bpf_map__fd(data_map), &key, &count, BPF_ANY)) {
2192 		ksft_print_msg("Error: could not update count element\n");
2193 		return TEST_FAILURE;
2194 	}
2195 
2196 	return testapp_validate_traffic(test);
2197 }
2198 
2199 static int testapp_xdp_shared_umem(struct test_spec *test)
2200 {
2201 	struct xsk_xdp_progs *skel_rx = test->ifobj_rx->xdp_progs;
2202 	struct xsk_xdp_progs *skel_tx = test->ifobj_tx->xdp_progs;
2203 
2204 	test->total_steps = 1;
2205 	test->nb_sockets = 2;
2206 
2207 	test_spec_set_xdp_prog(test, skel_rx->progs.xsk_xdp_shared_umem,
2208 			       skel_tx->progs.xsk_xdp_shared_umem,
2209 			       skel_rx->maps.xsk, skel_tx->maps.xsk);
2210 
2211 	pkt_stream_even_odd_sequence(test);
2212 
2213 	return testapp_validate_traffic(test);
2214 }
2215 
2216 static int testapp_poll_txq_tmout(struct test_spec *test)
2217 {
2218 	test->ifobj_tx->use_poll = true;
2219 	/* create invalid frame by set umem frame_size and pkt length equal to 2048 */
2220 	test->ifobj_tx->umem->frame_size = 2048;
2221 	pkt_stream_replace(test, 2 * DEFAULT_PKT_CNT, 2048);
2222 	return testapp_validate_traffic_single_thread(test, test->ifobj_tx);
2223 }
2224 
2225 static int testapp_poll_rxq_tmout(struct test_spec *test)
2226 {
2227 	test->ifobj_rx->use_poll = true;
2228 	return testapp_validate_traffic_single_thread(test, test->ifobj_rx);
2229 }
2230 
2231 static int testapp_too_many_frags(struct test_spec *test)
2232 {
2233 	struct pkt pkts[2 * XSK_DESC__MAX_SKB_FRAGS + 2] = {};
2234 	u32 max_frags, i;
2235 
2236 	if (test->mode == TEST_MODE_ZC)
2237 		max_frags = test->ifobj_tx->xdp_zc_max_segs;
2238 	else
2239 		max_frags = XSK_DESC__MAX_SKB_FRAGS;
2240 
2241 	test->mtu = MAX_ETH_JUMBO_SIZE;
2242 
2243 	/* Valid packet for synch */
2244 	pkts[0].len = MIN_PKT_SIZE;
2245 	pkts[0].valid = true;
2246 
2247 	/* One valid packet with the max amount of frags */
2248 	for (i = 1; i < max_frags + 1; i++) {
2249 		pkts[i].len = MIN_PKT_SIZE;
2250 		pkts[i].options = XDP_PKT_CONTD;
2251 		pkts[i].valid = true;
2252 	}
2253 	pkts[max_frags].options = 0;
2254 
2255 	/* An invalid packet with the max amount of frags but signals packet
2256 	 * continues on the last frag
2257 	 */
2258 	for (i = max_frags + 1; i < 2 * max_frags + 1; i++) {
2259 		pkts[i].len = MIN_PKT_SIZE;
2260 		pkts[i].options = XDP_PKT_CONTD;
2261 		pkts[i].valid = false;
2262 	}
2263 
2264 	/* Valid packet for synch */
2265 	pkts[2 * max_frags + 1].len = MIN_PKT_SIZE;
2266 	pkts[2 * max_frags + 1].valid = true;
2267 
2268 	pkt_stream_generate_custom(test, pkts, 2 * max_frags + 2);
2269 	return testapp_validate_traffic(test);
2270 }
2271 
2272 static int xsk_load_xdp_programs(struct ifobject *ifobj)
2273 {
2274 	ifobj->xdp_progs = xsk_xdp_progs__open_and_load();
2275 	if (libbpf_get_error(ifobj->xdp_progs))
2276 		return libbpf_get_error(ifobj->xdp_progs);
2277 
2278 	return 0;
2279 }
2280 
2281 static void xsk_unload_xdp_programs(struct ifobject *ifobj)
2282 {
2283 	xsk_xdp_progs__destroy(ifobj->xdp_progs);
2284 }
2285 
2286 /* Simple test */
2287 static bool hugepages_present(void)
2288 {
2289 	size_t mmap_sz = 2 * DEFAULT_UMEM_BUFFERS * XSK_UMEM__DEFAULT_FRAME_SIZE;
2290 	void *bufs;
2291 
2292 	bufs = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2293 		    MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, MAP_HUGE_2MB);
2294 	if (bufs == MAP_FAILED)
2295 		return false;
2296 
2297 	mmap_sz = ceil_u64(mmap_sz, HUGEPAGE_SIZE) * HUGEPAGE_SIZE;
2298 	munmap(bufs, mmap_sz);
2299 	return true;
2300 }
2301 
2302 static void init_iface(struct ifobject *ifobj, thread_func_t func_ptr)
2303 {
2304 	LIBBPF_OPTS(bpf_xdp_query_opts, query_opts);
2305 	int err;
2306 
2307 	ifobj->func_ptr = func_ptr;
2308 
2309 	err = xsk_load_xdp_programs(ifobj);
2310 	if (err) {
2311 		ksft_print_msg("Error loading XDP program\n");
2312 		exit_with_error(err);
2313 	}
2314 
2315 	if (hugepages_present())
2316 		ifobj->unaligned_supp = true;
2317 
2318 	err = bpf_xdp_query(ifobj->ifindex, XDP_FLAGS_DRV_MODE, &query_opts);
2319 	if (err) {
2320 		ksft_print_msg("Error querying XDP capabilities\n");
2321 		exit_with_error(-err);
2322 	}
2323 	if (query_opts.feature_flags & NETDEV_XDP_ACT_RX_SG)
2324 		ifobj->multi_buff_supp = true;
2325 	if (query_opts.feature_flags & NETDEV_XDP_ACT_XSK_ZEROCOPY) {
2326 		if (query_opts.xdp_zc_max_segs > 1) {
2327 			ifobj->multi_buff_zc_supp = true;
2328 			ifobj->xdp_zc_max_segs = query_opts.xdp_zc_max_segs;
2329 		} else {
2330 			ifobj->xdp_zc_max_segs = 0;
2331 		}
2332 	}
2333 }
2334 
2335 static int testapp_send_receive(struct test_spec *test)
2336 {
2337 	return testapp_validate_traffic(test);
2338 }
2339 
2340 static int testapp_send_receive_2k_frame(struct test_spec *test)
2341 {
2342 	test->ifobj_tx->umem->frame_size = 2048;
2343 	test->ifobj_rx->umem->frame_size = 2048;
2344 	pkt_stream_replace(test, DEFAULT_PKT_CNT, MIN_PKT_SIZE);
2345 	return testapp_validate_traffic(test);
2346 }
2347 
2348 static int testapp_poll_rx(struct test_spec *test)
2349 {
2350 	test->ifobj_rx->use_poll = true;
2351 	return testapp_validate_traffic(test);
2352 }
2353 
2354 static int testapp_poll_tx(struct test_spec *test)
2355 {
2356 	test->ifobj_tx->use_poll = true;
2357 	return testapp_validate_traffic(test);
2358 }
2359 
2360 static int testapp_aligned_inv_desc(struct test_spec *test)
2361 {
2362 	return testapp_invalid_desc(test);
2363 }
2364 
2365 static int testapp_aligned_inv_desc_2k_frame(struct test_spec *test)
2366 {
2367 	test->ifobj_tx->umem->frame_size = 2048;
2368 	test->ifobj_rx->umem->frame_size = 2048;
2369 	return testapp_invalid_desc(test);
2370 }
2371 
2372 static int testapp_unaligned_inv_desc(struct test_spec *test)
2373 {
2374 	test->ifobj_tx->umem->unaligned_mode = true;
2375 	test->ifobj_rx->umem->unaligned_mode = true;
2376 	return testapp_invalid_desc(test);
2377 }
2378 
2379 static int testapp_unaligned_inv_desc_4001_frame(struct test_spec *test)
2380 {
2381 	u64 page_size, umem_size;
2382 
2383 	/* Odd frame size so the UMEM doesn't end near a page boundary. */
2384 	test->ifobj_tx->umem->frame_size = 4001;
2385 	test->ifobj_rx->umem->frame_size = 4001;
2386 	test->ifobj_tx->umem->unaligned_mode = true;
2387 	test->ifobj_rx->umem->unaligned_mode = true;
2388 	/* This test exists to test descriptors that staddle the end of
2389 	 * the UMEM but not a page.
2390 	 */
2391 	page_size = sysconf(_SC_PAGESIZE);
2392 	umem_size = test->ifobj_tx->umem->num_frames * test->ifobj_tx->umem->frame_size;
2393 	assert(umem_size % page_size > MIN_PKT_SIZE);
2394 	assert(umem_size % page_size < page_size - MIN_PKT_SIZE);
2395 
2396 	return testapp_invalid_desc(test);
2397 }
2398 
2399 static int testapp_aligned_inv_desc_mb(struct test_spec *test)
2400 {
2401 	return testapp_invalid_desc_mb(test);
2402 }
2403 
2404 static int testapp_unaligned_inv_desc_mb(struct test_spec *test)
2405 {
2406 	test->ifobj_tx->umem->unaligned_mode = true;
2407 	test->ifobj_rx->umem->unaligned_mode = true;
2408 	return testapp_invalid_desc_mb(test);
2409 }
2410 
2411 static int testapp_xdp_metadata(struct test_spec *test)
2412 {
2413 	return testapp_xdp_metadata_copy(test);
2414 }
2415 
2416 static int testapp_xdp_metadata_mb(struct test_spec *test)
2417 {
2418 	test->mtu = MAX_ETH_JUMBO_SIZE;
2419 	return testapp_xdp_metadata_copy(test);
2420 }
2421 
2422 static int testapp_hw_sw_min_ring_size(struct test_spec *test)
2423 {
2424 	int ret;
2425 
2426 	test->set_ring = true;
2427 	test->total_steps = 2;
2428 	test->ifobj_tx->ring.tx_pending = DEFAULT_BATCH_SIZE;
2429 	test->ifobj_tx->ring.rx_pending = DEFAULT_BATCH_SIZE * 2;
2430 	test->ifobj_tx->xsk->batch_size = 1;
2431 	test->ifobj_rx->xsk->batch_size = 1;
2432 	ret = testapp_validate_traffic(test);
2433 	if (ret)
2434 		return ret;
2435 
2436 	/* Set batch size to hw_ring_size - 1 */
2437 	test->ifobj_tx->xsk->batch_size = DEFAULT_BATCH_SIZE - 1;
2438 	test->ifobj_rx->xsk->batch_size = DEFAULT_BATCH_SIZE - 1;
2439 	return testapp_validate_traffic(test);
2440 }
2441 
2442 static int testapp_hw_sw_max_ring_size(struct test_spec *test)
2443 {
2444 	u32 max_descs = XSK_RING_PROD__DEFAULT_NUM_DESCS * 2;
2445 	int ret;
2446 
2447 	test->set_ring = true;
2448 	test->total_steps = 2;
2449 	test->ifobj_tx->ring.tx_pending = test->ifobj_tx->ring.tx_max_pending;
2450 	test->ifobj_tx->ring.rx_pending  = test->ifobj_tx->ring.rx_max_pending;
2451 	test->ifobj_rx->umem->num_frames = max_descs;
2452 	test->ifobj_rx->xsk->rxqsize = max_descs;
2453 	test->ifobj_tx->xsk->batch_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
2454 	test->ifobj_rx->xsk->batch_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
2455 
2456 	ret = testapp_validate_traffic(test);
2457 	if (ret)
2458 		return ret;
2459 
2460 	/* Set batch_size to 4095 */
2461 	test->ifobj_tx->xsk->batch_size = max_descs - 1;
2462 	test->ifobj_rx->xsk->batch_size = max_descs - 1;
2463 	return testapp_validate_traffic(test);
2464 }
2465 
2466 static void run_pkt_test(struct test_spec *test)
2467 {
2468 	int ret;
2469 
2470 	ret = test->test_func(test);
2471 
2472 	if (ret == TEST_PASS)
2473 		ksft_test_result_pass("PASS: %s %s%s\n", mode_string(test), busy_poll_string(test),
2474 				      test->name);
2475 	pkt_stream_restore_default(test);
2476 }
2477 
2478 static struct ifobject *ifobject_create(void)
2479 {
2480 	struct ifobject *ifobj;
2481 
2482 	ifobj = calloc(1, sizeof(struct ifobject));
2483 	if (!ifobj)
2484 		return NULL;
2485 
2486 	ifobj->xsk_arr = calloc(MAX_SOCKETS, sizeof(*ifobj->xsk_arr));
2487 	if (!ifobj->xsk_arr)
2488 		goto out_xsk_arr;
2489 
2490 	ifobj->umem = calloc(1, sizeof(*ifobj->umem));
2491 	if (!ifobj->umem)
2492 		goto out_umem;
2493 
2494 	return ifobj;
2495 
2496 out_umem:
2497 	free(ifobj->xsk_arr);
2498 out_xsk_arr:
2499 	free(ifobj);
2500 	return NULL;
2501 }
2502 
2503 static void ifobject_delete(struct ifobject *ifobj)
2504 {
2505 	free(ifobj->umem);
2506 	free(ifobj->xsk_arr);
2507 	free(ifobj);
2508 }
2509 
2510 static bool is_xdp_supported(int ifindex)
2511 {
2512 	int flags = XDP_FLAGS_DRV_MODE;
2513 
2514 	LIBBPF_OPTS(bpf_link_create_opts, opts, .flags = flags);
2515 	struct bpf_insn insns[2] = {
2516 		BPF_MOV64_IMM(BPF_REG_0, XDP_PASS),
2517 		BPF_EXIT_INSN()
2518 	};
2519 	int prog_fd, insn_cnt = ARRAY_SIZE(insns);
2520 	int err;
2521 
2522 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_XDP, NULL, "GPL", insns, insn_cnt, NULL);
2523 	if (prog_fd < 0)
2524 		return false;
2525 
2526 	err = bpf_xdp_attach(ifindex, prog_fd, flags, NULL);
2527 	if (err) {
2528 		close(prog_fd);
2529 		return false;
2530 	}
2531 
2532 	bpf_xdp_detach(ifindex, flags, NULL);
2533 	close(prog_fd);
2534 
2535 	return true;
2536 }
2537 
2538 static const struct test_spec tests[] = {
2539 	{.name = "SEND_RECEIVE", .test_func = testapp_send_receive},
2540 	{.name = "SEND_RECEIVE_2K_FRAME", .test_func = testapp_send_receive_2k_frame},
2541 	{.name = "SEND_RECEIVE_SINGLE_PKT", .test_func = testapp_single_pkt},
2542 	{.name = "POLL_RX", .test_func = testapp_poll_rx},
2543 	{.name = "POLL_TX", .test_func = testapp_poll_tx},
2544 	{.name = "POLL_RXQ_FULL", .test_func = testapp_poll_rxq_tmout},
2545 	{.name = "POLL_TXQ_FULL", .test_func = testapp_poll_txq_tmout},
2546 	{.name = "SEND_RECEIVE_UNALIGNED", .test_func = testapp_send_receive_unaligned},
2547 	{.name = "ALIGNED_INV_DESC", .test_func = testapp_aligned_inv_desc},
2548 	{.name = "ALIGNED_INV_DESC_2K_FRAME_SIZE", .test_func = testapp_aligned_inv_desc_2k_frame},
2549 	{.name = "UNALIGNED_INV_DESC", .test_func = testapp_unaligned_inv_desc},
2550 	{.name = "UNALIGNED_INV_DESC_4001_FRAME_SIZE",
2551 	 .test_func = testapp_unaligned_inv_desc_4001_frame},
2552 	{.name = "UMEM_HEADROOM", .test_func = testapp_headroom},
2553 	{.name = "TEARDOWN", .test_func = testapp_teardown},
2554 	{.name = "BIDIRECTIONAL", .test_func = testapp_bidirectional},
2555 	{.name = "STAT_RX_DROPPED", .test_func = testapp_stats_rx_dropped},
2556 	{.name = "STAT_TX_INVALID", .test_func = testapp_stats_tx_invalid_descs},
2557 	{.name = "STAT_RX_FULL", .test_func = testapp_stats_rx_full},
2558 	{.name = "STAT_FILL_EMPTY", .test_func = testapp_stats_fill_empty},
2559 	{.name = "XDP_PROG_CLEANUP", .test_func = testapp_xdp_prog_cleanup},
2560 	{.name = "XDP_DROP_HALF", .test_func = testapp_xdp_drop},
2561 	{.name = "XDP_SHARED_UMEM", .test_func = testapp_xdp_shared_umem},
2562 	{.name = "XDP_METADATA_COPY", .test_func = testapp_xdp_metadata},
2563 	{.name = "XDP_METADATA_COPY_MULTI_BUFF", .test_func = testapp_xdp_metadata_mb},
2564 	{.name = "SEND_RECEIVE_9K_PACKETS", .test_func = testapp_send_receive_mb},
2565 	{.name = "SEND_RECEIVE_UNALIGNED_9K_PACKETS",
2566 	 .test_func = testapp_send_receive_unaligned_mb},
2567 	{.name = "ALIGNED_INV_DESC_MULTI_BUFF", .test_func = testapp_aligned_inv_desc_mb},
2568 	{.name = "UNALIGNED_INV_DESC_MULTI_BUFF", .test_func = testapp_unaligned_inv_desc_mb},
2569 	{.name = "TOO_MANY_FRAGS", .test_func = testapp_too_many_frags},
2570 	{.name = "HW_SW_MIN_RING_SIZE", .test_func = testapp_hw_sw_min_ring_size},
2571 	{.name = "HW_SW_MAX_RING_SIZE", .test_func = testapp_hw_sw_max_ring_size},
2572 	};
2573 
2574 static void print_tests(void)
2575 {
2576 	u32 i;
2577 
2578 	printf("Tests:\n");
2579 	for (i = 0; i < ARRAY_SIZE(tests); i++)
2580 		printf("%u: %s\n", i, tests[i].name);
2581 }
2582 
2583 int main(int argc, char **argv)
2584 {
2585 	struct pkt_stream *rx_pkt_stream_default;
2586 	struct pkt_stream *tx_pkt_stream_default;
2587 	struct ifobject *ifobj_tx, *ifobj_rx;
2588 	u32 i, j, failed_tests = 0, nb_tests;
2589 	int modes = TEST_MODE_SKB + 1;
2590 	struct test_spec test;
2591 	bool shared_netdev;
2592 	int ret;
2593 
2594 	/* Use libbpf 1.0 API mode */
2595 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
2596 
2597 	ifobj_tx = ifobject_create();
2598 	if (!ifobj_tx)
2599 		exit_with_error(ENOMEM);
2600 	ifobj_rx = ifobject_create();
2601 	if (!ifobj_rx)
2602 		exit_with_error(ENOMEM);
2603 
2604 	setlocale(LC_ALL, "");
2605 
2606 	parse_command_line(ifobj_tx, ifobj_rx, argc, argv);
2607 
2608 	if (opt_print_tests) {
2609 		print_tests();
2610 		ksft_exit_xpass();
2611 	}
2612 	if (opt_run_test != RUN_ALL_TESTS && opt_run_test >= ARRAY_SIZE(tests)) {
2613 		ksft_print_msg("Error: test %u does not exist.\n", opt_run_test);
2614 		ksft_exit_xfail();
2615 	}
2616 
2617 	shared_netdev = (ifobj_tx->ifindex == ifobj_rx->ifindex);
2618 	ifobj_tx->shared_umem = shared_netdev;
2619 	ifobj_rx->shared_umem = shared_netdev;
2620 
2621 	if (!validate_interface(ifobj_tx) || !validate_interface(ifobj_rx))
2622 		print_usage(argv);
2623 
2624 	if (is_xdp_supported(ifobj_tx->ifindex)) {
2625 		modes++;
2626 		if (ifobj_zc_avail(ifobj_tx))
2627 			modes++;
2628 	}
2629 
2630 	ret = get_hw_ring_size(ifobj_tx->ifname, &ifobj_tx->ring);
2631 	if (!ret) {
2632 		ifobj_tx->hw_ring_size_supp = true;
2633 		ifobj_tx->set_ring.default_tx = ifobj_tx->ring.tx_pending;
2634 		ifobj_tx->set_ring.default_rx = ifobj_tx->ring.rx_pending;
2635 	}
2636 
2637 	init_iface(ifobj_rx, worker_testapp_validate_rx);
2638 	init_iface(ifobj_tx, worker_testapp_validate_tx);
2639 
2640 	test_spec_init(&test, ifobj_tx, ifobj_rx, 0, &tests[0]);
2641 	tx_pkt_stream_default = pkt_stream_generate(DEFAULT_PKT_CNT, MIN_PKT_SIZE);
2642 	rx_pkt_stream_default = pkt_stream_generate(DEFAULT_PKT_CNT, MIN_PKT_SIZE);
2643 	if (!tx_pkt_stream_default || !rx_pkt_stream_default)
2644 		exit_with_error(ENOMEM);
2645 	test.tx_pkt_stream_default = tx_pkt_stream_default;
2646 	test.rx_pkt_stream_default = rx_pkt_stream_default;
2647 
2648 	if (opt_run_test == RUN_ALL_TESTS)
2649 		nb_tests = ARRAY_SIZE(tests);
2650 	else
2651 		nb_tests = 1;
2652 	if (opt_mode == TEST_MODE_ALL) {
2653 		ksft_set_plan(modes * nb_tests);
2654 	} else {
2655 		if (opt_mode == TEST_MODE_DRV && modes <= TEST_MODE_DRV) {
2656 			ksft_print_msg("Error: XDP_DRV mode not supported.\n");
2657 			ksft_exit_xfail();
2658 		}
2659 		if (opt_mode == TEST_MODE_ZC && modes <= TEST_MODE_ZC) {
2660 			ksft_print_msg("Error: zero-copy mode not supported.\n");
2661 			ksft_exit_xfail();
2662 		}
2663 
2664 		ksft_set_plan(nb_tests);
2665 	}
2666 
2667 	for (i = 0; i < modes; i++) {
2668 		if (opt_mode != TEST_MODE_ALL && i != opt_mode)
2669 			continue;
2670 
2671 		for (j = 0; j < ARRAY_SIZE(tests); j++) {
2672 			if (opt_run_test != RUN_ALL_TESTS && j != opt_run_test)
2673 				continue;
2674 
2675 			test_spec_init(&test, ifobj_tx, ifobj_rx, i, &tests[j]);
2676 			run_pkt_test(&test);
2677 			usleep(USLEEP_MAX);
2678 
2679 			if (test.fail)
2680 				failed_tests++;
2681 		}
2682 	}
2683 
2684 	if (ifobj_tx->hw_ring_size_supp)
2685 		hw_ring_size_reset(ifobj_tx);
2686 
2687 	pkt_stream_delete(tx_pkt_stream_default);
2688 	pkt_stream_delete(rx_pkt_stream_default);
2689 	xsk_unload_xdp_programs(ifobj_tx);
2690 	xsk_unload_xdp_programs(ifobj_rx);
2691 	ifobject_delete(ifobj_tx);
2692 	ifobject_delete(ifobj_rx);
2693 
2694 	if (failed_tests)
2695 		ksft_exit_fail();
2696 	else
2697 		ksft_exit_pass();
2698 }
2699