xref: /aosp_15_r20/external/linux-kselftest/tools/testing/selftests/vm/userfaultfd.c (revision 053f45be4e351dfd5e965df293cd45b779f579ee)
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 <linux/mman.h>
50 #include <sys/mman.h>
51 #include <sys/syscall.h>
52 #include <sys/ioctl.h>
53 #include <sys/wait.h>
54 #include <pthread.h>
55 #include <linux/userfaultfd.h>
56 #include <setjmp.h>
57 #include <stdbool.h>
58 #include <assert.h>
59 #include <inttypes.h>
60 #include <stdint.h>
61 #include <sys/random.h>
62 #include <linux/version.h>
63 #include <sys/utsname.h>
64 
65 #include "../kselftest.h"
66 #include "vm_util.h"
67 
68 #ifdef __NR_userfaultfd
69 
70 static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size, hpage_size;
71 
72 #define BOUNCE_RANDOM		(1<<0)
73 #define BOUNCE_RACINGFAULTS	(1<<1)
74 #define BOUNCE_VERIFY		(1<<2)
75 #define BOUNCE_POLL		(1<<3)
76 static int bounces;
77 
78 #define TEST_ANON	1
79 #define TEST_HUGETLB	2
80 #define TEST_SHMEM	3
81 static int test_type;
82 
83 #define UFFD_FLAGS	(O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY)
84 
85 #define BASE_PMD_ADDR ((void *)(1UL << 30))
86 
87 /* test using /dev/userfaultfd, instead of userfaultfd(2) */
88 static bool test_dev_userfaultfd;
89 
90 /* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
91 #define ALARM_INTERVAL_SECS 10
92 static volatile bool test_uffdio_copy_eexist = true;
93 static volatile bool test_uffdio_zeropage_eexist = true;
94 /* Whether to test uffd write-protection */
95 static bool test_uffdio_wp = false;
96 /* Whether to test uffd minor faults */
97 static bool test_uffdio_minor = false;
98 
99 static bool map_shared;
100 static int shm_fd;
101 static int huge_fd;
102 static unsigned long long *count_verify;
103 static int uffd = -1;
104 static int uffd_flags, finished, *pipefd;
105 static volatile bool ready_for_fork;
106 static char *area_src, *area_src_alias, *area_dst, *area_dst_alias, *area_remap;
107 static char *zeropage;
108 pthread_attr_t attr;
109 pthread_key_t long_jmp_key;
110 static bool test_collapse;
111 
112 /* Userfaultfd test statistics */
113 struct uffd_stats {
114 	int cpu;
115 	unsigned long missing_faults;
116 	unsigned long wp_faults;
117 	unsigned long minor_faults;
118 };
119 
120 /* pthread_mutex_t starts at page offset 0 */
121 #define area_mutex(___area, ___nr)					\
122 	((pthread_mutex_t *) ((___area) + (___nr)*page_size))
123 /*
124  * count is placed in the page after pthread_mutex_t naturally aligned
125  * to avoid non alignment faults on non-x86 archs.
126  */
127 #define area_count(___area, ___nr)					\
128 	((volatile unsigned long long *) ((unsigned long)		\
129 				 ((___area) + (___nr)*page_size +	\
130 				  sizeof(pthread_mutex_t) +		\
131 				  sizeof(unsigned long long) - 1) &	\
132 				 ~(unsigned long)(sizeof(unsigned long long) \
133 						  -  1)))
134 
135 #define swap(a, b) \
136 	do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
137 
138 #define factor_of_2(x) ((x) ^ ((x) & ((x) - 1)))
139 
140 const char *examples =
141     "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
142     "./userfaultfd anon 100 99999\n\n"
143     "# Run the same anonymous memory test, but using /dev/userfaultfd:\n"
144     "./userfaultfd anon:dev 100 99999\n\n"
145     "# Run share memory test on 1GiB region with 99 bounces:\n"
146     "./userfaultfd shmem 1000 99\n\n"
147     "# Run hugetlb memory test on 256MiB region with 50 bounces:\n"
148     "./userfaultfd hugetlb 256 50\n\n"
149     "# Run the same hugetlb test but using shared file:\n"
150     "./userfaultfd hugetlb_shared 256 50 /dev/hugepages/hugefile\n\n"
151     "# 10MiB-~6GiB 999 bounces anonymous test, "
152     "continue forever unless an error triggers\n"
153     "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
154 
usage(void)155 static void usage(void)
156 {
157 	fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
158 		"[hugetlbfs_file]\n\n");
159 	fprintf(stderr, "Supported <test type>: anon, hugetlb, "
160 		"hugetlb_shared, shmem\n\n");
161 	fprintf(stderr, "'Test mods' can be joined to the test type string with a ':'. "
162 		"Supported mods:\n");
163 	fprintf(stderr, "\tsyscall - Use userfaultfd(2) (default)\n");
164 	fprintf(stderr, "\tdev - Use /dev/userfaultfd instead of userfaultfd(2)\n");
165 	fprintf(stderr, "\tcollapse - Test MADV_COLLAPSE of UFFDIO_REGISTER_MODE_MINOR\n"
166 		"memory\n");
167 	fprintf(stderr, "\nExample test mod usage:\n");
168 	fprintf(stderr, "# Run anonymous memory test with /dev/userfaultfd:\n");
169 	fprintf(stderr, "./userfaultfd anon:dev 100 99999\n\n");
170 
171 	fprintf(stderr, "Examples:\n\n");
172 	fprintf(stderr, "%s", examples);
173 	exit(1);
174 }
175 
176 #define _err(fmt, ...)						\
177 	do {							\
178 		int ret = errno;				\
179 		fprintf(stderr, "ERROR: " fmt, ##__VA_ARGS__);	\
180 		fprintf(stderr, " (errno=%d, line=%d)\n",	\
181 			ret, __LINE__);				\
182 	} while (0)
183 
184 #define errexit(exitcode, fmt, ...)		\
185 	do {					\
186 		_err(fmt, ##__VA_ARGS__);	\
187 		exit(exitcode);			\
188 	} while (0)
189 
190 #define err(fmt, ...) errexit(1, fmt, ##__VA_ARGS__)
191 
uffd_stats_reset(struct uffd_stats * uffd_stats,unsigned long n_cpus)192 static void uffd_stats_reset(struct uffd_stats *uffd_stats,
193 			     unsigned long n_cpus)
194 {
195 	int i;
196 
197 	for (i = 0; i < n_cpus; i++) {
198 		uffd_stats[i].cpu = i;
199 		uffd_stats[i].missing_faults = 0;
200 		uffd_stats[i].wp_faults = 0;
201 		uffd_stats[i].minor_faults = 0;
202 	}
203 }
204 
uffd_stats_report(struct uffd_stats * stats,int n_cpus)205 static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
206 {
207 	int i;
208 	unsigned long long miss_total = 0, wp_total = 0, minor_total = 0;
209 
210 	for (i = 0; i < n_cpus; i++) {
211 		miss_total += stats[i].missing_faults;
212 		wp_total += stats[i].wp_faults;
213 		minor_total += stats[i].minor_faults;
214 	}
215 
216 	printf("userfaults: ");
217 	if (miss_total) {
218 		printf("%llu missing (", miss_total);
219 		for (i = 0; i < n_cpus; i++)
220 			printf("%lu+", stats[i].missing_faults);
221 		printf("\b) ");
222 	}
223 	if (wp_total) {
224 		printf("%llu wp (", wp_total);
225 		for (i = 0; i < n_cpus; i++)
226 			printf("%lu+", stats[i].wp_faults);
227 		printf("\b) ");
228 	}
229 	if (minor_total) {
230 		printf("%llu minor (", minor_total);
231 		for (i = 0; i < n_cpus; i++)
232 			printf("%lu+", stats[i].minor_faults);
233 		printf("\b)");
234 	}
235 	printf("\n");
236 }
237 
anon_release_pages(char * rel_area)238 static void anon_release_pages(char *rel_area)
239 {
240 	if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
241 		err("madvise(MADV_DONTNEED) failed");
242 }
243 
anon_allocate_area(void ** alloc_area,bool is_src)244 static void anon_allocate_area(void **alloc_area, bool is_src)
245 {
246 	*alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
247 			   MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
248 }
249 
noop_alias_mapping(__u64 * start,size_t len,unsigned long offset)250 static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
251 {
252 }
253 
hugetlb_release_pages(char * rel_area)254 static void hugetlb_release_pages(char *rel_area)
255 {
256 	if (!map_shared) {
257 		if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
258 			err("madvise(MADV_DONTNEED) failed");
259 	} else {
260 		if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
261 			err("madvise(MADV_REMOVE) failed");
262 	}
263 }
264 
hugetlb_allocate_area(void ** alloc_area,bool is_src)265 static void hugetlb_allocate_area(void **alloc_area, bool is_src)
266 {
267 	void *area_alias = NULL;
268 	char **alloc_area_alias;
269 
270 	if (!map_shared)
271 		*alloc_area = mmap(NULL,
272 			nr_pages * page_size,
273 			PROT_READ | PROT_WRITE,
274 			MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB |
275 				(is_src ? 0 : MAP_NORESERVE),
276 			-1,
277 			0);
278 	else
279 		*alloc_area = mmap(NULL,
280 			nr_pages * page_size,
281 			PROT_READ | PROT_WRITE,
282 			MAP_SHARED |
283 				(is_src ? 0 : MAP_NORESERVE),
284 			huge_fd,
285 			is_src ? 0 : nr_pages * page_size);
286 	if (*alloc_area == MAP_FAILED)
287 		err("mmap of hugetlbfs file failed");
288 
289 	if (map_shared) {
290 		area_alias = mmap(NULL,
291 			nr_pages * page_size,
292 			PROT_READ | PROT_WRITE,
293 			MAP_SHARED,
294 			huge_fd,
295 			is_src ? 0 : nr_pages * page_size);
296 		if (area_alias == MAP_FAILED)
297 			err("mmap of hugetlb file alias failed");
298 	}
299 
300 	if (is_src) {
301 		alloc_area_alias = &area_src_alias;
302 	} else {
303 		alloc_area_alias = &area_dst_alias;
304 	}
305 	if (area_alias)
306 		*alloc_area_alias = area_alias;
307 }
308 
hugetlb_alias_mapping(__u64 * start,size_t len,unsigned long offset)309 static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
310 {
311 	if (!map_shared)
312 		return;
313 
314 	*start = (unsigned long) area_dst_alias + offset;
315 }
316 
shmem_release_pages(char * rel_area)317 static void shmem_release_pages(char *rel_area)
318 {
319 	if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
320 		err("madvise(MADV_REMOVE) failed");
321 }
322 
shmem_allocate_area(void ** alloc_area,bool is_src)323 static void shmem_allocate_area(void **alloc_area, bool is_src)
324 {
325 	void *area_alias = NULL;
326 	size_t bytes = nr_pages * page_size;
327 	unsigned long offset = is_src ? 0 : bytes;
328 	char *p = NULL, *p_alias = NULL;
329 
330 	if (test_collapse) {
331 		p = BASE_PMD_ADDR;
332 		if (!is_src)
333 			/* src map + alias + interleaved hpages */
334 			p += 2 * (bytes + hpage_size);
335 		p_alias = p;
336 		p_alias += bytes;
337 		p_alias += hpage_size;  /* Prevent src/dst VMA merge */
338 	}
339 
340 	*alloc_area = mmap(p, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
341 			   shm_fd, offset);
342 	if (*alloc_area == MAP_FAILED)
343 		err("mmap of memfd failed");
344 	if (test_collapse && *alloc_area != p)
345 		err("mmap of memfd failed at %p", p);
346 
347 	area_alias = mmap(p_alias, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
348 			  shm_fd, offset);
349 	if (area_alias == MAP_FAILED)
350 		err("mmap of memfd alias failed");
351 	if (test_collapse && area_alias != p_alias)
352 		err("mmap of anonymous memory failed at %p", p_alias);
353 
354 	if (is_src)
355 		area_src_alias = area_alias;
356 	else
357 		area_dst_alias = area_alias;
358 }
359 
shmem_alias_mapping(__u64 * start,size_t len,unsigned long offset)360 static void shmem_alias_mapping(__u64 *start, size_t len, unsigned long offset)
361 {
362 	*start = (unsigned long)area_dst_alias + offset;
363 }
364 
shmem_check_pmd_mapping(void * p,int expect_nr_hpages)365 static void shmem_check_pmd_mapping(void *p, int expect_nr_hpages)
366 {
367 	if (!check_huge_shmem(area_dst_alias, expect_nr_hpages, hpage_size))
368 		err("Did not find expected %d number of hugepages",
369 		    expect_nr_hpages);
370 }
371 
372 struct uffd_test_ops {
373 	void (*allocate_area)(void **alloc_area, bool is_src);
374 	void (*release_pages)(char *rel_area);
375 	void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
376 	void (*check_pmd_mapping)(void *p, int expect_nr_hpages);
377 };
378 
379 static struct uffd_test_ops anon_uffd_test_ops = {
380 	.allocate_area	= anon_allocate_area,
381 	.release_pages	= anon_release_pages,
382 	.alias_mapping = noop_alias_mapping,
383 	.check_pmd_mapping = NULL,
384 };
385 
386 static struct uffd_test_ops shmem_uffd_test_ops = {
387 	.allocate_area	= shmem_allocate_area,
388 	.release_pages	= shmem_release_pages,
389 	.alias_mapping = shmem_alias_mapping,
390 	.check_pmd_mapping = shmem_check_pmd_mapping,
391 };
392 
393 static struct uffd_test_ops hugetlb_uffd_test_ops = {
394 	.allocate_area	= hugetlb_allocate_area,
395 	.release_pages	= hugetlb_release_pages,
396 	.alias_mapping = hugetlb_alias_mapping,
397 	.check_pmd_mapping = NULL,
398 };
399 
400 static struct uffd_test_ops *uffd_test_ops;
401 
uffd_minor_feature(void)402 static inline uint64_t uffd_minor_feature(void)
403 {
404 	if (test_type == TEST_HUGETLB && map_shared)
405 		return UFFD_FEATURE_MINOR_HUGETLBFS;
406 	else if (test_type == TEST_SHMEM)
407 		return UFFD_FEATURE_MINOR_SHMEM;
408 	else
409 		return 0;
410 }
411 
412 /* b/308714445
413  * _UFFDIO_POISON unsupported in kernel <6.6
414  * b/335674702
415  * _UFFDIO_MOVE unupported in kernel <6.8
416  */
get_kernel_version(void)417 static uint32_t get_kernel_version(void)
418 {
419 	uint32_t major, minor, patch;
420 	struct utsname info;
421 
422 	uname(&info);
423 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
424 		return 0;
425 	return KERNEL_VERSION(major, minor, patch);
426 }
427 
get_expected_ioctls(uint64_t mode)428 static uint64_t get_expected_ioctls(uint64_t mode)
429 {
430 	uint64_t ioctls = UFFD_API_RANGE_IOCTLS;
431 
432 	if (test_type == TEST_HUGETLB)
433 		ioctls &= ~(1 << _UFFDIO_ZEROPAGE);
434 
435 	if (!((mode & UFFDIO_REGISTER_MODE_WP) && test_uffdio_wp))
436 		ioctls &= ~(1 << _UFFDIO_WRITEPROTECT);
437 
438 	if (!((mode & UFFDIO_REGISTER_MODE_MINOR) && test_uffdio_minor))
439 		ioctls &= ~(1 << _UFFDIO_CONTINUE);
440 
441 	static uint32_t kernel_version = 0;
442 	if (kernel_version == 0) {
443 		kernel_version = get_kernel_version();
444 	}
445 	if (kernel_version < KERNEL_VERSION(6, 6, 0)) {
446 		// UFFDIO_POISON not supported until kernel 6.6.
447 		ioctls &= ~(1 << _UFFDIO_POISON);
448 	}
449 	if (kernel_version < KERNEL_VERSION(6, 8, 0)) {
450 		// UFFDIO_MOVE not supported until kernel 6.8.
451 		ioctls &= ~(1 << _UFFDIO_MOVE);
452 	}
453 
454 	return ioctls;
455 }
456 
assert_expected_ioctls_present(uint64_t mode,uint64_t ioctls)457 static void assert_expected_ioctls_present(uint64_t mode, uint64_t ioctls)
458 {
459 	uint64_t expected = get_expected_ioctls(mode);
460 	uint64_t actual = ioctls & expected;
461 
462 	if (actual != expected) {
463 		err("missing ioctl(s): expected %"PRIx64" actual: %"PRIx64,
464 		    expected, actual);
465 	}
466 }
467 
__userfaultfd_open_dev(void)468 static int __userfaultfd_open_dev(void)
469 {
470 	int fd, _uffd;
471 
472 	fd = open("/dev/userfaultfd", O_RDWR | O_CLOEXEC);
473 	if (fd < 0)
474 		errexit(KSFT_SKIP, "opening /dev/userfaultfd failed");
475 
476 	_uffd = ioctl(fd, USERFAULTFD_IOC_NEW, UFFD_FLAGS);
477 	if (_uffd < 0)
478 		errexit(errno == ENOTTY ? KSFT_SKIP : 1,
479 			"creating userfaultfd failed");
480 	close(fd);
481 	return _uffd;
482 }
483 
userfaultfd_open(uint64_t * features)484 static void userfaultfd_open(uint64_t *features)
485 {
486 	struct uffdio_api uffdio_api;
487 
488 	if (test_dev_userfaultfd)
489 		uffd = __userfaultfd_open_dev();
490 	else {
491 		uffd = syscall(__NR_userfaultfd, UFFD_FLAGS);
492 		if (uffd < 0)
493 			errexit(errno == ENOSYS ? KSFT_SKIP : 1,
494 				"creating userfaultfd failed");
495 	}
496 	uffd_flags = fcntl(uffd, F_GETFD, NULL);
497 
498 	uffdio_api.api = UFFD_API;
499 	uffdio_api.features = *features;
500 	if (ioctl(uffd, UFFDIO_API, &uffdio_api))
501 		err("UFFDIO_API failed.\nPlease make sure to "
502 		    "run with either root or ptrace capability.");
503 	if (uffdio_api.api != UFFD_API)
504 		err("UFFDIO_API error: %" PRIu64, (uint64_t)uffdio_api.api);
505 
506 	*features = uffdio_api.features;
507 }
508 
munmap_area(void ** area)509 static inline void munmap_area(void **area)
510 {
511 	if (*area)
512 		if (munmap(*area, nr_pages * page_size))
513 			err("munmap");
514 
515 	*area = NULL;
516 }
517 
uffd_test_ctx_clear(void)518 static void uffd_test_ctx_clear(void)
519 {
520 	size_t i;
521 
522 	if (pipefd) {
523 		for (i = 0; i < nr_cpus * 2; ++i) {
524 			if (close(pipefd[i]))
525 				err("close pipefd");
526 		}
527 		free(pipefd);
528 		pipefd = NULL;
529 	}
530 
531 	if (count_verify) {
532 		free(count_verify);
533 		count_verify = NULL;
534 	}
535 
536 	if (uffd != -1) {
537 		if (close(uffd))
538 			err("close uffd");
539 		uffd = -1;
540 	}
541 
542 	munmap_area((void **)&area_src);
543 	munmap_area((void **)&area_src_alias);
544 	munmap_area((void **)&area_dst);
545 	munmap_area((void **)&area_dst_alias);
546 	munmap_area((void **)&area_remap);
547 }
548 
uffd_test_ctx_init(uint64_t features)549 static void uffd_test_ctx_init(uint64_t features)
550 {
551 	unsigned long nr, cpu;
552 
553 	uffd_test_ctx_clear();
554 
555 	uffd_test_ops->allocate_area((void **)&area_src, true);
556 	uffd_test_ops->allocate_area((void **)&area_dst, false);
557 
558 	userfaultfd_open(&features);
559 
560 	count_verify = malloc(nr_pages * sizeof(unsigned long long));
561 	if (!count_verify)
562 		err("count_verify");
563 
564 	for (nr = 0; nr < nr_pages; nr++) {
565 		*area_mutex(area_src, nr) =
566 			(pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
567 		count_verify[nr] = *area_count(area_src, nr) = 1;
568 		/*
569 		 * In the transition between 255 to 256, powerpc will
570 		 * read out of order in my_bcmp and see both bytes as
571 		 * zero, so leave a placeholder below always non-zero
572 		 * after the count, to avoid my_bcmp to trigger false
573 		 * positives.
574 		 */
575 		*(area_count(area_src, nr) + 1) = 1;
576 	}
577 
578 	/*
579 	 * After initialization of area_src, we must explicitly release pages
580 	 * for area_dst to make sure it's fully empty.  Otherwise we could have
581 	 * some area_dst pages be errornously initialized with zero pages,
582 	 * hence we could hit memory corruption later in the test.
583 	 *
584 	 * One example is when THP is globally enabled, above allocate_area()
585 	 * calls could have the two areas merged into a single VMA (as they
586 	 * will have the same VMA flags so they're mergeable).  When we
587 	 * initialize the area_src above, it's possible that some part of
588 	 * area_dst could have been faulted in via one huge THP that will be
589 	 * shared between area_src and area_dst.  It could cause some of the
590 	 * area_dst won't be trapped by missing userfaults.
591 	 *
592 	 * This release_pages() will guarantee even if that happened, we'll
593 	 * proactively split the thp and drop any accidentally initialized
594 	 * pages within area_dst.
595 	 */
596 	uffd_test_ops->release_pages(area_dst);
597 
598 	pipefd = malloc(sizeof(int) * nr_cpus * 2);
599 	if (!pipefd)
600 		err("pipefd");
601 	for (cpu = 0; cpu < nr_cpus; cpu++)
602 		if (pipe2(&pipefd[cpu * 2], O_CLOEXEC | O_NONBLOCK))
603 			err("pipe");
604 }
605 
my_bcmp(char * str1,char * str2,size_t n)606 static int my_bcmp(char *str1, char *str2, size_t n)
607 {
608 	unsigned long i;
609 	for (i = 0; i < n; i++)
610 		if (str1[i] != str2[i])
611 			return 1;
612 	return 0;
613 }
614 
wp_range(int ufd,__u64 start,__u64 len,bool wp)615 static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
616 {
617 	struct uffdio_writeprotect prms;
618 
619 	/* Write protection page faults */
620 	prms.range.start = start;
621 	prms.range.len = len;
622 	/* Undo write-protect, do wakeup after that */
623 	prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
624 
625 	if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
626 		err("clear WP failed: address=0x%"PRIx64, (uint64_t)start);
627 }
628 
continue_range(int ufd,__u64 start,__u64 len)629 static void continue_range(int ufd, __u64 start, __u64 len)
630 {
631 	struct uffdio_continue req;
632 	int ret;
633 
634 	req.range.start = start;
635 	req.range.len = len;
636 	req.mode = 0;
637 
638 	if (ioctl(ufd, UFFDIO_CONTINUE, &req))
639 		err("UFFDIO_CONTINUE failed for address 0x%" PRIx64,
640 		    (uint64_t)start);
641 
642 	/*
643 	 * Error handling within the kernel for continue is subtly different
644 	 * from copy or zeropage, so it may be a source of bugs. Trigger an
645 	 * error (-EEXIST) on purpose, to verify doing so doesn't cause a BUG.
646 	 */
647 	req.mapped = 0;
648 	ret = ioctl(ufd, UFFDIO_CONTINUE, &req);
649 	if (ret >= 0 || req.mapped != -EEXIST)
650 		err("failed to exercise UFFDIO_CONTINUE error handling, ret=%d, mapped=%" PRId64,
651 		    ret, (int64_t) req.mapped);
652 }
653 
locking_thread(void * arg)654 static void *locking_thread(void *arg)
655 {
656 	unsigned long cpu = (unsigned long) arg;
657 	unsigned long page_nr;
658 	unsigned long long count;
659 
660 	if (!(bounces & BOUNCE_RANDOM)) {
661 		page_nr = -bounces;
662 		if (!(bounces & BOUNCE_RACINGFAULTS))
663 			page_nr += cpu * nr_pages_per_cpu;
664 	}
665 
666 	while (!finished) {
667 		if (bounces & BOUNCE_RANDOM) {
668 			if (getrandom(&page_nr, sizeof(page_nr), 0) != sizeof(page_nr))
669 				err("getrandom failed");
670 		} else
671 			page_nr += 1;
672 		page_nr %= nr_pages;
673 		pthread_mutex_lock(area_mutex(area_dst, page_nr));
674 		count = *area_count(area_dst, page_nr);
675 		if (count != count_verify[page_nr])
676 			err("page_nr %lu memory corruption %llu %llu",
677 			    page_nr, count, count_verify[page_nr]);
678 		count++;
679 		*area_count(area_dst, page_nr) = count_verify[page_nr] = count;
680 		pthread_mutex_unlock(area_mutex(area_dst, page_nr));
681 	}
682 
683 	return NULL;
684 }
685 
retry_copy_page(int ufd,struct uffdio_copy * uffdio_copy,unsigned long offset)686 static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
687 			    unsigned long offset)
688 {
689 	uffd_test_ops->alias_mapping(&uffdio_copy->dst,
690 				     uffdio_copy->len,
691 				     offset);
692 	if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
693 		/* real retval in ufdio_copy.copy */
694 		if (uffdio_copy->copy != -EEXIST)
695 			err("UFFDIO_COPY retry error: %"PRId64,
696 			    (int64_t)uffdio_copy->copy);
697 	} else {
698 		err("UFFDIO_COPY retry unexpected: %"PRId64,
699 		    (int64_t)uffdio_copy->copy);
700 	}
701 }
702 
wake_range(int ufd,unsigned long addr,unsigned long len)703 static void wake_range(int ufd, unsigned long addr, unsigned long len)
704 {
705 	struct uffdio_range uffdio_wake;
706 
707 	uffdio_wake.start = addr;
708 	uffdio_wake.len = len;
709 
710 	if (ioctl(ufd, UFFDIO_WAKE, &uffdio_wake))
711 		fprintf(stderr, "error waking %lu\n",
712 			addr), exit(1);
713 }
714 
__copy_page(int ufd,unsigned long offset,bool retry)715 static int __copy_page(int ufd, unsigned long offset, bool retry)
716 {
717 	struct uffdio_copy uffdio_copy;
718 
719 	if (offset >= nr_pages * page_size)
720 		err("unexpected offset %lu\n", offset);
721 	uffdio_copy.dst = (unsigned long) area_dst + offset;
722 	uffdio_copy.src = (unsigned long) area_src + offset;
723 	uffdio_copy.len = page_size;
724 	if (test_uffdio_wp)
725 		uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
726 	else
727 		uffdio_copy.mode = 0;
728 	uffdio_copy.copy = 0;
729 	if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
730 		/* real retval in ufdio_copy.copy */
731 		if (uffdio_copy.copy != -EEXIST)
732 			err("UFFDIO_COPY error: %"PRId64,
733 			    (int64_t)uffdio_copy.copy);
734 		wake_range(ufd, uffdio_copy.dst, page_size);
735 	} else if (uffdio_copy.copy != page_size) {
736 		err("UFFDIO_COPY error: %"PRId64, (int64_t)uffdio_copy.copy);
737 	} else {
738 		if (test_uffdio_copy_eexist && retry) {
739 			test_uffdio_copy_eexist = false;
740 			retry_copy_page(ufd, &uffdio_copy, offset);
741 		}
742 		return 1;
743 	}
744 	return 0;
745 }
746 
copy_page_retry(int ufd,unsigned long offset)747 static int copy_page_retry(int ufd, unsigned long offset)
748 {
749 	return __copy_page(ufd, offset, true);
750 }
751 
copy_page(int ufd,unsigned long offset)752 static int copy_page(int ufd, unsigned long offset)
753 {
754 	return __copy_page(ufd, offset, false);
755 }
756 
uffd_read_msg(int ufd,struct uffd_msg * msg)757 static int uffd_read_msg(int ufd, struct uffd_msg *msg)
758 {
759 	int ret = read(uffd, msg, sizeof(*msg));
760 
761 	if (ret != sizeof(*msg)) {
762 		if (ret < 0) {
763 			if (errno == EAGAIN || errno == EINTR)
764 				return 1;
765 			err("blocking read error");
766 		} else {
767 			err("short read");
768 		}
769 	}
770 
771 	return 0;
772 }
773 
uffd_handle_page_fault(struct uffd_msg * msg,struct uffd_stats * stats)774 static void uffd_handle_page_fault(struct uffd_msg *msg,
775 				   struct uffd_stats *stats)
776 {
777 	unsigned long offset;
778 
779 	if (msg->event != UFFD_EVENT_PAGEFAULT)
780 		err("unexpected msg event %u", msg->event);
781 
782 	if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
783 		/* Write protect page faults */
784 		wp_range(uffd, msg->arg.pagefault.address, page_size, false);
785 		stats->wp_faults++;
786 	} else if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_MINOR) {
787 		uint8_t *area;
788 		int b;
789 
790 		/*
791 		 * Minor page faults
792 		 *
793 		 * To prove we can modify the original range for testing
794 		 * purposes, we're going to bit flip this range before
795 		 * continuing.
796 		 *
797 		 * Note that this requires all minor page fault tests operate on
798 		 * area_dst (non-UFFD-registered) and area_dst_alias
799 		 * (UFFD-registered).
800 		 */
801 
802 		area = (uint8_t *)(area_dst +
803 				   ((char *)msg->arg.pagefault.address -
804 				    area_dst_alias));
805 		for (b = 0; b < page_size; ++b)
806 			area[b] = ~area[b];
807 		continue_range(uffd, msg->arg.pagefault.address, page_size);
808 		stats->minor_faults++;
809 	} else {
810 		/*
811 		 * Missing page faults.
812 		 *
813 		 * Here we force a write check for each of the missing mode
814 		 * faults.  It's guaranteed because the only threads that
815 		 * will trigger uffd faults are the locking threads, and
816 		 * their first instruction to touch the missing page will
817 		 * always be pthread_mutex_lock().
818 		 *
819 		 * Note that here we relied on an NPTL glibc impl detail to
820 		 * always read the lock type at the entry of the lock op
821 		 * (pthread_mutex_t.__data.__type, offset 0x10) before
822 		 * doing any locking operations to guarantee that.  It's
823 		 * actually not good to rely on this impl detail because
824 		 * logically a pthread-compatible lib can implement the
825 		 * locks without types and we can fail when linking with
826 		 * them.  However since we used to find bugs with this
827 		 * strict check we still keep it around.  Hopefully this
828 		 * could be a good hint when it fails again.  If one day
829 		 * it'll break on some other impl of glibc we'll revisit.
830 		 */
831 		if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
832 			err("unexpected write fault");
833 
834 		offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
835 		offset &= ~(page_size-1);
836 
837 		if (copy_page(uffd, offset))
838 			stats->missing_faults++;
839 	}
840 }
841 
uffd_poll_thread(void * arg)842 static void *uffd_poll_thread(void *arg)
843 {
844 	struct uffd_stats *stats = (struct uffd_stats *)arg;
845 	unsigned long cpu = stats->cpu;
846 	struct pollfd pollfd[2];
847 	struct uffd_msg msg;
848 	struct uffdio_register uffd_reg;
849 	int ret;
850 	char tmp_chr;
851 
852 	pollfd[0].fd = uffd;
853 	pollfd[0].events = POLLIN;
854 	pollfd[1].fd = pipefd[cpu*2];
855 	pollfd[1].events = POLLIN;
856 
857 	// Notify the main thread that it can now fork.
858 	ready_for_fork = true;
859 
860 	for (;;) {
861 		ret = poll(pollfd, 2, -1);
862 		if (ret <= 0) {
863 			if (errno == EINTR || errno == EAGAIN)
864 				continue;
865 			err("poll error: %d", ret);
866 		}
867 		if (pollfd[1].revents & POLLIN) {
868 			if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
869 				err("read pipefd error");
870 			break;
871 		}
872 		if (!(pollfd[0].revents & POLLIN))
873 			err("pollfd[0].revents %d", pollfd[0].revents);
874 		if (uffd_read_msg(uffd, &msg))
875 			continue;
876 		switch (msg.event) {
877 		default:
878 			err("unexpected msg event %u\n", msg.event);
879 			break;
880 		case UFFD_EVENT_PAGEFAULT:
881 			uffd_handle_page_fault(&msg, stats);
882 			break;
883 		case UFFD_EVENT_FORK:
884 			close(uffd);
885 			uffd = msg.arg.fork.ufd;
886 			pollfd[0].fd = uffd;
887 			break;
888 		case UFFD_EVENT_REMOVE:
889 			uffd_reg.range.start = msg.arg.remove.start;
890 			uffd_reg.range.len = msg.arg.remove.end -
891 				msg.arg.remove.start;
892 			if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
893 				err("remove failure");
894 			break;
895 		case UFFD_EVENT_REMAP:
896 			area_remap = area_dst;  /* save for later unmap */
897 			area_dst = (char *)(unsigned long)msg.arg.remap.to;
898 			break;
899 		}
900 	}
901 
902 	return NULL;
903 }
904 
905 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
906 
sigusr1_handler(int signum,siginfo_t * siginfo,void * ptr)907 static void sigusr1_handler(int signum, siginfo_t *siginfo, void *ptr)
908 {
909 	jmp_buf *env;
910 	env = pthread_getspecific(long_jmp_key);
911 	longjmp(*env, 1);
912 }
913 
uffd_read_thread(void * arg)914 static void *uffd_read_thread(void *arg)
915 {
916 	struct uffd_stats *stats = (struct uffd_stats *)arg;
917 	struct uffd_msg msg;
918 	jmp_buf env;
919 	int setjmp_ret;
920 
921 	pthread_setspecific(long_jmp_key, &env);
922 
923 	pthread_mutex_unlock(&uffd_read_mutex);
924 	// One first return setjmp return 0. On second (fake) return from
925 	// longjmp() it returns the provided value, which will be 1 in our case.
926 	setjmp_ret = setjmp(env);
927 	while (!setjmp_ret) {
928 		if (uffd_read_msg(uffd, &msg))
929 			continue;
930 		uffd_handle_page_fault(&msg, stats);
931 	}
932 
933 	return NULL;
934 }
935 
background_thread(void * arg)936 static void *background_thread(void *arg)
937 {
938 	unsigned long cpu = (unsigned long) arg;
939 	unsigned long page_nr, start_nr, mid_nr, end_nr;
940 
941 	start_nr = cpu * nr_pages_per_cpu;
942 	end_nr = (cpu+1) * nr_pages_per_cpu;
943 	mid_nr = (start_nr + end_nr) / 2;
944 
945 	/* Copy the first half of the pages */
946 	for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
947 		copy_page_retry(uffd, page_nr * page_size);
948 
949 	/*
950 	 * If we need to test uffd-wp, set it up now.  Then we'll have
951 	 * at least the first half of the pages mapped already which
952 	 * can be write-protected for testing
953 	 */
954 	if (test_uffdio_wp)
955 		wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
956 			nr_pages_per_cpu * page_size, true);
957 
958 	/*
959 	 * Continue the 2nd half of the page copying, handling write
960 	 * protection faults if any
961 	 */
962 	for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
963 		copy_page_retry(uffd, page_nr * page_size);
964 
965 	return NULL;
966 }
967 
stress(struct uffd_stats * uffd_stats)968 static int stress(struct uffd_stats *uffd_stats)
969 {
970 	unsigned long cpu;
971 	pthread_t locking_threads[nr_cpus];
972 	pthread_t uffd_threads[nr_cpus];
973 	pthread_t background_threads[nr_cpus];
974 
975 	finished = 0;
976 	for (cpu = 0; cpu < nr_cpus; cpu++) {
977 		if (pthread_create(&locking_threads[cpu], &attr,
978 				   locking_thread, (void *)cpu))
979 			return 1;
980 		if (bounces & BOUNCE_POLL) {
981 			if (pthread_create(&uffd_threads[cpu], &attr,
982 					   uffd_poll_thread,
983 					   (void *)&uffd_stats[cpu]))
984 				return 1;
985 		} else {
986 			if (pthread_create(&uffd_threads[cpu], &attr,
987 					   uffd_read_thread,
988 					   (void *)&uffd_stats[cpu]))
989 				return 1;
990 			pthread_mutex_lock(&uffd_read_mutex);
991 		}
992 		if (pthread_create(&background_threads[cpu], &attr,
993 				   background_thread, (void *)cpu))
994 			return 1;
995 	}
996 	for (cpu = 0; cpu < nr_cpus; cpu++)
997 		if (pthread_join(background_threads[cpu], NULL))
998 			return 1;
999 
1000 	/*
1001 	 * Be strict and immediately zap area_src, the whole area has
1002 	 * been transferred already by the background treads. The
1003 	 * area_src could then be faulted in a racy way by still
1004 	 * running uffdio_threads reading zeropages after we zapped
1005 	 * area_src (but they're guaranteed to get -EEXIST from
1006 	 * UFFDIO_COPY without writing zero pages into area_dst
1007 	 * because the background threads already completed).
1008 	 */
1009 	uffd_test_ops->release_pages(area_src);
1010 
1011 	finished = 1;
1012 	for (cpu = 0; cpu < nr_cpus; cpu++)
1013 		if (pthread_join(locking_threads[cpu], NULL))
1014 			return 1;
1015 
1016 	for (cpu = 0; cpu < nr_cpus; cpu++) {
1017 		char c;
1018 		if (bounces & BOUNCE_POLL) {
1019 			if (write(pipefd[cpu*2+1], &c, 1) != 1)
1020 				err("pipefd write error");
1021 			if (pthread_join(uffd_threads[cpu],
1022 					 (void *)&uffd_stats[cpu]))
1023 				return 1;
1024 		} else {
1025 			if (pthread_kill(uffd_threads[cpu], SIGUSR1))
1026 				return 1;
1027 			if (pthread_join(uffd_threads[cpu], NULL))
1028 				return 1;
1029 		}
1030 	}
1031 
1032 	return 0;
1033 }
1034 
1035 sigjmp_buf jbuf, *sigbuf;
1036 
sighndl(int sig,siginfo_t * siginfo,void * ptr)1037 static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
1038 {
1039 	if (sig == SIGBUS) {
1040 		if (sigbuf)
1041 			siglongjmp(*sigbuf, 1);
1042 		abort();
1043 	}
1044 }
1045 
1046 /*
1047  * For non-cooperative userfaultfd test we fork() a process that will
1048  * generate pagefaults, will mremap the area monitored by the
1049  * userfaultfd and at last this process will release the monitored
1050  * area.
1051  * For the anonymous and shared memory the area is divided into two
1052  * parts, the first part is accessed before mremap, and the second
1053  * part is accessed after mremap. Since hugetlbfs does not support
1054  * mremap, the entire monitored area is accessed in a single pass for
1055  * HUGETLB_TEST.
1056  * The release of the pages currently generates event for shmem and
1057  * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
1058  * for hugetlb.
1059  * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
1060  * monitored area, generate pagefaults and test that signal is delivered.
1061  * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
1062  * test robustness use case - we release monitored area, fork a process
1063  * that will generate pagefaults and verify signal is generated.
1064  * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
1065  * feature. Using monitor thread, verify no userfault events are generated.
1066  */
faulting_process(int signal_test)1067 static int faulting_process(int signal_test)
1068 {
1069 	unsigned long nr;
1070 	unsigned long long count;
1071 	unsigned long split_nr_pages;
1072 	unsigned long lastnr;
1073 	struct sigaction act;
1074 	volatile unsigned long signalled = 0;
1075 
1076 	split_nr_pages = (nr_pages + 1) / 2;
1077 
1078 	if (signal_test) {
1079 		sigbuf = &jbuf;
1080 		memset(&act, 0, sizeof(act));
1081 		act.sa_sigaction = sighndl;
1082 		act.sa_flags = SA_SIGINFO;
1083 		if (sigaction(SIGBUS, &act, 0))
1084 			err("sigaction");
1085 		lastnr = (unsigned long)-1;
1086 	}
1087 
1088 	for (nr = 0; nr < split_nr_pages; nr++) {
1089 		volatile int steps = 1;
1090 		unsigned long offset = nr * page_size;
1091 
1092 		if (signal_test) {
1093 			if (sigsetjmp(*sigbuf, 1) != 0) {
1094 				if (steps == 1 && nr == lastnr)
1095 					err("Signal repeated");
1096 
1097 				lastnr = nr;
1098 				if (signal_test == 1) {
1099 					if (steps == 1) {
1100 						/* This is a MISSING request */
1101 						steps++;
1102 						if (copy_page(uffd, offset))
1103 							signalled++;
1104 					} else {
1105 						/* This is a WP request */
1106 						assert(steps == 2);
1107 						wp_range(uffd,
1108 							 (__u64)area_dst +
1109 							 offset,
1110 							 page_size, false);
1111 					}
1112 				} else {
1113 					signalled++;
1114 					continue;
1115 				}
1116 			}
1117 		}
1118 
1119 		count = *area_count(area_dst, nr);
1120 		if (count != count_verify[nr])
1121 			err("nr %lu memory corruption %llu %llu\n",
1122 			    nr, count, count_verify[nr]);
1123 		/*
1124 		 * Trigger write protection if there is by writing
1125 		 * the same value back.
1126 		 */
1127 		*area_count(area_dst, nr) = count;
1128 	}
1129 
1130 	if (signal_test)
1131 		return signalled != split_nr_pages;
1132 
1133 	area_dst = mremap(area_dst, nr_pages * page_size,  nr_pages * page_size,
1134 			  MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
1135 	if (area_dst == MAP_FAILED)
1136 		err("mremap");
1137 	/* Reset area_src since we just clobbered it */
1138 	area_src = NULL;
1139 
1140 	for (; nr < nr_pages; nr++) {
1141 		count = *area_count(area_dst, nr);
1142 		if (count != count_verify[nr]) {
1143 			err("nr %lu memory corruption %llu %llu\n",
1144 			    nr, count, count_verify[nr]);
1145 		}
1146 		/*
1147 		 * Trigger write protection if there is by writing
1148 		 * the same value back.
1149 		 */
1150 		*area_count(area_dst, nr) = count;
1151 	}
1152 
1153 	uffd_test_ops->release_pages(area_dst);
1154 
1155 	for (nr = 0; nr < nr_pages; nr++)
1156 		if (my_bcmp(area_dst + nr * page_size, zeropage, page_size))
1157 			err("nr %lu is not zero", nr);
1158 
1159 	return 0;
1160 }
1161 
retry_uffdio_zeropage(int ufd,struct uffdio_zeropage * uffdio_zeropage,unsigned long offset)1162 static void retry_uffdio_zeropage(int ufd,
1163 				  struct uffdio_zeropage *uffdio_zeropage,
1164 				  unsigned long offset)
1165 {
1166 	uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
1167 				     uffdio_zeropage->range.len,
1168 				     offset);
1169 	if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
1170 		if (uffdio_zeropage->zeropage != -EEXIST)
1171 			err("UFFDIO_ZEROPAGE error: %"PRId64,
1172 			    (int64_t)uffdio_zeropage->zeropage);
1173 	} else {
1174 		err("UFFDIO_ZEROPAGE error: %"PRId64,
1175 		    (int64_t)uffdio_zeropage->zeropage);
1176 	}
1177 }
1178 
__uffdio_zeropage(int ufd,unsigned long offset,bool retry)1179 static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
1180 {
1181 	struct uffdio_zeropage uffdio_zeropage;
1182 	int ret;
1183 	bool has_zeropage = get_expected_ioctls(0) & (1 << _UFFDIO_ZEROPAGE);
1184 	__s64 res;
1185 
1186 	if (offset >= nr_pages * page_size)
1187 		err("unexpected offset %lu", offset);
1188 	uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
1189 	uffdio_zeropage.range.len = page_size;
1190 	uffdio_zeropage.mode = 0;
1191 	ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
1192 	res = uffdio_zeropage.zeropage;
1193 	if (ret) {
1194 		/* real retval in ufdio_zeropage.zeropage */
1195 		if (has_zeropage)
1196 			err("UFFDIO_ZEROPAGE error: %"PRId64, (int64_t)res);
1197 		else if (res != -EINVAL)
1198 			err("UFFDIO_ZEROPAGE not -EINVAL");
1199 	} else if (has_zeropage) {
1200 		if (res != page_size) {
1201 			err("UFFDIO_ZEROPAGE unexpected size");
1202 		} else {
1203 			if (test_uffdio_zeropage_eexist && retry) {
1204 				test_uffdio_zeropage_eexist = false;
1205 				retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1206 						      offset);
1207 			}
1208 			return 1;
1209 		}
1210 	} else
1211 		err("UFFDIO_ZEROPAGE succeeded");
1212 
1213 	return 0;
1214 }
1215 
uffdio_zeropage(int ufd,unsigned long offset)1216 static int uffdio_zeropage(int ufd, unsigned long offset)
1217 {
1218 	return __uffdio_zeropage(ufd, offset, false);
1219 }
1220 
1221 /* exercise UFFDIO_ZEROPAGE */
userfaultfd_zeropage_test(void)1222 static int userfaultfd_zeropage_test(void)
1223 {
1224 	struct uffdio_register uffdio_register;
1225 
1226 	printf("testing UFFDIO_ZEROPAGE: ");
1227 	fflush(stdout);
1228 
1229 	uffd_test_ctx_init(0);
1230 
1231 	uffdio_register.range.start = (unsigned long) area_dst;
1232 	uffdio_register.range.len = nr_pages * page_size;
1233 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1234 	if (test_uffdio_wp)
1235 		uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1236 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1237 		err("register failure");
1238 
1239 	assert_expected_ioctls_present(
1240 		uffdio_register.mode, uffdio_register.ioctls);
1241 
1242 	if (uffdio_zeropage(uffd, 0))
1243 		if (my_bcmp(area_dst, zeropage, page_size))
1244 			err("zeropage is not zero");
1245 
1246 	printf("done.\n");
1247 	return 0;
1248 }
1249 
userfaultfd_events_test(void)1250 static int userfaultfd_events_test(void)
1251 {
1252 	struct uffdio_register uffdio_register;
1253 	pthread_t uffd_mon;
1254 	int err, features;
1255 	pid_t pid;
1256 	char c;
1257 	struct uffd_stats stats = { 0 };
1258 
1259 	// All the syscalls below up to pthread_create will ensure that this
1260 	// write is completed before, the uffd_thread sets it to true.
1261 	ready_for_fork = false;
1262 
1263 	printf("testing events (fork, remap, remove): ");
1264 	fflush(stdout);
1265 
1266 	features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1267 		UFFD_FEATURE_EVENT_REMOVE;
1268 	uffd_test_ctx_init(features);
1269 
1270 	fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1271 
1272 	uffdio_register.range.start = (unsigned long) area_dst;
1273 	uffdio_register.range.len = nr_pages * page_size;
1274 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1275 	if (test_uffdio_wp)
1276 		uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1277 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1278 		err("register failure");
1279 
1280 	assert_expected_ioctls_present(
1281 		uffdio_register.mode, uffdio_register.ioctls);
1282 
1283 	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1284 		err("uffd_poll_thread create");
1285 
1286 	// Wait for the poll_thread to start executing before forking. This is
1287 	// required to avoid a deadlock, which can happen if poll_thread doesn't
1288 	// start getting executed by the time fork is invoked.
1289 	while (!ready_for_fork);
1290 
1291 	pid = fork();
1292 	if (pid < 0)
1293 		err("fork");
1294 
1295 	if (!pid)
1296 		exit(faulting_process(0));
1297 
1298 	waitpid(pid, &err, 0);
1299 	if (err)
1300 		err("faulting process failed");
1301 	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1302 		err("pipe write");
1303 	if (pthread_join(uffd_mon, NULL))
1304 		return 1;
1305 
1306 	uffd_stats_report(&stats, 1);
1307 
1308 	return stats.missing_faults != nr_pages;
1309 }
1310 
userfaultfd_sig_test(void)1311 static int userfaultfd_sig_test(void)
1312 {
1313 	struct uffdio_register uffdio_register;
1314 	unsigned long userfaults;
1315 	pthread_t uffd_mon;
1316 	int err, features;
1317 	pid_t pid;
1318 	char c;
1319 	struct uffd_stats stats = { 0 };
1320 
1321 	// All the syscalls below up to pthread_create will ensure that this
1322 	// write is completed before, the uffd_thread sets it to true.
1323 	ready_for_fork = false;
1324 
1325 	printf("testing signal delivery: ");
1326 	fflush(stdout);
1327 
1328 	features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1329 	uffd_test_ctx_init(features);
1330 
1331 	fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1332 
1333 	uffdio_register.range.start = (unsigned long) area_dst;
1334 	uffdio_register.range.len = nr_pages * page_size;
1335 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1336 	if (test_uffdio_wp)
1337 		uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1338 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1339 		err("register failure");
1340 
1341 	assert_expected_ioctls_present(
1342 		uffdio_register.mode, uffdio_register.ioctls);
1343 
1344 	if (faulting_process(1))
1345 		err("faulting process failed");
1346 
1347 	uffd_test_ops->release_pages(area_dst);
1348 
1349 	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1350 		err("uffd_poll_thread create");
1351 
1352 	// Wait for the poll_thread to start executing before forking. This is
1353 	// required to avoid a deadlock, which can happen if poll_thread doesn't
1354 	// start getting executed by the time fork is invoked.
1355 	while (!ready_for_fork);
1356 
1357 	pid = fork();
1358 	if (pid < 0)
1359 		err("fork");
1360 
1361 	if (!pid)
1362 		exit(faulting_process(2));
1363 
1364 	waitpid(pid, &err, 0);
1365 	if (err)
1366 		err("faulting process failed");
1367 	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1368 		err("pipe write");
1369 	if (pthread_join(uffd_mon, (void **)&userfaults))
1370 		return 1;
1371 
1372 	printf("done.\n");
1373 	if (userfaults)
1374 		err("Signal test failed, userfaults: %ld", userfaults);
1375 
1376 	return userfaults != 0;
1377 }
1378 
check_memory_contents(char * p)1379 void check_memory_contents(char *p)
1380 {
1381 	unsigned long i;
1382 	uint8_t expected_byte;
1383 	void *expected_page;
1384 
1385 	if (posix_memalign(&expected_page, page_size, page_size))
1386 		err("out of memory");
1387 
1388 	for (i = 0; i < nr_pages; ++i) {
1389 		expected_byte = ~((uint8_t)(i % ((uint8_t)-1)));
1390 		memset(expected_page, expected_byte, page_size);
1391 		if (my_bcmp(expected_page, p + (i * page_size), page_size))
1392 			err("unexpected page contents after minor fault");
1393 	}
1394 
1395 	free(expected_page);
1396 }
1397 
userfaultfd_minor_test(void)1398 static int userfaultfd_minor_test(void)
1399 {
1400 	unsigned long p;
1401 	struct uffdio_register uffdio_register;
1402 	pthread_t uffd_mon;
1403 	char c;
1404 	struct uffd_stats stats = { 0 };
1405 
1406 	if (!test_uffdio_minor)
1407 		return 0;
1408 
1409 	printf("testing minor faults: ");
1410 	fflush(stdout);
1411 
1412 	uffd_test_ctx_init(uffd_minor_feature());
1413 
1414 	uffdio_register.range.start = (unsigned long)area_dst_alias;
1415 	uffdio_register.range.len = nr_pages * page_size;
1416 	uffdio_register.mode = UFFDIO_REGISTER_MODE_MINOR;
1417 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1418 		err("register failure");
1419 
1420 	assert_expected_ioctls_present(
1421 		uffdio_register.mode, uffdio_register.ioctls);
1422 
1423 	/*
1424 	 * After registering with UFFD, populate the non-UFFD-registered side of
1425 	 * the shared mapping. This should *not* trigger any UFFD minor faults.
1426 	 */
1427 	for (p = 0; p < nr_pages; ++p) {
1428 		memset(area_dst + (p * page_size), p % ((uint8_t)-1),
1429 		       page_size);
1430 	}
1431 
1432 	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1433 		err("uffd_poll_thread create");
1434 
1435 	/*
1436 	 * Read each of the pages back using the UFFD-registered mapping. We
1437 	 * expect that the first time we touch a page, it will result in a minor
1438 	 * fault. uffd_poll_thread will resolve the fault by bit-flipping the
1439 	 * page's contents, and then issuing a CONTINUE ioctl.
1440 	 */
1441 	check_memory_contents(area_dst_alias);
1442 
1443 	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1444 		err("pipe write");
1445 	if (pthread_join(uffd_mon, NULL))
1446 		return 1;
1447 
1448 	uffd_stats_report(&stats, 1);
1449 
1450 	if (test_collapse) {
1451 		printf("testing collapse of uffd memory into PMD-mapped THPs:");
1452 		if (madvise(area_dst_alias, nr_pages * page_size,
1453 			    MADV_COLLAPSE))
1454 			err("madvise(MADV_COLLAPSE)");
1455 
1456 		uffd_test_ops->check_pmd_mapping(area_dst,
1457 						 nr_pages * page_size /
1458 						 hpage_size);
1459 		/*
1460 		 * This won't cause uffd-fault - it purely just makes sure there
1461 		 * was no corruption.
1462 		 */
1463 		check_memory_contents(area_dst_alias);
1464 		printf(" done.\n");
1465 	}
1466 
1467 	return stats.missing_faults != 0 || stats.minor_faults != nr_pages;
1468 }
1469 
1470 #define BIT_ULL(nr)                   (1ULL << (nr))
1471 #define PM_SOFT_DIRTY                 BIT_ULL(55)
1472 #define PM_MMAP_EXCLUSIVE             BIT_ULL(56)
1473 #define PM_UFFD_WP                    BIT_ULL(57)
1474 #define PM_FILE                       BIT_ULL(61)
1475 #define PM_SWAP                       BIT_ULL(62)
1476 #define PM_PRESENT                    BIT_ULL(63)
1477 
1478 /*
1479  * b/232026677
1480  * pagemap not compatible with < 5.14
1481  */
1482 #ifndef __ANDROID__
pagemap_open(void)1483 static int pagemap_open(void)
1484 {
1485 	int fd = open("/proc/self/pagemap", O_RDONLY);
1486 
1487 	if (fd < 0)
1488 		err("open pagemap");
1489 
1490 	return fd;
1491 }
1492 
pagemap_read_vaddr(int fd,void * vaddr)1493 static uint64_t pagemap_read_vaddr(int fd, void *vaddr)
1494 {
1495 	uint64_t value;
1496 	int ret;
1497 
1498 	ret = pread(fd, &value, sizeof(uint64_t),
1499 		    ((uint64_t)vaddr >> 12) * sizeof(uint64_t));
1500 	if (ret != sizeof(uint64_t))
1501 		err("pread() on pagemap failed");
1502 
1503 	return value;
1504 }
1505 
1506 /* This macro let __LINE__ works in err() */
1507 #define  pagemap_check_wp(value, wp) do {				\
1508 		if (!!(value & PM_UFFD_WP) != wp)			\
1509 			err("pagemap uffd-wp bit error: 0x%"PRIx64, value); \
1510 	} while (0)
1511 
pagemap_test_fork(bool present)1512 static int pagemap_test_fork(bool present)
1513 {
1514 	pid_t child = fork();
1515 	uint64_t value;
1516 	int fd, result;
1517 
1518 	if (!child) {
1519 		/* Open the pagemap fd of the child itself */
1520 		fd = pagemap_open();
1521 		value = pagemap_read_vaddr(fd, area_dst);
1522 		/*
1523 		 * After fork() uffd-wp bit should be gone as long as we're
1524 		 * without UFFD_FEATURE_EVENT_FORK
1525 		 */
1526 		pagemap_check_wp(value, false);
1527 		/* Succeed */
1528 		exit(0);
1529 	}
1530 	waitpid(child, &result, 0);
1531 	return result;
1532 }
1533 
userfaultfd_pagemap_test(unsigned int test_pgsize)1534 static void userfaultfd_pagemap_test(unsigned int test_pgsize)
1535 {
1536 	struct uffdio_register uffdio_register;
1537 	int pagemap_fd;
1538 	uint64_t value;
1539 
1540 	/* Pagemap tests uffd-wp only */
1541 	if (!test_uffdio_wp)
1542 		return;
1543 
1544 	/* Not enough memory to test this page size */
1545 	if (test_pgsize > nr_pages * page_size)
1546 		return;
1547 
1548 	printf("testing uffd-wp with pagemap (pgsize=%u): ", test_pgsize);
1549 	/* Flush so it doesn't flush twice in parent/child later */
1550 	fflush(stdout);
1551 
1552 	uffd_test_ctx_init(0);
1553 
1554 	if (test_pgsize > page_size) {
1555 		/* This is a thp test */
1556 		if (madvise(area_dst, nr_pages * page_size, MADV_HUGEPAGE))
1557 			err("madvise(MADV_HUGEPAGE) failed");
1558 	} else if (test_pgsize == page_size) {
1559 		/* This is normal page test; force no thp */
1560 		if (madvise(area_dst, nr_pages * page_size, MADV_NOHUGEPAGE))
1561 			err("madvise(MADV_NOHUGEPAGE) failed");
1562 	}
1563 
1564 	uffdio_register.range.start = (unsigned long) area_dst;
1565 	uffdio_register.range.len = nr_pages * page_size;
1566 	uffdio_register.mode = UFFDIO_REGISTER_MODE_WP;
1567 	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1568 		err("register failed");
1569 
1570 	pagemap_fd = pagemap_open();
1571 
1572 	/* Touch the page */
1573 	*area_dst = 1;
1574 	wp_range(uffd, (uint64_t)area_dst, test_pgsize, true);
1575 	value = pagemap_read_vaddr(pagemap_fd, area_dst);
1576 	pagemap_check_wp(value, true);
1577 	/* Make sure uffd-wp bit dropped when fork */
1578 	if (pagemap_test_fork(true))
1579 		err("Detected stall uffd-wp bit in child");
1580 
1581 	/* Exclusive required or PAGEOUT won't work */
1582 	if (!(value & PM_MMAP_EXCLUSIVE))
1583 		err("multiple mapping detected: 0x%"PRIx64, value);
1584 
1585 	if (madvise(area_dst, test_pgsize, MADV_PAGEOUT))
1586 		err("madvise(MADV_PAGEOUT) failed");
1587 
1588 	/* Uffd-wp should persist even swapped out */
1589 	value = pagemap_read_vaddr(pagemap_fd, area_dst);
1590 	pagemap_check_wp(value, true);
1591 	/* Make sure uffd-wp bit dropped when fork */
1592 	if (pagemap_test_fork(false))
1593 		err("Detected stall uffd-wp bit in child");
1594 
1595 	/* Unprotect; this tests swap pte modifications */
1596 	wp_range(uffd, (uint64_t)area_dst, page_size, false);
1597 	value = pagemap_read_vaddr(pagemap_fd, area_dst);
1598 	pagemap_check_wp(value, false);
1599 
1600 	/* Fault in the page from disk */
1601 	*area_dst = 2;
1602 	value = pagemap_read_vaddr(pagemap_fd, area_dst);
1603 	pagemap_check_wp(value, false);
1604 
1605 	close(pagemap_fd);
1606 	printf("done\n");
1607 }
1608 #endif
1609 
userfaultfd_stress(void)1610 static int userfaultfd_stress(void)
1611 {
1612 	void *area;
1613 	unsigned long nr;
1614 	struct uffdio_register uffdio_register;
1615 	struct sigaction act;
1616 	struct uffd_stats uffd_stats[nr_cpus];
1617 
1618 	uffd_test_ctx_init(0);
1619 
1620 	if (posix_memalign(&area, page_size, page_size))
1621 		err("out of memory");
1622 	zeropage = area;
1623 	bzero(zeropage, page_size);
1624 
1625 	pthread_mutex_lock(&uffd_read_mutex);
1626 
1627 	pthread_attr_init(&attr);
1628 	pthread_attr_setstacksize(&attr, 16*1024*1024);
1629 
1630 	// For handling thread termination of read thread in the absence of
1631 	// pthread_cancel().
1632 	pthread_key_create(&long_jmp_key, NULL);
1633 	memset(&act, 0, sizeof(act));
1634 	act.sa_sigaction = sigusr1_handler;
1635 	act.sa_flags = SA_SIGINFO;
1636 	if (sigaction(SIGUSR1, &act, 0)) {
1637 		perror("sigaction");
1638 		return 1;
1639 	}
1640 
1641 	while (bounces--) {
1642 		printf("bounces: %d, mode:", bounces);
1643 		if (bounces & BOUNCE_RANDOM)
1644 			printf(" rnd");
1645 		if (bounces & BOUNCE_RACINGFAULTS)
1646 			printf(" racing");
1647 		if (bounces & BOUNCE_VERIFY)
1648 			printf(" ver");
1649 		if (bounces & BOUNCE_POLL)
1650 			printf(" poll");
1651 		else
1652 			printf(" read");
1653 		printf(", ");
1654 		fflush(stdout);
1655 
1656 		if (bounces & BOUNCE_POLL)
1657 			fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1658 		else
1659 			fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1660 
1661 		/* register */
1662 		uffdio_register.range.start = (unsigned long) area_dst;
1663 		uffdio_register.range.len = nr_pages * page_size;
1664 		uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1665 		if (test_uffdio_wp)
1666 			uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1667 		if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1668 			err("register failure");
1669 		assert_expected_ioctls_present(
1670 			uffdio_register.mode, uffdio_register.ioctls);
1671 
1672 		if (area_dst_alias) {
1673 			uffdio_register.range.start = (unsigned long)
1674 				area_dst_alias;
1675 			if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1676 				err("register failure alias");
1677 		}
1678 
1679 		/*
1680 		 * The madvise done previously isn't enough: some
1681 		 * uffd_thread could have read userfaults (one of
1682 		 * those already resolved by the background thread)
1683 		 * and it may be in the process of calling
1684 		 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1685 		 * area_src and it would map a zero page in it (of
1686 		 * course such a UFFDIO_COPY is perfectly safe as it'd
1687 		 * return -EEXIST). The problem comes at the next
1688 		 * bounce though: that racing UFFDIO_COPY would
1689 		 * generate zeropages in the area_src, so invalidating
1690 		 * the previous MADV_DONTNEED. Without this additional
1691 		 * MADV_DONTNEED those zeropages leftovers in the
1692 		 * area_src would lead to -EEXIST failure during the
1693 		 * next bounce, effectively leaving a zeropage in the
1694 		 * area_dst.
1695 		 *
1696 		 * Try to comment this out madvise to see the memory
1697 		 * corruption being caught pretty quick.
1698 		 *
1699 		 * khugepaged is also inhibited to collapse THP after
1700 		 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1701 		 * required to MADV_DONTNEED here.
1702 		 */
1703 		uffd_test_ops->release_pages(area_dst);
1704 
1705 		uffd_stats_reset(uffd_stats, nr_cpus);
1706 
1707 		/* bounce pass */
1708 		if (stress(uffd_stats))
1709 			return 1;
1710 
1711 		/* Clear all the write protections if there is any */
1712 		if (test_uffdio_wp)
1713 			wp_range(uffd, (unsigned long)area_dst,
1714 				 nr_pages * page_size, false);
1715 
1716 		/* unregister */
1717 		if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range))
1718 			err("unregister failure");
1719 		if (area_dst_alias) {
1720 			uffdio_register.range.start = (unsigned long) area_dst;
1721 			if (ioctl(uffd, UFFDIO_UNREGISTER,
1722 				  &uffdio_register.range))
1723 				err("unregister failure alias");
1724 		}
1725 
1726 		/* verification */
1727 		if (bounces & BOUNCE_VERIFY)
1728 			for (nr = 0; nr < nr_pages; nr++)
1729 				if (*area_count(area_dst, nr) != count_verify[nr])
1730 					err("error area_count %llu %llu %lu\n",
1731 					    *area_count(area_src, nr),
1732 					    count_verify[nr], nr);
1733 
1734 		/* prepare next bounce */
1735 		swap(area_src, area_dst);
1736 
1737 		swap(area_src_alias, area_dst_alias);
1738 
1739 		uffd_stats_report(uffd_stats, nr_cpus);
1740 	}
1741 
1742 /*
1743  * b/232026677
1744  * pagemap not compatible with < 5.14
1745  */
1746 #ifndef __ANDROID__
1747 	if (test_type == TEST_ANON) {
1748 		/*
1749 		 * shmem/hugetlb won't be able to run since they have different
1750 		 * behavior on fork() (file-backed memory normally drops ptes
1751 		 * directly when fork), meanwhile the pagemap test will verify
1752 		 * pgtable entry of fork()ed child.
1753 		 */
1754 		userfaultfd_pagemap_test(page_size);
1755 		/*
1756 		 * Hard-code for x86_64 for now for 2M THP, as x86_64 is
1757 		 * currently the only one that supports uffd-wp
1758 		 */
1759 		userfaultfd_pagemap_test(page_size * 512);
1760 	}
1761 #endif
1762 
1763 	pthread_key_delete(long_jmp_key);
1764 
1765 	return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1766 		|| userfaultfd_events_test() || userfaultfd_minor_test();
1767 }
1768 
1769 /*
1770  * Copied from mlock2-tests.c
1771  */
default_huge_page_size(void)1772 unsigned long default_huge_page_size(void)
1773 {
1774 	unsigned long hps = 0;
1775 	char *line = NULL;
1776 	size_t linelen = 0;
1777 	FILE *f = fopen("/proc/meminfo", "r");
1778 
1779 	if (!f)
1780 		return 0;
1781 	while (getline(&line, &linelen, f) > 0) {
1782 		if (sscanf(line, "Hugepagesize:       %lu kB", &hps) == 1) {
1783 			hps <<= 10;
1784 			break;
1785 		}
1786 	}
1787 
1788 	free(line);
1789 	fclose(f);
1790 	return hps;
1791 }
1792 
set_test_type(const char * type)1793 static void set_test_type(const char *type)
1794 {
1795 	if (!strcmp(type, "anon")) {
1796 		test_type = TEST_ANON;
1797 		uffd_test_ops = &anon_uffd_test_ops;
1798 		/* Only enable write-protect test for anonymous test */
1799 		test_uffdio_wp = true;
1800 	} else if (!strcmp(type, "hugetlb")) {
1801 		test_type = TEST_HUGETLB;
1802 		uffd_test_ops = &hugetlb_uffd_test_ops;
1803 	} else if (!strcmp(type, "hugetlb_shared")) {
1804 		map_shared = true;
1805 		test_type = TEST_HUGETLB;
1806 		uffd_test_ops = &hugetlb_uffd_test_ops;
1807 		/* Minor faults require shared hugetlb; only enable here. */
1808 		test_uffdio_minor = true;
1809 	} else if (!strcmp(type, "shmem")) {
1810 		map_shared = true;
1811 		test_type = TEST_SHMEM;
1812 		uffd_test_ops = &shmem_uffd_test_ops;
1813 		test_uffdio_minor = true;
1814 	}
1815 }
1816 
parse_test_type_arg(const char * raw_type)1817 static void parse_test_type_arg(const char *raw_type)
1818 {
1819 	char *buf = strdup(raw_type);
1820 	/* b/234150821
1821 	 * UFFD_FEATURE_PAGEFAULT_FLAG_WP unsupported in kernel <5.7
1822 	 */
1823 #ifdef __ANDROID__
1824 	uint64_t features = (
1825 		UFFD_FEATURE_EVENT_FORK |        \
1826 		UFFD_FEATURE_EVENT_REMAP |       \
1827 		UFFD_FEATURE_EVENT_REMOVE |      \
1828 		UFFD_FEATURE_EVENT_UNMAP |       \
1829 		UFFD_FEATURE_MISSING_HUGETLBFS | \
1830 		UFFD_FEATURE_MISSING_SHMEM |     \
1831 		UFFD_FEATURE_SIGBUS |            \
1832 		UFFD_FEATURE_THREAD_ID |         \
1833 		UFFD_FEATURE_MINOR_HUGETLBFS |   \
1834 		UFFD_FEATURE_MINOR_SHMEM);
1835 #else
1836 	uint64_t features = UFFD_API_FEATURES;
1837 #endif
1838 
1839 	while (buf) {
1840 		const char *token = strsep(&buf, ":");
1841 
1842 		if (!test_type)
1843 			set_test_type(token);
1844 		else if (!strcmp(token, "dev"))
1845 			test_dev_userfaultfd = true;
1846 		else if (!strcmp(token, "syscall"))
1847 			test_dev_userfaultfd = false;
1848 		else if (!strcmp(token, "collapse"))
1849 			test_collapse = true;
1850 		else
1851 			err("unrecognized test mod '%s'", token);
1852 	}
1853 
1854 	if (!test_type)
1855 		err("failed to parse test type argument: '%s'", raw_type);
1856 
1857 	if (test_collapse && test_type != TEST_SHMEM)
1858 		err("Unsupported test: %s", raw_type);
1859 
1860 	if (test_type == TEST_HUGETLB)
1861 		page_size = hpage_size;
1862 	else
1863 		page_size = sysconf(_SC_PAGE_SIZE);
1864 
1865 	if (!page_size)
1866 		err("Unable to determine page size");
1867 	if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1868 	    > page_size)
1869 		err("Impossible to run this test");
1870 
1871 	/*
1872 	 * Whether we can test certain features depends not just on test type,
1873 	 * but also on whether or not this particular kernel supports the
1874 	 * feature.
1875 	 */
1876 
1877 	userfaultfd_open(&features);
1878 
1879 	test_uffdio_wp = test_uffdio_wp &&
1880 		(features & UFFD_FEATURE_PAGEFAULT_FLAG_WP);
1881 	test_uffdio_minor = test_uffdio_minor &&
1882 		(features & uffd_minor_feature());
1883 
1884 	close(uffd);
1885 	uffd = -1;
1886 }
1887 
sigalrm(int sig)1888 static void sigalrm(int sig)
1889 {
1890 	if (sig != SIGALRM)
1891 		abort();
1892 	test_uffdio_copy_eexist = true;
1893 	test_uffdio_zeropage_eexist = true;
1894 	alarm(ALARM_INTERVAL_SECS);
1895 }
1896 
main(int argc,char ** argv)1897 int main(int argc, char **argv)
1898 {
1899 	size_t bytes;
1900 
1901 	if (argc < 4)
1902 		usage();
1903 
1904 	if (signal(SIGALRM, sigalrm) == SIG_ERR)
1905 		err("failed to arm SIGALRM");
1906 	alarm(ALARM_INTERVAL_SECS);
1907 
1908 	hpage_size = default_huge_page_size();
1909 	parse_test_type_arg(argv[1]);
1910 	bytes = atol(argv[2]) * 1024 * 1024;
1911 
1912 	if (test_collapse && bytes & (hpage_size - 1))
1913 		err("MiB must be multiple of %lu if :collapse mod set",
1914 		    hpage_size >> 20);
1915 
1916 	nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1917 
1918 	if (test_collapse) {
1919 		/* nr_cpus must divide (bytes / page_size), otherwise,
1920 		 * area allocations of (nr_pages * paze_size) won't be a
1921 		 * multiple of hpage_size, even if bytes is a multiple of
1922 		 * hpage_size.
1923 		 *
1924 		 * This means that nr_cpus must divide (N * (2 << (H-P))
1925 		 * where:
1926 		 *	bytes = hpage_size * N
1927 		 *	hpage_size = 2 << H
1928 		 *	page_size = 2 << P
1929 		 *
1930 		 * And we want to chose nr_cpus to be the largest value
1931 		 * satisfying this constraint, not larger than the number
1932 		 * of online CPUs. Unfortunately, prime factorization of
1933 		 * N and nr_cpus may be arbitrary, so have to search for it.
1934 		 * Instead, just use the highest power of 2 dividing both
1935 		 * nr_cpus and (bytes / page_size).
1936 		 */
1937 		int x = factor_of_2(nr_cpus);
1938 		int y = factor_of_2(bytes / page_size);
1939 
1940 		nr_cpus = x < y ? x : y;
1941 	}
1942 	nr_pages_per_cpu = bytes / page_size / nr_cpus;
1943 	if (!nr_pages_per_cpu) {
1944 		_err("invalid MiB");
1945 		usage();
1946 	}
1947 
1948 	bounces = atoi(argv[3]);
1949 	if (bounces <= 0) {
1950 		_err("invalid bounces");
1951 		usage();
1952 	}
1953 	nr_pages = nr_pages_per_cpu * nr_cpus;
1954 
1955 	if (test_type == TEST_HUGETLB && map_shared) {
1956 		if (argc < 5)
1957 			usage();
1958 		huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1959 		if (huge_fd < 0)
1960 			err("Open of %s failed", argv[4]);
1961 		if (ftruncate(huge_fd, 0))
1962 			err("ftruncate %s to size 0 failed", argv[4]);
1963 	} else if (test_type == TEST_SHMEM) {
1964 		shm_fd = memfd_create(argv[0], 0);
1965 		if (shm_fd < 0)
1966 			err("memfd_create");
1967 		if (ftruncate(shm_fd, nr_pages * page_size * 2))
1968 			err("ftruncate");
1969 		if (fallocate(shm_fd,
1970 			      FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
1971 			      nr_pages * page_size * 2))
1972 			err("fallocate");
1973 	}
1974 	printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1975 	       nr_pages, nr_pages_per_cpu);
1976 	return userfaultfd_stress();
1977 }
1978 
1979 #else /* __NR_userfaultfd */
1980 
1981 #warning "missing __NR_userfaultfd definition"
1982 
main(void)1983 int main(void)
1984 {
1985 	printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1986 	return KSFT_SKIP;
1987 }
1988 
1989 #endif /* __NR_userfaultfd */
1990