1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2018 Google Inc.
4  * Author: Eric Dumazet (edumazet@google.com)
5  *
6  * Reference program demonstrating tcp mmap() usage,
7  * and SO_RCVLOWAT hints for receiver.
8  *
9  * Note : NIC with header split is needed to use mmap() on TCP :
10  * Each incoming frame must be a multiple of PAGE_SIZE bytes of TCP payload.
11  *
12  * How to use on loopback interface :
13  *
14  *  ifconfig lo mtu 61512  # 15*4096 + 40 (ipv6 header) + 32 (TCP with TS option header)
15  *  tcp_mmap -s -z &
16  *  tcp_mmap -H ::1 -z
17  *
18  *  Or leave default lo mtu, but use -M option to set TCP_MAXSEG option to (4096 + 12)
19  *      (4096 : page size on x86, 12: TCP TS option length)
20  *  tcp_mmap -s -z -M $((4096+12)) &
21  *  tcp_mmap -H ::1 -z -M $((4096+12))
22  *
23  * Note: -z option on sender uses MSG_ZEROCOPY, which forces a copy when packets go through loopback interface.
24  *       We might use sendfile() instead, but really this test program is about mmap(), for receivers ;)
25  *
26  * $ ./tcp_mmap -s &                                 # Without mmap()
27  * $ for i in {1..4}; do ./tcp_mmap -H ::1 -z ; done
28  * received 32768 MB (0 % mmap'ed) in 14.1157 s, 19.4732 Gbit
29  *   cpu usage user:0.057 sys:7.815, 240.234 usec per MB, 65531 c-switches
30  * received 32768 MB (0 % mmap'ed) in 14.6833 s, 18.7204 Gbit
31  *  cpu usage user:0.043 sys:8.103, 248.596 usec per MB, 65524 c-switches
32  * received 32768 MB (0 % mmap'ed) in 11.143 s, 24.6682 Gbit
33  *   cpu usage user:0.044 sys:6.576, 202.026 usec per MB, 65519 c-switches
34  * received 32768 MB (0 % mmap'ed) in 14.9056 s, 18.4413 Gbit
35  *   cpu usage user:0.036 sys:8.193, 251.129 usec per MB, 65530 c-switches
36  * $ kill %1   # kill tcp_mmap server
37  *
38  * $ ./tcp_mmap -s -z &                              # With mmap()
39  * $ for i in {1..4}; do ./tcp_mmap -H ::1 -z ; done
40  * received 32768 MB (99.9939 % mmap'ed) in 6.73792 s, 40.7956 Gbit
41  *   cpu usage user:0.045 sys:2.827, 87.6465 usec per MB, 65532 c-switches
42  * received 32768 MB (99.9939 % mmap'ed) in 7.26732 s, 37.8238 Gbit
43  *   cpu usage user:0.037 sys:3.087, 95.3369 usec per MB, 65532 c-switches
44  * received 32768 MB (99.9939 % mmap'ed) in 7.61661 s, 36.0893 Gbit
45  *   cpu usage user:0.046 sys:3.559, 110.016 usec per MB, 65529 c-switches
46  * received 32768 MB (99.9939 % mmap'ed) in 7.43764 s, 36.9577 Gbit
47  *   cpu usage user:0.035 sys:3.467, 106.873 usec per MB, 65530 c-switches
48  */
49 #define _GNU_SOURCE
50 #include <pthread.h>
51 #include <sys/types.h>
52 #include <fcntl.h>
53 #include <error.h>
54 #include <sys/socket.h>
55 #include <sys/mman.h>
56 #include <sys/resource.h>
57 #include <unistd.h>
58 #include <string.h>
59 #include <stdlib.h>
60 #include <stdio.h>
61 #include <errno.h>
62 #include <time.h>
63 #include <sys/time.h>
64 #include <netinet/in.h>
65 #include <arpa/inet.h>
66 #include <poll.h>
67 #include <linux/tcp.h>
68 #include <assert.h>
69 
70 #ifndef MSG_ZEROCOPY
71 #define MSG_ZEROCOPY    0x4000000
72 #endif
73 
74 #define FILE_SZ (1ULL << 35)
75 static int cfg_family = AF_INET6;
76 static socklen_t cfg_alen = sizeof(struct sockaddr_in6);
77 static int cfg_port = 8787;
78 
79 static int rcvbuf; /* Default: autotuning.  Can be set with -r <integer> option */
80 static int sndbuf; /* Default: autotuning.  Can be set with -w <integer> option */
81 static int zflg; /* zero copy option. (MSG_ZEROCOPY for sender, mmap() for receiver */
82 static int xflg; /* hash received data (simple xor) (-h option) */
83 static int keepflag; /* -k option: receiver shall keep all received file in memory (no munmap() calls) */
84 
85 static size_t chunk_size  = 512*1024;
86 
87 static size_t map_align;
88 
89 unsigned long htotal;
90 
91 static inline void prefetch(const void *x)
92 {
93 #if defined(__x86_64__)
94 	asm volatile("prefetcht0 %P0" : : "m" (*(const char *)x));
95 #endif
96 }
97 
98 void hash_zone(void *zone, unsigned int length)
99 {
100 	unsigned long temp = htotal;
101 
102 	while (length >= 8*sizeof(long)) {
103 		prefetch(zone + 384);
104 		temp ^= *(unsigned long *)zone;
105 		temp ^= *(unsigned long *)(zone + sizeof(long));
106 		temp ^= *(unsigned long *)(zone + 2*sizeof(long));
107 		temp ^= *(unsigned long *)(zone + 3*sizeof(long));
108 		temp ^= *(unsigned long *)(zone + 4*sizeof(long));
109 		temp ^= *(unsigned long *)(zone + 5*sizeof(long));
110 		temp ^= *(unsigned long *)(zone + 6*sizeof(long));
111 		temp ^= *(unsigned long *)(zone + 7*sizeof(long));
112 		zone += 8*sizeof(long);
113 		length -= 8*sizeof(long);
114 	}
115 	while (length >= 1) {
116 		temp ^= *(unsigned char *)zone;
117 		zone += 1;
118 		length--;
119 	}
120 	htotal = temp;
121 }
122 
123 #define ALIGN_UP(x, align_to)	(((x) + ((align_to)-1)) & ~((align_to)-1))
124 #define ALIGN_PTR_UP(p, ptr_align_to)	((typeof(p))ALIGN_UP((unsigned long)(p), ptr_align_to))
125 
126 void *child_thread(void *arg)
127 {
128 	unsigned long total_mmap = 0, total = 0;
129 	struct tcp_zerocopy_receive zc;
130 	unsigned long delta_usec;
131 	int flags = MAP_SHARED;
132 	struct timeval t0, t1;
133 	char *buffer = NULL;
134 	void *raddr = NULL;
135 	void *addr = NULL;
136 	double throughput;
137 	struct rusage ru;
138 	int lu, fd;
139 
140 	fd = (int)(unsigned long)arg;
141 
142 	gettimeofday(&t0, NULL);
143 
144 	fcntl(fd, F_SETFL, O_NDELAY);
145 	buffer = malloc(chunk_size);
146 	if (!buffer) {
147 		perror("malloc");
148 		goto error;
149 	}
150 	if (zflg) {
151 		raddr = mmap(NULL, chunk_size + map_align, PROT_READ, flags, fd, 0);
152 		if (raddr == (void *)-1) {
153 			perror("mmap");
154 			zflg = 0;
155 		} else {
156 			addr = ALIGN_PTR_UP(raddr, map_align);
157 		}
158 	}
159 	while (1) {
160 		struct pollfd pfd = { .fd = fd, .events = POLLIN, };
161 		int sub;
162 
163 		poll(&pfd, 1, 10000);
164 		if (zflg) {
165 			socklen_t zc_len = sizeof(zc);
166 			int res;
167 
168 			zc.address = (__u64)((unsigned long)addr);
169 			zc.length = chunk_size;
170 			zc.recv_skip_hint = 0;
171 			res = getsockopt(fd, IPPROTO_TCP, TCP_ZEROCOPY_RECEIVE,
172 					 &zc, &zc_len);
173 			if (res == -1)
174 				break;
175 
176 			if (zc.length) {
177 				assert(zc.length <= chunk_size);
178 				total_mmap += zc.length;
179 				if (xflg)
180 					hash_zone(addr, zc.length);
181 				total += zc.length;
182 			}
183 			if (zc.recv_skip_hint) {
184 				assert(zc.recv_skip_hint <= chunk_size);
185 				lu = read(fd, buffer, zc.recv_skip_hint);
186 				if (lu > 0) {
187 					if (xflg)
188 						hash_zone(buffer, lu);
189 					total += lu;
190 				}
191 			}
192 			continue;
193 		}
194 		sub = 0;
195 		while (sub < chunk_size) {
196 			lu = read(fd, buffer + sub, chunk_size - sub);
197 			if (lu == 0)
198 				goto end;
199 			if (lu < 0)
200 				break;
201 			if (xflg)
202 				hash_zone(buffer + sub, lu);
203 			total += lu;
204 			sub += lu;
205 		}
206 	}
207 end:
208 	gettimeofday(&t1, NULL);
209 	delta_usec = (t1.tv_sec - t0.tv_sec) * 1000000 + t1.tv_usec - t0.tv_usec;
210 
211 	throughput = 0;
212 	if (delta_usec)
213 		throughput = total * 8.0 / (double)delta_usec / 1000.0;
214 	getrusage(RUSAGE_THREAD, &ru);
215 	if (total > 1024*1024) {
216 		unsigned long total_usec;
217 		unsigned long mb = total >> 20;
218 		total_usec = 1000000*ru.ru_utime.tv_sec + ru.ru_utime.tv_usec +
219 			     1000000*ru.ru_stime.tv_sec + ru.ru_stime.tv_usec;
220 		printf("received %lg MB (%lg %% mmap'ed) in %lg s, %lg Gbit\n"
221 		       "  cpu usage user:%lg sys:%lg, %lg usec per MB, %lu c-switches\n",
222 				total / (1024.0 * 1024.0),
223 				100.0*total_mmap/total,
224 				(double)delta_usec / 1000000.0,
225 				throughput,
226 				(double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000.0,
227 				(double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec / 1000000.0,
228 				(double)total_usec/mb,
229 				ru.ru_nvcsw);
230 	}
231 error:
232 	free(buffer);
233 	close(fd);
234 	if (zflg)
235 		munmap(raddr, chunk_size + map_align);
236 	pthread_exit(0);
237 }
238 
239 static void apply_rcvsnd_buf(int fd)
240 {
241 	if (rcvbuf && setsockopt(fd, SOL_SOCKET,
242 				 SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) == -1) {
243 		perror("setsockopt SO_RCVBUF");
244 	}
245 
246 	if (sndbuf && setsockopt(fd, SOL_SOCKET,
247 				 SO_SNDBUF, &sndbuf, sizeof(sndbuf)) == -1) {
248 		perror("setsockopt SO_SNDBUF");
249 	}
250 }
251 
252 
253 static void setup_sockaddr(int domain, const char *str_addr,
254 			   struct sockaddr_storage *sockaddr)
255 {
256 	struct sockaddr_in6 *addr6 = (void *) sockaddr;
257 	struct sockaddr_in *addr4 = (void *) sockaddr;
258 
259 	switch (domain) {
260 	case PF_INET:
261 		memset(addr4, 0, sizeof(*addr4));
262 		addr4->sin_family = AF_INET;
263 		addr4->sin_port = htons(cfg_port);
264 		if (str_addr &&
265 		    inet_pton(AF_INET, str_addr, &(addr4->sin_addr)) != 1)
266 			error(1, 0, "ipv4 parse error: %s", str_addr);
267 		break;
268 	case PF_INET6:
269 		memset(addr6, 0, sizeof(*addr6));
270 		addr6->sin6_family = AF_INET6;
271 		addr6->sin6_port = htons(cfg_port);
272 		if (str_addr &&
273 		    inet_pton(AF_INET6, str_addr, &(addr6->sin6_addr)) != 1)
274 			error(1, 0, "ipv6 parse error: %s", str_addr);
275 		break;
276 	default:
277 		error(1, 0, "illegal domain");
278 	}
279 }
280 
281 static void do_accept(int fdlisten)
282 {
283 	pthread_attr_t attr;
284 
285 	pthread_attr_init(&attr);
286 	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
287 
288 	if (setsockopt(fdlisten, SOL_SOCKET, SO_RCVLOWAT,
289 		       &chunk_size, sizeof(chunk_size)) == -1) {
290 		perror("setsockopt SO_RCVLOWAT");
291 	}
292 
293 	apply_rcvsnd_buf(fdlisten);
294 
295 	while (1) {
296 		struct sockaddr_in addr;
297 		socklen_t addrlen = sizeof(addr);
298 		pthread_t th;
299 		int fd, res;
300 
301 		fd = accept(fdlisten, (struct sockaddr *)&addr, &addrlen);
302 		if (fd == -1) {
303 			perror("accept");
304 			continue;
305 		}
306 		res = pthread_create(&th, &attr, child_thread,
307 				     (void *)(unsigned long)fd);
308 		if (res) {
309 			errno = res;
310 			perror("pthread_create");
311 			close(fd);
312 		}
313 	}
314 }
315 
316 /* Each thread should reserve a big enough vma to avoid
317  * spinlock collisions in ptl locks.
318  * This size is 2MB on x86_64, and is exported in /proc/meminfo.
319  */
320 static unsigned long default_huge_page_size(void)
321 {
322 	FILE *f = fopen("/proc/meminfo", "r");
323 	unsigned long hps = 0;
324 	size_t linelen = 0;
325 	char *line = NULL;
326 
327 	if (!f)
328 		return 0;
329 	while (getline(&line, &linelen, f) > 0) {
330 		if (sscanf(line, "Hugepagesize:       %lu kB", &hps) == 1) {
331 			hps <<= 10;
332 			break;
333 		}
334 	}
335 	free(line);
336 	fclose(f);
337 	return hps;
338 }
339 
340 int main(int argc, char *argv[])
341 {
342 	struct sockaddr_storage listenaddr, addr;
343 	unsigned int max_pacing_rate = 0;
344 	size_t total = 0;
345 	char *host = NULL;
346 	int fd, c, on = 1;
347 	char *buffer;
348 	int sflg = 0;
349 	int mss = 0;
350 
351 	while ((c = getopt(argc, argv, "46p:svr:w:H:zxkP:M:C:a:")) != -1) {
352 		switch (c) {
353 		case '4':
354 			cfg_family = PF_INET;
355 			cfg_alen = sizeof(struct sockaddr_in);
356 			break;
357 		case '6':
358 			cfg_family = PF_INET6;
359 			cfg_alen = sizeof(struct sockaddr_in6);
360 			break;
361 		case 'p':
362 			cfg_port = atoi(optarg);
363 			break;
364 		case 'H':
365 			host = optarg;
366 			break;
367 		case 's': /* server : listen for incoming connections */
368 			sflg++;
369 			break;
370 		case 'r':
371 			rcvbuf = atoi(optarg);
372 			break;
373 		case 'w':
374 			sndbuf = atoi(optarg);
375 			break;
376 		case 'z':
377 			zflg = 1;
378 			break;
379 		case 'M':
380 			mss = atoi(optarg);
381 			break;
382 		case 'x':
383 			xflg = 1;
384 			break;
385 		case 'k':
386 			keepflag = 1;
387 			break;
388 		case 'P':
389 			max_pacing_rate = atoi(optarg) ;
390 			break;
391 		case 'C':
392 			chunk_size = atol(optarg);
393 			break;
394 		case 'a':
395 			map_align = atol(optarg);
396 			break;
397 		default:
398 			exit(1);
399 		}
400 	}
401 	if (!map_align) {
402 		map_align = default_huge_page_size();
403 		/* if really /proc/meminfo is not helping,
404 		 * we use the default x86_64 hugepagesize.
405 		 */
406 		if (!map_align)
407 			map_align = 2*1024*1024;
408 	}
409 	if (sflg) {
410 		int fdlisten = socket(cfg_family, SOCK_STREAM, 0);
411 
412 		if (fdlisten == -1) {
413 			perror("socket");
414 			exit(1);
415 		}
416 		apply_rcvsnd_buf(fdlisten);
417 		setsockopt(fdlisten, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
418 
419 		setup_sockaddr(cfg_family, host, &listenaddr);
420 
421 		if (mss &&
422 		    setsockopt(fdlisten, IPPROTO_TCP, TCP_MAXSEG,
423 			       &mss, sizeof(mss)) == -1) {
424 			perror("setsockopt TCP_MAXSEG");
425 			exit(1);
426 		}
427 		if (bind(fdlisten, (const struct sockaddr *)&listenaddr, cfg_alen) == -1) {
428 			perror("bind");
429 			exit(1);
430 		}
431 		if (listen(fdlisten, 128) == -1) {
432 			perror("listen");
433 			exit(1);
434 		}
435 		do_accept(fdlisten);
436 	}
437 	buffer = mmap(NULL, chunk_size, PROT_READ | PROT_WRITE,
438 			      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
439 	if (buffer == (char *)-1) {
440 		perror("mmap");
441 		exit(1);
442 	}
443 
444 	fd = socket(cfg_family, SOCK_STREAM, 0);
445 	if (fd == -1) {
446 		perror("socket");
447 		exit(1);
448 	}
449 	apply_rcvsnd_buf(fd);
450 
451 	setup_sockaddr(cfg_family, host, &addr);
452 
453 	if (mss &&
454 	    setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &mss, sizeof(mss)) == -1) {
455 		perror("setsockopt TCP_MAXSEG");
456 		exit(1);
457 	}
458 	if (connect(fd, (const struct sockaddr *)&addr, cfg_alen) == -1) {
459 		perror("connect");
460 		exit(1);
461 	}
462 	if (max_pacing_rate &&
463 	    setsockopt(fd, SOL_SOCKET, SO_MAX_PACING_RATE,
464 		       &max_pacing_rate, sizeof(max_pacing_rate)) == -1)
465 		perror("setsockopt SO_MAX_PACING_RATE");
466 
467 	if (zflg && setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY,
468 			       &on, sizeof(on)) == -1) {
469 		perror("setsockopt SO_ZEROCOPY, (-z option disabled)");
470 		zflg = 0;
471 	}
472 	while (total < FILE_SZ) {
473 		ssize_t wr = FILE_SZ - total;
474 
475 		if (wr > chunk_size)
476 			wr = chunk_size;
477 		/* Note : we just want to fill the pipe with 0 bytes */
478 		wr = send(fd, buffer, wr, zflg ? MSG_ZEROCOPY : 0);
479 		if (wr <= 0)
480 			break;
481 		total += wr;
482 	}
483 	close(fd);
484 	munmap(buffer, chunk_size);
485 	return 0;
486 }
487