1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright 2018 Google Inc.
4 * Author: Eric Dumazet (edumazet@google.com)
6 * Reference program demonstrating tcp mmap() usage,
7 * and SO_RCVLOWAT hints for receiver.
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.
12 * How to use on loopback interface :
14 * ifconfig lo mtu 61512 # 15*4096 + 40 (ipv6 header) + 32 (TCP with TS option header)
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))
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 ;)
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
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
51 #include <sys/types.h>
54 #include <sys/socket.h>
56 #include <sys/resource.h>
64 #include <netinet/in.h>
65 #include <arpa/inet.h>
67 #include <linux/tcp.h>
69 #include <openssl/pem.h>
72 #define MSG_ZEROCOPY 0x4000000
76 #define min(a, b) ((a) < (b) ? (a) : (b))
79 #define FILE_SZ (1ULL << 35)
80 static int cfg_family = AF_INET6;
81 static socklen_t cfg_alen = sizeof(struct sockaddr_in6);
82 static int cfg_port = 8787;
84 static int rcvbuf; /* Default: autotuning. Can be set with -r <integer> option */
85 static int sndbuf; /* Default: autotuning. Can be set with -w <integer> option */
86 static int zflg; /* zero copy option. (MSG_ZEROCOPY for sender, mmap() for receiver */
87 static int xflg; /* hash received data (simple xor) (-h option) */
88 static int keepflag; /* -k option: receiver shall keep all received file in memory (no munmap() calls) */
89 static int integrity; /* -i option: sender and receiver compute sha256 over the data.*/
91 static size_t chunk_size = 512*1024;
93 static size_t map_align;
96 unsigned int digest_len;
98 static inline void prefetch(const void *x)
100 #if defined(__x86_64__)
101 asm volatile("prefetcht0 %P0" : : "m" (*(const char *)x));
105 void hash_zone(void *zone, unsigned int length)
107 unsigned long temp = htotal;
109 while (length >= 8*sizeof(long)) {
110 prefetch(zone + 384);
111 temp ^= *(unsigned long *)zone;
112 temp ^= *(unsigned long *)(zone + sizeof(long));
113 temp ^= *(unsigned long *)(zone + 2*sizeof(long));
114 temp ^= *(unsigned long *)(zone + 3*sizeof(long));
115 temp ^= *(unsigned long *)(zone + 4*sizeof(long));
116 temp ^= *(unsigned long *)(zone + 5*sizeof(long));
117 temp ^= *(unsigned long *)(zone + 6*sizeof(long));
118 temp ^= *(unsigned long *)(zone + 7*sizeof(long));
119 zone += 8*sizeof(long);
120 length -= 8*sizeof(long);
122 while (length >= 1) {
123 temp ^= *(unsigned char *)zone;
130 #define ALIGN_UP(x, align_to) (((x) + ((align_to)-1)) & ~((align_to)-1))
131 #define ALIGN_PTR_UP(p, ptr_align_to) ((typeof(p))ALIGN_UP((unsigned long)(p), ptr_align_to))
134 static void *mmap_large_buffer(size_t need, size_t *allocated)
139 /* Attempt to use huge pages if possible. */
140 sz = ALIGN_UP(need, map_align);
141 buffer = mmap(NULL, sz, PROT_READ | PROT_WRITE,
142 MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
144 if (buffer == (void *)-1) {
146 buffer = mmap(NULL, sz, PROT_READ | PROT_WRITE,
147 MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE,
149 if (buffer != (void *)-1)
150 fprintf(stderr, "MAP_HUGETLB attempt failed, look at /sys/kernel/mm/hugepages for optimal performance\n");
156 static uint32_t tcp_info_get_rcv_mss(int fd)
158 socklen_t sz = sizeof(struct tcp_info);
159 struct tcp_info info;
161 if (getsockopt(fd, IPPROTO_TCP, TCP_INFO, &info, &sz)) {
162 fprintf(stderr, "Error fetching TCP_INFO\n");
166 return info.tcpi_rcv_mss;
169 void *child_thread(void *arg)
171 unsigned char digest[SHA256_DIGEST_LENGTH];
172 unsigned long total_mmap = 0, total = 0;
173 struct tcp_zerocopy_receive zc;
174 unsigned char *buffer = NULL;
175 unsigned long delta_usec;
176 EVP_MD_CTX *ctx = NULL;
177 int flags = MAP_SHARED;
178 struct timeval t0, t1;
186 fd = (int)(unsigned long)arg;
188 gettimeofday(&t0, NULL);
190 fcntl(fd, F_SETFL, O_NDELAY);
191 buffer = mmap_large_buffer(chunk_size, &buffer_sz);
192 if (buffer == (void *)-1) {
197 raddr = mmap(NULL, chunk_size + map_align, PROT_READ, flags, fd, 0);
198 if (raddr == (void *)-1) {
202 addr = ALIGN_PTR_UP(raddr, map_align);
206 ctx = EVP_MD_CTX_new();
208 perror("cannot enable SHA computing");
211 EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
214 struct pollfd pfd = { .fd = fd, .events = POLLIN, };
217 poll(&pfd, 1, 10000);
219 socklen_t zc_len = sizeof(zc);
222 memset(&zc, 0, sizeof(zc));
223 zc.address = (__u64)((unsigned long)addr);
224 zc.length = min(chunk_size, FILE_SZ - total);
226 res = getsockopt(fd, IPPROTO_TCP, TCP_ZEROCOPY_RECEIVE,
232 assert(zc.length <= chunk_size);
234 EVP_DigestUpdate(ctx, addr, zc.length);
235 total_mmap += zc.length;
237 hash_zone(addr, zc.length);
238 /* It is more efficient to unmap the pages right now,
239 * instead of doing this in next TCP_ZEROCOPY_RECEIVE.
241 madvise(addr, zc.length, MADV_DONTNEED);
244 if (zc.recv_skip_hint) {
245 assert(zc.recv_skip_hint <= chunk_size);
246 lu = read(fd, buffer, min(zc.recv_skip_hint,
250 EVP_DigestUpdate(ctx, buffer, lu);
252 hash_zone(buffer, lu);
261 while (sub < chunk_size) {
262 lu = read(fd, buffer + sub, min(chunk_size - sub,
269 EVP_DigestUpdate(ctx, buffer + sub, lu);
271 hash_zone(buffer + sub, lu);
277 gettimeofday(&t1, NULL);
278 delta_usec = (t1.tv_sec - t0.tv_sec) * 1000000 + t1.tv_usec - t0.tv_usec;
281 fcntl(fd, F_SETFL, 0);
282 EVP_DigestFinal_ex(ctx, digest, &digest_len);
283 lu = read(fd, buffer, SHA256_DIGEST_LENGTH);
284 if (lu != SHA256_DIGEST_LENGTH)
285 perror("Error: Cannot read SHA256\n");
287 if (memcmp(digest, buffer,
288 SHA256_DIGEST_LENGTH))
289 fprintf(stderr, "Error: SHA256 of the data is not right\n");
291 printf("\nSHA256 is correct\n");
296 throughput = total * 8.0 / (double)delta_usec / 1000.0;
297 getrusage(RUSAGE_THREAD, &ru);
298 if (total > 1024*1024) {
299 unsigned long total_usec;
300 unsigned long mb = total >> 20;
301 total_usec = 1000000*ru.ru_utime.tv_sec + ru.ru_utime.tv_usec +
302 1000000*ru.ru_stime.tv_sec + ru.ru_stime.tv_usec;
303 printf("received %lg MB (%lg %% mmap'ed) in %lg s, %lg Gbit\n"
304 " cpu usage user:%lg sys:%lg, %lg usec per MB, %lu c-switches, rcv_mss %u\n",
305 total / (1024.0 * 1024.0),
306 100.0*total_mmap/total,
307 (double)delta_usec / 1000000.0,
309 (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000.0,
310 (double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec / 1000000.0,
311 (double)total_usec/mb,
313 tcp_info_get_rcv_mss(fd));
316 munmap(buffer, buffer_sz);
319 munmap(raddr, chunk_size + map_align);
323 static void apply_rcvsnd_buf(int fd)
325 if (rcvbuf && setsockopt(fd, SOL_SOCKET,
326 SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) == -1) {
327 perror("setsockopt SO_RCVBUF");
330 if (sndbuf && setsockopt(fd, SOL_SOCKET,
331 SO_SNDBUF, &sndbuf, sizeof(sndbuf)) == -1) {
332 perror("setsockopt SO_SNDBUF");
337 static void setup_sockaddr(int domain, const char *str_addr,
338 struct sockaddr_storage *sockaddr)
340 struct sockaddr_in6 *addr6 = (void *) sockaddr;
341 struct sockaddr_in *addr4 = (void *) sockaddr;
345 memset(addr4, 0, sizeof(*addr4));
346 addr4->sin_family = AF_INET;
347 addr4->sin_port = htons(cfg_port);
349 inet_pton(AF_INET, str_addr, &(addr4->sin_addr)) != 1)
350 error(1, 0, "ipv4 parse error: %s", str_addr);
353 memset(addr6, 0, sizeof(*addr6));
354 addr6->sin6_family = AF_INET6;
355 addr6->sin6_port = htons(cfg_port);
357 inet_pton(AF_INET6, str_addr, &(addr6->sin6_addr)) != 1)
358 error(1, 0, "ipv6 parse error: %s", str_addr);
361 error(1, 0, "illegal domain");
365 static void do_accept(int fdlisten)
370 pthread_attr_init(&attr);
371 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
373 rcvlowat = chunk_size;
374 if (setsockopt(fdlisten, SOL_SOCKET, SO_RCVLOWAT,
375 &rcvlowat, sizeof(rcvlowat)) == -1) {
376 perror("setsockopt SO_RCVLOWAT");
379 apply_rcvsnd_buf(fdlisten);
382 struct sockaddr_in addr;
383 socklen_t addrlen = sizeof(addr);
387 fd = accept(fdlisten, (struct sockaddr *)&addr, &addrlen);
392 res = pthread_create(&th, &attr, child_thread,
393 (void *)(unsigned long)fd);
396 perror("pthread_create");
402 /* Each thread should reserve a big enough vma to avoid
403 * spinlock collisions in ptl locks.
404 * This size is 2MB on x86_64, and is exported in /proc/meminfo.
406 static unsigned long default_huge_page_size(void)
408 FILE *f = fopen("/proc/meminfo", "r");
409 unsigned long hps = 0;
415 while (getline(&line, &linelen, f) > 0) {
416 if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) {
426 static void randomize(void *target, size_t count)
428 static int urandom = -1;
431 urandom = open("/dev/urandom", O_RDONLY);
433 perror("open /dev/urandom");
436 got = read(urandom, target, count);
438 perror("read /dev/urandom");
443 int main(int argc, char *argv[])
445 unsigned char digest[SHA256_DIGEST_LENGTH];
446 struct sockaddr_storage listenaddr, addr;
447 unsigned int max_pacing_rate = 0;
448 EVP_MD_CTX *ctx = NULL;
449 unsigned char *buffer;
457 while ((c = getopt(argc, argv, "46p:svr:w:H:zxkP:M:C:a:i")) != -1) {
460 cfg_family = PF_INET;
461 cfg_alen = sizeof(struct sockaddr_in);
464 cfg_family = PF_INET6;
465 cfg_alen = sizeof(struct sockaddr_in6);
468 cfg_port = atoi(optarg);
473 case 's': /* server : listen for incoming connections */
477 rcvbuf = atoi(optarg);
480 sndbuf = atoi(optarg);
495 max_pacing_rate = atoi(optarg) ;
498 chunk_size = atol(optarg);
501 map_align = atol(optarg);
511 map_align = default_huge_page_size();
512 /* if really /proc/meminfo is not helping,
513 * we use the default x86_64 hugepagesize.
516 map_align = 2*1024*1024;
519 int fdlisten = socket(cfg_family, SOCK_STREAM, 0);
521 if (fdlisten == -1) {
525 apply_rcvsnd_buf(fdlisten);
526 setsockopt(fdlisten, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
528 setup_sockaddr(cfg_family, host, &listenaddr);
531 setsockopt(fdlisten, IPPROTO_TCP, TCP_MAXSEG,
532 &mss, sizeof(mss)) == -1) {
533 perror("setsockopt TCP_MAXSEG");
536 if (bind(fdlisten, (const struct sockaddr *)&listenaddr, cfg_alen) == -1) {
540 if (listen(fdlisten, 128) == -1) {
547 buffer = mmap_large_buffer(chunk_size, &buffer_sz);
548 if (buffer == (unsigned char *)-1) {
553 fd = socket(cfg_family, SOCK_STREAM, 0);
558 apply_rcvsnd_buf(fd);
560 setup_sockaddr(cfg_family, host, &addr);
563 setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &mss, sizeof(mss)) == -1) {
564 perror("setsockopt TCP_MAXSEG");
567 if (connect(fd, (const struct sockaddr *)&addr, cfg_alen) == -1) {
571 if (max_pacing_rate &&
572 setsockopt(fd, SOL_SOCKET, SO_MAX_PACING_RATE,
573 &max_pacing_rate, sizeof(max_pacing_rate)) == -1)
574 perror("setsockopt SO_MAX_PACING_RATE");
576 if (zflg && setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY,
577 &on, sizeof(on)) == -1) {
578 perror("setsockopt SO_ZEROCOPY, (-z option disabled)");
582 randomize(buffer, buffer_sz);
583 ctx = EVP_MD_CTX_new();
585 perror("cannot enable SHA computing");
588 EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
590 while (total < FILE_SZ) {
591 size_t offset = total % chunk_size;
592 int64_t wr = FILE_SZ - total;
594 if (wr > chunk_size - offset)
595 wr = chunk_size - offset;
596 /* Note : we just want to fill the pipe with random bytes */
597 wr = send(fd, buffer + offset,
598 (size_t)wr, zflg ? MSG_ZEROCOPY : 0);
602 EVP_DigestUpdate(ctx, buffer + offset, wr);
605 if (integrity && total == FILE_SZ) {
606 EVP_DigestFinal_ex(ctx, digest, &digest_len);
607 send(fd, digest, (size_t)SHA256_DIGEST_LENGTH, 0);
610 munmap(buffer, buffer_sz);