xref: /linux/tools/testing/selftests/mm/uffd-common.c (revision 18fbf5151d2c0bfe433c7428eef03cabf5fdb2fa)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Userfaultfd tests util functions
4  *
5  * Copyright (C) 2015-2023  Red Hat, Inc.
6  */
7 
8 #include "uffd-common.h"
9 
10 uffd_test_ops_t *uffd_test_ops;
11 uffd_test_case_ops_t *uffd_test_case_ops;
12 
13 
14 /* pthread_mutex_t starts at page offset 0 */
15 pthread_mutex_t *area_mutex(char *area, unsigned long nr, uffd_global_test_opts_t *gopts)
16 {
17 	return (pthread_mutex_t *) (area + nr * gopts->page_size);
18 }
19 
20 /*
21  * count is placed in the page after pthread_mutex_t naturally aligned
22  * to avoid non alignment faults on non-x86 archs.
23  */
24 volatile unsigned long long *area_count(char *area, unsigned long nr,
25 					uffd_global_test_opts_t *gopts)
26 {
27 	return (volatile unsigned long long *)
28 	       ((unsigned long)(area + nr * gopts->page_size +
29 	       sizeof(pthread_mutex_t) + sizeof(unsigned long long) - 1) &
30 	       ~(unsigned long)(sizeof(unsigned long long) - 1));
31 }
32 
33 static int uffd_mem_fd_create(off_t mem_size, bool hugetlb)
34 {
35 	unsigned int memfd_flags = 0;
36 	int mem_fd;
37 
38 	if (hugetlb)
39 		memfd_flags = MFD_HUGETLB;
40 	mem_fd = memfd_create("uffd-test", memfd_flags);
41 	if (mem_fd < 0)
42 		err("memfd_create");
43 	if (ftruncate(mem_fd, mem_size))
44 		err("ftruncate");
45 	if (fallocate(mem_fd,
46 		      FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
47 		      mem_size))
48 		err("fallocate");
49 
50 	return mem_fd;
51 }
52 
53 static void anon_release_pages(uffd_global_test_opts_t *gopts, char *rel_area)
54 {
55 	if (madvise(rel_area, gopts->nr_pages * gopts->page_size, MADV_DONTNEED))
56 		err("madvise(MADV_DONTNEED) failed");
57 }
58 
59 static int anon_allocate_area(uffd_global_test_opts_t *gopts, void **alloc_area, bool is_src)
60 {
61 	*alloc_area = mmap(NULL, gopts->nr_pages * gopts->page_size, PROT_READ | PROT_WRITE,
62 			   MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
63 	if (*alloc_area == MAP_FAILED) {
64 		*alloc_area = NULL;
65 		return -errno;
66 	}
67 	return 0;
68 }
69 
70 static void noop_alias_mapping(uffd_global_test_opts_t *gopts, __u64 *start,
71 			       size_t len, unsigned long offset)
72 {
73 }
74 
75 static void hugetlb_release_pages(uffd_global_test_opts_t *gopts, char *rel_area)
76 {
77 	if (!gopts->map_shared) {
78 		if (madvise(rel_area, gopts->nr_pages * gopts->page_size, MADV_DONTNEED))
79 			err("madvise(MADV_DONTNEED) failed");
80 	} else {
81 		if (madvise(rel_area, gopts->nr_pages * gopts->page_size, MADV_REMOVE))
82 			err("madvise(MADV_REMOVE) failed");
83 	}
84 }
85 
86 static int hugetlb_allocate_area(uffd_global_test_opts_t *gopts, void **alloc_area, bool is_src)
87 {
88 	off_t size = gopts->nr_pages * gopts->page_size;
89 	off_t offset = is_src ? 0 : size;
90 	void *area_alias = NULL;
91 	char **alloc_area_alias;
92 	int mem_fd = uffd_mem_fd_create(size * 2, true);
93 
94 	*alloc_area = mmap(NULL, size, PROT_READ | PROT_WRITE,
95 			   (gopts->map_shared ? MAP_SHARED : MAP_PRIVATE) |
96 			   (is_src ? 0 : MAP_NORESERVE),
97 			   mem_fd, offset);
98 	if (*alloc_area == MAP_FAILED) {
99 		*alloc_area = NULL;
100 		return -errno;
101 	}
102 
103 	if (gopts->map_shared) {
104 		area_alias = mmap(NULL, size, PROT_READ | PROT_WRITE,
105 				  MAP_SHARED, mem_fd, offset);
106 		if (area_alias == MAP_FAILED)
107 			return -errno;
108 	}
109 
110 	if (is_src) {
111 		alloc_area_alias = &gopts->area_src_alias;
112 	} else {
113 		alloc_area_alias = &gopts->area_dst_alias;
114 	}
115 	if (area_alias)
116 		*alloc_area_alias = area_alias;
117 
118 	close(mem_fd);
119 	return 0;
120 }
121 
122 static void hugetlb_alias_mapping(uffd_global_test_opts_t *gopts, __u64 *start,
123 				  size_t len, unsigned long offset)
124 {
125 	if (!gopts->map_shared)
126 		return;
127 
128 	*start = (unsigned long) gopts->area_dst_alias + offset;
129 }
130 
131 static void shmem_release_pages(uffd_global_test_opts_t *gopts, char *rel_area)
132 {
133 	if (madvise(rel_area, gopts->nr_pages * gopts->page_size, MADV_REMOVE))
134 		err("madvise(MADV_REMOVE) failed");
135 }
136 
137 static int shmem_allocate_area(uffd_global_test_opts_t *gopts, void **alloc_area, bool is_src)
138 {
139 	void *area_alias = NULL;
140 	size_t bytes = gopts->nr_pages * gopts->page_size, hpage_size = read_pmd_pagesize();
141 	unsigned long offset = is_src ? 0 : bytes;
142 	char *p = NULL, *p_alias = NULL;
143 	int mem_fd = uffd_mem_fd_create(bytes * 2, false);
144 	size_t region_size = bytes * 2 + hpage_size;
145 
146 	void *reserve = mmap(NULL, region_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS,
147 			-1, 0);
148 	if (reserve == MAP_FAILED) {
149 		close(mem_fd);
150 		return -errno;
151 	}
152 
153 	p = reserve;
154 	p_alias = p;
155 	p_alias += bytes;
156 	p_alias += hpage_size;  /* Prevent src/dst VMA merge */
157 
158 	*alloc_area = mmap(p, bytes, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED,
159 			   mem_fd, offset);
160 	if (*alloc_area == MAP_FAILED) {
161 		*alloc_area = NULL;
162 		munmap(reserve, region_size);
163 		close(mem_fd);
164 		return -errno;
165 	}
166 	if (*alloc_area != p)
167 		err("mmap of memfd failed at %p", p);
168 
169 	area_alias = mmap(p_alias, bytes, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED,
170 			  mem_fd, offset);
171 	if (area_alias == MAP_FAILED) {
172 		*alloc_area = NULL;
173 		munmap(reserve, region_size);
174 		close(mem_fd);
175 		return -errno;
176 	}
177 	if (area_alias != p_alias)
178 		err("mmap of anonymous memory failed at %p", p_alias);
179 
180 	if (is_src)
181 		gopts->area_src_alias = area_alias;
182 	else
183 		gopts->area_dst_alias = area_alias;
184 
185 	close(mem_fd);
186 	return 0;
187 }
188 
189 static void shmem_alias_mapping(uffd_global_test_opts_t *gopts, __u64 *start,
190 				size_t len, unsigned long offset)
191 {
192 	*start = (unsigned long)gopts->area_dst_alias + offset;
193 }
194 
195 static void shmem_check_pmd_mapping(uffd_global_test_opts_t *gopts, void *p, int expect_nr_hpages)
196 {
197 	size_t len = expect_nr_hpages * read_pmd_pagesize();
198 
199 	if (!check_huge_shmem(gopts->area_dst_alias, len, expect_nr_hpages,
200 			      read_pmd_pagesize()))
201 		err("Did not find expected %d number of hugepages",
202 		    expect_nr_hpages);
203 }
204 
205 struct uffd_test_ops anon_uffd_test_ops = {
206 	.allocate_area = anon_allocate_area,
207 	.release_pages = anon_release_pages,
208 	.alias_mapping = noop_alias_mapping,
209 	.check_pmd_mapping = NULL,
210 };
211 
212 struct uffd_test_ops shmem_uffd_test_ops = {
213 	.allocate_area = shmem_allocate_area,
214 	.release_pages = shmem_release_pages,
215 	.alias_mapping = shmem_alias_mapping,
216 	.check_pmd_mapping = shmem_check_pmd_mapping,
217 };
218 
219 struct uffd_test_ops hugetlb_uffd_test_ops = {
220 	.allocate_area = hugetlb_allocate_area,
221 	.release_pages = hugetlb_release_pages,
222 	.alias_mapping = hugetlb_alias_mapping,
223 	.check_pmd_mapping = NULL,
224 };
225 
226 void uffd_stats_report(struct uffd_args *args, int n_cpus)
227 {
228 	int i;
229 	unsigned long long miss_total = 0, wp_total = 0, minor_total = 0;
230 
231 	for (i = 0; i < n_cpus; i++) {
232 		miss_total += args[i].missing_faults;
233 		wp_total += args[i].wp_faults;
234 		minor_total += args[i].minor_faults;
235 	}
236 
237 	printf("userfaults: ");
238 	if (miss_total) {
239 		printf("%llu missing (", miss_total);
240 		for (i = 0; i < n_cpus; i++)
241 			printf("%lu+", args[i].missing_faults);
242 		printf("\b) ");
243 	}
244 	if (wp_total) {
245 		printf("%llu wp (", wp_total);
246 		for (i = 0; i < n_cpus; i++)
247 			printf("%lu+", args[i].wp_faults);
248 		printf("\b) ");
249 	}
250 	if (minor_total) {
251 		printf("%llu minor (", minor_total);
252 		for (i = 0; i < n_cpus; i++)
253 			printf("%lu+", args[i].minor_faults);
254 		printf("\b)");
255 	}
256 	printf("\n");
257 }
258 
259 int userfaultfd_open(uffd_global_test_opts_t *gopts, uint64_t *features)
260 {
261 	struct uffdio_api uffdio_api;
262 
263 	gopts->uffd = uffd_open(UFFD_FLAGS);
264 	if (gopts->uffd < 0)
265 		return -1;
266 	gopts->uffd_flags = fcntl(gopts->uffd, F_GETFD, NULL);
267 
268 	uffdio_api.api = UFFD_API;
269 	uffdio_api.features = *features;
270 	if (ioctl(gopts->uffd, UFFDIO_API, &uffdio_api))
271 		/* Probably lack of CAP_PTRACE? */
272 		return -1;
273 	if (uffdio_api.api != UFFD_API)
274 		err("UFFDIO_API error: %" PRIu64, (uint64_t)uffdio_api.api);
275 
276 	*features = uffdio_api.features;
277 	return 0;
278 }
279 
280 static inline void munmap_area(uffd_global_test_opts_t *gopts, void **area)
281 {
282 	if (*area)
283 		if (munmap(*area, gopts->nr_pages * gopts->page_size))
284 			err("munmap");
285 
286 	*area = NULL;
287 }
288 
289 void uffd_test_ctx_clear(uffd_global_test_opts_t *gopts)
290 {
291 	size_t i;
292 
293 	if (gopts->pipefd) {
294 		for (i = 0; i < gopts->nr_parallel * 2; ++i) {
295 			if (close(gopts->pipefd[i]))
296 				err("close pipefd");
297 		}
298 		free(gopts->pipefd);
299 		gopts->pipefd = NULL;
300 	}
301 
302 	if (gopts->count_verify) {
303 		free(gopts->count_verify);
304 		gopts->count_verify = NULL;
305 	}
306 
307 	if (gopts->uffd != -1) {
308 		if (close(gopts->uffd))
309 			err("close uffd");
310 		gopts->uffd = -1;
311 	}
312 
313 	munmap_area(gopts, (void **)&gopts->area_src);
314 	munmap_area(gopts, (void **)&gopts->area_src_alias);
315 	munmap_area(gopts, (void **)&gopts->area_dst);
316 	munmap_area(gopts, (void **)&gopts->area_dst_alias);
317 	munmap_area(gopts, (void **)&gopts->area_remap);
318 }
319 
320 int uffd_test_ctx_init(uffd_global_test_opts_t *gopts, uint64_t features, const char **errmsg)
321 {
322 	unsigned long nr, cpu;
323 	int ret;
324 
325 	gopts->area_src_alias = NULL;
326 	gopts->area_dst_alias = NULL;
327 	gopts->area_remap = NULL;
328 
329 	if (uffd_test_case_ops && uffd_test_case_ops->pre_alloc) {
330 		ret = uffd_test_case_ops->pre_alloc(gopts, errmsg);
331 		if (ret)
332 			return ret;
333 	}
334 
335 	ret = uffd_test_ops->allocate_area(gopts, (void **) &gopts->area_src, true);
336 	ret |= uffd_test_ops->allocate_area(gopts, (void **) &gopts->area_dst, false);
337 	if (ret) {
338 		if (errmsg)
339 			*errmsg = "memory allocation failed";
340 		return ret;
341 	}
342 
343 	if (uffd_test_case_ops && uffd_test_case_ops->post_alloc) {
344 		ret = uffd_test_case_ops->post_alloc(gopts, errmsg);
345 		if (ret)
346 			return ret;
347 	}
348 
349 	ret = userfaultfd_open(gopts, &features);
350 	if (ret) {
351 		if (errmsg)
352 			*errmsg = "possible lack of privilege";
353 		return ret;
354 	}
355 
356 	gopts->count_verify = malloc(gopts->nr_pages * sizeof(unsigned long long));
357 	if (!gopts->count_verify)
358 		err("count_verify");
359 
360 	for (nr = 0; nr < gopts->nr_pages; nr++) {
361 		*area_mutex(gopts->area_src, nr, gopts) =
362 			(pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
363 		gopts->count_verify[nr] = *area_count(gopts->area_src, nr, gopts) = 1;
364 		/*
365 		 * In the transition between 255 to 256, powerpc will
366 		 * read out of order in my_bcmp and see both bytes as
367 		 * zero, so leave a placeholder below always non-zero
368 		 * after the count, to avoid my_bcmp to trigger false
369 		 * positives.
370 		 */
371 		*(area_count(gopts->area_src, nr, gopts) + 1) = 1;
372 	}
373 
374 	/*
375 	 * After initialization of area_src, we must explicitly release pages
376 	 * for area_dst to make sure it's fully empty.  Otherwise we could have
377 	 * some area_dst pages be erroneously initialized with zero pages,
378 	 * hence we could hit memory corruption later in the test.
379 	 *
380 	 * One example is when THP is globally enabled, above allocate_area()
381 	 * calls could have the two areas merged into a single VMA (as they
382 	 * will have the same VMA flags so they're mergeable).  When we
383 	 * initialize the area_src above, it's possible that some part of
384 	 * area_dst could have been faulted in via one huge THP that will be
385 	 * shared between area_src and area_dst.  It could cause some of the
386 	 * area_dst won't be trapped by missing userfaults.
387 	 *
388 	 * This release_pages() will guarantee even if that happened, we'll
389 	 * proactively split the thp and drop any accidentally initialized
390 	 * pages within area_dst.
391 	 */
392 	uffd_test_ops->release_pages(gopts, gopts->area_dst);
393 
394 	gopts->pipefd = malloc(sizeof(int) * gopts->nr_parallel * 2);
395 	if (!gopts->pipefd)
396 		err("pipefd");
397 	for (cpu = 0; cpu < gopts->nr_parallel; cpu++)
398 		if (pipe2(&gopts->pipefd[cpu * 2], O_CLOEXEC | O_NONBLOCK))
399 			err("pipe");
400 
401 	return 0;
402 }
403 
404 void wp_range(int ufd, __u64 start, __u64 len, bool wp)
405 {
406 	struct uffdio_writeprotect prms;
407 
408 	/* Write protection page faults */
409 	prms.range.start = start;
410 	prms.range.len = len;
411 	/* Undo write-protect, do wakeup after that */
412 	prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
413 
414 	if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
415 		err("clear WP failed: address=0x%"PRIx64, (uint64_t)start);
416 }
417 
418 static void continue_range(int ufd, __u64 start, __u64 len, bool wp)
419 {
420 	struct uffdio_continue req;
421 	int ret;
422 
423 	req.range.start = start;
424 	req.range.len = len;
425 	req.mode = 0;
426 	if (wp)
427 		req.mode |= UFFDIO_CONTINUE_MODE_WP;
428 
429 	if (ioctl(ufd, UFFDIO_CONTINUE, &req))
430 		err("UFFDIO_CONTINUE failed for address 0x%" PRIx64,
431 		    (uint64_t)start);
432 
433 	/*
434 	 * Error handling within the kernel for continue is subtly different
435 	 * from copy or zeropage, so it may be a source of bugs. Trigger an
436 	 * error (-EEXIST) on purpose, to verify doing so doesn't cause a BUG.
437 	 */
438 	req.mapped = 0;
439 	ret = ioctl(ufd, UFFDIO_CONTINUE, &req);
440 	if (ret >= 0 || req.mapped != -EEXIST)
441 		err("failed to exercise UFFDIO_CONTINUE error handling, ret=%d, mapped=%" PRId64,
442 		    ret, (int64_t) req.mapped);
443 }
444 
445 int uffd_read_msg(uffd_global_test_opts_t *gopts, struct uffd_msg *msg)
446 {
447 	int ret = read(gopts->uffd, msg, sizeof(*msg));
448 
449 	if (ret != sizeof(*msg)) {
450 		if (ret < 0) {
451 			if (errno == EAGAIN || errno == EINTR)
452 				return 1;
453 			err("blocking read error");
454 		} else {
455 			err("short read");
456 		}
457 	}
458 
459 	return 0;
460 }
461 
462 void uffd_handle_page_fault(uffd_global_test_opts_t *gopts, struct uffd_msg *msg,
463 			    struct uffd_args *args)
464 {
465 	unsigned long offset;
466 
467 	if (msg->event != UFFD_EVENT_PAGEFAULT)
468 		err("unexpected msg event %u", msg->event);
469 
470 	if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
471 		/* Write protect page faults */
472 		wp_range(gopts->uffd, msg->arg.pagefault.address, gopts->page_size, false);
473 		args->wp_faults++;
474 	} else if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_MINOR) {
475 		uint8_t *area;
476 		int b;
477 
478 		/*
479 		 * Minor page faults
480 		 *
481 		 * To prove we can modify the original range for testing
482 		 * purposes, we're going to bit flip this range before
483 		 * continuing.
484 		 *
485 		 * Note that this requires all minor page fault tests operate on
486 		 * area_dst (non-UFFD-registered) and area_dst_alias
487 		 * (UFFD-registered).
488 		 */
489 
490 		area = (uint8_t *)(gopts->area_dst +
491 		       ((char *)msg->arg.pagefault.address -
492 		       gopts->area_dst_alias));
493 		for (b = 0; b < gopts->page_size; ++b)
494 			area[b] = ~area[b];
495 		continue_range(gopts->uffd, msg->arg.pagefault.address, gopts->page_size,
496 			       args->apply_wp);
497 		args->minor_faults++;
498 	} else {
499 		/*
500 		 * Missing page faults.
501 		 *
502 		 * Here we force a write check for each of the missing mode
503 		 * faults.  It's guaranteed because the only threads that
504 		 * will trigger uffd faults are the locking threads, and
505 		 * their first instruction to touch the missing page will
506 		 * always be pthread_mutex_lock().
507 		 *
508 		 * Note that here we relied on an NPTL glibc impl detail to
509 		 * always read the lock type at the entry of the lock op
510 		 * (pthread_mutex_t.__data.__type, offset 0x10) before
511 		 * doing any locking operations to guarantee that.  It's
512 		 * actually not good to rely on this impl detail because
513 		 * logically a pthread-compatible lib can implement the
514 		 * locks without types and we can fail when linking with
515 		 * them.  However since we used to find bugs with this
516 		 * strict check we still keep it around.  Hopefully this
517 		 * could be a good hint when it fails again.  If one day
518 		 * it'll break on some other impl of glibc we'll revisit.
519 		 */
520 		if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
521 			err("unexpected write fault");
522 
523 		offset = (char *)(unsigned long)msg->arg.pagefault.address - gopts->area_dst;
524 		offset &= ~(gopts->page_size-1);
525 
526 		if (copy_page(gopts, offset, args->apply_wp))
527 			args->missing_faults++;
528 	}
529 }
530 
531 void *uffd_poll_thread(void *arg)
532 {
533 	struct uffd_args *args = (struct uffd_args *)arg;
534 	uffd_global_test_opts_t *gopts = args->gopts;
535 	unsigned long cpu = args->cpu;
536 	struct pollfd pollfd[2];
537 	struct uffd_msg msg;
538 	struct uffdio_register uffd_reg;
539 	int ret;
540 	char tmp_chr;
541 
542 	if (!args->handle_fault)
543 		args->handle_fault = uffd_handle_page_fault;
544 
545 	pollfd[0].fd = gopts->uffd;
546 	pollfd[0].events = POLLIN;
547 	pollfd[1].fd = gopts->pipefd[cpu*2];
548 	pollfd[1].events = POLLIN;
549 
550 	gopts->ready_for_fork = true;
551 
552 	for (;;) {
553 		ret = poll(pollfd, 2, -1);
554 		if (ret <= 0) {
555 			if (errno == EINTR || errno == EAGAIN)
556 				continue;
557 			err("poll error: %d", ret);
558 		}
559 		if (pollfd[1].revents) {
560 			if (!(pollfd[1].revents & POLLIN))
561 				err("pollfd[1].revents %d", pollfd[1].revents);
562 			if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
563 				err("read pipefd error");
564 			break;
565 		}
566 		if (!(pollfd[0].revents & POLLIN))
567 			err("pollfd[0].revents %d", pollfd[0].revents);
568 		if (uffd_read_msg(gopts, &msg))
569 			continue;
570 		switch (msg.event) {
571 		default:
572 			err("unexpected msg event %u\n", msg.event);
573 			break;
574 		case UFFD_EVENT_PAGEFAULT:
575 			args->handle_fault(gopts, &msg, args);
576 			break;
577 		case UFFD_EVENT_FORK:
578 			close(gopts->uffd);
579 			gopts->uffd = msg.arg.fork.ufd;
580 			pollfd[0].fd = gopts->uffd;
581 			break;
582 		case UFFD_EVENT_REMOVE:
583 			uffd_reg.range.start = msg.arg.remove.start;
584 			uffd_reg.range.len = msg.arg.remove.end -
585 				msg.arg.remove.start;
586 			if (ioctl(gopts->uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
587 				err("remove failure");
588 			break;
589 		case UFFD_EVENT_REMAP:
590 			gopts->area_remap = gopts->area_dst;  /* save for later unmap */
591 			gopts->area_dst = (char *)(unsigned long)msg.arg.remap.to;
592 			break;
593 		}
594 	}
595 
596 	return NULL;
597 }
598 
599 static void retry_copy_page(uffd_global_test_opts_t *gopts, struct uffdio_copy *uffdio_copy,
600 			    unsigned long offset)
601 {
602 	uffd_test_ops->alias_mapping(gopts,
603 				     &uffdio_copy->dst,
604 				     uffdio_copy->len,
605 				     offset);
606 	if (ioctl(gopts->uffd, UFFDIO_COPY, uffdio_copy)) {
607 		/* real retval in ufdio_copy.copy */
608 		if (uffdio_copy->copy != -EEXIST)
609 			err("UFFDIO_COPY retry error: %"PRId64,
610 			(int64_t)uffdio_copy->copy);
611 	} else {
612 		err("UFFDIO_COPY retry unexpected: %"PRId64,
613 		    (int64_t)uffdio_copy->copy);
614 	}
615 }
616 
617 static void wake_range(int ufd, unsigned long addr, unsigned long len)
618 {
619 	struct uffdio_range uffdio_wake;
620 
621 	uffdio_wake.start = addr;
622 	uffdio_wake.len = len;
623 
624 	if (ioctl(ufd, UFFDIO_WAKE, &uffdio_wake))
625 		fprintf(stderr, "error waking %lu\n",
626 			addr), exit(1);
627 }
628 
629 int __copy_page(uffd_global_test_opts_t *gopts, unsigned long offset, bool retry, bool wp)
630 {
631 	struct uffdio_copy uffdio_copy;
632 
633 	if (offset >= gopts->nr_pages * gopts->page_size)
634 		err("unexpected offset %lu\n", offset);
635 	uffdio_copy.dst = (unsigned long) gopts->area_dst + offset;
636 	uffdio_copy.src = (unsigned long) gopts->area_src + offset;
637 	uffdio_copy.len = gopts->page_size;
638 	if (wp)
639 		uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
640 	else
641 		uffdio_copy.mode = 0;
642 	uffdio_copy.copy = 0;
643 	if (ioctl(gopts->uffd, UFFDIO_COPY, &uffdio_copy)) {
644 		/*
645 		 * real retval in uffdio_copy.copy
646 		 *
647 		 * -EEXIST: the page was faulted in concurrently
648 		 * -ENOENT: the destination range was concurrently removed
649 		 */
650 		if (uffdio_copy.copy != -EEXIST && uffdio_copy.copy != -ENOENT)
651 			err("UFFDIO_COPY error: %"PRId64,
652 			    (int64_t)uffdio_copy.copy);
653 		wake_range(gopts->uffd, uffdio_copy.dst, gopts->page_size);
654 	} else if (uffdio_copy.copy != gopts->page_size) {
655 		err("UFFDIO_COPY error: %"PRId64, (int64_t)uffdio_copy.copy);
656 	} else {
657 		if (gopts->test_uffdio_copy_eexist && retry) {
658 			gopts->test_uffdio_copy_eexist = false;
659 			retry_copy_page(gopts, &uffdio_copy, offset);
660 		}
661 		return 1;
662 	}
663 	return 0;
664 }
665 
666 int copy_page(uffd_global_test_opts_t *gopts, unsigned long offset, bool wp)
667 {
668 	return __copy_page(gopts, offset, false, wp);
669 }
670 
671 int move_page(uffd_global_test_opts_t *gopts, unsigned long offset, unsigned long len)
672 {
673 	struct uffdio_move uffdio_move;
674 
675 	if (offset + len > gopts->nr_pages * gopts->page_size)
676 		err("unexpected offset %lu and length %lu\n", offset, len);
677 	uffdio_move.dst = (unsigned long) gopts->area_dst + offset;
678 	uffdio_move.src = (unsigned long) gopts->area_src + offset;
679 	uffdio_move.len = len;
680 	uffdio_move.mode = UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES;
681 	uffdio_move.move = 0;
682 	if (ioctl(gopts->uffd, UFFDIO_MOVE, &uffdio_move)) {
683 		/* real retval in uffdio_move.move */
684 		if (uffdio_move.move != -EEXIST)
685 			err("UFFDIO_MOVE error: %"PRId64,
686 			    (int64_t)uffdio_move.move);
687 		wake_range(gopts->uffd, uffdio_move.dst, len);
688 	} else if (uffdio_move.move != len) {
689 		err("UFFDIO_MOVE error: %"PRId64, (int64_t)uffdio_move.move);
690 	} else
691 		return 1;
692 	return 0;
693 }
694 
695 int uffd_open_dev(unsigned int flags)
696 {
697 	int fd, uffd;
698 
699 	fd = open("/dev/userfaultfd", O_RDWR | O_CLOEXEC);
700 	if (fd < 0)
701 		return fd;
702 	uffd = ioctl(fd, USERFAULTFD_IOC_NEW, flags);
703 	close(fd);
704 
705 	return uffd;
706 }
707 
708 int uffd_open_sys(unsigned int flags)
709 {
710 #ifdef __NR_userfaultfd
711 	return syscall(__NR_userfaultfd, flags);
712 #else
713 	return -1;
714 #endif
715 }
716 
717 int uffd_open(unsigned int flags)
718 {
719 	int uffd = uffd_open_sys(flags);
720 
721 	if (uffd < 0)
722 		uffd = uffd_open_dev(flags);
723 
724 	return uffd;
725 }
726 
727 int uffd_get_features(uint64_t *features)
728 {
729 	struct uffdio_api uffdio_api = { .api = UFFD_API, .features = 0 };
730 	/*
731 	 * This should by default work in most kernels; the feature list
732 	 * will be the same no matter what we pass in here.
733 	 */
734 	int fd = uffd_open(UFFD_USER_MODE_ONLY);
735 
736 	if (fd < 0)
737 		/* Maybe the kernel is older than user-only mode? */
738 		fd = uffd_open(0);
739 
740 	if (fd < 0)
741 		return fd;
742 
743 	if (ioctl(fd, UFFDIO_API, &uffdio_api)) {
744 		close(fd);
745 		return -errno;
746 	}
747 
748 	*features = uffdio_api.features;
749 	close(fd);
750 
751 	return 0;
752 }
753