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;
97 static bool map_shared;
100 static unsigned long long *count_verify;
101 static int uffd = -1;
102 static int uffd_flags, finished, *pipefd;
103 static char *area_src, *area_src_alias, *area_dst, *area_dst_alias, *area_remap;
104 static char *zeropage;
106 static bool test_collapse;
108 /* Userfaultfd test statistics */
111 unsigned long missing_faults;
112 unsigned long wp_faults;
113 unsigned long minor_faults;
116 /* pthread_mutex_t starts at page offset 0 */
117 #define area_mutex(___area, ___nr) \
118 ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
120 * count is placed in the page after pthread_mutex_t naturally aligned
121 * to avoid non alignment faults on non-x86 archs.
123 #define area_count(___area, ___nr) \
124 ((volatile unsigned long long *) ((unsigned long) \
125 ((___area) + (___nr)*page_size + \
126 sizeof(pthread_mutex_t) + \
127 sizeof(unsigned long long) - 1) & \
128 ~(unsigned long)(sizeof(unsigned long long) \
132 do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
134 #define factor_of_2(x) ((x) ^ ((x) & ((x) - 1)))
136 const char *examples =
137 "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
138 "./userfaultfd anon 100 99999\n\n"
139 "# Run the same anonymous memory test, but using /dev/userfaultfd:\n"
140 "./userfaultfd anon:dev 100 99999\n\n"
141 "# Run share memory test on 1GiB region with 99 bounces:\n"
142 "./userfaultfd shmem 1000 99\n\n"
143 "# Run hugetlb memory test on 256MiB region with 50 bounces:\n"
144 "./userfaultfd hugetlb 256 50\n\n"
145 "# Run the same hugetlb test but using shared file:\n"
146 "./userfaultfd hugetlb_shared 256 50 /dev/hugepages/hugefile\n\n"
147 "# 10MiB-~6GiB 999 bounces anonymous test, "
148 "continue forever unless an error triggers\n"
149 "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
151 static void usage(void)
153 fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
154 "[hugetlbfs_file]\n\n");
155 fprintf(stderr, "Supported <test type>: anon, hugetlb, "
156 "hugetlb_shared, shmem\n\n");
157 fprintf(stderr, "'Test mods' can be joined to the test type string with a ':'. "
158 "Supported mods:\n");
159 fprintf(stderr, "\tsyscall - Use userfaultfd(2) (default)\n");
160 fprintf(stderr, "\tdev - Use /dev/userfaultfd instead of userfaultfd(2)\n");
161 fprintf(stderr, "\tcollapse - Test MADV_COLLAPSE of UFFDIO_REGISTER_MODE_MINOR\n"
163 fprintf(stderr, "\nExample test mod usage:\n");
164 fprintf(stderr, "# Run anonymous memory test with /dev/userfaultfd:\n");
165 fprintf(stderr, "./userfaultfd anon:dev 100 99999\n\n");
167 fprintf(stderr, "Examples:\n\n");
168 fprintf(stderr, "%s", examples);
172 #define _err(fmt, ...) \
175 fprintf(stderr, "ERROR: " fmt, ##__VA_ARGS__); \
176 fprintf(stderr, " (errno=%d, line=%d)\n", \
180 #define errexit(exitcode, fmt, ...) \
182 _err(fmt, ##__VA_ARGS__); \
186 #define err(fmt, ...) errexit(1, fmt, ##__VA_ARGS__)
188 static void uffd_stats_reset(struct uffd_stats *uffd_stats,
189 unsigned long n_cpus)
193 for (i = 0; i < n_cpus; i++) {
194 uffd_stats[i].cpu = i;
195 uffd_stats[i].missing_faults = 0;
196 uffd_stats[i].wp_faults = 0;
197 uffd_stats[i].minor_faults = 0;
201 static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
204 unsigned long long miss_total = 0, wp_total = 0, minor_total = 0;
206 for (i = 0; i < n_cpus; i++) {
207 miss_total += stats[i].missing_faults;
208 wp_total += stats[i].wp_faults;
209 minor_total += stats[i].minor_faults;
212 printf("userfaults: ");
214 printf("%llu missing (", miss_total);
215 for (i = 0; i < n_cpus; i++)
216 printf("%lu+", stats[i].missing_faults);
220 printf("%llu wp (", wp_total);
221 for (i = 0; i < n_cpus; i++)
222 printf("%lu+", stats[i].wp_faults);
226 printf("%llu minor (", minor_total);
227 for (i = 0; i < n_cpus; i++)
228 printf("%lu+", stats[i].minor_faults);
234 static void anon_release_pages(char *rel_area)
236 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
237 err("madvise(MADV_DONTNEED) failed");
240 static void anon_allocate_area(void **alloc_area, bool is_src)
242 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
243 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
246 static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
250 static void hugetlb_release_pages(char *rel_area)
253 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
254 err("madvise(MADV_DONTNEED) failed");
256 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
257 err("madvise(MADV_REMOVE) failed");
261 static void hugetlb_allocate_area(void **alloc_area, bool is_src)
263 void *area_alias = NULL;
264 char **alloc_area_alias;
267 *alloc_area = mmap(NULL,
268 nr_pages * page_size,
269 PROT_READ | PROT_WRITE,
270 MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB |
271 (is_src ? 0 : MAP_NORESERVE),
275 *alloc_area = mmap(NULL,
276 nr_pages * page_size,
277 PROT_READ | PROT_WRITE,
279 (is_src ? 0 : MAP_NORESERVE),
281 is_src ? 0 : nr_pages * page_size);
282 if (*alloc_area == MAP_FAILED)
283 err("mmap of hugetlbfs file failed");
286 area_alias = mmap(NULL,
287 nr_pages * page_size,
288 PROT_READ | PROT_WRITE,
291 is_src ? 0 : nr_pages * page_size);
292 if (area_alias == MAP_FAILED)
293 err("mmap of hugetlb file alias failed");
297 alloc_area_alias = &area_src_alias;
299 alloc_area_alias = &area_dst_alias;
302 *alloc_area_alias = area_alias;
305 static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
310 *start = (unsigned long) area_dst_alias + offset;
313 static void shmem_release_pages(char *rel_area)
315 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
316 err("madvise(MADV_REMOVE) failed");
319 static void shmem_allocate_area(void **alloc_area, bool is_src)
321 void *area_alias = NULL;
322 size_t bytes = nr_pages * page_size;
323 unsigned long offset = is_src ? 0 : bytes;
324 char *p = NULL, *p_alias = NULL;
329 /* src map + alias + interleaved hpages */
330 p += 2 * (bytes + hpage_size);
333 p_alias += hpage_size; /* Prevent src/dst VMA merge */
336 *alloc_area = mmap(p, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
338 if (*alloc_area == MAP_FAILED)
339 err("mmap of memfd failed");
340 if (test_collapse && *alloc_area != p)
341 err("mmap of memfd failed at %p", p);
343 area_alias = mmap(p_alias, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
345 if (area_alias == MAP_FAILED)
346 err("mmap of memfd alias failed");
347 if (test_collapse && area_alias != p_alias)
348 err("mmap of anonymous memory failed at %p", p_alias);
351 area_src_alias = area_alias;
353 area_dst_alias = area_alias;
356 static void shmem_alias_mapping(__u64 *start, size_t len, unsigned long offset)
358 *start = (unsigned long)area_dst_alias + offset;
361 static void shmem_check_pmd_mapping(void *p, int expect_nr_hpages)
363 if (!check_huge_shmem(area_dst_alias, expect_nr_hpages, hpage_size))
364 err("Did not find expected %d number of hugepages",
368 struct uffd_test_ops {
369 void (*allocate_area)(void **alloc_area, bool is_src);
370 void (*release_pages)(char *rel_area);
371 void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
372 void (*check_pmd_mapping)(void *p, int expect_nr_hpages);
375 static struct uffd_test_ops anon_uffd_test_ops = {
376 .allocate_area = anon_allocate_area,
377 .release_pages = anon_release_pages,
378 .alias_mapping = noop_alias_mapping,
379 .check_pmd_mapping = NULL,
382 static struct uffd_test_ops shmem_uffd_test_ops = {
383 .allocate_area = shmem_allocate_area,
384 .release_pages = shmem_release_pages,
385 .alias_mapping = shmem_alias_mapping,
386 .check_pmd_mapping = shmem_check_pmd_mapping,
389 static struct uffd_test_ops hugetlb_uffd_test_ops = {
390 .allocate_area = hugetlb_allocate_area,
391 .release_pages = hugetlb_release_pages,
392 .alias_mapping = hugetlb_alias_mapping,
393 .check_pmd_mapping = NULL,
396 static struct uffd_test_ops *uffd_test_ops;
398 static inline uint64_t uffd_minor_feature(void)
400 if (test_type == TEST_HUGETLB && map_shared)
401 return UFFD_FEATURE_MINOR_HUGETLBFS;
402 else if (test_type == TEST_SHMEM)
403 return UFFD_FEATURE_MINOR_SHMEM;
408 static uint64_t get_expected_ioctls(uint64_t mode)
410 uint64_t ioctls = UFFD_API_RANGE_IOCTLS;
412 if (test_type == TEST_HUGETLB)
413 ioctls &= ~(1 << _UFFDIO_ZEROPAGE);
415 if (!((mode & UFFDIO_REGISTER_MODE_WP) && test_uffdio_wp))
416 ioctls &= ~(1 << _UFFDIO_WRITEPROTECT);
418 if (!((mode & UFFDIO_REGISTER_MODE_MINOR) && test_uffdio_minor))
419 ioctls &= ~(1 << _UFFDIO_CONTINUE);
424 static void assert_expected_ioctls_present(uint64_t mode, uint64_t ioctls)
426 uint64_t expected = get_expected_ioctls(mode);
427 uint64_t actual = ioctls & expected;
429 if (actual != expected) {
430 err("missing ioctl(s): expected %"PRIx64" actual: %"PRIx64,
435 static int __userfaultfd_open_dev(void)
439 fd = open("/dev/userfaultfd", O_RDWR | O_CLOEXEC);
441 errexit(KSFT_SKIP, "opening /dev/userfaultfd failed");
443 _uffd = ioctl(fd, USERFAULTFD_IOC_NEW, UFFD_FLAGS);
445 errexit(errno == ENOTTY ? KSFT_SKIP : 1,
446 "creating userfaultfd failed");
451 static void userfaultfd_open(uint64_t *features)
453 struct uffdio_api uffdio_api;
455 if (test_dev_userfaultfd)
456 uffd = __userfaultfd_open_dev();
458 uffd = syscall(__NR_userfaultfd, UFFD_FLAGS);
460 errexit(errno == ENOSYS ? KSFT_SKIP : 1,
461 "creating userfaultfd failed");
463 uffd_flags = fcntl(uffd, F_GETFD, NULL);
465 uffdio_api.api = UFFD_API;
466 uffdio_api.features = *features;
467 if (ioctl(uffd, UFFDIO_API, &uffdio_api))
468 err("UFFDIO_API failed.\nPlease make sure to "
469 "run with either root or ptrace capability.");
470 if (uffdio_api.api != UFFD_API)
471 err("UFFDIO_API error: %" PRIu64, (uint64_t)uffdio_api.api);
473 *features = uffdio_api.features;
476 static inline void munmap_area(void **area)
479 if (munmap(*area, nr_pages * page_size))
485 static void uffd_test_ctx_clear(void)
490 for (i = 0; i < nr_cpus * 2; ++i) {
491 if (close(pipefd[i]))
509 munmap_area((void **)&area_src);
510 munmap_area((void **)&area_src_alias);
511 munmap_area((void **)&area_dst);
512 munmap_area((void **)&area_dst_alias);
513 munmap_area((void **)&area_remap);
516 static void uffd_test_ctx_init(uint64_t features)
518 unsigned long nr, cpu;
520 uffd_test_ctx_clear();
522 uffd_test_ops->allocate_area((void **)&area_src, true);
523 uffd_test_ops->allocate_area((void **)&area_dst, false);
525 userfaultfd_open(&features);
527 count_verify = malloc(nr_pages * sizeof(unsigned long long));
531 for (nr = 0; nr < nr_pages; nr++) {
532 *area_mutex(area_src, nr) =
533 (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
534 count_verify[nr] = *area_count(area_src, nr) = 1;
536 * In the transition between 255 to 256, powerpc will
537 * read out of order in my_bcmp and see both bytes as
538 * zero, so leave a placeholder below always non-zero
539 * after the count, to avoid my_bcmp to trigger false
542 *(area_count(area_src, nr) + 1) = 1;
546 * After initialization of area_src, we must explicitly release pages
547 * for area_dst to make sure it's fully empty. Otherwise we could have
548 * some area_dst pages be errornously initialized with zero pages,
549 * hence we could hit memory corruption later in the test.
551 * One example is when THP is globally enabled, above allocate_area()
552 * calls could have the two areas merged into a single VMA (as they
553 * will have the same VMA flags so they're mergeable). When we
554 * initialize the area_src above, it's possible that some part of
555 * area_dst could have been faulted in via one huge THP that will be
556 * shared between area_src and area_dst. It could cause some of the
557 * area_dst won't be trapped by missing userfaults.
559 * This release_pages() will guarantee even if that happened, we'll
560 * proactively split the thp and drop any accidentally initialized
561 * pages within area_dst.
563 uffd_test_ops->release_pages(area_dst);
565 pipefd = malloc(sizeof(int) * nr_cpus * 2);
568 for (cpu = 0; cpu < nr_cpus; cpu++)
569 if (pipe2(&pipefd[cpu * 2], O_CLOEXEC | O_NONBLOCK))
573 static int my_bcmp(char *str1, char *str2, size_t n)
576 for (i = 0; i < n; i++)
577 if (str1[i] != str2[i])
582 static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
584 struct uffdio_writeprotect prms;
586 /* Write protection page faults */
587 prms.range.start = start;
588 prms.range.len = len;
589 /* Undo write-protect, do wakeup after that */
590 prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
592 if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
593 err("clear WP failed: address=0x%"PRIx64, (uint64_t)start);
596 static void continue_range(int ufd, __u64 start, __u64 len)
598 struct uffdio_continue req;
601 req.range.start = start;
605 if (ioctl(ufd, UFFDIO_CONTINUE, &req))
606 err("UFFDIO_CONTINUE failed for address 0x%" PRIx64,
610 * Error handling within the kernel for continue is subtly different
611 * from copy or zeropage, so it may be a source of bugs. Trigger an
612 * error (-EEXIST) on purpose, to verify doing so doesn't cause a BUG.
615 ret = ioctl(ufd, UFFDIO_CONTINUE, &req);
616 if (ret >= 0 || req.mapped != -EEXIST)
617 err("failed to exercise UFFDIO_CONTINUE error handling, ret=%d, mapped=%" PRId64,
618 ret, (int64_t) req.mapped);
621 static void *locking_thread(void *arg)
623 unsigned long cpu = (unsigned long) arg;
624 unsigned long page_nr;
625 unsigned long long count;
627 if (!(bounces & BOUNCE_RANDOM)) {
629 if (!(bounces & BOUNCE_RACINGFAULTS))
630 page_nr += cpu * nr_pages_per_cpu;
634 if (bounces & BOUNCE_RANDOM) {
635 if (getrandom(&page_nr, sizeof(page_nr), 0) != sizeof(page_nr))
636 err("getrandom failed");
640 pthread_mutex_lock(area_mutex(area_dst, page_nr));
641 count = *area_count(area_dst, page_nr);
642 if (count != count_verify[page_nr])
643 err("page_nr %lu memory corruption %llu %llu",
644 page_nr, count, count_verify[page_nr]);
646 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
647 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
653 static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
654 unsigned long offset)
656 uffd_test_ops->alias_mapping(&uffdio_copy->dst,
659 if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
660 /* real retval in ufdio_copy.copy */
661 if (uffdio_copy->copy != -EEXIST)
662 err("UFFDIO_COPY retry error: %"PRId64,
663 (int64_t)uffdio_copy->copy);
665 err("UFFDIO_COPY retry unexpected: %"PRId64,
666 (int64_t)uffdio_copy->copy);
670 static void wake_range(int ufd, unsigned long addr, unsigned long len)
672 struct uffdio_range uffdio_wake;
674 uffdio_wake.start = addr;
675 uffdio_wake.len = len;
677 if (ioctl(ufd, UFFDIO_WAKE, &uffdio_wake))
678 fprintf(stderr, "error waking %lu\n",
682 static int __copy_page(int ufd, unsigned long offset, bool retry)
684 struct uffdio_copy uffdio_copy;
686 if (offset >= nr_pages * page_size)
687 err("unexpected offset %lu\n", offset);
688 uffdio_copy.dst = (unsigned long) area_dst + offset;
689 uffdio_copy.src = (unsigned long) area_src + offset;
690 uffdio_copy.len = page_size;
692 uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
694 uffdio_copy.mode = 0;
695 uffdio_copy.copy = 0;
696 if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
697 /* real retval in ufdio_copy.copy */
698 if (uffdio_copy.copy != -EEXIST)
699 err("UFFDIO_COPY error: %"PRId64,
700 (int64_t)uffdio_copy.copy);
701 wake_range(ufd, uffdio_copy.dst, page_size);
702 } else if (uffdio_copy.copy != page_size) {
703 err("UFFDIO_COPY error: %"PRId64, (int64_t)uffdio_copy.copy);
705 if (test_uffdio_copy_eexist && retry) {
706 test_uffdio_copy_eexist = false;
707 retry_copy_page(ufd, &uffdio_copy, offset);
714 static int copy_page_retry(int ufd, unsigned long offset)
716 return __copy_page(ufd, offset, true);
719 static int copy_page(int ufd, unsigned long offset)
721 return __copy_page(ufd, offset, false);
724 static int uffd_read_msg(int ufd, struct uffd_msg *msg)
726 int ret = read(uffd, msg, sizeof(*msg));
728 if (ret != sizeof(*msg)) {
730 if (errno == EAGAIN || errno == EINTR)
732 err("blocking read error");
741 static void uffd_handle_page_fault(struct uffd_msg *msg,
742 struct uffd_stats *stats)
744 unsigned long offset;
746 if (msg->event != UFFD_EVENT_PAGEFAULT)
747 err("unexpected msg event %u", msg->event);
749 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
750 /* Write protect page faults */
751 wp_range(uffd, msg->arg.pagefault.address, page_size, false);
753 } else if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_MINOR) {
760 * To prove we can modify the original range for testing
761 * purposes, we're going to bit flip this range before
764 * Note that this requires all minor page fault tests operate on
765 * area_dst (non-UFFD-registered) and area_dst_alias
769 area = (uint8_t *)(area_dst +
770 ((char *)msg->arg.pagefault.address -
772 for (b = 0; b < page_size; ++b)
774 continue_range(uffd, msg->arg.pagefault.address, page_size);
775 stats->minor_faults++;
777 /* Missing page faults */
778 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
779 err("unexpected write fault");
781 offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
782 offset &= ~(page_size-1);
784 if (copy_page(uffd, offset))
785 stats->missing_faults++;
789 static void *uffd_poll_thread(void *arg)
791 struct uffd_stats *stats = (struct uffd_stats *)arg;
792 unsigned long cpu = stats->cpu;
793 struct pollfd pollfd[2];
795 struct uffdio_register uffd_reg;
800 pollfd[0].events = POLLIN;
801 pollfd[1].fd = pipefd[cpu*2];
802 pollfd[1].events = POLLIN;
805 ret = poll(pollfd, 2, -1);
807 if (errno == EINTR || errno == EAGAIN)
809 err("poll error: %d", ret);
811 if (pollfd[1].revents & POLLIN) {
812 if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
813 err("read pipefd error");
816 if (!(pollfd[0].revents & POLLIN))
817 err("pollfd[0].revents %d", pollfd[0].revents);
818 if (uffd_read_msg(uffd, &msg))
822 err("unexpected msg event %u\n", msg.event);
824 case UFFD_EVENT_PAGEFAULT:
825 uffd_handle_page_fault(&msg, stats);
827 case UFFD_EVENT_FORK:
829 uffd = msg.arg.fork.ufd;
832 case UFFD_EVENT_REMOVE:
833 uffd_reg.range.start = msg.arg.remove.start;
834 uffd_reg.range.len = msg.arg.remove.end -
835 msg.arg.remove.start;
836 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
837 err("remove failure");
839 case UFFD_EVENT_REMAP:
840 area_remap = area_dst; /* save for later unmap */
841 area_dst = (char *)(unsigned long)msg.arg.remap.to;
849 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
851 static void *uffd_read_thread(void *arg)
853 struct uffd_stats *stats = (struct uffd_stats *)arg;
856 pthread_mutex_unlock(&uffd_read_mutex);
857 /* from here cancellation is ok */
860 if (uffd_read_msg(uffd, &msg))
862 uffd_handle_page_fault(&msg, stats);
868 static void *background_thread(void *arg)
870 unsigned long cpu = (unsigned long) arg;
871 unsigned long page_nr, start_nr, mid_nr, end_nr;
873 start_nr = cpu * nr_pages_per_cpu;
874 end_nr = (cpu+1) * nr_pages_per_cpu;
875 mid_nr = (start_nr + end_nr) / 2;
877 /* Copy the first half of the pages */
878 for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
879 copy_page_retry(uffd, page_nr * page_size);
882 * If we need to test uffd-wp, set it up now. Then we'll have
883 * at least the first half of the pages mapped already which
884 * can be write-protected for testing
887 wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
888 nr_pages_per_cpu * page_size, true);
891 * Continue the 2nd half of the page copying, handling write
892 * protection faults if any
894 for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
895 copy_page_retry(uffd, page_nr * page_size);
900 static int stress(struct uffd_stats *uffd_stats)
903 pthread_t locking_threads[nr_cpus];
904 pthread_t uffd_threads[nr_cpus];
905 pthread_t background_threads[nr_cpus];
908 for (cpu = 0; cpu < nr_cpus; cpu++) {
909 if (pthread_create(&locking_threads[cpu], &attr,
910 locking_thread, (void *)cpu))
912 if (bounces & BOUNCE_POLL) {
913 if (pthread_create(&uffd_threads[cpu], &attr,
915 (void *)&uffd_stats[cpu]))
918 if (pthread_create(&uffd_threads[cpu], &attr,
920 (void *)&uffd_stats[cpu]))
922 pthread_mutex_lock(&uffd_read_mutex);
924 if (pthread_create(&background_threads[cpu], &attr,
925 background_thread, (void *)cpu))
928 for (cpu = 0; cpu < nr_cpus; cpu++)
929 if (pthread_join(background_threads[cpu], NULL))
933 * Be strict and immediately zap area_src, the whole area has
934 * been transferred already by the background treads. The
935 * area_src could then be faulted in a racy way by still
936 * running uffdio_threads reading zeropages after we zapped
937 * area_src (but they're guaranteed to get -EEXIST from
938 * UFFDIO_COPY without writing zero pages into area_dst
939 * because the background threads already completed).
941 uffd_test_ops->release_pages(area_src);
944 for (cpu = 0; cpu < nr_cpus; cpu++)
945 if (pthread_join(locking_threads[cpu], NULL))
948 for (cpu = 0; cpu < nr_cpus; cpu++) {
950 if (bounces & BOUNCE_POLL) {
951 if (write(pipefd[cpu*2+1], &c, 1) != 1)
952 err("pipefd write error");
953 if (pthread_join(uffd_threads[cpu],
954 (void *)&uffd_stats[cpu]))
957 if (pthread_cancel(uffd_threads[cpu]))
959 if (pthread_join(uffd_threads[cpu], NULL))
967 sigjmp_buf jbuf, *sigbuf;
969 static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
973 siglongjmp(*sigbuf, 1);
979 * For non-cooperative userfaultfd test we fork() a process that will
980 * generate pagefaults, will mremap the area monitored by the
981 * userfaultfd and at last this process will release the monitored
983 * For the anonymous and shared memory the area is divided into two
984 * parts, the first part is accessed before mremap, and the second
985 * part is accessed after mremap. Since hugetlbfs does not support
986 * mremap, the entire monitored area is accessed in a single pass for
988 * The release of the pages currently generates event for shmem and
989 * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
991 * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
992 * monitored area, generate pagefaults and test that signal is delivered.
993 * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
994 * test robustness use case - we release monitored area, fork a process
995 * that will generate pagefaults and verify signal is generated.
996 * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
997 * feature. Using monitor thread, verify no userfault events are generated.
999 static int faulting_process(int signal_test)
1002 unsigned long long count;
1003 unsigned long split_nr_pages;
1004 unsigned long lastnr;
1005 struct sigaction act;
1006 volatile unsigned long signalled = 0;
1008 split_nr_pages = (nr_pages + 1) / 2;
1012 memset(&act, 0, sizeof(act));
1013 act.sa_sigaction = sighndl;
1014 act.sa_flags = SA_SIGINFO;
1015 if (sigaction(SIGBUS, &act, 0))
1017 lastnr = (unsigned long)-1;
1020 for (nr = 0; nr < split_nr_pages; nr++) {
1021 volatile int steps = 1;
1022 unsigned long offset = nr * page_size;
1025 if (sigsetjmp(*sigbuf, 1) != 0) {
1026 if (steps == 1 && nr == lastnr)
1027 err("Signal repeated");
1030 if (signal_test == 1) {
1032 /* This is a MISSING request */
1034 if (copy_page(uffd, offset))
1037 /* This is a WP request */
1051 count = *area_count(area_dst, nr);
1052 if (count != count_verify[nr])
1053 err("nr %lu memory corruption %llu %llu\n",
1054 nr, count, count_verify[nr]);
1056 * Trigger write protection if there is by writing
1057 * the same value back.
1059 *area_count(area_dst, nr) = count;
1063 return signalled != split_nr_pages;
1065 area_dst = mremap(area_dst, nr_pages * page_size, nr_pages * page_size,
1066 MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
1067 if (area_dst == MAP_FAILED)
1069 /* Reset area_src since we just clobbered it */
1072 for (; nr < nr_pages; nr++) {
1073 count = *area_count(area_dst, nr);
1074 if (count != count_verify[nr]) {
1075 err("nr %lu memory corruption %llu %llu\n",
1076 nr, count, count_verify[nr]);
1079 * Trigger write protection if there is by writing
1080 * the same value back.
1082 *area_count(area_dst, nr) = count;
1085 uffd_test_ops->release_pages(area_dst);
1087 for (nr = 0; nr < nr_pages; nr++)
1088 if (my_bcmp(area_dst + nr * page_size, zeropage, page_size))
1089 err("nr %lu is not zero", nr);
1094 static void retry_uffdio_zeropage(int ufd,
1095 struct uffdio_zeropage *uffdio_zeropage,
1096 unsigned long offset)
1098 uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
1099 uffdio_zeropage->range.len,
1101 if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
1102 if (uffdio_zeropage->zeropage != -EEXIST)
1103 err("UFFDIO_ZEROPAGE error: %"PRId64,
1104 (int64_t)uffdio_zeropage->zeropage);
1106 err("UFFDIO_ZEROPAGE error: %"PRId64,
1107 (int64_t)uffdio_zeropage->zeropage);
1111 static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
1113 struct uffdio_zeropage uffdio_zeropage;
1115 bool has_zeropage = get_expected_ioctls(0) & (1 << _UFFDIO_ZEROPAGE);
1118 if (offset >= nr_pages * page_size)
1119 err("unexpected offset %lu", offset);
1120 uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
1121 uffdio_zeropage.range.len = page_size;
1122 uffdio_zeropage.mode = 0;
1123 ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
1124 res = uffdio_zeropage.zeropage;
1126 /* real retval in ufdio_zeropage.zeropage */
1128 err("UFFDIO_ZEROPAGE error: %"PRId64, (int64_t)res);
1129 else if (res != -EINVAL)
1130 err("UFFDIO_ZEROPAGE not -EINVAL");
1131 } else if (has_zeropage) {
1132 if (res != page_size) {
1133 err("UFFDIO_ZEROPAGE unexpected size");
1135 if (test_uffdio_zeropage_eexist && retry) {
1136 test_uffdio_zeropage_eexist = false;
1137 retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1143 err("UFFDIO_ZEROPAGE succeeded");
1148 static int uffdio_zeropage(int ufd, unsigned long offset)
1150 return __uffdio_zeropage(ufd, offset, false);
1153 /* exercise UFFDIO_ZEROPAGE */
1154 static int userfaultfd_zeropage_test(void)
1156 struct uffdio_register uffdio_register;
1158 printf("testing UFFDIO_ZEROPAGE: ");
1161 uffd_test_ctx_init(0);
1163 uffdio_register.range.start = (unsigned long) area_dst;
1164 uffdio_register.range.len = nr_pages * page_size;
1165 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1167 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1168 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1169 err("register failure");
1171 assert_expected_ioctls_present(
1172 uffdio_register.mode, uffdio_register.ioctls);
1174 if (uffdio_zeropage(uffd, 0))
1175 if (my_bcmp(area_dst, zeropage, page_size))
1176 err("zeropage is not zero");
1182 static int userfaultfd_events_test(void)
1184 struct uffdio_register uffdio_register;
1189 struct uffd_stats stats = { 0 };
1191 printf("testing events (fork, remap, remove): ");
1194 features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1195 UFFD_FEATURE_EVENT_REMOVE;
1196 uffd_test_ctx_init(features);
1198 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1200 uffdio_register.range.start = (unsigned long) area_dst;
1201 uffdio_register.range.len = nr_pages * page_size;
1202 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1204 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1205 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1206 err("register failure");
1208 assert_expected_ioctls_present(
1209 uffdio_register.mode, uffdio_register.ioctls);
1211 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1212 err("uffd_poll_thread create");
1219 exit(faulting_process(0));
1221 waitpid(pid, &err, 0);
1223 err("faulting process failed");
1224 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1226 if (pthread_join(uffd_mon, NULL))
1229 uffd_stats_report(&stats, 1);
1231 return stats.missing_faults != nr_pages;
1234 static int userfaultfd_sig_test(void)
1236 struct uffdio_register uffdio_register;
1237 unsigned long userfaults;
1242 struct uffd_stats stats = { 0 };
1244 printf("testing signal delivery: ");
1247 features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1248 uffd_test_ctx_init(features);
1250 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1252 uffdio_register.range.start = (unsigned long) area_dst;
1253 uffdio_register.range.len = nr_pages * page_size;
1254 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1256 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1257 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1258 err("register failure");
1260 assert_expected_ioctls_present(
1261 uffdio_register.mode, uffdio_register.ioctls);
1263 if (faulting_process(1))
1264 err("faulting process failed");
1266 uffd_test_ops->release_pages(area_dst);
1268 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1269 err("uffd_poll_thread create");
1276 exit(faulting_process(2));
1278 waitpid(pid, &err, 0);
1280 err("faulting process failed");
1281 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1283 if (pthread_join(uffd_mon, (void **)&userfaults))
1288 err("Signal test failed, userfaults: %ld", userfaults);
1290 return userfaults != 0;
1293 void check_memory_contents(char *p)
1296 uint8_t expected_byte;
1297 void *expected_page;
1299 if (posix_memalign(&expected_page, page_size, page_size))
1300 err("out of memory");
1302 for (i = 0; i < nr_pages; ++i) {
1303 expected_byte = ~((uint8_t)(i % ((uint8_t)-1)));
1304 memset(expected_page, expected_byte, page_size);
1305 if (my_bcmp(expected_page, p + (i * page_size), page_size))
1306 err("unexpected page contents after minor fault");
1309 free(expected_page);
1312 static int userfaultfd_minor_test(void)
1315 struct uffdio_register uffdio_register;
1318 struct uffd_stats stats = { 0 };
1320 if (!test_uffdio_minor)
1323 printf("testing minor faults: ");
1326 uffd_test_ctx_init(uffd_minor_feature());
1328 uffdio_register.range.start = (unsigned long)area_dst_alias;
1329 uffdio_register.range.len = nr_pages * page_size;
1330 uffdio_register.mode = UFFDIO_REGISTER_MODE_MINOR;
1331 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1332 err("register failure");
1334 assert_expected_ioctls_present(
1335 uffdio_register.mode, uffdio_register.ioctls);
1338 * After registering with UFFD, populate the non-UFFD-registered side of
1339 * the shared mapping. This should *not* trigger any UFFD minor faults.
1341 for (p = 0; p < nr_pages; ++p) {
1342 memset(area_dst + (p * page_size), p % ((uint8_t)-1),
1346 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1347 err("uffd_poll_thread create");
1350 * Read each of the pages back using the UFFD-registered mapping. We
1351 * expect that the first time we touch a page, it will result in a minor
1352 * fault. uffd_poll_thread will resolve the fault by bit-flipping the
1353 * page's contents, and then issuing a CONTINUE ioctl.
1355 check_memory_contents(area_dst_alias);
1357 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1359 if (pthread_join(uffd_mon, NULL))
1362 uffd_stats_report(&stats, 1);
1364 if (test_collapse) {
1365 printf("testing collapse of uffd memory into PMD-mapped THPs:");
1366 if (madvise(area_dst_alias, nr_pages * page_size,
1368 err("madvise(MADV_COLLAPSE)");
1370 uffd_test_ops->check_pmd_mapping(area_dst,
1371 nr_pages * page_size /
1374 * This won't cause uffd-fault - it purely just makes sure there
1375 * was no corruption.
1377 check_memory_contents(area_dst_alias);
1381 return stats.missing_faults != 0 || stats.minor_faults != nr_pages;
1384 #define BIT_ULL(nr) (1ULL << (nr))
1385 #define PM_SOFT_DIRTY BIT_ULL(55)
1386 #define PM_MMAP_EXCLUSIVE BIT_ULL(56)
1387 #define PM_UFFD_WP BIT_ULL(57)
1388 #define PM_FILE BIT_ULL(61)
1389 #define PM_SWAP BIT_ULL(62)
1390 #define PM_PRESENT BIT_ULL(63)
1392 static int pagemap_open(void)
1394 int fd = open("/proc/self/pagemap", O_RDONLY);
1397 err("open pagemap");
1402 static uint64_t pagemap_read_vaddr(int fd, void *vaddr)
1407 ret = pread(fd, &value, sizeof(uint64_t),
1408 ((uint64_t)vaddr >> 12) * sizeof(uint64_t));
1409 if (ret != sizeof(uint64_t))
1410 err("pread() on pagemap failed");
1415 /* This macro let __LINE__ works in err() */
1416 #define pagemap_check_wp(value, wp) do { \
1417 if (!!(value & PM_UFFD_WP) != wp) \
1418 err("pagemap uffd-wp bit error: 0x%"PRIx64, value); \
1421 static int pagemap_test_fork(bool present)
1423 pid_t child = fork();
1428 /* Open the pagemap fd of the child itself */
1429 fd = pagemap_open();
1430 value = pagemap_read_vaddr(fd, area_dst);
1432 * After fork() uffd-wp bit should be gone as long as we're
1433 * without UFFD_FEATURE_EVENT_FORK
1435 pagemap_check_wp(value, false);
1439 waitpid(child, &result, 0);
1443 static void userfaultfd_pagemap_test(unsigned int test_pgsize)
1445 struct uffdio_register uffdio_register;
1449 /* Pagemap tests uffd-wp only */
1450 if (!test_uffdio_wp)
1453 /* Not enough memory to test this page size */
1454 if (test_pgsize > nr_pages * page_size)
1457 printf("testing uffd-wp with pagemap (pgsize=%u): ", test_pgsize);
1458 /* Flush so it doesn't flush twice in parent/child later */
1461 uffd_test_ctx_init(0);
1463 if (test_pgsize > page_size) {
1464 /* This is a thp test */
1465 if (madvise(area_dst, nr_pages * page_size, MADV_HUGEPAGE))
1466 err("madvise(MADV_HUGEPAGE) failed");
1467 } else if (test_pgsize == page_size) {
1468 /* This is normal page test; force no thp */
1469 if (madvise(area_dst, nr_pages * page_size, MADV_NOHUGEPAGE))
1470 err("madvise(MADV_NOHUGEPAGE) failed");
1473 uffdio_register.range.start = (unsigned long) area_dst;
1474 uffdio_register.range.len = nr_pages * page_size;
1475 uffdio_register.mode = UFFDIO_REGISTER_MODE_WP;
1476 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1477 err("register failed");
1479 pagemap_fd = pagemap_open();
1481 /* Touch the page */
1483 wp_range(uffd, (uint64_t)area_dst, test_pgsize, true);
1484 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1485 pagemap_check_wp(value, true);
1486 /* Make sure uffd-wp bit dropped when fork */
1487 if (pagemap_test_fork(true))
1488 err("Detected stall uffd-wp bit in child");
1490 /* Exclusive required or PAGEOUT won't work */
1491 if (!(value & PM_MMAP_EXCLUSIVE))
1492 err("multiple mapping detected: 0x%"PRIx64, value);
1494 if (madvise(area_dst, test_pgsize, MADV_PAGEOUT))
1495 err("madvise(MADV_PAGEOUT) failed");
1497 /* Uffd-wp should persist even swapped out */
1498 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1499 pagemap_check_wp(value, true);
1500 /* Make sure uffd-wp bit dropped when fork */
1501 if (pagemap_test_fork(false))
1502 err("Detected stall uffd-wp bit in child");
1504 /* Unprotect; this tests swap pte modifications */
1505 wp_range(uffd, (uint64_t)area_dst, page_size, false);
1506 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1507 pagemap_check_wp(value, false);
1509 /* Fault in the page from disk */
1511 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1512 pagemap_check_wp(value, false);
1518 static int userfaultfd_stress(void)
1522 struct uffdio_register uffdio_register;
1523 struct uffd_stats uffd_stats[nr_cpus];
1525 uffd_test_ctx_init(0);
1527 if (posix_memalign(&area, page_size, page_size))
1528 err("out of memory");
1530 bzero(zeropage, page_size);
1532 pthread_mutex_lock(&uffd_read_mutex);
1534 pthread_attr_init(&attr);
1535 pthread_attr_setstacksize(&attr, 16*1024*1024);
1538 printf("bounces: %d, mode:", bounces);
1539 if (bounces & BOUNCE_RANDOM)
1541 if (bounces & BOUNCE_RACINGFAULTS)
1543 if (bounces & BOUNCE_VERIFY)
1545 if (bounces & BOUNCE_POLL)
1552 if (bounces & BOUNCE_POLL)
1553 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1555 fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1558 uffdio_register.range.start = (unsigned long) area_dst;
1559 uffdio_register.range.len = nr_pages * page_size;
1560 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1562 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1563 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1564 err("register failure");
1565 assert_expected_ioctls_present(
1566 uffdio_register.mode, uffdio_register.ioctls);
1568 if (area_dst_alias) {
1569 uffdio_register.range.start = (unsigned long)
1571 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1572 err("register failure alias");
1576 * The madvise done previously isn't enough: some
1577 * uffd_thread could have read userfaults (one of
1578 * those already resolved by the background thread)
1579 * and it may be in the process of calling
1580 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1581 * area_src and it would map a zero page in it (of
1582 * course such a UFFDIO_COPY is perfectly safe as it'd
1583 * return -EEXIST). The problem comes at the next
1584 * bounce though: that racing UFFDIO_COPY would
1585 * generate zeropages in the area_src, so invalidating
1586 * the previous MADV_DONTNEED. Without this additional
1587 * MADV_DONTNEED those zeropages leftovers in the
1588 * area_src would lead to -EEXIST failure during the
1589 * next bounce, effectively leaving a zeropage in the
1592 * Try to comment this out madvise to see the memory
1593 * corruption being caught pretty quick.
1595 * khugepaged is also inhibited to collapse THP after
1596 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1597 * required to MADV_DONTNEED here.
1599 uffd_test_ops->release_pages(area_dst);
1601 uffd_stats_reset(uffd_stats, nr_cpus);
1604 if (stress(uffd_stats))
1607 /* Clear all the write protections if there is any */
1609 wp_range(uffd, (unsigned long)area_dst,
1610 nr_pages * page_size, false);
1613 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range))
1614 err("unregister failure");
1615 if (area_dst_alias) {
1616 uffdio_register.range.start = (unsigned long) area_dst;
1617 if (ioctl(uffd, UFFDIO_UNREGISTER,
1618 &uffdio_register.range))
1619 err("unregister failure alias");
1623 if (bounces & BOUNCE_VERIFY)
1624 for (nr = 0; nr < nr_pages; nr++)
1625 if (*area_count(area_dst, nr) != count_verify[nr])
1626 err("error area_count %llu %llu %lu\n",
1627 *area_count(area_src, nr),
1628 count_verify[nr], nr);
1630 /* prepare next bounce */
1631 swap(area_src, area_dst);
1633 swap(area_src_alias, area_dst_alias);
1635 uffd_stats_report(uffd_stats, nr_cpus);
1638 if (test_type == TEST_ANON) {
1640 * shmem/hugetlb won't be able to run since they have different
1641 * behavior on fork() (file-backed memory normally drops ptes
1642 * directly when fork), meanwhile the pagemap test will verify
1643 * pgtable entry of fork()ed child.
1645 userfaultfd_pagemap_test(page_size);
1647 * Hard-code for x86_64 for now for 2M THP, as x86_64 is
1648 * currently the only one that supports uffd-wp
1650 userfaultfd_pagemap_test(page_size * 512);
1653 return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1654 || userfaultfd_events_test() || userfaultfd_minor_test();
1658 * Copied from mlock2-tests.c
1660 unsigned long default_huge_page_size(void)
1662 unsigned long hps = 0;
1665 FILE *f = fopen("/proc/meminfo", "r");
1669 while (getline(&line, &linelen, f) > 0) {
1670 if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) {
1681 static void set_test_type(const char *type)
1683 if (!strcmp(type, "anon")) {
1684 test_type = TEST_ANON;
1685 uffd_test_ops = &anon_uffd_test_ops;
1686 } else if (!strcmp(type, "hugetlb")) {
1687 test_type = TEST_HUGETLB;
1688 uffd_test_ops = &hugetlb_uffd_test_ops;
1689 } else if (!strcmp(type, "hugetlb_shared")) {
1691 test_type = TEST_HUGETLB;
1692 uffd_test_ops = &hugetlb_uffd_test_ops;
1693 /* Minor faults require shared hugetlb; only enable here. */
1694 test_uffdio_minor = true;
1695 } else if (!strcmp(type, "shmem")) {
1697 test_type = TEST_SHMEM;
1698 uffd_test_ops = &shmem_uffd_test_ops;
1699 test_uffdio_minor = true;
1703 static void parse_test_type_arg(const char *raw_type)
1705 char *buf = strdup(raw_type);
1706 uint64_t features = UFFD_API_FEATURES;
1709 const char *token = strsep(&buf, ":");
1712 set_test_type(token);
1713 else if (!strcmp(token, "dev"))
1714 test_dev_userfaultfd = true;
1715 else if (!strcmp(token, "syscall"))
1716 test_dev_userfaultfd = false;
1717 else if (!strcmp(token, "collapse"))
1718 test_collapse = true;
1720 err("unrecognized test mod '%s'", token);
1724 err("failed to parse test type argument: '%s'", raw_type);
1726 if (test_collapse && test_type != TEST_SHMEM)
1727 err("Unsupported test: %s", raw_type);
1729 if (test_type == TEST_HUGETLB)
1730 page_size = hpage_size;
1732 page_size = sysconf(_SC_PAGE_SIZE);
1735 err("Unable to determine page size");
1736 if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1738 err("Impossible to run this test");
1741 * Whether we can test certain features depends not just on test type,
1742 * but also on whether or not this particular kernel supports the
1746 userfaultfd_open(&features);
1748 test_uffdio_wp = test_uffdio_wp &&
1749 (features & UFFD_FEATURE_PAGEFAULT_FLAG_WP);
1750 test_uffdio_minor = test_uffdio_minor &&
1751 (features & uffd_minor_feature());
1757 static void sigalrm(int sig)
1761 test_uffdio_copy_eexist = true;
1762 test_uffdio_zeropage_eexist = true;
1763 alarm(ALARM_INTERVAL_SECS);
1766 int main(int argc, char **argv)
1773 if (signal(SIGALRM, sigalrm) == SIG_ERR)
1774 err("failed to arm SIGALRM");
1775 alarm(ALARM_INTERVAL_SECS);
1777 hpage_size = default_huge_page_size();
1778 parse_test_type_arg(argv[1]);
1779 bytes = atol(argv[2]) * 1024 * 1024;
1781 if (test_collapse && bytes & (hpage_size - 1))
1782 err("MiB must be multiple of %lu if :collapse mod set",
1785 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1787 if (test_collapse) {
1788 /* nr_cpus must divide (bytes / page_size), otherwise,
1789 * area allocations of (nr_pages * paze_size) won't be a
1790 * multiple of hpage_size, even if bytes is a multiple of
1793 * This means that nr_cpus must divide (N * (2 << (H-P))
1795 * bytes = hpage_size * N
1796 * hpage_size = 2 << H
1797 * page_size = 2 << P
1799 * And we want to chose nr_cpus to be the largest value
1800 * satisfying this constraint, not larger than the number
1801 * of online CPUs. Unfortunately, prime factorization of
1802 * N and nr_cpus may be arbitrary, so have to search for it.
1803 * Instead, just use the highest power of 2 dividing both
1804 * nr_cpus and (bytes / page_size).
1806 int x = factor_of_2(nr_cpus);
1807 int y = factor_of_2(bytes / page_size);
1809 nr_cpus = x < y ? x : y;
1811 nr_pages_per_cpu = bytes / page_size / nr_cpus;
1812 if (!nr_pages_per_cpu) {
1813 _err("invalid MiB");
1817 bounces = atoi(argv[3]);
1819 _err("invalid bounces");
1822 nr_pages = nr_pages_per_cpu * nr_cpus;
1824 if (test_type == TEST_HUGETLB && map_shared) {
1827 huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1829 err("Open of %s failed", argv[4]);
1830 if (ftruncate(huge_fd, 0))
1831 err("ftruncate %s to size 0 failed", argv[4]);
1832 } else if (test_type == TEST_SHMEM) {
1833 shm_fd = memfd_create(argv[0], 0);
1835 err("memfd_create");
1836 if (ftruncate(shm_fd, nr_pages * page_size * 2))
1838 if (fallocate(shm_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 */