1 // SPDX-License-Identifier: GPL-2.0-only
3 * Stress userfaultfd syscall.
5 * Copyright (C) 2015 Red Hat, Inc.
7 * This test allocates two virtual areas and bounces the physical
8 * memory across the two virtual areas (from area_src to area_dst)
11 * There are three threads running per CPU:
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.
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.
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
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
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).
42 #include <sys/types.h>
49 #include <linux/mman.h>
51 #include <sys/syscall.h>
52 #include <sys/ioctl.h>
55 #include <linux/userfaultfd.h>
61 #include <sys/random.h>
63 #include "../kselftest.h"
66 #ifdef __NR_userfaultfd
68 static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size, hpage_size;
70 #define BOUNCE_RANDOM (1<<0)
71 #define BOUNCE_RACINGFAULTS (1<<1)
72 #define BOUNCE_VERIFY (1<<2)
73 #define BOUNCE_POLL (1<<3)
77 #define TEST_HUGETLB 2
81 #define UFFD_FLAGS (O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY)
83 #define BASE_PMD_ADDR ((void *)(1UL << 30))
85 /* test using /dev/userfaultfd, instead of userfaultfd(2) */
86 static bool test_dev_userfaultfd;
88 /* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
89 #define ALARM_INTERVAL_SECS 10
90 static volatile bool test_uffdio_copy_eexist = true;
91 static volatile bool test_uffdio_zeropage_eexist = true;
92 /* Whether to test uffd write-protection */
93 static bool test_uffdio_wp = true;
94 /* Whether to test uffd minor faults */
95 static bool test_uffdio_minor = false;
96 static bool map_shared;
98 static unsigned long long *count_verify;
100 static int uffd_flags, finished, *pipefd;
101 static char *area_src, *area_src_alias, *area_dst, *area_dst_alias, *area_remap;
102 static char *zeropage;
104 static bool test_collapse;
106 /* Userfaultfd test statistics */
109 unsigned long missing_faults;
110 unsigned long wp_faults;
111 unsigned long minor_faults;
114 /* pthread_mutex_t starts at page offset 0 */
115 #define area_mutex(___area, ___nr) \
116 ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
118 * count is placed in the page after pthread_mutex_t naturally aligned
119 * to avoid non alignment faults on non-x86 archs.
121 #define area_count(___area, ___nr) \
122 ((volatile unsigned long long *) ((unsigned long) \
123 ((___area) + (___nr)*page_size + \
124 sizeof(pthread_mutex_t) + \
125 sizeof(unsigned long long) - 1) & \
126 ~(unsigned long)(sizeof(unsigned long long) \
130 do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
132 #define factor_of_2(x) ((x) ^ ((x) & ((x) - 1)))
134 const char *examples =
135 "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
136 "./userfaultfd anon 100 99999\n\n"
137 "# Run the same anonymous memory test, but using /dev/userfaultfd:\n"
138 "./userfaultfd anon:dev 100 99999\n\n"
139 "# Run share memory test on 1GiB region with 99 bounces:\n"
140 "./userfaultfd shmem 1000 99\n\n"
141 "# Run hugetlb memory test on 256MiB region with 50 bounces:\n"
142 "./userfaultfd hugetlb 256 50\n\n"
143 "# Run the same hugetlb test but using shared file:\n"
144 "./userfaultfd hugetlb_shared 256 50\n\n"
145 "# 10MiB-~6GiB 999 bounces anonymous test, "
146 "continue forever unless an error triggers\n"
147 "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
149 static void usage(void)
151 fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
152 "[hugetlbfs_file]\n\n");
153 fprintf(stderr, "Supported <test type>: anon, hugetlb, "
154 "hugetlb_shared, shmem\n\n");
155 fprintf(stderr, "'Test mods' can be joined to the test type string with a ':'. "
156 "Supported mods:\n");
157 fprintf(stderr, "\tsyscall - Use userfaultfd(2) (default)\n");
158 fprintf(stderr, "\tdev - Use /dev/userfaultfd instead of userfaultfd(2)\n");
159 fprintf(stderr, "\tcollapse - Test MADV_COLLAPSE of UFFDIO_REGISTER_MODE_MINOR\n"
161 fprintf(stderr, "\nExample test mod usage:\n");
162 fprintf(stderr, "# Run anonymous memory test with /dev/userfaultfd:\n");
163 fprintf(stderr, "./userfaultfd anon:dev 100 99999\n\n");
165 fprintf(stderr, "Examples:\n\n");
166 fprintf(stderr, "%s", examples);
170 #define _err(fmt, ...) \
173 fprintf(stderr, "ERROR: " fmt, ##__VA_ARGS__); \
174 fprintf(stderr, " (errno=%d, line=%d)\n", \
178 #define errexit(exitcode, fmt, ...) \
180 _err(fmt, ##__VA_ARGS__); \
184 #define err(fmt, ...) errexit(1, fmt, ##__VA_ARGS__)
186 static void uffd_stats_reset(struct uffd_stats *uffd_stats,
187 unsigned long n_cpus)
191 for (i = 0; i < n_cpus; i++) {
192 uffd_stats[i].cpu = i;
193 uffd_stats[i].missing_faults = 0;
194 uffd_stats[i].wp_faults = 0;
195 uffd_stats[i].minor_faults = 0;
199 static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
202 unsigned long long miss_total = 0, wp_total = 0, minor_total = 0;
204 for (i = 0; i < n_cpus; i++) {
205 miss_total += stats[i].missing_faults;
206 wp_total += stats[i].wp_faults;
207 minor_total += stats[i].minor_faults;
210 printf("userfaults: ");
212 printf("%llu missing (", miss_total);
213 for (i = 0; i < n_cpus; i++)
214 printf("%lu+", stats[i].missing_faults);
218 printf("%llu wp (", wp_total);
219 for (i = 0; i < n_cpus; i++)
220 printf("%lu+", stats[i].wp_faults);
224 printf("%llu minor (", minor_total);
225 for (i = 0; i < n_cpus; i++)
226 printf("%lu+", stats[i].minor_faults);
232 static void anon_release_pages(char *rel_area)
234 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
235 err("madvise(MADV_DONTNEED) failed");
238 static void anon_allocate_area(void **alloc_area, bool is_src)
240 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
241 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
244 static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
248 static void hugetlb_release_pages(char *rel_area)
251 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
252 err("madvise(MADV_DONTNEED) failed");
254 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
255 err("madvise(MADV_REMOVE) failed");
259 static void hugetlb_allocate_area(void **alloc_area, bool is_src)
261 off_t size = nr_pages * page_size;
262 off_t offset = is_src ? 0 : size;
263 void *area_alias = NULL;
264 char **alloc_area_alias;
266 *alloc_area = mmap(NULL, size, PROT_READ | PROT_WRITE,
267 (map_shared ? MAP_SHARED : MAP_PRIVATE) |
268 (is_src ? 0 : MAP_NORESERVE),
270 if (*alloc_area == MAP_FAILED)
271 err("mmap of hugetlbfs file failed");
274 area_alias = mmap(NULL, size, PROT_READ | PROT_WRITE,
275 MAP_SHARED, mem_fd, offset);
276 if (area_alias == MAP_FAILED)
277 err("mmap of hugetlb file alias failed");
281 alloc_area_alias = &area_src_alias;
283 alloc_area_alias = &area_dst_alias;
286 *alloc_area_alias = area_alias;
289 static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
294 *start = (unsigned long) area_dst_alias + offset;
297 static void shmem_release_pages(char *rel_area)
299 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
300 err("madvise(MADV_REMOVE) failed");
303 static void shmem_allocate_area(void **alloc_area, bool is_src)
305 void *area_alias = NULL;
306 size_t bytes = nr_pages * page_size;
307 unsigned long offset = is_src ? 0 : bytes;
308 char *p = NULL, *p_alias = NULL;
313 /* src map + alias + interleaved hpages */
314 p += 2 * (bytes + hpage_size);
317 p_alias += hpage_size; /* Prevent src/dst VMA merge */
320 *alloc_area = mmap(p, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
322 if (*alloc_area == MAP_FAILED)
323 err("mmap of memfd failed");
324 if (test_collapse && *alloc_area != p)
325 err("mmap of memfd failed at %p", p);
327 area_alias = mmap(p_alias, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
329 if (area_alias == MAP_FAILED)
330 err("mmap of memfd alias failed");
331 if (test_collapse && area_alias != p_alias)
332 err("mmap of anonymous memory failed at %p", p_alias);
335 area_src_alias = area_alias;
337 area_dst_alias = area_alias;
340 static void shmem_alias_mapping(__u64 *start, size_t len, unsigned long offset)
342 *start = (unsigned long)area_dst_alias + offset;
345 static void shmem_check_pmd_mapping(void *p, int expect_nr_hpages)
347 if (!check_huge_shmem(area_dst_alias, expect_nr_hpages, hpage_size))
348 err("Did not find expected %d number of hugepages",
352 struct uffd_test_ops {
353 void (*allocate_area)(void **alloc_area, bool is_src);
354 void (*release_pages)(char *rel_area);
355 void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
356 void (*check_pmd_mapping)(void *p, int expect_nr_hpages);
359 static struct uffd_test_ops anon_uffd_test_ops = {
360 .allocate_area = anon_allocate_area,
361 .release_pages = anon_release_pages,
362 .alias_mapping = noop_alias_mapping,
363 .check_pmd_mapping = NULL,
366 static struct uffd_test_ops shmem_uffd_test_ops = {
367 .allocate_area = shmem_allocate_area,
368 .release_pages = shmem_release_pages,
369 .alias_mapping = shmem_alias_mapping,
370 .check_pmd_mapping = shmem_check_pmd_mapping,
373 static struct uffd_test_ops hugetlb_uffd_test_ops = {
374 .allocate_area = hugetlb_allocate_area,
375 .release_pages = hugetlb_release_pages,
376 .alias_mapping = hugetlb_alias_mapping,
377 .check_pmd_mapping = NULL,
380 static struct uffd_test_ops *uffd_test_ops;
382 static inline uint64_t uffd_minor_feature(void)
384 if (test_type == TEST_HUGETLB && map_shared)
385 return UFFD_FEATURE_MINOR_HUGETLBFS;
386 else if (test_type == TEST_SHMEM)
387 return UFFD_FEATURE_MINOR_SHMEM;
392 static uint64_t get_expected_ioctls(uint64_t mode)
394 uint64_t ioctls = UFFD_API_RANGE_IOCTLS;
396 if (test_type == TEST_HUGETLB)
397 ioctls &= ~(1 << _UFFDIO_ZEROPAGE);
399 if (!((mode & UFFDIO_REGISTER_MODE_WP) && test_uffdio_wp))
400 ioctls &= ~(1 << _UFFDIO_WRITEPROTECT);
402 if (!((mode & UFFDIO_REGISTER_MODE_MINOR) && test_uffdio_minor))
403 ioctls &= ~(1 << _UFFDIO_CONTINUE);
408 static void assert_expected_ioctls_present(uint64_t mode, uint64_t ioctls)
410 uint64_t expected = get_expected_ioctls(mode);
411 uint64_t actual = ioctls & expected;
413 if (actual != expected) {
414 err("missing ioctl(s): expected %"PRIx64" actual: %"PRIx64,
419 static int __userfaultfd_open_dev(void)
423 fd = open("/dev/userfaultfd", O_RDWR | O_CLOEXEC);
425 errexit(KSFT_SKIP, "opening /dev/userfaultfd failed");
427 _uffd = ioctl(fd, USERFAULTFD_IOC_NEW, UFFD_FLAGS);
429 errexit(errno == ENOTTY ? KSFT_SKIP : 1,
430 "creating userfaultfd failed");
435 static void userfaultfd_open(uint64_t *features)
437 struct uffdio_api uffdio_api;
439 if (test_dev_userfaultfd)
440 uffd = __userfaultfd_open_dev();
442 uffd = syscall(__NR_userfaultfd, UFFD_FLAGS);
444 errexit(errno == ENOSYS ? KSFT_SKIP : 1,
445 "creating userfaultfd failed");
447 uffd_flags = fcntl(uffd, F_GETFD, NULL);
449 uffdio_api.api = UFFD_API;
450 uffdio_api.features = *features;
451 if (ioctl(uffd, UFFDIO_API, &uffdio_api))
452 err("UFFDIO_API failed.\nPlease make sure to "
453 "run with either root or ptrace capability.");
454 if (uffdio_api.api != UFFD_API)
455 err("UFFDIO_API error: %" PRIu64, (uint64_t)uffdio_api.api);
457 *features = uffdio_api.features;
460 static inline void munmap_area(void **area)
463 if (munmap(*area, nr_pages * page_size))
469 static void uffd_test_ctx_clear(void)
474 for (i = 0; i < nr_cpus * 2; ++i) {
475 if (close(pipefd[i]))
493 munmap_area((void **)&area_src);
494 munmap_area((void **)&area_src_alias);
495 munmap_area((void **)&area_dst);
496 munmap_area((void **)&area_dst_alias);
497 munmap_area((void **)&area_remap);
500 static void uffd_test_ctx_init(uint64_t features)
502 unsigned long nr, cpu;
504 uffd_test_ctx_clear();
506 uffd_test_ops->allocate_area((void **)&area_src, true);
507 uffd_test_ops->allocate_area((void **)&area_dst, false);
509 userfaultfd_open(&features);
511 count_verify = malloc(nr_pages * sizeof(unsigned long long));
515 for (nr = 0; nr < nr_pages; nr++) {
516 *area_mutex(area_src, nr) =
517 (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
518 count_verify[nr] = *area_count(area_src, nr) = 1;
520 * In the transition between 255 to 256, powerpc will
521 * read out of order in my_bcmp and see both bytes as
522 * zero, so leave a placeholder below always non-zero
523 * after the count, to avoid my_bcmp to trigger false
526 *(area_count(area_src, nr) + 1) = 1;
530 * After initialization of area_src, we must explicitly release pages
531 * for area_dst to make sure it's fully empty. Otherwise we could have
532 * some area_dst pages be errornously initialized with zero pages,
533 * hence we could hit memory corruption later in the test.
535 * One example is when THP is globally enabled, above allocate_area()
536 * calls could have the two areas merged into a single VMA (as they
537 * will have the same VMA flags so they're mergeable). When we
538 * initialize the area_src above, it's possible that some part of
539 * area_dst could have been faulted in via one huge THP that will be
540 * shared between area_src and area_dst. It could cause some of the
541 * area_dst won't be trapped by missing userfaults.
543 * This release_pages() will guarantee even if that happened, we'll
544 * proactively split the thp and drop any accidentally initialized
545 * pages within area_dst.
547 uffd_test_ops->release_pages(area_dst);
549 pipefd = malloc(sizeof(int) * nr_cpus * 2);
552 for (cpu = 0; cpu < nr_cpus; cpu++)
553 if (pipe2(&pipefd[cpu * 2], O_CLOEXEC | O_NONBLOCK))
557 static int my_bcmp(char *str1, char *str2, size_t n)
560 for (i = 0; i < n; i++)
561 if (str1[i] != str2[i])
566 static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
568 struct uffdio_writeprotect prms;
570 /* Write protection page faults */
571 prms.range.start = start;
572 prms.range.len = len;
573 /* Undo write-protect, do wakeup after that */
574 prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
576 if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
577 err("clear WP failed: address=0x%"PRIx64, (uint64_t)start);
580 static void continue_range(int ufd, __u64 start, __u64 len)
582 struct uffdio_continue req;
585 req.range.start = start;
589 if (ioctl(ufd, UFFDIO_CONTINUE, &req))
590 err("UFFDIO_CONTINUE failed for address 0x%" PRIx64,
594 * Error handling within the kernel for continue is subtly different
595 * from copy or zeropage, so it may be a source of bugs. Trigger an
596 * error (-EEXIST) on purpose, to verify doing so doesn't cause a BUG.
599 ret = ioctl(ufd, UFFDIO_CONTINUE, &req);
600 if (ret >= 0 || req.mapped != -EEXIST)
601 err("failed to exercise UFFDIO_CONTINUE error handling, ret=%d, mapped=%" PRId64,
602 ret, (int64_t) req.mapped);
605 static void *locking_thread(void *arg)
607 unsigned long cpu = (unsigned long) arg;
608 unsigned long page_nr;
609 unsigned long long count;
611 if (!(bounces & BOUNCE_RANDOM)) {
613 if (!(bounces & BOUNCE_RACINGFAULTS))
614 page_nr += cpu * nr_pages_per_cpu;
618 if (bounces & BOUNCE_RANDOM) {
619 if (getrandom(&page_nr, sizeof(page_nr), 0) != sizeof(page_nr))
620 err("getrandom failed");
624 pthread_mutex_lock(area_mutex(area_dst, page_nr));
625 count = *area_count(area_dst, page_nr);
626 if (count != count_verify[page_nr])
627 err("page_nr %lu memory corruption %llu %llu",
628 page_nr, count, count_verify[page_nr]);
630 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
631 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
637 static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
638 unsigned long offset)
640 uffd_test_ops->alias_mapping(&uffdio_copy->dst,
643 if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
644 /* real retval in ufdio_copy.copy */
645 if (uffdio_copy->copy != -EEXIST)
646 err("UFFDIO_COPY retry error: %"PRId64,
647 (int64_t)uffdio_copy->copy);
649 err("UFFDIO_COPY retry unexpected: %"PRId64,
650 (int64_t)uffdio_copy->copy);
654 static void wake_range(int ufd, unsigned long addr, unsigned long len)
656 struct uffdio_range uffdio_wake;
658 uffdio_wake.start = addr;
659 uffdio_wake.len = len;
661 if (ioctl(ufd, UFFDIO_WAKE, &uffdio_wake))
662 fprintf(stderr, "error waking %lu\n",
666 static int __copy_page(int ufd, unsigned long offset, bool retry)
668 struct uffdio_copy uffdio_copy;
670 if (offset >= nr_pages * page_size)
671 err("unexpected offset %lu\n", offset);
672 uffdio_copy.dst = (unsigned long) area_dst + offset;
673 uffdio_copy.src = (unsigned long) area_src + offset;
674 uffdio_copy.len = page_size;
676 uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
678 uffdio_copy.mode = 0;
679 uffdio_copy.copy = 0;
680 if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
681 /* real retval in ufdio_copy.copy */
682 if (uffdio_copy.copy != -EEXIST)
683 err("UFFDIO_COPY error: %"PRId64,
684 (int64_t)uffdio_copy.copy);
685 wake_range(ufd, uffdio_copy.dst, page_size);
686 } else if (uffdio_copy.copy != page_size) {
687 err("UFFDIO_COPY error: %"PRId64, (int64_t)uffdio_copy.copy);
689 if (test_uffdio_copy_eexist && retry) {
690 test_uffdio_copy_eexist = false;
691 retry_copy_page(ufd, &uffdio_copy, offset);
698 static int copy_page_retry(int ufd, unsigned long offset)
700 return __copy_page(ufd, offset, true);
703 static int copy_page(int ufd, unsigned long offset)
705 return __copy_page(ufd, offset, false);
708 static int uffd_read_msg(int ufd, struct uffd_msg *msg)
710 int ret = read(uffd, msg, sizeof(*msg));
712 if (ret != sizeof(*msg)) {
714 if (errno == EAGAIN || errno == EINTR)
716 err("blocking read error");
725 static void uffd_handle_page_fault(struct uffd_msg *msg,
726 struct uffd_stats *stats)
728 unsigned long offset;
730 if (msg->event != UFFD_EVENT_PAGEFAULT)
731 err("unexpected msg event %u", msg->event);
733 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
734 /* Write protect page faults */
735 wp_range(uffd, msg->arg.pagefault.address, page_size, false);
737 } else if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_MINOR) {
744 * To prove we can modify the original range for testing
745 * purposes, we're going to bit flip this range before
748 * Note that this requires all minor page fault tests operate on
749 * area_dst (non-UFFD-registered) and area_dst_alias
753 area = (uint8_t *)(area_dst +
754 ((char *)msg->arg.pagefault.address -
756 for (b = 0; b < page_size; ++b)
758 continue_range(uffd, msg->arg.pagefault.address, page_size);
759 stats->minor_faults++;
762 * Missing page faults.
764 * Here we force a write check for each of the missing mode
765 * faults. It's guaranteed because the only threads that
766 * will trigger uffd faults are the locking threads, and
767 * their first instruction to touch the missing page will
768 * always be pthread_mutex_lock().
770 * Note that here we relied on an NPTL glibc impl detail to
771 * always read the lock type at the entry of the lock op
772 * (pthread_mutex_t.__data.__type, offset 0x10) before
773 * doing any locking operations to guarantee that. It's
774 * actually not good to rely on this impl detail because
775 * logically a pthread-compatible lib can implement the
776 * locks without types and we can fail when linking with
777 * them. However since we used to find bugs with this
778 * strict check we still keep it around. Hopefully this
779 * could be a good hint when it fails again. If one day
780 * it'll break on some other impl of glibc we'll revisit.
782 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
783 err("unexpected write fault");
785 offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
786 offset &= ~(page_size-1);
788 if (copy_page(uffd, offset))
789 stats->missing_faults++;
793 static void *uffd_poll_thread(void *arg)
795 struct uffd_stats *stats = (struct uffd_stats *)arg;
796 unsigned long cpu = stats->cpu;
797 struct pollfd pollfd[2];
799 struct uffdio_register uffd_reg;
804 pollfd[0].events = POLLIN;
805 pollfd[1].fd = pipefd[cpu*2];
806 pollfd[1].events = POLLIN;
809 ret = poll(pollfd, 2, -1);
811 if (errno == EINTR || errno == EAGAIN)
813 err("poll error: %d", ret);
815 if (pollfd[1].revents & POLLIN) {
816 if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
817 err("read pipefd error");
820 if (!(pollfd[0].revents & POLLIN))
821 err("pollfd[0].revents %d", pollfd[0].revents);
822 if (uffd_read_msg(uffd, &msg))
826 err("unexpected msg event %u\n", msg.event);
828 case UFFD_EVENT_PAGEFAULT:
829 uffd_handle_page_fault(&msg, stats);
831 case UFFD_EVENT_FORK:
833 uffd = msg.arg.fork.ufd;
836 case UFFD_EVENT_REMOVE:
837 uffd_reg.range.start = msg.arg.remove.start;
838 uffd_reg.range.len = msg.arg.remove.end -
839 msg.arg.remove.start;
840 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
841 err("remove failure");
843 case UFFD_EVENT_REMAP:
844 area_remap = area_dst; /* save for later unmap */
845 area_dst = (char *)(unsigned long)msg.arg.remap.to;
853 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
855 static void *uffd_read_thread(void *arg)
857 struct uffd_stats *stats = (struct uffd_stats *)arg;
860 pthread_mutex_unlock(&uffd_read_mutex);
861 /* from here cancellation is ok */
864 if (uffd_read_msg(uffd, &msg))
866 uffd_handle_page_fault(&msg, stats);
872 static void *background_thread(void *arg)
874 unsigned long cpu = (unsigned long) arg;
875 unsigned long page_nr, start_nr, mid_nr, end_nr;
877 start_nr = cpu * nr_pages_per_cpu;
878 end_nr = (cpu+1) * nr_pages_per_cpu;
879 mid_nr = (start_nr + end_nr) / 2;
881 /* Copy the first half of the pages */
882 for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
883 copy_page_retry(uffd, page_nr * page_size);
886 * If we need to test uffd-wp, set it up now. Then we'll have
887 * at least the first half of the pages mapped already which
888 * can be write-protected for testing
891 wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
892 nr_pages_per_cpu * page_size, true);
895 * Continue the 2nd half of the page copying, handling write
896 * protection faults if any
898 for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
899 copy_page_retry(uffd, page_nr * page_size);
904 static int stress(struct uffd_stats *uffd_stats)
907 pthread_t locking_threads[nr_cpus];
908 pthread_t uffd_threads[nr_cpus];
909 pthread_t background_threads[nr_cpus];
912 for (cpu = 0; cpu < nr_cpus; cpu++) {
913 if (pthread_create(&locking_threads[cpu], &attr,
914 locking_thread, (void *)cpu))
916 if (bounces & BOUNCE_POLL) {
917 if (pthread_create(&uffd_threads[cpu], &attr,
919 (void *)&uffd_stats[cpu]))
922 if (pthread_create(&uffd_threads[cpu], &attr,
924 (void *)&uffd_stats[cpu]))
926 pthread_mutex_lock(&uffd_read_mutex);
928 if (pthread_create(&background_threads[cpu], &attr,
929 background_thread, (void *)cpu))
932 for (cpu = 0; cpu < nr_cpus; cpu++)
933 if (pthread_join(background_threads[cpu], NULL))
937 * Be strict and immediately zap area_src, the whole area has
938 * been transferred already by the background treads. The
939 * area_src could then be faulted in a racy way by still
940 * running uffdio_threads reading zeropages after we zapped
941 * area_src (but they're guaranteed to get -EEXIST from
942 * UFFDIO_COPY without writing zero pages into area_dst
943 * because the background threads already completed).
945 uffd_test_ops->release_pages(area_src);
948 for (cpu = 0; cpu < nr_cpus; cpu++)
949 if (pthread_join(locking_threads[cpu], NULL))
952 for (cpu = 0; cpu < nr_cpus; cpu++) {
954 if (bounces & BOUNCE_POLL) {
955 if (write(pipefd[cpu*2+1], &c, 1) != 1)
956 err("pipefd write error");
957 if (pthread_join(uffd_threads[cpu],
958 (void *)&uffd_stats[cpu]))
961 if (pthread_cancel(uffd_threads[cpu]))
963 if (pthread_join(uffd_threads[cpu], NULL))
971 sigjmp_buf jbuf, *sigbuf;
973 static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
977 siglongjmp(*sigbuf, 1);
983 * For non-cooperative userfaultfd test we fork() a process that will
984 * generate pagefaults, will mremap the area monitored by the
985 * userfaultfd and at last this process will release the monitored
987 * For the anonymous and shared memory the area is divided into two
988 * parts, the first part is accessed before mremap, and the second
989 * part is accessed after mremap. Since hugetlbfs does not support
990 * mremap, the entire monitored area is accessed in a single pass for
992 * The release of the pages currently generates event for shmem and
993 * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
995 * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
996 * monitored area, generate pagefaults and test that signal is delivered.
997 * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
998 * test robustness use case - we release monitored area, fork a process
999 * that will generate pagefaults and verify signal is generated.
1000 * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
1001 * feature. Using monitor thread, verify no userfault events are generated.
1003 static int faulting_process(int signal_test)
1006 unsigned long long count;
1007 unsigned long split_nr_pages;
1008 unsigned long lastnr;
1009 struct sigaction act;
1010 volatile unsigned long signalled = 0;
1012 split_nr_pages = (nr_pages + 1) / 2;
1016 memset(&act, 0, sizeof(act));
1017 act.sa_sigaction = sighndl;
1018 act.sa_flags = SA_SIGINFO;
1019 if (sigaction(SIGBUS, &act, 0))
1021 lastnr = (unsigned long)-1;
1024 for (nr = 0; nr < split_nr_pages; nr++) {
1025 volatile int steps = 1;
1026 unsigned long offset = nr * page_size;
1029 if (sigsetjmp(*sigbuf, 1) != 0) {
1030 if (steps == 1 && nr == lastnr)
1031 err("Signal repeated");
1034 if (signal_test == 1) {
1036 /* This is a MISSING request */
1038 if (copy_page(uffd, offset))
1041 /* This is a WP request */
1055 count = *area_count(area_dst, nr);
1056 if (count != count_verify[nr])
1057 err("nr %lu memory corruption %llu %llu\n",
1058 nr, count, count_verify[nr]);
1060 * Trigger write protection if there is by writing
1061 * the same value back.
1063 *area_count(area_dst, nr) = count;
1067 return signalled != split_nr_pages;
1069 area_dst = mremap(area_dst, nr_pages * page_size, nr_pages * page_size,
1070 MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
1071 if (area_dst == MAP_FAILED)
1073 /* Reset area_src since we just clobbered it */
1076 for (; nr < nr_pages; nr++) {
1077 count = *area_count(area_dst, nr);
1078 if (count != count_verify[nr]) {
1079 err("nr %lu memory corruption %llu %llu\n",
1080 nr, count, count_verify[nr]);
1083 * Trigger write protection if there is by writing
1084 * the same value back.
1086 *area_count(area_dst, nr) = count;
1089 uffd_test_ops->release_pages(area_dst);
1091 for (nr = 0; nr < nr_pages; nr++)
1092 if (my_bcmp(area_dst + nr * page_size, zeropage, page_size))
1093 err("nr %lu is not zero", nr);
1098 static void retry_uffdio_zeropage(int ufd,
1099 struct uffdio_zeropage *uffdio_zeropage,
1100 unsigned long offset)
1102 uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
1103 uffdio_zeropage->range.len,
1105 if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
1106 if (uffdio_zeropage->zeropage != -EEXIST)
1107 err("UFFDIO_ZEROPAGE error: %"PRId64,
1108 (int64_t)uffdio_zeropage->zeropage);
1110 err("UFFDIO_ZEROPAGE error: %"PRId64,
1111 (int64_t)uffdio_zeropage->zeropage);
1115 static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
1117 struct uffdio_zeropage uffdio_zeropage;
1119 bool has_zeropage = get_expected_ioctls(0) & (1 << _UFFDIO_ZEROPAGE);
1122 if (offset >= nr_pages * page_size)
1123 err("unexpected offset %lu", offset);
1124 uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
1125 uffdio_zeropage.range.len = page_size;
1126 uffdio_zeropage.mode = 0;
1127 ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
1128 res = uffdio_zeropage.zeropage;
1130 /* real retval in ufdio_zeropage.zeropage */
1132 err("UFFDIO_ZEROPAGE error: %"PRId64, (int64_t)res);
1133 else if (res != -EINVAL)
1134 err("UFFDIO_ZEROPAGE not -EINVAL");
1135 } else if (has_zeropage) {
1136 if (res != page_size) {
1137 err("UFFDIO_ZEROPAGE unexpected size");
1139 if (test_uffdio_zeropage_eexist && retry) {
1140 test_uffdio_zeropage_eexist = false;
1141 retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1147 err("UFFDIO_ZEROPAGE succeeded");
1152 static int uffdio_zeropage(int ufd, unsigned long offset)
1154 return __uffdio_zeropage(ufd, offset, false);
1157 /* exercise UFFDIO_ZEROPAGE */
1158 static int userfaultfd_zeropage_test(void)
1160 struct uffdio_register uffdio_register;
1162 printf("testing UFFDIO_ZEROPAGE: ");
1165 uffd_test_ctx_init(0);
1167 uffdio_register.range.start = (unsigned long) area_dst;
1168 uffdio_register.range.len = nr_pages * page_size;
1169 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1171 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1172 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1173 err("register failure");
1175 assert_expected_ioctls_present(
1176 uffdio_register.mode, uffdio_register.ioctls);
1178 if (uffdio_zeropage(uffd, 0))
1179 if (my_bcmp(area_dst, zeropage, page_size))
1180 err("zeropage is not zero");
1186 static int userfaultfd_events_test(void)
1188 struct uffdio_register uffdio_register;
1193 struct uffd_stats stats = { 0 };
1195 printf("testing events (fork, remap, remove): ");
1198 features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1199 UFFD_FEATURE_EVENT_REMOVE;
1200 uffd_test_ctx_init(features);
1202 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1204 uffdio_register.range.start = (unsigned long) area_dst;
1205 uffdio_register.range.len = nr_pages * page_size;
1206 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1208 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1209 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1210 err("register failure");
1212 assert_expected_ioctls_present(
1213 uffdio_register.mode, uffdio_register.ioctls);
1215 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1216 err("uffd_poll_thread create");
1223 exit(faulting_process(0));
1225 waitpid(pid, &err, 0);
1227 err("faulting process failed");
1228 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1230 if (pthread_join(uffd_mon, NULL))
1233 uffd_stats_report(&stats, 1);
1235 return stats.missing_faults != nr_pages;
1238 static int userfaultfd_sig_test(void)
1240 struct uffdio_register uffdio_register;
1241 unsigned long userfaults;
1246 struct uffd_stats stats = { 0 };
1248 printf("testing signal delivery: ");
1251 features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1252 uffd_test_ctx_init(features);
1254 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1256 uffdio_register.range.start = (unsigned long) area_dst;
1257 uffdio_register.range.len = nr_pages * page_size;
1258 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1260 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1261 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1262 err("register failure");
1264 assert_expected_ioctls_present(
1265 uffdio_register.mode, uffdio_register.ioctls);
1267 if (faulting_process(1))
1268 err("faulting process failed");
1270 uffd_test_ops->release_pages(area_dst);
1272 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1273 err("uffd_poll_thread create");
1280 exit(faulting_process(2));
1282 waitpid(pid, &err, 0);
1284 err("faulting process failed");
1285 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1287 if (pthread_join(uffd_mon, (void **)&userfaults))
1292 err("Signal test failed, userfaults: %ld", userfaults);
1294 return userfaults != 0;
1297 void check_memory_contents(char *p)
1300 uint8_t expected_byte;
1301 void *expected_page;
1303 if (posix_memalign(&expected_page, page_size, page_size))
1304 err("out of memory");
1306 for (i = 0; i < nr_pages; ++i) {
1307 expected_byte = ~((uint8_t)(i % ((uint8_t)-1)));
1308 memset(expected_page, expected_byte, page_size);
1309 if (my_bcmp(expected_page, p + (i * page_size), page_size))
1310 err("unexpected page contents after minor fault");
1313 free(expected_page);
1316 static int userfaultfd_minor_test(void)
1319 struct uffdio_register uffdio_register;
1322 struct uffd_stats stats = { 0 };
1324 if (!test_uffdio_minor)
1327 printf("testing minor faults: ");
1330 uffd_test_ctx_init(uffd_minor_feature());
1332 uffdio_register.range.start = (unsigned long)area_dst_alias;
1333 uffdio_register.range.len = nr_pages * page_size;
1334 uffdio_register.mode = UFFDIO_REGISTER_MODE_MINOR;
1335 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1336 err("register failure");
1338 assert_expected_ioctls_present(
1339 uffdio_register.mode, uffdio_register.ioctls);
1342 * After registering with UFFD, populate the non-UFFD-registered side of
1343 * the shared mapping. This should *not* trigger any UFFD minor faults.
1345 for (p = 0; p < nr_pages; ++p) {
1346 memset(area_dst + (p * page_size), p % ((uint8_t)-1),
1350 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1351 err("uffd_poll_thread create");
1354 * Read each of the pages back using the UFFD-registered mapping. We
1355 * expect that the first time we touch a page, it will result in a minor
1356 * fault. uffd_poll_thread will resolve the fault by bit-flipping the
1357 * page's contents, and then issuing a CONTINUE ioctl.
1359 check_memory_contents(area_dst_alias);
1361 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1363 if (pthread_join(uffd_mon, NULL))
1366 uffd_stats_report(&stats, 1);
1368 if (test_collapse) {
1369 printf("testing collapse of uffd memory into PMD-mapped THPs:");
1370 if (madvise(area_dst_alias, nr_pages * page_size,
1372 err("madvise(MADV_COLLAPSE)");
1374 uffd_test_ops->check_pmd_mapping(area_dst,
1375 nr_pages * page_size /
1378 * This won't cause uffd-fault - it purely just makes sure there
1379 * was no corruption.
1381 check_memory_contents(area_dst_alias);
1385 return stats.missing_faults != 0 || stats.minor_faults != nr_pages;
1388 #define BIT_ULL(nr) (1ULL << (nr))
1389 #define PM_SOFT_DIRTY BIT_ULL(55)
1390 #define PM_MMAP_EXCLUSIVE BIT_ULL(56)
1391 #define PM_UFFD_WP BIT_ULL(57)
1392 #define PM_FILE BIT_ULL(61)
1393 #define PM_SWAP BIT_ULL(62)
1394 #define PM_PRESENT BIT_ULL(63)
1396 static int pagemap_open(void)
1398 int fd = open("/proc/self/pagemap", O_RDONLY);
1401 err("open pagemap");
1406 static uint64_t pagemap_read_vaddr(int fd, void *vaddr)
1411 ret = pread(fd, &value, sizeof(uint64_t),
1412 ((uint64_t)vaddr >> 12) * sizeof(uint64_t));
1413 if (ret != sizeof(uint64_t))
1414 err("pread() on pagemap failed");
1419 /* This macro let __LINE__ works in err() */
1420 #define pagemap_check_wp(value, wp) do { \
1421 if (!!(value & PM_UFFD_WP) != wp) \
1422 err("pagemap uffd-wp bit error: 0x%"PRIx64, value); \
1425 static int pagemap_test_fork(bool present)
1427 pid_t child = fork();
1432 /* Open the pagemap fd of the child itself */
1433 fd = pagemap_open();
1434 value = pagemap_read_vaddr(fd, area_dst);
1436 * After fork() uffd-wp bit should be gone as long as we're
1437 * without UFFD_FEATURE_EVENT_FORK
1439 pagemap_check_wp(value, false);
1443 waitpid(child, &result, 0);
1447 static void userfaultfd_pagemap_test(unsigned int test_pgsize)
1449 struct uffdio_register uffdio_register;
1453 /* Pagemap tests uffd-wp only */
1454 if (!test_uffdio_wp)
1457 /* Not enough memory to test this page size */
1458 if (test_pgsize > nr_pages * page_size)
1461 printf("testing uffd-wp with pagemap (pgsize=%u): ", test_pgsize);
1462 /* Flush so it doesn't flush twice in parent/child later */
1465 uffd_test_ctx_init(0);
1467 if (test_pgsize > page_size) {
1468 /* This is a thp test */
1469 if (madvise(area_dst, nr_pages * page_size, MADV_HUGEPAGE))
1470 err("madvise(MADV_HUGEPAGE) failed");
1471 } else if (test_pgsize == page_size) {
1472 /* This is normal page test; force no thp */
1473 if (madvise(area_dst, nr_pages * page_size, MADV_NOHUGEPAGE))
1474 err("madvise(MADV_NOHUGEPAGE) failed");
1477 uffdio_register.range.start = (unsigned long) area_dst;
1478 uffdio_register.range.len = nr_pages * page_size;
1479 uffdio_register.mode = UFFDIO_REGISTER_MODE_WP;
1480 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1481 err("register failed");
1483 pagemap_fd = pagemap_open();
1485 /* Touch the page */
1487 wp_range(uffd, (uint64_t)area_dst, test_pgsize, true);
1488 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1489 pagemap_check_wp(value, true);
1490 /* Make sure uffd-wp bit dropped when fork */
1491 if (pagemap_test_fork(true))
1492 err("Detected stall uffd-wp bit in child");
1494 /* Exclusive required or PAGEOUT won't work */
1495 if (!(value & PM_MMAP_EXCLUSIVE))
1496 err("multiple mapping detected: 0x%"PRIx64, value);
1498 if (madvise(area_dst, test_pgsize, MADV_PAGEOUT))
1499 err("madvise(MADV_PAGEOUT) failed");
1501 /* Uffd-wp should persist even swapped out */
1502 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1503 pagemap_check_wp(value, true);
1504 /* Make sure uffd-wp bit dropped when fork */
1505 if (pagemap_test_fork(false))
1506 err("Detected stall uffd-wp bit in child");
1508 /* Unprotect; this tests swap pte modifications */
1509 wp_range(uffd, (uint64_t)area_dst, page_size, false);
1510 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1511 pagemap_check_wp(value, false);
1513 /* Fault in the page from disk */
1515 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1516 pagemap_check_wp(value, false);
1522 static int userfaultfd_stress(void)
1526 struct uffdio_register uffdio_register;
1527 struct uffd_stats uffd_stats[nr_cpus];
1529 uffd_test_ctx_init(0);
1531 if (posix_memalign(&area, page_size, page_size))
1532 err("out of memory");
1534 bzero(zeropage, page_size);
1536 pthread_mutex_lock(&uffd_read_mutex);
1538 pthread_attr_init(&attr);
1539 pthread_attr_setstacksize(&attr, 16*1024*1024);
1542 printf("bounces: %d, mode:", bounces);
1543 if (bounces & BOUNCE_RANDOM)
1545 if (bounces & BOUNCE_RACINGFAULTS)
1547 if (bounces & BOUNCE_VERIFY)
1549 if (bounces & BOUNCE_POLL)
1556 if (bounces & BOUNCE_POLL)
1557 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1559 fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1562 uffdio_register.range.start = (unsigned long) area_dst;
1563 uffdio_register.range.len = nr_pages * page_size;
1564 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1566 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1567 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1568 err("register failure");
1569 assert_expected_ioctls_present(
1570 uffdio_register.mode, uffdio_register.ioctls);
1572 if (area_dst_alias) {
1573 uffdio_register.range.start = (unsigned long)
1575 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1576 err("register failure alias");
1580 * The madvise done previously isn't enough: some
1581 * uffd_thread could have read userfaults (one of
1582 * those already resolved by the background thread)
1583 * and it may be in the process of calling
1584 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1585 * area_src and it would map a zero page in it (of
1586 * course such a UFFDIO_COPY is perfectly safe as it'd
1587 * return -EEXIST). The problem comes at the next
1588 * bounce though: that racing UFFDIO_COPY would
1589 * generate zeropages in the area_src, so invalidating
1590 * the previous MADV_DONTNEED. Without this additional
1591 * MADV_DONTNEED those zeropages leftovers in the
1592 * area_src would lead to -EEXIST failure during the
1593 * next bounce, effectively leaving a zeropage in the
1596 * Try to comment this out madvise to see the memory
1597 * corruption being caught pretty quick.
1599 * khugepaged is also inhibited to collapse THP after
1600 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1601 * required to MADV_DONTNEED here.
1603 uffd_test_ops->release_pages(area_dst);
1605 uffd_stats_reset(uffd_stats, nr_cpus);
1608 if (stress(uffd_stats))
1611 /* Clear all the write protections if there is any */
1613 wp_range(uffd, (unsigned long)area_dst,
1614 nr_pages * page_size, false);
1617 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range))
1618 err("unregister failure");
1619 if (area_dst_alias) {
1620 uffdio_register.range.start = (unsigned long) area_dst;
1621 if (ioctl(uffd, UFFDIO_UNREGISTER,
1622 &uffdio_register.range))
1623 err("unregister failure alias");
1627 if (bounces & BOUNCE_VERIFY)
1628 for (nr = 0; nr < nr_pages; nr++)
1629 if (*area_count(area_dst, nr) != count_verify[nr])
1630 err("error area_count %llu %llu %lu\n",
1631 *area_count(area_src, nr),
1632 count_verify[nr], nr);
1634 /* prepare next bounce */
1635 swap(area_src, area_dst);
1637 swap(area_src_alias, area_dst_alias);
1639 uffd_stats_report(uffd_stats, nr_cpus);
1642 if (test_type == TEST_ANON) {
1644 * shmem/hugetlb won't be able to run since they have different
1645 * behavior on fork() (file-backed memory normally drops ptes
1646 * directly when fork), meanwhile the pagemap test will verify
1647 * pgtable entry of fork()ed child.
1649 userfaultfd_pagemap_test(page_size);
1651 * Hard-code for x86_64 for now for 2M THP, as x86_64 is
1652 * currently the only one that supports uffd-wp
1654 userfaultfd_pagemap_test(page_size * 512);
1657 return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1658 || userfaultfd_events_test() || userfaultfd_minor_test();
1662 * Copied from mlock2-tests.c
1664 unsigned long default_huge_page_size(void)
1666 unsigned long hps = 0;
1669 FILE *f = fopen("/proc/meminfo", "r");
1673 while (getline(&line, &linelen, f) > 0) {
1674 if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) {
1685 static void set_test_type(const char *type)
1687 if (!strcmp(type, "anon")) {
1688 test_type = TEST_ANON;
1689 uffd_test_ops = &anon_uffd_test_ops;
1690 } else if (!strcmp(type, "hugetlb")) {
1691 test_type = TEST_HUGETLB;
1692 uffd_test_ops = &hugetlb_uffd_test_ops;
1693 } else if (!strcmp(type, "hugetlb_shared")) {
1695 test_type = TEST_HUGETLB;
1696 uffd_test_ops = &hugetlb_uffd_test_ops;
1697 /* Minor faults require shared hugetlb; only enable here. */
1698 test_uffdio_minor = true;
1699 } else if (!strcmp(type, "shmem")) {
1701 test_type = TEST_SHMEM;
1702 uffd_test_ops = &shmem_uffd_test_ops;
1703 test_uffdio_minor = true;
1707 static void parse_test_type_arg(const char *raw_type)
1709 char *buf = strdup(raw_type);
1710 uint64_t features = UFFD_API_FEATURES;
1713 const char *token = strsep(&buf, ":");
1716 set_test_type(token);
1717 else if (!strcmp(token, "dev"))
1718 test_dev_userfaultfd = true;
1719 else if (!strcmp(token, "syscall"))
1720 test_dev_userfaultfd = false;
1721 else if (!strcmp(token, "collapse"))
1722 test_collapse = true;
1724 err("unrecognized test mod '%s'", token);
1728 err("failed to parse test type argument: '%s'", raw_type);
1730 if (test_collapse && test_type != TEST_SHMEM)
1731 err("Unsupported test: %s", raw_type);
1733 if (test_type == TEST_HUGETLB)
1734 page_size = hpage_size;
1736 page_size = sysconf(_SC_PAGE_SIZE);
1739 err("Unable to determine page size");
1740 if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1742 err("Impossible to run this test");
1745 * Whether we can test certain features depends not just on test type,
1746 * but also on whether or not this particular kernel supports the
1750 userfaultfd_open(&features);
1752 test_uffdio_wp = test_uffdio_wp &&
1753 (features & UFFD_FEATURE_PAGEFAULT_FLAG_WP);
1754 test_uffdio_minor = test_uffdio_minor &&
1755 (features & uffd_minor_feature());
1761 static void sigalrm(int sig)
1765 test_uffdio_copy_eexist = true;
1766 test_uffdio_zeropage_eexist = true;
1767 alarm(ALARM_INTERVAL_SECS);
1770 int main(int argc, char **argv)
1777 if (signal(SIGALRM, sigalrm) == SIG_ERR)
1778 err("failed to arm SIGALRM");
1779 alarm(ALARM_INTERVAL_SECS);
1781 hpage_size = default_huge_page_size();
1782 parse_test_type_arg(argv[1]);
1783 bytes = atol(argv[2]) * 1024 * 1024;
1785 if (test_collapse && bytes & (hpage_size - 1))
1786 err("MiB must be multiple of %lu if :collapse mod set",
1789 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1791 if (test_collapse) {
1792 /* nr_cpus must divide (bytes / page_size), otherwise,
1793 * area allocations of (nr_pages * paze_size) won't be a
1794 * multiple of hpage_size, even if bytes is a multiple of
1797 * This means that nr_cpus must divide (N * (2 << (H-P))
1799 * bytes = hpage_size * N
1800 * hpage_size = 2 << H
1801 * page_size = 2 << P
1803 * And we want to chose nr_cpus to be the largest value
1804 * satisfying this constraint, not larger than the number
1805 * of online CPUs. Unfortunately, prime factorization of
1806 * N and nr_cpus may be arbitrary, so have to search for it.
1807 * Instead, just use the highest power of 2 dividing both
1808 * nr_cpus and (bytes / page_size).
1810 int x = factor_of_2(nr_cpus);
1811 int y = factor_of_2(bytes / page_size);
1813 nr_cpus = x < y ? x : y;
1815 nr_pages_per_cpu = bytes / page_size / nr_cpus;
1816 if (!nr_pages_per_cpu) {
1817 _err("invalid MiB");
1821 bounces = atoi(argv[3]);
1823 _err("invalid bounces");
1826 nr_pages = nr_pages_per_cpu * nr_cpus;
1828 if (test_type == TEST_SHMEM || test_type == TEST_HUGETLB) {
1829 unsigned int memfd_flags = 0;
1831 if (test_type == TEST_HUGETLB)
1832 memfd_flags = MFD_HUGETLB;
1833 mem_fd = memfd_create(argv[0], memfd_flags);
1835 err("memfd_create");
1836 if (ftruncate(mem_fd, nr_pages * page_size * 2))
1838 if (fallocate(mem_fd,
1839 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
1840 nr_pages * page_size * 2))
1843 printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1844 nr_pages, nr_pages_per_cpu);
1845 return userfaultfd_stress();
1848 #else /* __NR_userfaultfd */
1850 #warning "missing __NR_userfaultfd definition"
1854 printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1858 #endif /* __NR_userfaultfd */