1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Stress userfaultfd syscall.
4  *
5  *  Copyright (C) 2015  Red Hat, Inc.
6  *
7  * This test allocates two virtual areas and bounces the physical
8  * memory across the two virtual areas (from area_src to area_dst)
9  * using userfaultfd.
10  *
11  * There are three threads running per CPU:
12  *
13  * 1) one per-CPU thread takes a per-page pthread_mutex in a random
14  *    page of the area_dst (while the physical page may still be in
15  *    area_src), and increments a per-page counter in the same page,
16  *    and checks its value against a verification region.
17  *
18  * 2) another per-CPU thread handles the userfaults generated by
19  *    thread 1 above. userfaultfd blocking reads or poll() modes are
20  *    exercised interleaved.
21  *
22  * 3) one last per-CPU thread transfers the memory in the background
23  *    at maximum bandwidth (if not already transferred by thread
24  *    2). Each cpu thread takes cares of transferring a portion of the
25  *    area.
26  *
27  * When all threads of type 3 completed the transfer, one bounce is
28  * complete. area_src and area_dst are then swapped. All threads are
29  * respawned and so the bounce is immediately restarted in the
30  * opposite direction.
31  *
32  * per-CPU threads 1 by triggering userfaults inside
33  * pthread_mutex_lock will also verify the atomicity of the memory
34  * transfer (UFFDIO_COPY).
35  */
36 
37 #define _GNU_SOURCE
38 #include <stdio.h>
39 #include <errno.h>
40 #include <unistd.h>
41 #include <stdlib.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45 #include <time.h>
46 #include <signal.h>
47 #include <poll.h>
48 #include <string.h>
49 #include <sys/mman.h>
50 #include <sys/syscall.h>
51 #include <sys/ioctl.h>
52 #include <sys/wait.h>
53 #include <pthread.h>
54 #include <linux/userfaultfd.h>
55 #include <setjmp.h>
56 #include <stdbool.h>
57 #include <assert.h>
58 
59 #include "../kselftest.h"
60 
61 #ifdef __NR_userfaultfd
62 
63 static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size;
64 
65 #define BOUNCE_RANDOM		(1<<0)
66 #define BOUNCE_RACINGFAULTS	(1<<1)
67 #define BOUNCE_VERIFY		(1<<2)
68 #define BOUNCE_POLL		(1<<3)
69 static int bounces;
70 
71 #define TEST_ANON	1
72 #define TEST_HUGETLB	2
73 #define TEST_SHMEM	3
74 static int test_type;
75 
76 /* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
77 #define ALARM_INTERVAL_SECS 10
78 static volatile bool test_uffdio_copy_eexist = true;
79 static volatile bool test_uffdio_zeropage_eexist = true;
80 /* Whether to test uffd write-protection */
81 static bool test_uffdio_wp = false;
82 
83 static bool map_shared;
84 static int huge_fd;
85 static char *huge_fd_off0;
86 static unsigned long long *count_verify;
87 static int uffd, uffd_flags, finished, *pipefd;
88 static char *area_src, *area_src_alias, *area_dst, *area_dst_alias;
89 static char *zeropage;
90 pthread_attr_t attr;
91 
92 /* Userfaultfd test statistics */
93 struct uffd_stats {
94 	int cpu;
95 	unsigned long missing_faults;
96 	unsigned long wp_faults;
97 };
98 
99 /* pthread_mutex_t starts at page offset 0 */
100 #define area_mutex(___area, ___nr)					\
101 	((pthread_mutex_t *) ((___area) + (___nr)*page_size))
102 /*
103  * count is placed in the page after pthread_mutex_t naturally aligned
104  * to avoid non alignment faults on non-x86 archs.
105  */
106 #define area_count(___area, ___nr)					\
107 	((volatile unsigned long long *) ((unsigned long)		\
108 				 ((___area) + (___nr)*page_size +	\
109 				  sizeof(pthread_mutex_t) +		\
110 				  sizeof(unsigned long long) - 1) &	\
111 				 ~(unsigned long)(sizeof(unsigned long long) \
112 						  -  1)))
113 
114 const char *examples =
115     "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
116     "./userfaultfd anon 100 99999\n\n"
117     "# Run share memory test on 1GiB region with 99 bounces:\n"
118     "./userfaultfd shmem 1000 99\n\n"
119     "# Run hugetlb memory test on 256MiB region with 50 bounces (using /dev/hugepages/hugefile):\n"
120     "./userfaultfd hugetlb 256 50 /dev/hugepages/hugefile\n\n"
121     "# Run the same hugetlb test but using shmem:\n"
122     "./userfaultfd hugetlb_shared 256 50 /dev/hugepages/hugefile\n\n"
123     "# 10MiB-~6GiB 999 bounces anonymous test, "
124     "continue forever unless an error triggers\n"
125     "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
126 
usage(void)127 static void usage(void)
128 {
129 	fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
130 		"[hugetlbfs_file]\n\n");
131 	fprintf(stderr, "Supported <test type>: anon, hugetlb, "
132 		"hugetlb_shared, shmem\n\n");
133 	fprintf(stderr, "Examples:\n\n");
134 	fprintf(stderr, "%s", examples);
135 	exit(1);
136 }
137 
uffd_stats_reset(struct uffd_stats * uffd_stats,unsigned long n_cpus)138 static void uffd_stats_reset(struct uffd_stats *uffd_stats,
139 			     unsigned long n_cpus)
140 {
141 	int i;
142 
143 	for (i = 0; i < n_cpus; i++) {
144 		uffd_stats[i].cpu = i;
145 		uffd_stats[i].missing_faults = 0;
146 		uffd_stats[i].wp_faults = 0;
147 	}
148 }
149 
uffd_stats_report(struct uffd_stats * stats,int n_cpus)150 static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
151 {
152 	int i;
153 	unsigned long long miss_total = 0, wp_total = 0;
154 
155 	for (i = 0; i < n_cpus; i++) {
156 		miss_total += stats[i].missing_faults;
157 		wp_total += stats[i].wp_faults;
158 	}
159 
160 	printf("userfaults: %llu missing (", miss_total);
161 	for (i = 0; i < n_cpus; i++)
162 		printf("%lu+", stats[i].missing_faults);
163 	printf("\b), %llu wp (", wp_total);
164 	for (i = 0; i < n_cpus; i++)
165 		printf("%lu+", stats[i].wp_faults);
166 	printf("\b)\n");
167 }
168 
anon_release_pages(char * rel_area)169 static int anon_release_pages(char *rel_area)
170 {
171 	int ret = 0;
172 
173 	if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED)) {
174 		perror("madvise");
175 		ret = 1;
176 	}
177 
178 	return ret;
179 }
180 
anon_allocate_area(void ** alloc_area)181 static void anon_allocate_area(void **alloc_area)
182 {
183 	if (posix_memalign(alloc_area, page_size, nr_pages * page_size)) {
184 		fprintf(stderr, "out of memory\n");
185 		*alloc_area = NULL;
186 	}
187 }
188 
noop_alias_mapping(__u64 * start,size_t len,unsigned long offset)189 static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
190 {
191 }
192 
193 /* HugeTLB memory */
hugetlb_release_pages(char * rel_area)194 static int hugetlb_release_pages(char *rel_area)
195 {
196 	int ret = 0;
197 
198 	if (fallocate(huge_fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
199 				rel_area == huge_fd_off0 ? 0 :
200 				nr_pages * page_size,
201 				nr_pages * page_size)) {
202 		perror("fallocate");
203 		ret = 1;
204 	}
205 
206 	return ret;
207 }
208 
hugetlb_allocate_area(void ** alloc_area)209 static void hugetlb_allocate_area(void **alloc_area)
210 {
211 	void *area_alias = NULL;
212 	char **alloc_area_alias;
213 
214 	*alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
215 			   (map_shared ? MAP_SHARED : MAP_PRIVATE) |
216 			   MAP_HUGETLB,
217 			   huge_fd, *alloc_area == area_src ? 0 :
218 			   nr_pages * page_size);
219 	if (*alloc_area == MAP_FAILED) {
220 		perror("mmap of hugetlbfs file failed");
221 		goto fail;
222 	}
223 
224 	if (map_shared) {
225 		area_alias = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
226 				  MAP_SHARED | MAP_HUGETLB,
227 				  huge_fd, *alloc_area == area_src ? 0 :
228 				  nr_pages * page_size);
229 		if (area_alias == MAP_FAILED) {
230 			perror("mmap of hugetlb file alias failed");
231 			goto fail_munmap;
232 		}
233 	}
234 
235 	if (*alloc_area == area_src) {
236 		huge_fd_off0 = *alloc_area;
237 		alloc_area_alias = &area_src_alias;
238 	} else {
239 		alloc_area_alias = &area_dst_alias;
240 	}
241 	if (area_alias)
242 		*alloc_area_alias = area_alias;
243 
244 	return;
245 
246 fail_munmap:
247 	if (munmap(*alloc_area, nr_pages * page_size) < 0) {
248 		perror("hugetlb munmap");
249 		exit(1);
250 	}
251 fail:
252 	*alloc_area = NULL;
253 }
254 
hugetlb_alias_mapping(__u64 * start,size_t len,unsigned long offset)255 static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
256 {
257 	if (!map_shared)
258 		return;
259 	/*
260 	 * We can't zap just the pagetable with hugetlbfs because
261 	 * MADV_DONTEED won't work. So exercise -EEXIST on a alias
262 	 * mapping where the pagetables are not established initially,
263 	 * this way we'll exercise the -EEXEC at the fs level.
264 	 */
265 	*start = (unsigned long) area_dst_alias + offset;
266 }
267 
268 /* Shared memory */
shmem_release_pages(char * rel_area)269 static int shmem_release_pages(char *rel_area)
270 {
271 	int ret = 0;
272 
273 	if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE)) {
274 		perror("madvise");
275 		ret = 1;
276 	}
277 
278 	return ret;
279 }
280 
shmem_allocate_area(void ** alloc_area)281 static void shmem_allocate_area(void **alloc_area)
282 {
283 	*alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
284 			   MAP_ANONYMOUS | MAP_SHARED, -1, 0);
285 	if (*alloc_area == MAP_FAILED) {
286 		fprintf(stderr, "shared memory mmap failed\n");
287 		*alloc_area = NULL;
288 	}
289 }
290 
291 struct uffd_test_ops {
292 	unsigned long expected_ioctls;
293 	void (*allocate_area)(void **alloc_area);
294 	int (*release_pages)(char *rel_area);
295 	void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
296 };
297 
298 #define SHMEM_EXPECTED_IOCTLS		((1 << _UFFDIO_WAKE) | \
299 					 (1 << _UFFDIO_COPY) | \
300 					 (1 << _UFFDIO_ZEROPAGE))
301 
302 #define ANON_EXPECTED_IOCTLS		((1 << _UFFDIO_WAKE) | \
303 					 (1 << _UFFDIO_COPY) | \
304 					 (1 << _UFFDIO_ZEROPAGE) | \
305 					 (1 << _UFFDIO_WRITEPROTECT))
306 
307 static struct uffd_test_ops anon_uffd_test_ops = {
308 	.expected_ioctls = ANON_EXPECTED_IOCTLS,
309 	.allocate_area	= anon_allocate_area,
310 	.release_pages	= anon_release_pages,
311 	.alias_mapping = noop_alias_mapping,
312 };
313 
314 static struct uffd_test_ops shmem_uffd_test_ops = {
315 	.expected_ioctls = SHMEM_EXPECTED_IOCTLS,
316 	.allocate_area	= shmem_allocate_area,
317 	.release_pages	= shmem_release_pages,
318 	.alias_mapping = noop_alias_mapping,
319 };
320 
321 static struct uffd_test_ops hugetlb_uffd_test_ops = {
322 	.expected_ioctls = UFFD_API_RANGE_IOCTLS_BASIC,
323 	.allocate_area	= hugetlb_allocate_area,
324 	.release_pages	= hugetlb_release_pages,
325 	.alias_mapping = hugetlb_alias_mapping,
326 };
327 
328 static struct uffd_test_ops *uffd_test_ops;
329 
my_bcmp(char * str1,char * str2,size_t n)330 static int my_bcmp(char *str1, char *str2, size_t n)
331 {
332 	unsigned long i;
333 	for (i = 0; i < n; i++)
334 		if (str1[i] != str2[i])
335 			return 1;
336 	return 0;
337 }
338 
wp_range(int ufd,__u64 start,__u64 len,bool wp)339 static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
340 {
341 	struct uffdio_writeprotect prms = { 0 };
342 
343 	/* Write protection page faults */
344 	prms.range.start = start;
345 	prms.range.len = len;
346 	/* Undo write-protect, do wakeup after that */
347 	prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
348 
349 	if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms)) {
350 		fprintf(stderr, "clear WP failed for address 0x%Lx\n", start);
351 		exit(1);
352 	}
353 }
354 
locking_thread(void * arg)355 static void *locking_thread(void *arg)
356 {
357 	unsigned long cpu = (unsigned long) arg;
358 	struct random_data rand;
359 	unsigned long page_nr = *(&(page_nr)); /* uninitialized warning */
360 	int32_t rand_nr;
361 	unsigned long long count;
362 	char randstate[64];
363 	unsigned int seed;
364 	time_t start;
365 
366 	if (bounces & BOUNCE_RANDOM) {
367 		seed = (unsigned int) time(NULL) - bounces;
368 		if (!(bounces & BOUNCE_RACINGFAULTS))
369 			seed += cpu;
370 		bzero(&rand, sizeof(rand));
371 		bzero(&randstate, sizeof(randstate));
372 		if (initstate_r(seed, randstate, sizeof(randstate), &rand)) {
373 			fprintf(stderr, "srandom_r error\n");
374 			exit(1);
375 		}
376 	} else {
377 		page_nr = -bounces;
378 		if (!(bounces & BOUNCE_RACINGFAULTS))
379 			page_nr += cpu * nr_pages_per_cpu;
380 	}
381 
382 	while (!finished) {
383 		if (bounces & BOUNCE_RANDOM) {
384 			if (random_r(&rand, &rand_nr)) {
385 				fprintf(stderr, "random_r 1 error\n");
386 				exit(1);
387 			}
388 			page_nr = rand_nr;
389 			if (sizeof(page_nr) > sizeof(rand_nr)) {
390 				if (random_r(&rand, &rand_nr)) {
391 					fprintf(stderr, "random_r 2 error\n");
392 					exit(1);
393 				}
394 				page_nr |= (((unsigned long) rand_nr) << 16) <<
395 					   16;
396 			}
397 		} else
398 			page_nr += 1;
399 		page_nr %= nr_pages;
400 
401 		start = time(NULL);
402 		if (bounces & BOUNCE_VERIFY) {
403 			count = *area_count(area_dst, page_nr);
404 			if (!count) {
405 				fprintf(stderr,
406 					"page_nr %lu wrong count %Lu %Lu\n",
407 					page_nr, count,
408 					count_verify[page_nr]);
409 				exit(1);
410 			}
411 
412 
413 			/*
414 			 * We can't use bcmp (or memcmp) because that
415 			 * returns 0 erroneously if the memory is
416 			 * changing under it (even if the end of the
417 			 * page is never changing and always
418 			 * different).
419 			 */
420 #if 1
421 			if (!my_bcmp(area_dst + page_nr * page_size, zeropage,
422 				     page_size)) {
423 				fprintf(stderr,
424 					"my_bcmp page_nr %lu wrong count %Lu %Lu\n",
425 					page_nr, count, count_verify[page_nr]);
426 				exit(1);
427 			}
428 #else
429 			unsigned long loops;
430 
431 			loops = 0;
432 			/* uncomment the below line to test with mutex */
433 			/* pthread_mutex_lock(area_mutex(area_dst, page_nr)); */
434 			while (!bcmp(area_dst + page_nr * page_size, zeropage,
435 				     page_size)) {
436 				loops += 1;
437 				if (loops > 10)
438 					break;
439 			}
440 			/* uncomment below line to test with mutex */
441 			/* pthread_mutex_unlock(area_mutex(area_dst, page_nr)); */
442 			if (loops) {
443 				fprintf(stderr,
444 					"page_nr %lu all zero thread %lu %p %lu\n",
445 					page_nr, cpu, area_dst + page_nr * page_size,
446 					loops);
447 				if (loops > 10)
448 					exit(1);
449 			}
450 #endif
451 		}
452 
453 		pthread_mutex_lock(area_mutex(area_dst, page_nr));
454 		count = *area_count(area_dst, page_nr);
455 		if (count != count_verify[page_nr]) {
456 			fprintf(stderr,
457 				"page_nr %lu memory corruption %Lu %Lu\n",
458 				page_nr, count,
459 				count_verify[page_nr]); exit(1);
460 		}
461 		count++;
462 		*area_count(area_dst, page_nr) = count_verify[page_nr] = count;
463 		pthread_mutex_unlock(area_mutex(area_dst, page_nr));
464 
465 		if (time(NULL) - start > 1)
466 			fprintf(stderr,
467 				"userfault too slow %ld "
468 				"possible false positive with overcommit\n",
469 				time(NULL) - start);
470 	}
471 
472 	return NULL;
473 }
474 
retry_copy_page(int ufd,struct uffdio_copy * uffdio_copy,unsigned long offset)475 static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
476 			    unsigned long offset)
477 {
478 	uffd_test_ops->alias_mapping(&uffdio_copy->dst,
479 				     uffdio_copy->len,
480 				     offset);
481 	if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
482 		/* real retval in ufdio_copy.copy */
483 		if (uffdio_copy->copy != -EEXIST) {
484 			fprintf(stderr, "UFFDIO_COPY retry error %Ld\n",
485 				uffdio_copy->copy);
486 			exit(1);
487 		}
488 	} else {
489 		fprintf(stderr,	"UFFDIO_COPY retry unexpected %Ld\n",
490 			uffdio_copy->copy); exit(1);
491 	}
492 }
493 
__copy_page(int ufd,unsigned long offset,bool retry)494 static int __copy_page(int ufd, unsigned long offset, bool retry)
495 {
496 	struct uffdio_copy uffdio_copy;
497 
498 	if (offset >= nr_pages * page_size) {
499 		fprintf(stderr, "unexpected offset %lu\n", offset);
500 		exit(1);
501 	}
502 	uffdio_copy.dst = (unsigned long) area_dst + offset;
503 	uffdio_copy.src = (unsigned long) area_src + offset;
504 	uffdio_copy.len = page_size;
505 	if (test_uffdio_wp)
506 		uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
507 	else
508 		uffdio_copy.mode = 0;
509 	uffdio_copy.copy = 0;
510 	if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
511 		/* real retval in ufdio_copy.copy */
512 		if (uffdio_copy.copy != -EEXIST) {
513 			fprintf(stderr, "UFFDIO_COPY error %Ld\n",
514 				uffdio_copy.copy);
515 			exit(1);
516 		}
517 	} else if (uffdio_copy.copy != page_size) {
518 		fprintf(stderr, "UFFDIO_COPY unexpected copy %Ld\n",
519 			uffdio_copy.copy); exit(1);
520 	} else {
521 		if (test_uffdio_copy_eexist && retry) {
522 			test_uffdio_copy_eexist = false;
523 			retry_copy_page(ufd, &uffdio_copy, offset);
524 		}
525 		return 1;
526 	}
527 	return 0;
528 }
529 
copy_page_retry(int ufd,unsigned long offset)530 static int copy_page_retry(int ufd, unsigned long offset)
531 {
532 	return __copy_page(ufd, offset, true);
533 }
534 
copy_page(int ufd,unsigned long offset)535 static int copy_page(int ufd, unsigned long offset)
536 {
537 	return __copy_page(ufd, offset, false);
538 }
539 
uffd_read_msg(int ufd,struct uffd_msg * msg)540 static int uffd_read_msg(int ufd, struct uffd_msg *msg)
541 {
542 	int ret = read(uffd, msg, sizeof(*msg));
543 
544 	if (ret != sizeof(*msg)) {
545 		if (ret < 0) {
546 			if (errno == EAGAIN)
547 				return 1;
548 			perror("blocking read error");
549 		} else {
550 			fprintf(stderr, "short read\n");
551 		}
552 		exit(1);
553 	}
554 
555 	return 0;
556 }
557 
uffd_handle_page_fault(struct uffd_msg * msg,struct uffd_stats * stats)558 static void uffd_handle_page_fault(struct uffd_msg *msg,
559 				   struct uffd_stats *stats)
560 {
561 	unsigned long offset;
562 
563 	if (msg->event != UFFD_EVENT_PAGEFAULT) {
564 		fprintf(stderr, "unexpected msg event %u\n", msg->event);
565 		exit(1);
566 	}
567 
568 	if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
569 		wp_range(uffd, msg->arg.pagefault.address, page_size, false);
570 		stats->wp_faults++;
571 	} else {
572 		/* Missing page faults */
573 		if (bounces & BOUNCE_VERIFY &&
574 		    msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE) {
575 			fprintf(stderr, "unexpected write fault\n");
576 			exit(1);
577 		}
578 
579 		offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
580 		offset &= ~(page_size-1);
581 
582 		if (copy_page(uffd, offset))
583 			stats->missing_faults++;
584 	}
585 }
586 
uffd_poll_thread(void * arg)587 static void *uffd_poll_thread(void *arg)
588 {
589 	struct uffd_stats *stats = (struct uffd_stats *)arg;
590 	unsigned long cpu = stats->cpu;
591 	struct pollfd pollfd[2];
592 	struct uffd_msg msg;
593 	struct uffdio_register uffd_reg;
594 	int ret;
595 	char tmp_chr;
596 
597 	pollfd[0].fd = uffd;
598 	pollfd[0].events = POLLIN;
599 	pollfd[1].fd = pipefd[cpu*2];
600 	pollfd[1].events = POLLIN;
601 
602 	for (;;) {
603 		ret = poll(pollfd, 2, -1);
604 		if (!ret) {
605 			fprintf(stderr, "poll error %d\n", ret);
606 			exit(1);
607 		}
608 		if (ret < 0) {
609 			perror("poll");
610 			exit(1);
611 		}
612 		if (pollfd[1].revents & POLLIN) {
613 			if (read(pollfd[1].fd, &tmp_chr, 1) != 1) {
614 				fprintf(stderr, "read pipefd error\n");
615 				exit(1);
616 			}
617 			break;
618 		}
619 		if (!(pollfd[0].revents & POLLIN)) {
620 			fprintf(stderr, "pollfd[0].revents %d\n",
621 				pollfd[0].revents);
622 			exit(1);
623 		}
624 		if (uffd_read_msg(uffd, &msg))
625 			continue;
626 		switch (msg.event) {
627 		default:
628 			fprintf(stderr, "unexpected msg event %u\n",
629 				msg.event); exit(1);
630 			break;
631 		case UFFD_EVENT_PAGEFAULT:
632 			uffd_handle_page_fault(&msg, stats);
633 			break;
634 		case UFFD_EVENT_FORK:
635 			close(uffd);
636 			uffd = msg.arg.fork.ufd;
637 			pollfd[0].fd = uffd;
638 			break;
639 		case UFFD_EVENT_REMOVE:
640 			uffd_reg.range.start = msg.arg.remove.start;
641 			uffd_reg.range.len = msg.arg.remove.end -
642 				msg.arg.remove.start;
643 			if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range)) {
644 				fprintf(stderr, "remove failure\n");
645 				exit(1);
646 			}
647 			break;
648 		case UFFD_EVENT_REMAP:
649 			area_dst = (char *)(unsigned long)msg.arg.remap.to;
650 			break;
651 		}
652 	}
653 
654 	return NULL;
655 }
656 
657 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
658 
uffd_read_thread(void * arg)659 static void *uffd_read_thread(void *arg)
660 {
661 	struct uffd_stats *stats = (struct uffd_stats *)arg;
662 	struct uffd_msg msg;
663 
664 	pthread_mutex_unlock(&uffd_read_mutex);
665 	/* from here cancellation is ok */
666 
667 	for (;;) {
668 		if (uffd_read_msg(uffd, &msg))
669 			continue;
670 		uffd_handle_page_fault(&msg, stats);
671 	}
672 
673 	return NULL;
674 }
675 
background_thread(void * arg)676 static void *background_thread(void *arg)
677 {
678 	unsigned long cpu = (unsigned long) arg;
679 	unsigned long page_nr, start_nr, mid_nr, end_nr;
680 
681 	start_nr = cpu * nr_pages_per_cpu;
682 	end_nr = (cpu+1) * nr_pages_per_cpu;
683 	mid_nr = (start_nr + end_nr) / 2;
684 
685 	/* Copy the first half of the pages */
686 	for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
687 		copy_page_retry(uffd, page_nr * page_size);
688 
689 	/*
690 	 * If we need to test uffd-wp, set it up now.  Then we'll have
691 	 * at least the first half of the pages mapped already which
692 	 * can be write-protected for testing
693 	 */
694 	if (test_uffdio_wp)
695 		wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
696 			nr_pages_per_cpu * page_size, true);
697 
698 	/*
699 	 * Continue the 2nd half of the page copying, handling write
700 	 * protection faults if any
701 	 */
702 	for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
703 		copy_page_retry(uffd, page_nr * page_size);
704 
705 	return NULL;
706 }
707 
stress(struct uffd_stats * uffd_stats)708 static int stress(struct uffd_stats *uffd_stats)
709 {
710 	unsigned long cpu;
711 	pthread_t locking_threads[nr_cpus];
712 	pthread_t uffd_threads[nr_cpus];
713 	pthread_t background_threads[nr_cpus];
714 
715 	finished = 0;
716 	for (cpu = 0; cpu < nr_cpus; cpu++) {
717 		if (pthread_create(&locking_threads[cpu], &attr,
718 				   locking_thread, (void *)cpu))
719 			return 1;
720 		if (bounces & BOUNCE_POLL) {
721 			if (pthread_create(&uffd_threads[cpu], &attr,
722 					   uffd_poll_thread,
723 					   (void *)&uffd_stats[cpu]))
724 				return 1;
725 		} else {
726 			if (pthread_create(&uffd_threads[cpu], &attr,
727 					   uffd_read_thread,
728 					   (void *)&uffd_stats[cpu]))
729 				return 1;
730 			pthread_mutex_lock(&uffd_read_mutex);
731 		}
732 		if (pthread_create(&background_threads[cpu], &attr,
733 				   background_thread, (void *)cpu))
734 			return 1;
735 	}
736 	for (cpu = 0; cpu < nr_cpus; cpu++)
737 		if (pthread_join(background_threads[cpu], NULL))
738 			return 1;
739 
740 	/*
741 	 * Be strict and immediately zap area_src, the whole area has
742 	 * been transferred already by the background treads. The
743 	 * area_src could then be faulted in in a racy way by still
744 	 * running uffdio_threads reading zeropages after we zapped
745 	 * area_src (but they're guaranteed to get -EEXIST from
746 	 * UFFDIO_COPY without writing zero pages into area_dst
747 	 * because the background threads already completed).
748 	 */
749 	if (uffd_test_ops->release_pages(area_src))
750 		return 1;
751 
752 
753 	finished = 1;
754 	for (cpu = 0; cpu < nr_cpus; cpu++)
755 		if (pthread_join(locking_threads[cpu], NULL))
756 			return 1;
757 
758 	for (cpu = 0; cpu < nr_cpus; cpu++) {
759 		char c;
760 		if (bounces & BOUNCE_POLL) {
761 			if (write(pipefd[cpu*2+1], &c, 1) != 1) {
762 				fprintf(stderr, "pipefd write error\n");
763 				return 1;
764 			}
765 			if (pthread_join(uffd_threads[cpu],
766 					 (void *)&uffd_stats[cpu]))
767 				return 1;
768 		} else {
769 			if (pthread_cancel(uffd_threads[cpu]))
770 				return 1;
771 			if (pthread_join(uffd_threads[cpu], NULL))
772 				return 1;
773 		}
774 	}
775 
776 	return 0;
777 }
778 
userfaultfd_open(int features)779 static int userfaultfd_open(int features)
780 {
781 	struct uffdio_api uffdio_api;
782 
783 	uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
784 	if (uffd < 0) {
785 		fprintf(stderr,
786 			"userfaultfd syscall not available in this kernel\n");
787 		return 1;
788 	}
789 	uffd_flags = fcntl(uffd, F_GETFD, NULL);
790 
791 	uffdio_api.api = UFFD_API;
792 	uffdio_api.features = features;
793 	if (ioctl(uffd, UFFDIO_API, &uffdio_api)) {
794 		fprintf(stderr, "UFFDIO_API\n");
795 		return 1;
796 	}
797 	if (uffdio_api.api != UFFD_API) {
798 		fprintf(stderr, "UFFDIO_API error %Lu\n", uffdio_api.api);
799 		return 1;
800 	}
801 
802 	return 0;
803 }
804 
805 sigjmp_buf jbuf, *sigbuf;
806 
sighndl(int sig,siginfo_t * siginfo,void * ptr)807 static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
808 {
809 	if (sig == SIGBUS) {
810 		if (sigbuf)
811 			siglongjmp(*sigbuf, 1);
812 		abort();
813 	}
814 }
815 
816 /*
817  * For non-cooperative userfaultfd test we fork() a process that will
818  * generate pagefaults, will mremap the area monitored by the
819  * userfaultfd and at last this process will release the monitored
820  * area.
821  * For the anonymous and shared memory the area is divided into two
822  * parts, the first part is accessed before mremap, and the second
823  * part is accessed after mremap. Since hugetlbfs does not support
824  * mremap, the entire monitored area is accessed in a single pass for
825  * HUGETLB_TEST.
826  * The release of the pages currently generates event for shmem and
827  * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
828  * for hugetlb.
829  * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
830  * monitored area, generate pagefaults and test that signal is delivered.
831  * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
832  * test robustness use case - we release monitored area, fork a process
833  * that will generate pagefaults and verify signal is generated.
834  * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
835  * feature. Using monitor thread, verify no userfault events are generated.
836  */
faulting_process(int signal_test)837 static int faulting_process(int signal_test)
838 {
839 	unsigned long nr;
840 	unsigned long long count;
841 	unsigned long split_nr_pages;
842 	unsigned long lastnr;
843 	struct sigaction act;
844 	unsigned long signalled = 0;
845 
846 	if (test_type != TEST_HUGETLB)
847 		split_nr_pages = (nr_pages + 1) / 2;
848 	else
849 		split_nr_pages = nr_pages;
850 
851 	if (signal_test) {
852 		sigbuf = &jbuf;
853 		memset(&act, 0, sizeof(act));
854 		act.sa_sigaction = sighndl;
855 		act.sa_flags = SA_SIGINFO;
856 		if (sigaction(SIGBUS, &act, 0)) {
857 			perror("sigaction");
858 			return 1;
859 		}
860 		lastnr = (unsigned long)-1;
861 	}
862 
863 	for (nr = 0; nr < split_nr_pages; nr++) {
864 		int steps = 1;
865 		unsigned long offset = nr * page_size;
866 
867 		if (signal_test) {
868 			if (sigsetjmp(*sigbuf, 1) != 0) {
869 				if (steps == 1 && nr == lastnr) {
870 					fprintf(stderr, "Signal repeated\n");
871 					return 1;
872 				}
873 
874 				lastnr = nr;
875 				if (signal_test == 1) {
876 					if (steps == 1) {
877 						/* This is a MISSING request */
878 						steps++;
879 						if (copy_page(uffd, offset))
880 							signalled++;
881 					} else {
882 						/* This is a WP request */
883 						assert(steps == 2);
884 						wp_range(uffd,
885 							 (__u64)area_dst +
886 							 offset,
887 							 page_size, false);
888 					}
889 				} else {
890 					signalled++;
891 					continue;
892 				}
893 			}
894 		}
895 
896 		count = *area_count(area_dst, nr);
897 		if (count != count_verify[nr]) {
898 			fprintf(stderr,
899 				"nr %lu memory corruption %Lu %Lu\n",
900 				nr, count,
901 				count_verify[nr]);
902 	        }
903 		/*
904 		 * Trigger write protection if there is by writting
905 		 * the same value back.
906 		 */
907 		*area_count(area_dst, nr) = count;
908 	}
909 
910 	if (signal_test)
911 		return signalled != split_nr_pages;
912 
913 	if (test_type == TEST_HUGETLB)
914 		return 0;
915 
916 	area_dst = mremap(area_dst, nr_pages * page_size,  nr_pages * page_size,
917 			  MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
918 	if (area_dst == MAP_FAILED) {
919 		perror("mremap");
920 		exit(1);
921 	}
922 
923 	for (; nr < nr_pages; nr++) {
924 		count = *area_count(area_dst, nr);
925 		if (count != count_verify[nr]) {
926 			fprintf(stderr,
927 				"nr %lu memory corruption %Lu %Lu\n",
928 				nr, count,
929 				count_verify[nr]); exit(1);
930 		}
931 		/*
932 		 * Trigger write protection if there is by writting
933 		 * the same value back.
934 		 */
935 		*area_count(area_dst, nr) = count;
936 	}
937 
938 	if (uffd_test_ops->release_pages(area_dst))
939 		return 1;
940 
941 	for (nr = 0; nr < nr_pages; nr++) {
942 		if (my_bcmp(area_dst + nr * page_size, zeropage, page_size)) {
943 			fprintf(stderr, "nr %lu is not zero\n", nr);
944 			exit(1);
945 		}
946 	}
947 
948 	return 0;
949 }
950 
retry_uffdio_zeropage(int ufd,struct uffdio_zeropage * uffdio_zeropage,unsigned long offset)951 static void retry_uffdio_zeropage(int ufd,
952 				  struct uffdio_zeropage *uffdio_zeropage,
953 				  unsigned long offset)
954 {
955 	uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
956 				     uffdio_zeropage->range.len,
957 				     offset);
958 	if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
959 		if (uffdio_zeropage->zeropage != -EEXIST) {
960 			fprintf(stderr, "UFFDIO_ZEROPAGE retry error %Ld\n",
961 				uffdio_zeropage->zeropage);
962 			exit(1);
963 		}
964 	} else {
965 		fprintf(stderr, "UFFDIO_ZEROPAGE retry unexpected %Ld\n",
966 			uffdio_zeropage->zeropage); exit(1);
967 	}
968 }
969 
__uffdio_zeropage(int ufd,unsigned long offset,bool retry)970 static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
971 {
972 	struct uffdio_zeropage uffdio_zeropage;
973 	int ret;
974 	unsigned long has_zeropage;
975 
976 	has_zeropage = uffd_test_ops->expected_ioctls & (1 << _UFFDIO_ZEROPAGE);
977 
978 	if (offset >= nr_pages * page_size) {
979 		fprintf(stderr, "unexpected offset %lu\n", offset);
980 		exit(1);
981 	}
982 	uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
983 	uffdio_zeropage.range.len = page_size;
984 	uffdio_zeropage.mode = 0;
985 	ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
986 	if (ret) {
987 		/* real retval in ufdio_zeropage.zeropage */
988 		if (has_zeropage) {
989 			if (uffdio_zeropage.zeropage == -EEXIST) {
990 				fprintf(stderr, "UFFDIO_ZEROPAGE -EEXIST\n");
991 				exit(1);
992 			} else {
993 				fprintf(stderr, "UFFDIO_ZEROPAGE error %Ld\n",
994 					uffdio_zeropage.zeropage);
995 				exit(1);
996 			}
997 		} else {
998 			if (uffdio_zeropage.zeropage != -EINVAL) {
999 				fprintf(stderr,
1000 					"UFFDIO_ZEROPAGE not -EINVAL %Ld\n",
1001 					uffdio_zeropage.zeropage);
1002 				exit(1);
1003 			}
1004 		}
1005 	} else if (has_zeropage) {
1006 		if (uffdio_zeropage.zeropage != page_size) {
1007 			fprintf(stderr, "UFFDIO_ZEROPAGE unexpected %Ld\n",
1008 				uffdio_zeropage.zeropage); exit(1);
1009 		} else {
1010 			if (test_uffdio_zeropage_eexist && retry) {
1011 				test_uffdio_zeropage_eexist = false;
1012 				retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1013 						      offset);
1014 			}
1015 			return 1;
1016 		}
1017 	} else {
1018 		fprintf(stderr,
1019 			"UFFDIO_ZEROPAGE succeeded %Ld\n",
1020 			uffdio_zeropage.zeropage); exit(1);
1021 	}
1022 
1023 	return 0;
1024 }
1025 
uffdio_zeropage(int ufd,unsigned long offset)1026 static int uffdio_zeropage(int ufd, unsigned long offset)
1027 {
1028 	return __uffdio_zeropage(ufd, offset, false);
1029 }
1030 
1031 /* exercise UFFDIO_ZEROPAGE */
userfaultfd_zeropage_test(void)1032 static int userfaultfd_zeropage_test(void)
1033 {
1034 	struct uffdio_register uffdio_register;
1035 	unsigned long expected_ioctls;
1036 
1037 	printf("testing UFFDIO_ZEROPAGE: ");
1038 	fflush(stdout);
1039 
1040 	if (uffd_test_ops->release_pages(area_dst))
1041 		return 1;
1042 
1043 	if (userfaultfd_open(0) < 0)
1044 		return 1;
1045 	uffdio_register.range.start = (unsigned long) area_dst;
1046 	uffdio_register.range.len = nr_pages * page_size;
1047 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1048 	if (test_uffdio_wp)
1049 		uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1050 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1051 		fprintf(stderr, "register failure\n");
1052 		exit(1);
1053 	}
1054 
1055 	expected_ioctls = uffd_test_ops->expected_ioctls;
1056 	if ((uffdio_register.ioctls & expected_ioctls) !=
1057 	    expected_ioctls) {
1058 		fprintf(stderr,
1059 			"unexpected missing ioctl for anon memory\n");
1060 		exit(1);
1061 	}
1062 
1063 	if (uffdio_zeropage(uffd, 0)) {
1064 		if (my_bcmp(area_dst, zeropage, page_size)) {
1065 			fprintf(stderr, "zeropage is not zero\n");
1066 			exit(1);
1067 		}
1068 	}
1069 
1070 	close(uffd);
1071 	printf("done.\n");
1072 	return 0;
1073 }
1074 
userfaultfd_events_test(void)1075 static int userfaultfd_events_test(void)
1076 {
1077 	struct uffdio_register uffdio_register;
1078 	unsigned long expected_ioctls;
1079 	pthread_t uffd_mon;
1080 	int err, features;
1081 	pid_t pid;
1082 	char c;
1083 	struct uffd_stats stats = { 0 };
1084 
1085 	printf("testing events (fork, remap, remove): ");
1086 	fflush(stdout);
1087 
1088 	if (uffd_test_ops->release_pages(area_dst))
1089 		return 1;
1090 
1091 	features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1092 		UFFD_FEATURE_EVENT_REMOVE;
1093 	if (userfaultfd_open(features) < 0)
1094 		return 1;
1095 	fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1096 
1097 	uffdio_register.range.start = (unsigned long) area_dst;
1098 	uffdio_register.range.len = nr_pages * page_size;
1099 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1100 	if (test_uffdio_wp)
1101 		uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1102 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1103 		fprintf(stderr, "register failure\n");
1104 		exit(1);
1105 	}
1106 
1107 	expected_ioctls = uffd_test_ops->expected_ioctls;
1108 	if ((uffdio_register.ioctls & expected_ioctls) != expected_ioctls) {
1109 		fprintf(stderr, "unexpected missing ioctl for anon memory\n");
1110 		exit(1);
1111 	}
1112 
1113 	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats)) {
1114 		perror("uffd_poll_thread create");
1115 		exit(1);
1116 	}
1117 
1118 	pid = fork();
1119 	if (pid < 0) {
1120 		perror("fork");
1121 		exit(1);
1122 	}
1123 
1124 	if (!pid)
1125 		return faulting_process(0);
1126 
1127 	waitpid(pid, &err, 0);
1128 	if (err) {
1129 		fprintf(stderr, "faulting process failed\n");
1130 		exit(1);
1131 	}
1132 
1133 	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c)) {
1134 		perror("pipe write");
1135 		exit(1);
1136 	}
1137 	if (pthread_join(uffd_mon, NULL))
1138 		return 1;
1139 
1140 	close(uffd);
1141 
1142 	uffd_stats_report(&stats, 1);
1143 
1144 	return stats.missing_faults != nr_pages;
1145 }
1146 
userfaultfd_sig_test(void)1147 static int userfaultfd_sig_test(void)
1148 {
1149 	struct uffdio_register uffdio_register;
1150 	unsigned long expected_ioctls;
1151 	unsigned long userfaults;
1152 	pthread_t uffd_mon;
1153 	int err, features;
1154 	pid_t pid;
1155 	char c;
1156 	struct uffd_stats stats = { 0 };
1157 
1158 	printf("testing signal delivery: ");
1159 	fflush(stdout);
1160 
1161 	if (uffd_test_ops->release_pages(area_dst))
1162 		return 1;
1163 
1164 	features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1165 	if (userfaultfd_open(features) < 0)
1166 		return 1;
1167 	fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1168 
1169 	uffdio_register.range.start = (unsigned long) area_dst;
1170 	uffdio_register.range.len = nr_pages * page_size;
1171 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1172 	if (test_uffdio_wp)
1173 		uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1174 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1175 		fprintf(stderr, "register failure\n");
1176 		exit(1);
1177 	}
1178 
1179 	expected_ioctls = uffd_test_ops->expected_ioctls;
1180 	if ((uffdio_register.ioctls & expected_ioctls) != expected_ioctls) {
1181 		fprintf(stderr, "unexpected missing ioctl for anon memory\n");
1182 		exit(1);
1183 	}
1184 
1185 	if (faulting_process(1)) {
1186 		fprintf(stderr, "faulting process failed\n");
1187 		exit(1);
1188 	}
1189 
1190 	if (uffd_test_ops->release_pages(area_dst))
1191 		return 1;
1192 
1193 	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats)) {
1194 		perror("uffd_poll_thread create");
1195 		exit(1);
1196 	}
1197 
1198 	pid = fork();
1199 	if (pid < 0) {
1200 		perror("fork");
1201 		exit(1);
1202 	}
1203 
1204 	if (!pid)
1205 		exit(faulting_process(2));
1206 
1207 	waitpid(pid, &err, 0);
1208 	if (err) {
1209 		fprintf(stderr, "faulting process failed\n");
1210 		exit(1);
1211 	}
1212 
1213 	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c)) {
1214 		perror("pipe write");
1215 		exit(1);
1216 	}
1217 	if (pthread_join(uffd_mon, (void **)&userfaults))
1218 		return 1;
1219 
1220 	printf("done.\n");
1221 	if (userfaults)
1222 		fprintf(stderr, "Signal test failed, userfaults: %ld\n",
1223 			userfaults);
1224 	close(uffd);
1225 	return userfaults != 0;
1226 }
1227 
userfaultfd_stress(void)1228 static int userfaultfd_stress(void)
1229 {
1230 	void *area;
1231 	char *tmp_area;
1232 	unsigned long nr;
1233 	struct uffdio_register uffdio_register;
1234 	unsigned long cpu;
1235 	int err;
1236 	struct uffd_stats uffd_stats[nr_cpus];
1237 
1238 	uffd_test_ops->allocate_area((void **)&area_src);
1239 	if (!area_src)
1240 		return 1;
1241 	uffd_test_ops->allocate_area((void **)&area_dst);
1242 	if (!area_dst)
1243 		return 1;
1244 
1245 	if (userfaultfd_open(0) < 0)
1246 		return 1;
1247 
1248 	count_verify = malloc(nr_pages * sizeof(unsigned long long));
1249 	if (!count_verify) {
1250 		perror("count_verify");
1251 		return 1;
1252 	}
1253 
1254 	for (nr = 0; nr < nr_pages; nr++) {
1255 		*area_mutex(area_src, nr) = (pthread_mutex_t)
1256 			PTHREAD_MUTEX_INITIALIZER;
1257 		count_verify[nr] = *area_count(area_src, nr) = 1;
1258 		/*
1259 		 * In the transition between 255 to 256, powerpc will
1260 		 * read out of order in my_bcmp and see both bytes as
1261 		 * zero, so leave a placeholder below always non-zero
1262 		 * after the count, to avoid my_bcmp to trigger false
1263 		 * positives.
1264 		 */
1265 		*(area_count(area_src, nr) + 1) = 1;
1266 	}
1267 
1268 	pipefd = malloc(sizeof(int) * nr_cpus * 2);
1269 	if (!pipefd) {
1270 		perror("pipefd");
1271 		return 1;
1272 	}
1273 	for (cpu = 0; cpu < nr_cpus; cpu++) {
1274 		if (pipe2(&pipefd[cpu*2], O_CLOEXEC | O_NONBLOCK)) {
1275 			perror("pipe");
1276 			return 1;
1277 		}
1278 	}
1279 
1280 	if (posix_memalign(&area, page_size, page_size)) {
1281 		fprintf(stderr, "out of memory\n");
1282 		return 1;
1283 	}
1284 	zeropage = area;
1285 	bzero(zeropage, page_size);
1286 
1287 	pthread_mutex_lock(&uffd_read_mutex);
1288 
1289 	pthread_attr_init(&attr);
1290 	pthread_attr_setstacksize(&attr, 16*1024*1024);
1291 
1292 	err = 0;
1293 	while (bounces--) {
1294 		unsigned long expected_ioctls;
1295 
1296 		printf("bounces: %d, mode:", bounces);
1297 		if (bounces & BOUNCE_RANDOM)
1298 			printf(" rnd");
1299 		if (bounces & BOUNCE_RACINGFAULTS)
1300 			printf(" racing");
1301 		if (bounces & BOUNCE_VERIFY)
1302 			printf(" ver");
1303 		if (bounces & BOUNCE_POLL)
1304 			printf(" poll");
1305 		printf(", ");
1306 		fflush(stdout);
1307 
1308 		if (bounces & BOUNCE_POLL)
1309 			fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1310 		else
1311 			fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1312 
1313 		/* register */
1314 		uffdio_register.range.start = (unsigned long) area_dst;
1315 		uffdio_register.range.len = nr_pages * page_size;
1316 		uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1317 		if (test_uffdio_wp)
1318 			uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1319 		if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1320 			fprintf(stderr, "register failure\n");
1321 			return 1;
1322 		}
1323 		expected_ioctls = uffd_test_ops->expected_ioctls;
1324 		if ((uffdio_register.ioctls & expected_ioctls) !=
1325 		    expected_ioctls) {
1326 			fprintf(stderr,
1327 				"unexpected missing ioctl for anon memory\n");
1328 			return 1;
1329 		}
1330 
1331 		if (area_dst_alias) {
1332 			uffdio_register.range.start = (unsigned long)
1333 				area_dst_alias;
1334 			if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1335 				fprintf(stderr, "register failure alias\n");
1336 				return 1;
1337 			}
1338 		}
1339 
1340 		/*
1341 		 * The madvise done previously isn't enough: some
1342 		 * uffd_thread could have read userfaults (one of
1343 		 * those already resolved by the background thread)
1344 		 * and it may be in the process of calling
1345 		 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1346 		 * area_src and it would map a zero page in it (of
1347 		 * course such a UFFDIO_COPY is perfectly safe as it'd
1348 		 * return -EEXIST). The problem comes at the next
1349 		 * bounce though: that racing UFFDIO_COPY would
1350 		 * generate zeropages in the area_src, so invalidating
1351 		 * the previous MADV_DONTNEED. Without this additional
1352 		 * MADV_DONTNEED those zeropages leftovers in the
1353 		 * area_src would lead to -EEXIST failure during the
1354 		 * next bounce, effectively leaving a zeropage in the
1355 		 * area_dst.
1356 		 *
1357 		 * Try to comment this out madvise to see the memory
1358 		 * corruption being caught pretty quick.
1359 		 *
1360 		 * khugepaged is also inhibited to collapse THP after
1361 		 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1362 		 * required to MADV_DONTNEED here.
1363 		 */
1364 		if (uffd_test_ops->release_pages(area_dst))
1365 			return 1;
1366 
1367 		uffd_stats_reset(uffd_stats, nr_cpus);
1368 
1369 		/* bounce pass */
1370 		if (stress(uffd_stats))
1371 			return 1;
1372 
1373 		/* Clear all the write protections if there is any */
1374 		if (test_uffdio_wp)
1375 			wp_range(uffd, (unsigned long)area_dst,
1376 				 nr_pages * page_size, false);
1377 
1378 		/* unregister */
1379 		if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range)) {
1380 			fprintf(stderr, "unregister failure\n");
1381 			return 1;
1382 		}
1383 		if (area_dst_alias) {
1384 			uffdio_register.range.start = (unsigned long) area_dst;
1385 			if (ioctl(uffd, UFFDIO_UNREGISTER,
1386 				  &uffdio_register.range)) {
1387 				fprintf(stderr, "unregister failure alias\n");
1388 				return 1;
1389 			}
1390 		}
1391 
1392 		/* verification */
1393 		if (bounces & BOUNCE_VERIFY) {
1394 			for (nr = 0; nr < nr_pages; nr++) {
1395 				if (*area_count(area_dst, nr) != count_verify[nr]) {
1396 					fprintf(stderr,
1397 						"error area_count %Lu %Lu %lu\n",
1398 						*area_count(area_src, nr),
1399 						count_verify[nr],
1400 						nr);
1401 					err = 1;
1402 					bounces = 0;
1403 				}
1404 			}
1405 		}
1406 
1407 		/* prepare next bounce */
1408 		tmp_area = area_src;
1409 		area_src = area_dst;
1410 		area_dst = tmp_area;
1411 
1412 		tmp_area = area_src_alias;
1413 		area_src_alias = area_dst_alias;
1414 		area_dst_alias = tmp_area;
1415 
1416 		uffd_stats_report(uffd_stats, nr_cpus);
1417 	}
1418 
1419 	if (err)
1420 		return err;
1421 
1422 	close(uffd);
1423 	return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1424 		|| userfaultfd_events_test();
1425 }
1426 
1427 /*
1428  * Copied from mlock2-tests.c
1429  */
default_huge_page_size(void)1430 unsigned long default_huge_page_size(void)
1431 {
1432 	unsigned long hps = 0;
1433 	char *line = NULL;
1434 	size_t linelen = 0;
1435 	FILE *f = fopen("/proc/meminfo", "r");
1436 
1437 	if (!f)
1438 		return 0;
1439 	while (getline(&line, &linelen, f) > 0) {
1440 		if (sscanf(line, "Hugepagesize:       %lu kB", &hps) == 1) {
1441 			hps <<= 10;
1442 			break;
1443 		}
1444 	}
1445 
1446 	free(line);
1447 	fclose(f);
1448 	return hps;
1449 }
1450 
set_test_type(const char * type)1451 static void set_test_type(const char *type)
1452 {
1453 	if (!strcmp(type, "anon")) {
1454 		test_type = TEST_ANON;
1455 		uffd_test_ops = &anon_uffd_test_ops;
1456 		/* Only enable write-protect test for anonymous test */
1457 		test_uffdio_wp = true;
1458 	} else if (!strcmp(type, "hugetlb")) {
1459 		test_type = TEST_HUGETLB;
1460 		uffd_test_ops = &hugetlb_uffd_test_ops;
1461 	} else if (!strcmp(type, "hugetlb_shared")) {
1462 		map_shared = true;
1463 		test_type = TEST_HUGETLB;
1464 		uffd_test_ops = &hugetlb_uffd_test_ops;
1465 	} else if (!strcmp(type, "shmem")) {
1466 		map_shared = true;
1467 		test_type = TEST_SHMEM;
1468 		uffd_test_ops = &shmem_uffd_test_ops;
1469 	} else {
1470 		fprintf(stderr, "Unknown test type: %s\n", type); exit(1);
1471 	}
1472 
1473 	if (test_type == TEST_HUGETLB)
1474 		page_size = default_huge_page_size();
1475 	else
1476 		page_size = sysconf(_SC_PAGE_SIZE);
1477 
1478 	if (!page_size) {
1479 		fprintf(stderr, "Unable to determine page size\n");
1480 		exit(2);
1481 	}
1482 	if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1483 	    > page_size) {
1484 		fprintf(stderr, "Impossible to run this test\n");
1485 		exit(2);
1486 	}
1487 }
1488 
sigalrm(int sig)1489 static void sigalrm(int sig)
1490 {
1491 	if (sig != SIGALRM)
1492 		abort();
1493 	test_uffdio_copy_eexist = true;
1494 	test_uffdio_zeropage_eexist = true;
1495 	alarm(ALARM_INTERVAL_SECS);
1496 }
1497 
main(int argc,char ** argv)1498 int main(int argc, char **argv)
1499 {
1500 	if (argc < 4)
1501 		usage();
1502 
1503 	if (signal(SIGALRM, sigalrm) == SIG_ERR) {
1504 		fprintf(stderr, "failed to arm SIGALRM");
1505 		exit(1);
1506 	}
1507 	alarm(ALARM_INTERVAL_SECS);
1508 
1509 	set_test_type(argv[1]);
1510 
1511 	nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1512 	nr_pages_per_cpu = atol(argv[2]) * 1024*1024 / page_size /
1513 		nr_cpus;
1514 	if (!nr_pages_per_cpu) {
1515 		fprintf(stderr, "invalid MiB\n");
1516 		usage();
1517 	}
1518 
1519 	bounces = atoi(argv[3]);
1520 	if (bounces <= 0) {
1521 		fprintf(stderr, "invalid bounces\n");
1522 		usage();
1523 	}
1524 	nr_pages = nr_pages_per_cpu * nr_cpus;
1525 
1526 	if (test_type == TEST_HUGETLB) {
1527 		if (argc < 5)
1528 			usage();
1529 		huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1530 		if (huge_fd < 0) {
1531 			fprintf(stderr, "Open of %s failed", argv[3]);
1532 			perror("open");
1533 			exit(1);
1534 		}
1535 		if (ftruncate(huge_fd, 0)) {
1536 			fprintf(stderr, "ftruncate %s to size 0 failed", argv[3]);
1537 			perror("ftruncate");
1538 			exit(1);
1539 		}
1540 	}
1541 	printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1542 	       nr_pages, nr_pages_per_cpu);
1543 	return userfaultfd_stress();
1544 }
1545 
1546 #else /* __NR_userfaultfd */
1547 
1548 #warning "missing __NR_userfaultfd definition"
1549 
main(void)1550 int main(void)
1551 {
1552 	printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1553 	return KSFT_SKIP;
1554 }
1555 
1556 #endif /* __NR_userfaultfd */
1557