xref: /linux/tools/testing/selftests/drivers/net/hw/toeplitz.c (revision 8b4e023d79b760d217dd1c462848c4a27fcc7677)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Toeplitz test
3  *
4  * 1. Read packets and their rx_hash using PF_PACKET/TPACKET_V3
5  * 2. Compute the rx_hash in software based on the packet contents
6  * 3. Compare the two
7  *
8  * Optionally, either '-C $rx_irq_cpu_list' or '-r $rps_bitmap' may be given.
9  *
10  * If '-C $rx_irq_cpu_list' is given, also
11  *
12  * 4. Identify the cpu on which the packet arrived with PACKET_FANOUT_CPU
13  * 5. Compute the rxqueue that RSS would select based on this rx_hash
14  * 6. Using the $rx_irq_cpu_list map, identify the arriving cpu based on rxq irq
15  * 7. Compare the cpus from 4 and 6
16  *
17  * Else if '-r $rps_bitmap' is given, also
18  *
19  * 4. Identify the cpu on which the packet arrived with PACKET_FANOUT_CPU
20  * 5. Compute the cpu that RPS should select based on rx_hash and $rps_bitmap
21  * 6. Compare the cpus from 4 and 5
22  */
23 
24 #define _GNU_SOURCE
25 
26 #include <arpa/inet.h>
27 #include <errno.h>
28 #include <error.h>
29 #include <fcntl.h>
30 #include <getopt.h>
31 #include <linux/filter.h>
32 #include <linux/if_ether.h>
33 #include <linux/if_packet.h>
34 #include <net/if.h>
35 #include <netdb.h>
36 #include <netinet/ip.h>
37 #include <netinet/ip6.h>
38 #include <netinet/tcp.h>
39 #include <netinet/udp.h>
40 #include <poll.h>
41 #include <stdbool.h>
42 #include <stddef.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <sys/mman.h>
48 #include <sys/socket.h>
49 #include <sys/stat.h>
50 #include <sys/sysinfo.h>
51 #include <sys/time.h>
52 #include <sys/types.h>
53 #include <unistd.h>
54 
55 #include "../../../kselftest.h"
56 #include "../../../net/lib/ksft.h"
57 
58 #define TOEPLITZ_KEY_MIN_LEN	40
59 #define TOEPLITZ_KEY_MAX_LEN	60
60 
61 #define TOEPLITZ_STR_LEN(K)	(((K) * 3) - 1)	/* hex encoded: AA:BB:CC:...:ZZ */
62 #define TOEPLITZ_STR_MIN_LEN	TOEPLITZ_STR_LEN(TOEPLITZ_KEY_MIN_LEN)
63 #define TOEPLITZ_STR_MAX_LEN	TOEPLITZ_STR_LEN(TOEPLITZ_KEY_MAX_LEN)
64 
65 #define FOUR_TUPLE_MAX_LEN	((sizeof(struct in6_addr) * 2) + (sizeof(uint16_t) * 2))
66 
67 #define RSS_MAX_CPUS (1 << 16)	/* real constraint is PACKET_FANOUT_MAX */
68 
69 #define RPS_MAX_CPUS 16UL	/* must be a power of 2 */
70 
71 /* configuration options (cmdline arguments) */
72 static uint16_t cfg_dport =	8000;
73 static int cfg_family =		AF_INET6;
74 static char *cfg_ifname =	"eth0";
75 static int cfg_num_queues;
76 static int cfg_num_rps_cpus;
77 static bool cfg_sink;
78 static int cfg_type =		SOCK_STREAM;
79 static int cfg_timeout_msec =	1000;
80 static bool cfg_verbose;
81 
82 /* global vars */
83 static int num_cpus;
84 static int ring_block_nr;
85 static int ring_block_sz;
86 
87 /* stats */
88 static int frames_received;
89 static int frames_nohash;
90 static int frames_error;
91 
92 #define log_verbose(args...)	do { if (cfg_verbose) fprintf(stderr, args); } while (0)
93 
94 /* tpacket ring */
95 struct ring_state {
96 	int fd;
97 	char *mmap;
98 	int idx;
99 	int cpu;
100 };
101 
102 static unsigned int rx_irq_cpus[RSS_MAX_CPUS];	/* map from rxq to cpu */
103 static int rps_silo_to_cpu[RPS_MAX_CPUS];
104 static unsigned char toeplitz_key[TOEPLITZ_KEY_MAX_LEN];
105 static struct ring_state rings[RSS_MAX_CPUS];
106 
107 static inline uint32_t toeplitz(const unsigned char *four_tuple,
108 				const unsigned char *key)
109 {
110 	int i, bit, ret = 0;
111 	uint32_t key32;
112 
113 	key32 = ntohl(*((uint32_t *)key));
114 	key += 4;
115 
116 	for (i = 0; i < FOUR_TUPLE_MAX_LEN; i++) {
117 		for (bit = 7; bit >= 0; bit--) {
118 			if (four_tuple[i] & (1 << bit))
119 				ret ^= key32;
120 
121 			key32 <<= 1;
122 			key32 |= !!(key[0] & (1 << bit));
123 		}
124 		key++;
125 	}
126 
127 	return ret;
128 }
129 
130 /* Compare computed cpu with arrival cpu from packet_fanout_cpu */
131 static void verify_rss(uint32_t rx_hash, int cpu)
132 {
133 	int queue = rx_hash % cfg_num_queues;
134 
135 	log_verbose(" rxq %d (cpu %d)", queue, rx_irq_cpus[queue]);
136 	if (rx_irq_cpus[queue] != cpu) {
137 		log_verbose(". error: rss cpu mismatch (%d)", cpu);
138 		frames_error++;
139 	}
140 }
141 
142 static void verify_rps(uint64_t rx_hash, int cpu)
143 {
144 	int silo = (rx_hash * cfg_num_rps_cpus) >> 32;
145 
146 	log_verbose(" silo %d (cpu %d)", silo, rps_silo_to_cpu[silo]);
147 	if (rps_silo_to_cpu[silo] != cpu) {
148 		log_verbose(". error: rps cpu mismatch (%d)", cpu);
149 		frames_error++;
150 	}
151 }
152 
153 static void log_rxhash(int cpu, uint32_t rx_hash,
154 		       const char *addrs, int addr_len)
155 {
156 	char saddr[INET6_ADDRSTRLEN], daddr[INET6_ADDRSTRLEN];
157 	uint16_t *ports;
158 
159 	if (!inet_ntop(cfg_family, addrs, saddr, sizeof(saddr)) ||
160 	    !inet_ntop(cfg_family, addrs + addr_len, daddr, sizeof(daddr)))
161 		error(1, 0, "address parse error");
162 
163 	ports = (void *)addrs + (addr_len * 2);
164 	log_verbose("cpu %d: rx_hash 0x%08x [saddr %s daddr %s sport %02hu dport %02hu]",
165 		    cpu, rx_hash, saddr, daddr,
166 		    ntohs(ports[0]), ntohs(ports[1]));
167 }
168 
169 /* Compare computed rxhash with rxhash received from tpacket_v3 */
170 static void verify_rxhash(const char *pkt, uint32_t rx_hash, int cpu)
171 {
172 	unsigned char four_tuple[FOUR_TUPLE_MAX_LEN] = {0};
173 	uint32_t rx_hash_sw;
174 	const char *addrs;
175 	int addr_len;
176 
177 	if (cfg_family == AF_INET) {
178 		addr_len = sizeof(struct in_addr);
179 		addrs = pkt + offsetof(struct iphdr, saddr);
180 	} else {
181 		addr_len = sizeof(struct in6_addr);
182 		addrs = pkt + offsetof(struct ip6_hdr, ip6_src);
183 	}
184 
185 	memcpy(four_tuple, addrs, (addr_len * 2) + (sizeof(uint16_t) * 2));
186 	rx_hash_sw = toeplitz(four_tuple, toeplitz_key);
187 
188 	if (cfg_verbose)
189 		log_rxhash(cpu, rx_hash, addrs, addr_len);
190 
191 	if (rx_hash != rx_hash_sw) {
192 		log_verbose(" != expected 0x%x\n", rx_hash_sw);
193 		frames_error++;
194 		return;
195 	}
196 
197 	log_verbose(" OK");
198 	if (cfg_num_queues)
199 		verify_rss(rx_hash, cpu);
200 	else if (cfg_num_rps_cpus)
201 		verify_rps(rx_hash, cpu);
202 	log_verbose("\n");
203 }
204 
205 static char *recv_frame(const struct ring_state *ring, char *frame)
206 {
207 	struct tpacket3_hdr *hdr = (void *)frame;
208 
209 	if (hdr->hv1.tp_rxhash)
210 		verify_rxhash(frame + hdr->tp_net, hdr->hv1.tp_rxhash,
211 			      ring->cpu);
212 	else
213 		frames_nohash++;
214 
215 	return frame + hdr->tp_next_offset;
216 }
217 
218 /* A single TPACKET_V3 block can hold multiple frames */
219 static bool recv_block(struct ring_state *ring)
220 {
221 	struct tpacket_block_desc *block;
222 	char *frame;
223 	int i;
224 
225 	block = (void *)(ring->mmap + ring->idx * ring_block_sz);
226 	if (!(block->hdr.bh1.block_status & TP_STATUS_USER))
227 		return false;
228 
229 	frame = (char *)block;
230 	frame += block->hdr.bh1.offset_to_first_pkt;
231 
232 	for (i = 0; i < block->hdr.bh1.num_pkts; i++) {
233 		frame = recv_frame(ring, frame);
234 		frames_received++;
235 	}
236 
237 	block->hdr.bh1.block_status = TP_STATUS_KERNEL;
238 	ring->idx = (ring->idx + 1) % ring_block_nr;
239 
240 	return true;
241 }
242 
243 /* simple test: sleep once unconditionally and then process all rings */
244 static void process_rings(void)
245 {
246 	int i;
247 
248 	usleep(1000 * cfg_timeout_msec);
249 
250 	for (i = 0; i < num_cpus; i++)
251 		do {} while (recv_block(&rings[i]));
252 
253 	fprintf(stderr, "count: pass=%u nohash=%u fail=%u\n",
254 		frames_received - frames_nohash - frames_error,
255 		frames_nohash, frames_error);
256 }
257 
258 static char *setup_ring(int fd)
259 {
260 	struct tpacket_req3 req3 = {0};
261 	void *ring;
262 
263 	req3.tp_retire_blk_tov = cfg_timeout_msec / 8;
264 	req3.tp_feature_req_word = TP_FT_REQ_FILL_RXHASH;
265 
266 	req3.tp_frame_size = 2048;
267 	req3.tp_frame_nr = 1 << 10;
268 	req3.tp_block_nr = 16;
269 
270 	req3.tp_block_size = req3.tp_frame_size * req3.tp_frame_nr;
271 	req3.tp_block_size /= req3.tp_block_nr;
272 
273 	if (setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &req3, sizeof(req3)))
274 		error(1, errno, "setsockopt PACKET_RX_RING");
275 
276 	ring_block_sz = req3.tp_block_size;
277 	ring_block_nr = req3.tp_block_nr;
278 
279 	ring = mmap(0, req3.tp_block_size * req3.tp_block_nr,
280 		    PROT_READ | PROT_WRITE,
281 		    MAP_SHARED | MAP_LOCKED | MAP_POPULATE, fd, 0);
282 	if (ring == MAP_FAILED)
283 		error(1, 0, "mmap failed");
284 
285 	return ring;
286 }
287 
288 static void __set_filter(int fd, int off_proto, uint8_t proto, int off_dport)
289 {
290 	struct sock_filter filter[] = {
291 		BPF_STMT(BPF_LD  + BPF_B   + BPF_ABS, SKF_AD_OFF + SKF_AD_PKTTYPE),
292 		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, PACKET_HOST, 0, 4),
293 		BPF_STMT(BPF_LD  + BPF_B   + BPF_ABS, off_proto),
294 		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, proto, 0, 2),
295 		BPF_STMT(BPF_LD  + BPF_H   + BPF_ABS, off_dport),
296 		BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, cfg_dport, 1, 0),
297 		BPF_STMT(BPF_RET + BPF_K, 0),
298 		BPF_STMT(BPF_RET + BPF_K, 0xFFFF),
299 	};
300 	struct sock_fprog prog = {};
301 
302 	prog.filter = filter;
303 	prog.len = ARRAY_SIZE(filter);
304 	if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog)))
305 		error(1, errno, "setsockopt filter");
306 }
307 
308 /* filter on transport protocol and destination port */
309 static void set_filter(int fd)
310 {
311 	const int off_dport = offsetof(struct tcphdr, dest);	/* same for udp */
312 	uint8_t proto;
313 
314 	proto = cfg_type == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP;
315 	if (cfg_family == AF_INET)
316 		__set_filter(fd, offsetof(struct iphdr, protocol), proto,
317 			     sizeof(struct iphdr) + off_dport);
318 	else
319 		__set_filter(fd, offsetof(struct ip6_hdr, ip6_nxt), proto,
320 			     sizeof(struct ip6_hdr) + off_dport);
321 }
322 
323 /* drop everything: used temporarily during setup */
324 static void set_filter_null(int fd)
325 {
326 	struct sock_filter filter[] = {
327 		BPF_STMT(BPF_RET + BPF_K, 0),
328 	};
329 	struct sock_fprog prog = {};
330 
331 	prog.filter = filter;
332 	prog.len = ARRAY_SIZE(filter);
333 	if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog)))
334 		error(1, errno, "setsockopt filter");
335 }
336 
337 static int create_ring(char **ring)
338 {
339 	struct fanout_args args = {
340 		.id = 1,
341 		.type_flags = PACKET_FANOUT_CPU,
342 		.max_num_members = RSS_MAX_CPUS
343 	};
344 	struct sockaddr_ll ll = { 0 };
345 	int fd, val;
346 
347 	fd = socket(PF_PACKET, SOCK_DGRAM, 0);
348 	if (fd == -1)
349 		error(1, errno, "socket creation failed");
350 
351 	val = TPACKET_V3;
352 	if (setsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val)))
353 		error(1, errno, "setsockopt PACKET_VERSION");
354 	*ring = setup_ring(fd);
355 
356 	/* block packets until all rings are added to the fanout group:
357 	 * else packets can arrive during setup and get misclassified
358 	 */
359 	set_filter_null(fd);
360 
361 	ll.sll_family = AF_PACKET;
362 	ll.sll_ifindex = if_nametoindex(cfg_ifname);
363 	ll.sll_protocol = cfg_family == AF_INET ? htons(ETH_P_IP) :
364 						  htons(ETH_P_IPV6);
365 	if (bind(fd, (void *)&ll, sizeof(ll)))
366 		error(1, errno, "bind");
367 
368 	/* must come after bind: verifies all programs in group match */
369 	if (setsockopt(fd, SOL_PACKET, PACKET_FANOUT, &args, sizeof(args))) {
370 		/* on failure, retry using old API if that is sufficient:
371 		 * it has a hard limit of 256 sockets, so only try if
372 		 * (a) only testing rxhash, not RSS or (b) <= 256 cpus.
373 		 * in this API, the third argument is left implicit.
374 		 */
375 		if (cfg_num_queues || num_cpus > 256 ||
376 		    setsockopt(fd, SOL_PACKET, PACKET_FANOUT,
377 			       &args, sizeof(uint32_t)))
378 			error(1, errno, "setsockopt PACKET_FANOUT cpu");
379 	}
380 
381 	return fd;
382 }
383 
384 /* setup inet(6) socket to blackhole the test traffic, if arg '-s' */
385 static int setup_sink(void)
386 {
387 	int fd, val;
388 
389 	fd = socket(cfg_family, cfg_type, 0);
390 	if (fd == -1)
391 		error(1, errno, "socket %d.%d", cfg_family, cfg_type);
392 
393 	val = 1 << 20;
394 	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &val, sizeof(val)))
395 		error(1, errno, "setsockopt rcvbuf");
396 
397 	return fd;
398 }
399 
400 static void setup_rings(void)
401 {
402 	int i;
403 
404 	for (i = 0; i < num_cpus; i++) {
405 		rings[i].cpu = i;
406 		rings[i].fd = create_ring(&rings[i].mmap);
407 	}
408 
409 	/* accept packets once all rings in the fanout group are up */
410 	for (i = 0; i < num_cpus; i++)
411 		set_filter(rings[i].fd);
412 }
413 
414 static void cleanup_rings(void)
415 {
416 	int i;
417 
418 	for (i = 0; i < num_cpus; i++) {
419 		if (munmap(rings[i].mmap, ring_block_nr * ring_block_sz))
420 			error(1, errno, "munmap");
421 		if (close(rings[i].fd))
422 			error(1, errno, "close");
423 	}
424 }
425 
426 static void parse_cpulist(const char *arg)
427 {
428 	do {
429 		rx_irq_cpus[cfg_num_queues++] = strtol(arg, NULL, 10);
430 
431 		arg = strchr(arg, ',');
432 		if (!arg)
433 			break;
434 		arg++;			// skip ','
435 	} while (1);
436 }
437 
438 static void show_cpulist(void)
439 {
440 	int i;
441 
442 	for (i = 0; i < cfg_num_queues; i++)
443 		fprintf(stderr, "rxq %d: cpu %d\n", i, rx_irq_cpus[i]);
444 }
445 
446 static void show_silos(void)
447 {
448 	int i;
449 
450 	for (i = 0; i < cfg_num_rps_cpus; i++)
451 		fprintf(stderr, "silo %d: cpu %d\n", i, rps_silo_to_cpu[i]);
452 }
453 
454 static void parse_toeplitz_key(const char *str, int slen, unsigned char *key)
455 {
456 	int i, ret, off;
457 
458 	if (slen < TOEPLITZ_STR_MIN_LEN ||
459 	    slen > TOEPLITZ_STR_MAX_LEN + 1)
460 		error(1, 0, "invalid toeplitz key");
461 
462 	for (i = 0, off = 0; off < slen; i++, off += 3) {
463 		ret = sscanf(str + off, "%hhx", &key[i]);
464 		if (ret != 1)
465 			error(1, 0, "key parse error at %d off %d len %d",
466 			      i, off, slen);
467 	}
468 }
469 
470 static void parse_rps_bitmap(const char *arg)
471 {
472 	unsigned long bitmap;
473 	int i;
474 
475 	bitmap = strtoul(arg, NULL, 0);
476 
477 	if (bitmap & ~(RPS_MAX_CPUS - 1))
478 		error(1, 0, "rps bitmap 0x%lx out of bounds 0..%lu",
479 		      bitmap, RPS_MAX_CPUS - 1);
480 
481 	for (i = 0; i < RPS_MAX_CPUS; i++)
482 		if (bitmap & 1UL << i)
483 			rps_silo_to_cpu[cfg_num_rps_cpus++] = i;
484 }
485 
486 static void parse_opts(int argc, char **argv)
487 {
488 	static struct option long_options[] = {
489 	    {"dport",	required_argument, 0, 'd'},
490 	    {"cpus",	required_argument, 0, 'C'},
491 	    {"key",	required_argument, 0, 'k'},
492 	    {"iface",	required_argument, 0, 'i'},
493 	    {"ipv4",	no_argument, 0, '4'},
494 	    {"ipv6",	no_argument, 0, '6'},
495 	    {"sink",	no_argument, 0, 's'},
496 	    {"tcp",	no_argument, 0, 't'},
497 	    {"timeout",	required_argument, 0, 'T'},
498 	    {"udp",	no_argument, 0, 'u'},
499 	    {"verbose",	no_argument, 0, 'v'},
500 	    {"rps",	required_argument, 0, 'r'},
501 	    {0, 0, 0, 0}
502 	};
503 	bool have_toeplitz = false;
504 	int index, c;
505 
506 	while ((c = getopt_long(argc, argv, "46C:d:i:k:r:stT:uv", long_options, &index)) != -1) {
507 		switch (c) {
508 		case '4':
509 			cfg_family = AF_INET;
510 			break;
511 		case '6':
512 			cfg_family = AF_INET6;
513 			break;
514 		case 'C':
515 			parse_cpulist(optarg);
516 			break;
517 		case 'd':
518 			cfg_dport = strtol(optarg, NULL, 0);
519 			break;
520 		case 'i':
521 			cfg_ifname = optarg;
522 			break;
523 		case 'k':
524 			parse_toeplitz_key(optarg, strlen(optarg),
525 					   toeplitz_key);
526 			have_toeplitz = true;
527 			break;
528 		case 'r':
529 			parse_rps_bitmap(optarg);
530 			break;
531 		case 's':
532 			cfg_sink = true;
533 			break;
534 		case 't':
535 			cfg_type = SOCK_STREAM;
536 			break;
537 		case 'T':
538 			cfg_timeout_msec = strtol(optarg, NULL, 0);
539 			break;
540 		case 'u':
541 			cfg_type = SOCK_DGRAM;
542 			break;
543 		case 'v':
544 			cfg_verbose = true;
545 			break;
546 
547 		default:
548 			error(1, 0, "unknown option %c", optopt);
549 			break;
550 		}
551 	}
552 
553 	if (!have_toeplitz)
554 		error(1, 0, "Must supply rss key ('-k')");
555 
556 	num_cpus = get_nprocs();
557 	if (num_cpus > RSS_MAX_CPUS)
558 		error(1, 0, "increase RSS_MAX_CPUS");
559 
560 	if (cfg_num_queues && cfg_num_rps_cpus)
561 		error(1, 0,
562 		      "Can't supply both RSS cpus ('-C') and RPS map ('-r')");
563 	if (cfg_verbose) {
564 		show_cpulist();
565 		show_silos();
566 	}
567 }
568 
569 int main(int argc, char **argv)
570 {
571 	const int min_tests = 10;
572 	int fd_sink = -1;
573 
574 	parse_opts(argc, argv);
575 
576 	if (cfg_sink)
577 		fd_sink = setup_sink();
578 
579 	setup_rings();
580 
581 	/* Signal to test framework that we're ready to receive */
582 	ksft_ready();
583 
584 	process_rings();
585 	cleanup_rings();
586 
587 	if (cfg_sink && close(fd_sink))
588 		error(1, errno, "close sink");
589 
590 	if (frames_received - frames_nohash < min_tests)
591 		error(1, 0, "too few frames for verification");
592 
593 	return frames_error;
594 }
595