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>
50 #include <sys/syscall.h>
51 #include <sys/ioctl.h>
54 #include <linux/userfaultfd.h>
61 #include "../kselftest.h"
63 #ifdef __NR_userfaultfd
65 static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size;
67 #define BOUNCE_RANDOM (1<<0)
68 #define BOUNCE_RACINGFAULTS (1<<1)
69 #define BOUNCE_VERIFY (1<<2)
70 #define BOUNCE_POLL (1<<3)
74 #define TEST_HUGETLB 2
78 /* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
79 #define ALARM_INTERVAL_SECS 10
80 static volatile bool test_uffdio_copy_eexist = true;
81 static volatile bool test_uffdio_zeropage_eexist = true;
82 /* Whether to test uffd write-protection */
83 static bool test_uffdio_wp = false;
85 static bool map_shared;
87 static char *huge_fd_off0;
88 static unsigned long long *count_verify;
89 static int uffd, uffd_flags, finished, *pipefd;
90 static char *area_src, *area_src_alias, *area_dst, *area_dst_alias;
91 static char *zeropage;
94 /* Userfaultfd test statistics */
97 unsigned long missing_faults;
98 unsigned long wp_faults;
101 /* pthread_mutex_t starts at page offset 0 */
102 #define area_mutex(___area, ___nr) \
103 ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
105 * count is placed in the page after pthread_mutex_t naturally aligned
106 * to avoid non alignment faults on non-x86 archs.
108 #define area_count(___area, ___nr) \
109 ((volatile unsigned long long *) ((unsigned long) \
110 ((___area) + (___nr)*page_size + \
111 sizeof(pthread_mutex_t) + \
112 sizeof(unsigned long long) - 1) & \
113 ~(unsigned long)(sizeof(unsigned long long) \
116 const char *examples =
117 "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
118 "./userfaultfd anon 100 99999\n\n"
119 "# Run share memory test on 1GiB region with 99 bounces:\n"
120 "./userfaultfd shmem 1000 99\n\n"
121 "# Run hugetlb memory test on 256MiB region with 50 bounces (using /dev/hugepages/hugefile):\n"
122 "./userfaultfd hugetlb 256 50 /dev/hugepages/hugefile\n\n"
123 "# Run the same hugetlb test but using shmem:\n"
124 "./userfaultfd hugetlb_shared 256 50 /dev/hugepages/hugefile\n\n"
125 "# 10MiB-~6GiB 999 bounces anonymous test, "
126 "continue forever unless an error triggers\n"
127 "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
129 static void usage(void)
131 fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
132 "[hugetlbfs_file]\n\n");
133 fprintf(stderr, "Supported <test type>: anon, hugetlb, "
134 "hugetlb_shared, shmem\n\n");
135 fprintf(stderr, "Examples:\n\n");
136 fprintf(stderr, "%s", examples);
140 #define uffd_error(code, fmt, ...) \
142 fprintf(stderr, fmt, ##__VA_ARGS__); \
143 fprintf(stderr, ": %" PRId64 "\n", (int64_t)(code)); \
147 static void uffd_stats_reset(struct uffd_stats *uffd_stats,
148 unsigned long n_cpus)
152 for (i = 0; i < n_cpus; i++) {
153 uffd_stats[i].cpu = i;
154 uffd_stats[i].missing_faults = 0;
155 uffd_stats[i].wp_faults = 0;
159 static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
162 unsigned long long miss_total = 0, wp_total = 0;
164 for (i = 0; i < n_cpus; i++) {
165 miss_total += stats[i].missing_faults;
166 wp_total += stats[i].wp_faults;
169 printf("userfaults: %llu missing (", miss_total);
170 for (i = 0; i < n_cpus; i++)
171 printf("%lu+", stats[i].missing_faults);
172 printf("\b), %llu wp (", wp_total);
173 for (i = 0; i < n_cpus; i++)
174 printf("%lu+", stats[i].wp_faults);
178 static int anon_release_pages(char *rel_area)
182 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED)) {
190 static void anon_allocate_area(void **alloc_area)
192 if (posix_memalign(alloc_area, page_size, nr_pages * page_size)) {
193 fprintf(stderr, "out of memory\n");
198 static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
203 static int hugetlb_release_pages(char *rel_area)
207 if (fallocate(huge_fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
208 rel_area == huge_fd_off0 ? 0 :
209 nr_pages * page_size,
210 nr_pages * page_size)) {
218 static void hugetlb_allocate_area(void **alloc_area)
220 void *area_alias = NULL;
221 char **alloc_area_alias;
223 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
224 (map_shared ? MAP_SHARED : MAP_PRIVATE) |
226 huge_fd, *alloc_area == area_src ? 0 :
227 nr_pages * page_size);
228 if (*alloc_area == MAP_FAILED) {
229 perror("mmap of hugetlbfs file failed");
234 area_alias = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
235 MAP_SHARED | MAP_HUGETLB,
236 huge_fd, *alloc_area == area_src ? 0 :
237 nr_pages * page_size);
238 if (area_alias == MAP_FAILED) {
239 perror("mmap of hugetlb file alias failed");
244 if (*alloc_area == area_src) {
245 huge_fd_off0 = *alloc_area;
246 alloc_area_alias = &area_src_alias;
248 alloc_area_alias = &area_dst_alias;
251 *alloc_area_alias = area_alias;
256 if (munmap(*alloc_area, nr_pages * page_size) < 0) {
257 perror("hugetlb munmap");
264 static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
269 * We can't zap just the pagetable with hugetlbfs because
270 * MADV_DONTEED won't work. So exercise -EEXIST on a alias
271 * mapping where the pagetables are not established initially,
272 * this way we'll exercise the -EEXEC at the fs level.
274 *start = (unsigned long) area_dst_alias + offset;
278 static int shmem_release_pages(char *rel_area)
282 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE)) {
290 static void shmem_allocate_area(void **alloc_area)
292 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
293 MAP_ANONYMOUS | MAP_SHARED, -1, 0);
294 if (*alloc_area == MAP_FAILED) {
295 fprintf(stderr, "shared memory mmap failed\n");
300 struct uffd_test_ops {
301 unsigned long expected_ioctls;
302 void (*allocate_area)(void **alloc_area);
303 int (*release_pages)(char *rel_area);
304 void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
307 #define SHMEM_EXPECTED_IOCTLS ((1 << _UFFDIO_WAKE) | \
308 (1 << _UFFDIO_COPY) | \
309 (1 << _UFFDIO_ZEROPAGE))
311 #define ANON_EXPECTED_IOCTLS ((1 << _UFFDIO_WAKE) | \
312 (1 << _UFFDIO_COPY) | \
313 (1 << _UFFDIO_ZEROPAGE) | \
314 (1 << _UFFDIO_WRITEPROTECT))
316 static struct uffd_test_ops anon_uffd_test_ops = {
317 .expected_ioctls = ANON_EXPECTED_IOCTLS,
318 .allocate_area = anon_allocate_area,
319 .release_pages = anon_release_pages,
320 .alias_mapping = noop_alias_mapping,
323 static struct uffd_test_ops shmem_uffd_test_ops = {
324 .expected_ioctls = SHMEM_EXPECTED_IOCTLS,
325 .allocate_area = shmem_allocate_area,
326 .release_pages = shmem_release_pages,
327 .alias_mapping = noop_alias_mapping,
330 static struct uffd_test_ops hugetlb_uffd_test_ops = {
331 .expected_ioctls = UFFD_API_RANGE_IOCTLS_BASIC,
332 .allocate_area = hugetlb_allocate_area,
333 .release_pages = hugetlb_release_pages,
334 .alias_mapping = hugetlb_alias_mapping,
337 static struct uffd_test_ops *uffd_test_ops;
339 static int my_bcmp(char *str1, char *str2, size_t n)
342 for (i = 0; i < n; i++)
343 if (str1[i] != str2[i])
348 static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
350 struct uffdio_writeprotect prms;
352 /* Write protection page faults */
353 prms.range.start = start;
354 prms.range.len = len;
355 /* Undo write-protect, do wakeup after that */
356 prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
358 if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms)) {
359 fprintf(stderr, "clear WP failed for address 0x%" PRIx64 "\n",
365 static void *locking_thread(void *arg)
367 unsigned long cpu = (unsigned long) arg;
368 struct random_data rand;
369 unsigned long page_nr = *(&(page_nr)); /* uninitialized warning */
371 unsigned long long count;
376 if (bounces & BOUNCE_RANDOM) {
377 seed = (unsigned int) time(NULL) - bounces;
378 if (!(bounces & BOUNCE_RACINGFAULTS))
380 bzero(&rand, sizeof(rand));
381 bzero(&randstate, sizeof(randstate));
382 if (initstate_r(seed, randstate, sizeof(randstate), &rand)) {
383 fprintf(stderr, "srandom_r error\n");
388 if (!(bounces & BOUNCE_RACINGFAULTS))
389 page_nr += cpu * nr_pages_per_cpu;
393 if (bounces & BOUNCE_RANDOM) {
394 if (random_r(&rand, &rand_nr)) {
395 fprintf(stderr, "random_r 1 error\n");
399 if (sizeof(page_nr) > sizeof(rand_nr)) {
400 if (random_r(&rand, &rand_nr)) {
401 fprintf(stderr, "random_r 2 error\n");
404 page_nr |= (((unsigned long) rand_nr) << 16) <<
412 if (bounces & BOUNCE_VERIFY) {
413 count = *area_count(area_dst, page_nr);
416 "page_nr %lu wrong count %Lu %Lu\n",
418 count_verify[page_nr]);
424 * We can't use bcmp (or memcmp) because that
425 * returns 0 erroneously if the memory is
426 * changing under it (even if the end of the
427 * page is never changing and always
431 if (!my_bcmp(area_dst + page_nr * page_size, zeropage,
434 "my_bcmp page_nr %lu wrong count %Lu %Lu\n",
435 page_nr, count, count_verify[page_nr]);
442 /* uncomment the below line to test with mutex */
443 /* pthread_mutex_lock(area_mutex(area_dst, page_nr)); */
444 while (!bcmp(area_dst + page_nr * page_size, zeropage,
450 /* uncomment below line to test with mutex */
451 /* pthread_mutex_unlock(area_mutex(area_dst, page_nr)); */
454 "page_nr %lu all zero thread %lu %p %lu\n",
455 page_nr, cpu, area_dst + page_nr * page_size,
463 pthread_mutex_lock(area_mutex(area_dst, page_nr));
464 count = *area_count(area_dst, page_nr);
465 if (count != count_verify[page_nr]) {
467 "page_nr %lu memory corruption %Lu %Lu\n",
469 count_verify[page_nr]); exit(1);
472 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
473 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
475 if (time(NULL) - start > 1)
477 "userfault too slow %ld "
478 "possible false positive with overcommit\n",
485 static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
486 unsigned long offset)
488 uffd_test_ops->alias_mapping(&uffdio_copy->dst,
491 if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
492 /* real retval in ufdio_copy.copy */
493 if (uffdio_copy->copy != -EEXIST) {
494 uffd_error(uffdio_copy->copy,
495 "UFFDIO_COPY retry error");
498 uffd_error(uffdio_copy->copy, "UFFDIO_COPY retry unexpected");
501 static int __copy_page(int ufd, unsigned long offset, bool retry)
503 struct uffdio_copy uffdio_copy;
505 if (offset >= nr_pages * page_size) {
506 fprintf(stderr, "unexpected offset %lu\n", offset);
509 uffdio_copy.dst = (unsigned long) area_dst + offset;
510 uffdio_copy.src = (unsigned long) area_src + offset;
511 uffdio_copy.len = page_size;
513 uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
515 uffdio_copy.mode = 0;
516 uffdio_copy.copy = 0;
517 if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
518 /* real retval in ufdio_copy.copy */
519 if (uffdio_copy.copy != -EEXIST)
520 uffd_error(uffdio_copy.copy, "UFFDIO_COPY error");
521 } else if (uffdio_copy.copy != page_size) {
522 uffd_error(uffdio_copy.copy, "UFFDIO_COPY unexpected copy");
524 if (test_uffdio_copy_eexist && retry) {
525 test_uffdio_copy_eexist = false;
526 retry_copy_page(ufd, &uffdio_copy, offset);
533 static int copy_page_retry(int ufd, unsigned long offset)
535 return __copy_page(ufd, offset, true);
538 static int copy_page(int ufd, unsigned long offset)
540 return __copy_page(ufd, offset, false);
543 static int uffd_read_msg(int ufd, struct uffd_msg *msg)
545 int ret = read(uffd, msg, sizeof(*msg));
547 if (ret != sizeof(*msg)) {
551 perror("blocking read error");
553 fprintf(stderr, "short read\n");
561 static void uffd_handle_page_fault(struct uffd_msg *msg,
562 struct uffd_stats *stats)
564 unsigned long offset;
566 if (msg->event != UFFD_EVENT_PAGEFAULT) {
567 fprintf(stderr, "unexpected msg event %u\n", msg->event);
571 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
572 wp_range(uffd, msg->arg.pagefault.address, page_size, false);
575 /* Missing page faults */
576 if (bounces & BOUNCE_VERIFY &&
577 msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE) {
578 fprintf(stderr, "unexpected write fault\n");
582 offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
583 offset &= ~(page_size-1);
585 if (copy_page(uffd, offset))
586 stats->missing_faults++;
590 static void *uffd_poll_thread(void *arg)
592 struct uffd_stats *stats = (struct uffd_stats *)arg;
593 unsigned long cpu = stats->cpu;
594 struct pollfd pollfd[2];
596 struct uffdio_register uffd_reg;
601 pollfd[0].events = POLLIN;
602 pollfd[1].fd = pipefd[cpu*2];
603 pollfd[1].events = POLLIN;
606 ret = poll(pollfd, 2, -1);
608 fprintf(stderr, "poll error %d\n", ret);
615 if (pollfd[1].revents & POLLIN) {
616 if (read(pollfd[1].fd, &tmp_chr, 1) != 1) {
617 fprintf(stderr, "read pipefd error\n");
622 if (!(pollfd[0].revents & POLLIN)) {
623 fprintf(stderr, "pollfd[0].revents %d\n",
627 if (uffd_read_msg(uffd, &msg))
631 fprintf(stderr, "unexpected msg event %u\n",
634 case UFFD_EVENT_PAGEFAULT:
635 uffd_handle_page_fault(&msg, stats);
637 case UFFD_EVENT_FORK:
639 uffd = msg.arg.fork.ufd;
642 case UFFD_EVENT_REMOVE:
643 uffd_reg.range.start = msg.arg.remove.start;
644 uffd_reg.range.len = msg.arg.remove.end -
645 msg.arg.remove.start;
646 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range)) {
647 fprintf(stderr, "remove failure\n");
651 case UFFD_EVENT_REMAP:
652 area_dst = (char *)(unsigned long)msg.arg.remap.to;
660 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
662 static void *uffd_read_thread(void *arg)
664 struct uffd_stats *stats = (struct uffd_stats *)arg;
667 pthread_mutex_unlock(&uffd_read_mutex);
668 /* from here cancellation is ok */
671 if (uffd_read_msg(uffd, &msg))
673 uffd_handle_page_fault(&msg, stats);
679 static void *background_thread(void *arg)
681 unsigned long cpu = (unsigned long) arg;
682 unsigned long page_nr, start_nr, mid_nr, end_nr;
684 start_nr = cpu * nr_pages_per_cpu;
685 end_nr = (cpu+1) * nr_pages_per_cpu;
686 mid_nr = (start_nr + end_nr) / 2;
688 /* Copy the first half of the pages */
689 for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
690 copy_page_retry(uffd, page_nr * page_size);
693 * If we need to test uffd-wp, set it up now. Then we'll have
694 * at least the first half of the pages mapped already which
695 * can be write-protected for testing
698 wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
699 nr_pages_per_cpu * page_size, true);
702 * Continue the 2nd half of the page copying, handling write
703 * protection faults if any
705 for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
706 copy_page_retry(uffd, page_nr * page_size);
711 static int stress(struct uffd_stats *uffd_stats)
714 pthread_t locking_threads[nr_cpus];
715 pthread_t uffd_threads[nr_cpus];
716 pthread_t background_threads[nr_cpus];
719 for (cpu = 0; cpu < nr_cpus; cpu++) {
720 if (pthread_create(&locking_threads[cpu], &attr,
721 locking_thread, (void *)cpu))
723 if (bounces & BOUNCE_POLL) {
724 if (pthread_create(&uffd_threads[cpu], &attr,
726 (void *)&uffd_stats[cpu]))
729 if (pthread_create(&uffd_threads[cpu], &attr,
731 (void *)&uffd_stats[cpu]))
733 pthread_mutex_lock(&uffd_read_mutex);
735 if (pthread_create(&background_threads[cpu], &attr,
736 background_thread, (void *)cpu))
739 for (cpu = 0; cpu < nr_cpus; cpu++)
740 if (pthread_join(background_threads[cpu], NULL))
744 * Be strict and immediately zap area_src, the whole area has
745 * been transferred already by the background treads. The
746 * area_src could then be faulted in in a racy way by still
747 * running uffdio_threads reading zeropages after we zapped
748 * area_src (but they're guaranteed to get -EEXIST from
749 * UFFDIO_COPY without writing zero pages into area_dst
750 * because the background threads already completed).
752 if (uffd_test_ops->release_pages(area_src))
757 for (cpu = 0; cpu < nr_cpus; cpu++)
758 if (pthread_join(locking_threads[cpu], NULL))
761 for (cpu = 0; cpu < nr_cpus; cpu++) {
763 if (bounces & BOUNCE_POLL) {
764 if (write(pipefd[cpu*2+1], &c, 1) != 1) {
765 fprintf(stderr, "pipefd write error\n");
768 if (pthread_join(uffd_threads[cpu],
769 (void *)&uffd_stats[cpu]))
772 if (pthread_cancel(uffd_threads[cpu]))
774 if (pthread_join(uffd_threads[cpu], NULL))
782 static int userfaultfd_open(int features)
784 struct uffdio_api uffdio_api;
786 uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
789 "userfaultfd syscall not available in this kernel\n");
792 uffd_flags = fcntl(uffd, F_GETFD, NULL);
794 uffdio_api.api = UFFD_API;
795 uffdio_api.features = features;
796 if (ioctl(uffd, UFFDIO_API, &uffdio_api)) {
797 fprintf(stderr, "UFFDIO_API failed.\nPlease make sure to "
798 "run with either root or ptrace capability.\n");
801 if (uffdio_api.api != UFFD_API) {
802 fprintf(stderr, "UFFDIO_API error: %" PRIu64 "\n",
803 (uint64_t)uffdio_api.api);
810 sigjmp_buf jbuf, *sigbuf;
812 static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
816 siglongjmp(*sigbuf, 1);
822 * For non-cooperative userfaultfd test we fork() a process that will
823 * generate pagefaults, will mremap the area monitored by the
824 * userfaultfd and at last this process will release the monitored
826 * For the anonymous and shared memory the area is divided into two
827 * parts, the first part is accessed before mremap, and the second
828 * part is accessed after mremap. Since hugetlbfs does not support
829 * mremap, the entire monitored area is accessed in a single pass for
831 * The release of the pages currently generates event for shmem and
832 * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
834 * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
835 * monitored area, generate pagefaults and test that signal is delivered.
836 * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
837 * test robustness use case - we release monitored area, fork a process
838 * that will generate pagefaults and verify signal is generated.
839 * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
840 * feature. Using monitor thread, verify no userfault events are generated.
842 static int faulting_process(int signal_test)
845 unsigned long long count;
846 unsigned long split_nr_pages;
847 unsigned long lastnr;
848 struct sigaction act;
849 unsigned long signalled = 0;
851 if (test_type != TEST_HUGETLB)
852 split_nr_pages = (nr_pages + 1) / 2;
854 split_nr_pages = nr_pages;
858 memset(&act, 0, sizeof(act));
859 act.sa_sigaction = sighndl;
860 act.sa_flags = SA_SIGINFO;
861 if (sigaction(SIGBUS, &act, 0)) {
865 lastnr = (unsigned long)-1;
868 for (nr = 0; nr < split_nr_pages; nr++) {
870 unsigned long offset = nr * page_size;
873 if (sigsetjmp(*sigbuf, 1) != 0) {
874 if (steps == 1 && nr == lastnr) {
875 fprintf(stderr, "Signal repeated\n");
880 if (signal_test == 1) {
882 /* This is a MISSING request */
884 if (copy_page(uffd, offset))
887 /* This is a WP request */
901 count = *area_count(area_dst, nr);
902 if (count != count_verify[nr]) {
904 "nr %lu memory corruption %Lu %Lu\n",
909 * Trigger write protection if there is by writing
910 * the same value back.
912 *area_count(area_dst, nr) = count;
916 return signalled != split_nr_pages;
918 if (test_type == TEST_HUGETLB)
921 area_dst = mremap(area_dst, nr_pages * page_size, nr_pages * page_size,
922 MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
923 if (area_dst == MAP_FAILED) {
928 for (; nr < nr_pages; nr++) {
929 count = *area_count(area_dst, nr);
930 if (count != count_verify[nr]) {
932 "nr %lu memory corruption %Lu %Lu\n",
934 count_verify[nr]); exit(1);
937 * Trigger write protection if there is by writing
938 * the same value back.
940 *area_count(area_dst, nr) = count;
943 if (uffd_test_ops->release_pages(area_dst))
946 for (nr = 0; nr < nr_pages; nr++) {
947 if (my_bcmp(area_dst + nr * page_size, zeropage, page_size)) {
948 fprintf(stderr, "nr %lu is not zero\n", nr);
956 static void retry_uffdio_zeropage(int ufd,
957 struct uffdio_zeropage *uffdio_zeropage,
958 unsigned long offset)
960 uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
961 uffdio_zeropage->range.len,
963 if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
964 if (uffdio_zeropage->zeropage != -EEXIST) {
965 uffd_error(uffdio_zeropage->zeropage,
966 "UFFDIO_ZEROPAGE retry error");
969 uffd_error(uffdio_zeropage->zeropage,
970 "UFFDIO_ZEROPAGE retry unexpected");
974 static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
976 struct uffdio_zeropage uffdio_zeropage;
978 unsigned long has_zeropage;
981 has_zeropage = uffd_test_ops->expected_ioctls & (1 << _UFFDIO_ZEROPAGE);
983 if (offset >= nr_pages * page_size) {
984 fprintf(stderr, "unexpected offset %lu\n", offset);
987 uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
988 uffdio_zeropage.range.len = page_size;
989 uffdio_zeropage.mode = 0;
990 ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
991 res = uffdio_zeropage.zeropage;
993 /* real retval in ufdio_zeropage.zeropage */
995 uffd_error(res, "UFFDIO_ZEROPAGE %s",
996 res == -EEXIST ? "-EEXIST" : "error");
997 } else if (res != -EINVAL)
998 uffd_error(res, "UFFDIO_ZEROPAGE not -EINVAL");
999 } else if (has_zeropage) {
1000 if (res != page_size) {
1001 uffd_error(res, "UFFDIO_ZEROPAGE unexpected");
1003 if (test_uffdio_zeropage_eexist && retry) {
1004 test_uffdio_zeropage_eexist = false;
1005 retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1011 uffd_error(res, "UFFDIO_ZEROPAGE succeeded");
1016 static int uffdio_zeropage(int ufd, unsigned long offset)
1018 return __uffdio_zeropage(ufd, offset, false);
1021 /* exercise UFFDIO_ZEROPAGE */
1022 static int userfaultfd_zeropage_test(void)
1024 struct uffdio_register uffdio_register;
1025 unsigned long expected_ioctls;
1027 printf("testing UFFDIO_ZEROPAGE: ");
1030 if (uffd_test_ops->release_pages(area_dst))
1033 if (userfaultfd_open(0))
1035 uffdio_register.range.start = (unsigned long) area_dst;
1036 uffdio_register.range.len = nr_pages * page_size;
1037 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1039 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1040 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1041 fprintf(stderr, "register failure\n");
1045 expected_ioctls = uffd_test_ops->expected_ioctls;
1046 if ((uffdio_register.ioctls & expected_ioctls) !=
1049 "unexpected missing ioctl for anon memory\n");
1053 if (uffdio_zeropage(uffd, 0)) {
1054 if (my_bcmp(area_dst, zeropage, page_size)) {
1055 fprintf(stderr, "zeropage is not zero\n");
1065 static int userfaultfd_events_test(void)
1067 struct uffdio_register uffdio_register;
1068 unsigned long expected_ioctls;
1073 struct uffd_stats stats = { 0 };
1075 printf("testing events (fork, remap, remove): ");
1078 if (uffd_test_ops->release_pages(area_dst))
1081 features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1082 UFFD_FEATURE_EVENT_REMOVE;
1083 if (userfaultfd_open(features))
1085 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1087 uffdio_register.range.start = (unsigned long) area_dst;
1088 uffdio_register.range.len = nr_pages * page_size;
1089 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1091 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1092 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1093 fprintf(stderr, "register failure\n");
1097 expected_ioctls = uffd_test_ops->expected_ioctls;
1098 if ((uffdio_register.ioctls & expected_ioctls) != expected_ioctls) {
1099 fprintf(stderr, "unexpected missing ioctl for anon memory\n");
1103 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats)) {
1104 perror("uffd_poll_thread create");
1115 return faulting_process(0);
1117 waitpid(pid, &err, 0);
1119 fprintf(stderr, "faulting process failed\n");
1123 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c)) {
1124 perror("pipe write");
1127 if (pthread_join(uffd_mon, NULL))
1132 uffd_stats_report(&stats, 1);
1134 return stats.missing_faults != nr_pages;
1137 static int userfaultfd_sig_test(void)
1139 struct uffdio_register uffdio_register;
1140 unsigned long expected_ioctls;
1141 unsigned long userfaults;
1146 struct uffd_stats stats = { 0 };
1148 printf("testing signal delivery: ");
1151 if (uffd_test_ops->release_pages(area_dst))
1154 features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1155 if (userfaultfd_open(features))
1157 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1159 uffdio_register.range.start = (unsigned long) area_dst;
1160 uffdio_register.range.len = nr_pages * page_size;
1161 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1163 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1164 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1165 fprintf(stderr, "register failure\n");
1169 expected_ioctls = uffd_test_ops->expected_ioctls;
1170 if ((uffdio_register.ioctls & expected_ioctls) != expected_ioctls) {
1171 fprintf(stderr, "unexpected missing ioctl for anon memory\n");
1175 if (faulting_process(1)) {
1176 fprintf(stderr, "faulting process failed\n");
1180 if (uffd_test_ops->release_pages(area_dst))
1183 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats)) {
1184 perror("uffd_poll_thread create");
1195 exit(faulting_process(2));
1197 waitpid(pid, &err, 0);
1199 fprintf(stderr, "faulting process failed\n");
1203 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c)) {
1204 perror("pipe write");
1207 if (pthread_join(uffd_mon, (void **)&userfaults))
1212 fprintf(stderr, "Signal test failed, userfaults: %ld\n",
1215 return userfaults != 0;
1218 static int userfaultfd_stress(void)
1223 struct uffdio_register uffdio_register;
1226 struct uffd_stats uffd_stats[nr_cpus];
1228 uffd_test_ops->allocate_area((void **)&area_src);
1231 uffd_test_ops->allocate_area((void **)&area_dst);
1235 if (userfaultfd_open(0))
1238 count_verify = malloc(nr_pages * sizeof(unsigned long long));
1239 if (!count_verify) {
1240 perror("count_verify");
1244 for (nr = 0; nr < nr_pages; nr++) {
1245 *area_mutex(area_src, nr) = (pthread_mutex_t)
1246 PTHREAD_MUTEX_INITIALIZER;
1247 count_verify[nr] = *area_count(area_src, nr) = 1;
1249 * In the transition between 255 to 256, powerpc will
1250 * read out of order in my_bcmp and see both bytes as
1251 * zero, so leave a placeholder below always non-zero
1252 * after the count, to avoid my_bcmp to trigger false
1255 *(area_count(area_src, nr) + 1) = 1;
1258 pipefd = malloc(sizeof(int) * nr_cpus * 2);
1263 for (cpu = 0; cpu < nr_cpus; cpu++) {
1264 if (pipe2(&pipefd[cpu*2], O_CLOEXEC | O_NONBLOCK)) {
1270 if (posix_memalign(&area, page_size, page_size)) {
1271 fprintf(stderr, "out of memory\n");
1275 bzero(zeropage, page_size);
1277 pthread_mutex_lock(&uffd_read_mutex);
1279 pthread_attr_init(&attr);
1280 pthread_attr_setstacksize(&attr, 16*1024*1024);
1284 unsigned long expected_ioctls;
1286 printf("bounces: %d, mode:", bounces);
1287 if (bounces & BOUNCE_RANDOM)
1289 if (bounces & BOUNCE_RACINGFAULTS)
1291 if (bounces & BOUNCE_VERIFY)
1293 if (bounces & BOUNCE_POLL)
1300 if (bounces & BOUNCE_POLL)
1301 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1303 fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1306 uffdio_register.range.start = (unsigned long) area_dst;
1307 uffdio_register.range.len = nr_pages * page_size;
1308 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1310 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1311 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1312 fprintf(stderr, "register failure\n");
1315 expected_ioctls = uffd_test_ops->expected_ioctls;
1316 if ((uffdio_register.ioctls & expected_ioctls) !=
1319 "unexpected missing ioctl for anon memory\n");
1323 if (area_dst_alias) {
1324 uffdio_register.range.start = (unsigned long)
1326 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1327 fprintf(stderr, "register failure alias\n");
1333 * The madvise done previously isn't enough: some
1334 * uffd_thread could have read userfaults (one of
1335 * those already resolved by the background thread)
1336 * and it may be in the process of calling
1337 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1338 * area_src and it would map a zero page in it (of
1339 * course such a UFFDIO_COPY is perfectly safe as it'd
1340 * return -EEXIST). The problem comes at the next
1341 * bounce though: that racing UFFDIO_COPY would
1342 * generate zeropages in the area_src, so invalidating
1343 * the previous MADV_DONTNEED. Without this additional
1344 * MADV_DONTNEED those zeropages leftovers in the
1345 * area_src would lead to -EEXIST failure during the
1346 * next bounce, effectively leaving a zeropage in the
1349 * Try to comment this out madvise to see the memory
1350 * corruption being caught pretty quick.
1352 * khugepaged is also inhibited to collapse THP after
1353 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1354 * required to MADV_DONTNEED here.
1356 if (uffd_test_ops->release_pages(area_dst))
1359 uffd_stats_reset(uffd_stats, nr_cpus);
1362 if (stress(uffd_stats))
1365 /* Clear all the write protections if there is any */
1367 wp_range(uffd, (unsigned long)area_dst,
1368 nr_pages * page_size, false);
1371 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range)) {
1372 fprintf(stderr, "unregister failure\n");
1375 if (area_dst_alias) {
1376 uffdio_register.range.start = (unsigned long) area_dst;
1377 if (ioctl(uffd, UFFDIO_UNREGISTER,
1378 &uffdio_register.range)) {
1379 fprintf(stderr, "unregister failure alias\n");
1385 if (bounces & BOUNCE_VERIFY) {
1386 for (nr = 0; nr < nr_pages; nr++) {
1387 if (*area_count(area_dst, nr) != count_verify[nr]) {
1389 "error area_count %Lu %Lu %lu\n",
1390 *area_count(area_src, nr),
1399 /* prepare next bounce */
1400 tmp_area = area_src;
1401 area_src = area_dst;
1402 area_dst = tmp_area;
1404 tmp_area = area_src_alias;
1405 area_src_alias = area_dst_alias;
1406 area_dst_alias = tmp_area;
1408 uffd_stats_report(uffd_stats, nr_cpus);
1415 return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1416 || userfaultfd_events_test();
1420 * Copied from mlock2-tests.c
1422 unsigned long default_huge_page_size(void)
1424 unsigned long hps = 0;
1427 FILE *f = fopen("/proc/meminfo", "r");
1431 while (getline(&line, &linelen, f) > 0) {
1432 if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) {
1443 static void set_test_type(const char *type)
1445 if (!strcmp(type, "anon")) {
1446 test_type = TEST_ANON;
1447 uffd_test_ops = &anon_uffd_test_ops;
1448 /* Only enable write-protect test for anonymous test */
1449 test_uffdio_wp = true;
1450 } else if (!strcmp(type, "hugetlb")) {
1451 test_type = TEST_HUGETLB;
1452 uffd_test_ops = &hugetlb_uffd_test_ops;
1453 } else if (!strcmp(type, "hugetlb_shared")) {
1455 test_type = TEST_HUGETLB;
1456 uffd_test_ops = &hugetlb_uffd_test_ops;
1457 } else if (!strcmp(type, "shmem")) {
1459 test_type = TEST_SHMEM;
1460 uffd_test_ops = &shmem_uffd_test_ops;
1462 fprintf(stderr, "Unknown test type: %s\n", type); exit(1);
1465 if (test_type == TEST_HUGETLB)
1466 page_size = default_huge_page_size();
1468 page_size = sysconf(_SC_PAGE_SIZE);
1471 fprintf(stderr, "Unable to determine page size\n");
1474 if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1476 fprintf(stderr, "Impossible to run this test\n");
1481 static void sigalrm(int sig)
1485 test_uffdio_copy_eexist = true;
1486 test_uffdio_zeropage_eexist = true;
1487 alarm(ALARM_INTERVAL_SECS);
1490 int main(int argc, char **argv)
1495 if (signal(SIGALRM, sigalrm) == SIG_ERR) {
1496 fprintf(stderr, "failed to arm SIGALRM");
1499 alarm(ALARM_INTERVAL_SECS);
1501 set_test_type(argv[1]);
1503 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1504 nr_pages_per_cpu = atol(argv[2]) * 1024*1024 / page_size /
1506 if (!nr_pages_per_cpu) {
1507 fprintf(stderr, "invalid MiB\n");
1511 bounces = atoi(argv[3]);
1513 fprintf(stderr, "invalid bounces\n");
1516 nr_pages = nr_pages_per_cpu * nr_cpus;
1518 if (test_type == TEST_HUGETLB) {
1521 huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1523 fprintf(stderr, "Open of %s failed", argv[3]);
1527 if (ftruncate(huge_fd, 0)) {
1528 fprintf(stderr, "ftruncate %s to size 0 failed", argv[3]);
1529 perror("ftruncate");
1533 printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1534 nr_pages, nr_pages_per_cpu);
1535 return userfaultfd_stress();
1538 #else /* __NR_userfaultfd */
1540 #warning "missing __NR_userfaultfd definition"
1544 printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1548 #endif /* __NR_userfaultfd */