Merge tag 'docs-6.1-2' of git://git.lwn.net/linux
[linux-block.git] / tools / testing / selftests / vm / userfaultfd.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Stress userfaultfd syscall.
4  *
5  *  Copyright (C) 2015  Red Hat, Inc.
6  *
7  * This test allocates two virtual areas and bounces the physical
8  * memory across the two virtual areas (from area_src to area_dst)
9  * using userfaultfd.
10  *
11  * There are three threads running per CPU:
12  *
13  * 1) one per-CPU thread takes a per-page pthread_mutex in a random
14  *    page of the area_dst (while the physical page may still be in
15  *    area_src), and increments a per-page counter in the same page,
16  *    and checks its value against a verification region.
17  *
18  * 2) another per-CPU thread handles the userfaults generated by
19  *    thread 1 above. userfaultfd blocking reads or poll() modes are
20  *    exercised interleaved.
21  *
22  * 3) one last per-CPU thread transfers the memory in the background
23  *    at maximum bandwidth (if not already transferred by thread
24  *    2). Each cpu thread takes cares of transferring a portion of the
25  *    area.
26  *
27  * When all threads of type 3 completed the transfer, one bounce is
28  * complete. area_src and area_dst are then swapped. All threads are
29  * respawned and so the bounce is immediately restarted in the
30  * opposite direction.
31  *
32  * per-CPU threads 1 by triggering userfaults inside
33  * pthread_mutex_lock will also verify the atomicity of the memory
34  * transfer (UFFDIO_COPY).
35  */
36
37 #define _GNU_SOURCE
38 #include <stdio.h>
39 #include <errno.h>
40 #include <unistd.h>
41 #include <stdlib.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45 #include <time.h>
46 #include <signal.h>
47 #include <poll.h>
48 #include <string.h>
49 #include <linux/mman.h>
50 #include <sys/mman.h>
51 #include <sys/syscall.h>
52 #include <sys/ioctl.h>
53 #include <sys/wait.h>
54 #include <pthread.h>
55 #include <linux/userfaultfd.h>
56 #include <setjmp.h>
57 #include <stdbool.h>
58 #include <assert.h>
59 #include <inttypes.h>
60 #include <stdint.h>
61 #include <sys/random.h>
62
63 #include "../kselftest.h"
64 #include "vm_util.h"
65
66 #ifdef __NR_userfaultfd
67
68 static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size, hpage_size;
69
70 #define BOUNCE_RANDOM           (1<<0)
71 #define BOUNCE_RACINGFAULTS     (1<<1)
72 #define BOUNCE_VERIFY           (1<<2)
73 #define BOUNCE_POLL             (1<<3)
74 static int bounces;
75
76 #define TEST_ANON       1
77 #define TEST_HUGETLB    2
78 #define TEST_SHMEM      3
79 static int test_type;
80
81 #define UFFD_FLAGS      (O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY)
82
83 #define BASE_PMD_ADDR ((void *)(1UL << 30))
84
85 /* test using /dev/userfaultfd, instead of userfaultfd(2) */
86 static bool test_dev_userfaultfd;
87
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
97 static bool map_shared;
98 static int shm_fd;
99 static int huge_fd;
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;
105 pthread_attr_t attr;
106 static bool test_collapse;
107
108 /* Userfaultfd test statistics */
109 struct uffd_stats {
110         int cpu;
111         unsigned long missing_faults;
112         unsigned long wp_faults;
113         unsigned long minor_faults;
114 };
115
116 /* pthread_mutex_t starts at page offset 0 */
117 #define area_mutex(___area, ___nr)                                      \
118         ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
119 /*
120  * count is placed in the page after pthread_mutex_t naturally aligned
121  * to avoid non alignment faults on non-x86 archs.
122  */
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) \
129                                                   -  1)))
130
131 #define swap(a, b) \
132         do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
133
134 #define factor_of_2(x) ((x) ^ ((x) & ((x) - 1)))
135
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";
150
151 static void usage(void)
152 {
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"
162                 "memory\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");
166
167         fprintf(stderr, "Examples:\n\n");
168         fprintf(stderr, "%s", examples);
169         exit(1);
170 }
171
172 #define _err(fmt, ...)                                          \
173         do {                                                    \
174                 int ret = errno;                                \
175                 fprintf(stderr, "ERROR: " fmt, ##__VA_ARGS__);  \
176                 fprintf(stderr, " (errno=%d, line=%d)\n",       \
177                         ret, __LINE__);                         \
178         } while (0)
179
180 #define errexit(exitcode, fmt, ...)             \
181         do {                                    \
182                 _err(fmt, ##__VA_ARGS__);       \
183                 exit(exitcode);                 \
184         } while (0)
185
186 #define err(fmt, ...) errexit(1, fmt, ##__VA_ARGS__)
187
188 static void uffd_stats_reset(struct uffd_stats *uffd_stats,
189                              unsigned long n_cpus)
190 {
191         int i;
192
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;
198         }
199 }
200
201 static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
202 {
203         int i;
204         unsigned long long miss_total = 0, wp_total = 0, minor_total = 0;
205
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;
210         }
211
212         printf("userfaults: ");
213         if (miss_total) {
214                 printf("%llu missing (", miss_total);
215                 for (i = 0; i < n_cpus; i++)
216                         printf("%lu+", stats[i].missing_faults);
217                 printf("\b) ");
218         }
219         if (wp_total) {
220                 printf("%llu wp (", wp_total);
221                 for (i = 0; i < n_cpus; i++)
222                         printf("%lu+", stats[i].wp_faults);
223                 printf("\b) ");
224         }
225         if (minor_total) {
226                 printf("%llu minor (", minor_total);
227                 for (i = 0; i < n_cpus; i++)
228                         printf("%lu+", stats[i].minor_faults);
229                 printf("\b)");
230         }
231         printf("\n");
232 }
233
234 static void anon_release_pages(char *rel_area)
235 {
236         if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
237                 err("madvise(MADV_DONTNEED) failed");
238 }
239
240 static void anon_allocate_area(void **alloc_area, bool is_src)
241 {
242         *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
243                            MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
244 }
245
246 static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
247 {
248 }
249
250 static void hugetlb_release_pages(char *rel_area)
251 {
252         if (!map_shared) {
253                 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
254                         err("madvise(MADV_DONTNEED) failed");
255         } else {
256                 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
257                         err("madvise(MADV_REMOVE) failed");
258         }
259 }
260
261 static void hugetlb_allocate_area(void **alloc_area, bool is_src)
262 {
263         void *area_alias = NULL;
264         char **alloc_area_alias;
265
266         if (!map_shared)
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),
272                         -1,
273                         0);
274         else
275                 *alloc_area = mmap(NULL,
276                         nr_pages * page_size,
277                         PROT_READ | PROT_WRITE,
278                         MAP_SHARED |
279                                 (is_src ? 0 : MAP_NORESERVE),
280                         huge_fd,
281                         is_src ? 0 : nr_pages * page_size);
282         if (*alloc_area == MAP_FAILED)
283                 err("mmap of hugetlbfs file failed");
284
285         if (map_shared) {
286                 area_alias = mmap(NULL,
287                         nr_pages * page_size,
288                         PROT_READ | PROT_WRITE,
289                         MAP_SHARED,
290                         huge_fd,
291                         is_src ? 0 : nr_pages * page_size);
292                 if (area_alias == MAP_FAILED)
293                         err("mmap of hugetlb file alias failed");
294         }
295
296         if (is_src) {
297                 alloc_area_alias = &area_src_alias;
298         } else {
299                 alloc_area_alias = &area_dst_alias;
300         }
301         if (area_alias)
302                 *alloc_area_alias = area_alias;
303 }
304
305 static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
306 {
307         if (!map_shared)
308                 return;
309
310         *start = (unsigned long) area_dst_alias + offset;
311 }
312
313 static void shmem_release_pages(char *rel_area)
314 {
315         if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
316                 err("madvise(MADV_REMOVE) failed");
317 }
318
319 static void shmem_allocate_area(void **alloc_area, bool is_src)
320 {
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;
325
326         if (test_collapse) {
327                 p = BASE_PMD_ADDR;
328                 if (!is_src)
329                         /* src map + alias + interleaved hpages */
330                         p += 2 * (bytes + hpage_size);
331                 p_alias = p;
332                 p_alias += bytes;
333                 p_alias += hpage_size;  /* Prevent src/dst VMA merge */
334         }
335
336         *alloc_area = mmap(p, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
337                            shm_fd, offset);
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);
342
343         area_alias = mmap(p_alias, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
344                           shm_fd, offset);
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);
349
350         if (is_src)
351                 area_src_alias = area_alias;
352         else
353                 area_dst_alias = area_alias;
354 }
355
356 static void shmem_alias_mapping(__u64 *start, size_t len, unsigned long offset)
357 {
358         *start = (unsigned long)area_dst_alias + offset;
359 }
360
361 static void shmem_check_pmd_mapping(void *p, int expect_nr_hpages)
362 {
363         if (!check_huge_shmem(area_dst_alias, expect_nr_hpages, hpage_size))
364                 err("Did not find expected %d number of hugepages",
365                     expect_nr_hpages);
366 }
367
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);
373 };
374
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,
380 };
381
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,
387 };
388
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,
394 };
395
396 static struct uffd_test_ops *uffd_test_ops;
397
398 static inline uint64_t uffd_minor_feature(void)
399 {
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;
404         else
405                 return 0;
406 }
407
408 static uint64_t get_expected_ioctls(uint64_t mode)
409 {
410         uint64_t ioctls = UFFD_API_RANGE_IOCTLS;
411
412         if (test_type == TEST_HUGETLB)
413                 ioctls &= ~(1 << _UFFDIO_ZEROPAGE);
414
415         if (!((mode & UFFDIO_REGISTER_MODE_WP) && test_uffdio_wp))
416                 ioctls &= ~(1 << _UFFDIO_WRITEPROTECT);
417
418         if (!((mode & UFFDIO_REGISTER_MODE_MINOR) && test_uffdio_minor))
419                 ioctls &= ~(1 << _UFFDIO_CONTINUE);
420
421         return ioctls;
422 }
423
424 static void assert_expected_ioctls_present(uint64_t mode, uint64_t ioctls)
425 {
426         uint64_t expected = get_expected_ioctls(mode);
427         uint64_t actual = ioctls & expected;
428
429         if (actual != expected) {
430                 err("missing ioctl(s): expected %"PRIx64" actual: %"PRIx64,
431                     expected, actual);
432         }
433 }
434
435 static int __userfaultfd_open_dev(void)
436 {
437         int fd, _uffd;
438
439         fd = open("/dev/userfaultfd", O_RDWR | O_CLOEXEC);
440         if (fd < 0)
441                 errexit(KSFT_SKIP, "opening /dev/userfaultfd failed");
442
443         _uffd = ioctl(fd, USERFAULTFD_IOC_NEW, UFFD_FLAGS);
444         if (_uffd < 0)
445                 errexit(errno == ENOTTY ? KSFT_SKIP : 1,
446                         "creating userfaultfd failed");
447         close(fd);
448         return _uffd;
449 }
450
451 static void userfaultfd_open(uint64_t *features)
452 {
453         struct uffdio_api uffdio_api;
454
455         if (test_dev_userfaultfd)
456                 uffd = __userfaultfd_open_dev();
457         else {
458                 uffd = syscall(__NR_userfaultfd, UFFD_FLAGS);
459                 if (uffd < 0)
460                         errexit(errno == ENOSYS ? KSFT_SKIP : 1,
461                                 "creating userfaultfd failed");
462         }
463         uffd_flags = fcntl(uffd, F_GETFD, NULL);
464
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);
472
473         *features = uffdio_api.features;
474 }
475
476 static inline void munmap_area(void **area)
477 {
478         if (*area)
479                 if (munmap(*area, nr_pages * page_size))
480                         err("munmap");
481
482         *area = NULL;
483 }
484
485 static void uffd_test_ctx_clear(void)
486 {
487         size_t i;
488
489         if (pipefd) {
490                 for (i = 0; i < nr_cpus * 2; ++i) {
491                         if (close(pipefd[i]))
492                                 err("close pipefd");
493                 }
494                 free(pipefd);
495                 pipefd = NULL;
496         }
497
498         if (count_verify) {
499                 free(count_verify);
500                 count_verify = NULL;
501         }
502
503         if (uffd != -1) {
504                 if (close(uffd))
505                         err("close uffd");
506                 uffd = -1;
507         }
508
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);
514 }
515
516 static void uffd_test_ctx_init(uint64_t features)
517 {
518         unsigned long nr, cpu;
519
520         uffd_test_ctx_clear();
521
522         uffd_test_ops->allocate_area((void **)&area_src, true);
523         uffd_test_ops->allocate_area((void **)&area_dst, false);
524
525         userfaultfd_open(&features);
526
527         count_verify = malloc(nr_pages * sizeof(unsigned long long));
528         if (!count_verify)
529                 err("count_verify");
530
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;
535                 /*
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
540                  * positives.
541                  */
542                 *(area_count(area_src, nr) + 1) = 1;
543         }
544
545         /*
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.
550          *
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.
558          *
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.
562          */
563         uffd_test_ops->release_pages(area_dst);
564
565         pipefd = malloc(sizeof(int) * nr_cpus * 2);
566         if (!pipefd)
567                 err("pipefd");
568         for (cpu = 0; cpu < nr_cpus; cpu++)
569                 if (pipe2(&pipefd[cpu * 2], O_CLOEXEC | O_NONBLOCK))
570                         err("pipe");
571 }
572
573 static int my_bcmp(char *str1, char *str2, size_t n)
574 {
575         unsigned long i;
576         for (i = 0; i < n; i++)
577                 if (str1[i] != str2[i])
578                         return 1;
579         return 0;
580 }
581
582 static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
583 {
584         struct uffdio_writeprotect prms;
585
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;
591
592         if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
593                 err("clear WP failed: address=0x%"PRIx64, (uint64_t)start);
594 }
595
596 static void continue_range(int ufd, __u64 start, __u64 len)
597 {
598         struct uffdio_continue req;
599         int ret;
600
601         req.range.start = start;
602         req.range.len = len;
603         req.mode = 0;
604
605         if (ioctl(ufd, UFFDIO_CONTINUE, &req))
606                 err("UFFDIO_CONTINUE failed for address 0x%" PRIx64,
607                     (uint64_t)start);
608
609         /*
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.
613          */
614         req.mapped = 0;
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);
619 }
620
621 static void *locking_thread(void *arg)
622 {
623         unsigned long cpu = (unsigned long) arg;
624         unsigned long page_nr;
625         unsigned long long count;
626
627         if (!(bounces & BOUNCE_RANDOM)) {
628                 page_nr = -bounces;
629                 if (!(bounces & BOUNCE_RACINGFAULTS))
630                         page_nr += cpu * nr_pages_per_cpu;
631         }
632
633         while (!finished) {
634                 if (bounces & BOUNCE_RANDOM) {
635                         if (getrandom(&page_nr, sizeof(page_nr), 0) != sizeof(page_nr))
636                                 err("getrandom failed");
637                 } else
638                         page_nr += 1;
639                 page_nr %= nr_pages;
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]);
645                 count++;
646                 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
647                 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
648         }
649
650         return NULL;
651 }
652
653 static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
654                             unsigned long offset)
655 {
656         uffd_test_ops->alias_mapping(&uffdio_copy->dst,
657                                      uffdio_copy->len,
658                                      offset);
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);
664         } else {
665                 err("UFFDIO_COPY retry unexpected: %"PRId64,
666                     (int64_t)uffdio_copy->copy);
667         }
668 }
669
670 static void wake_range(int ufd, unsigned long addr, unsigned long len)
671 {
672         struct uffdio_range uffdio_wake;
673
674         uffdio_wake.start = addr;
675         uffdio_wake.len = len;
676
677         if (ioctl(ufd, UFFDIO_WAKE, &uffdio_wake))
678                 fprintf(stderr, "error waking %lu\n",
679                         addr), exit(1);
680 }
681
682 static int __copy_page(int ufd, unsigned long offset, bool retry)
683 {
684         struct uffdio_copy uffdio_copy;
685
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;
691         if (test_uffdio_wp)
692                 uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
693         else
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);
704         } else {
705                 if (test_uffdio_copy_eexist && retry) {
706                         test_uffdio_copy_eexist = false;
707                         retry_copy_page(ufd, &uffdio_copy, offset);
708                 }
709                 return 1;
710         }
711         return 0;
712 }
713
714 static int copy_page_retry(int ufd, unsigned long offset)
715 {
716         return __copy_page(ufd, offset, true);
717 }
718
719 static int copy_page(int ufd, unsigned long offset)
720 {
721         return __copy_page(ufd, offset, false);
722 }
723
724 static int uffd_read_msg(int ufd, struct uffd_msg *msg)
725 {
726         int ret = read(uffd, msg, sizeof(*msg));
727
728         if (ret != sizeof(*msg)) {
729                 if (ret < 0) {
730                         if (errno == EAGAIN || errno == EINTR)
731                                 return 1;
732                         err("blocking read error");
733                 } else {
734                         err("short read");
735                 }
736         }
737
738         return 0;
739 }
740
741 static void uffd_handle_page_fault(struct uffd_msg *msg,
742                                    struct uffd_stats *stats)
743 {
744         unsigned long offset;
745
746         if (msg->event != UFFD_EVENT_PAGEFAULT)
747                 err("unexpected msg event %u", msg->event);
748
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);
752                 stats->wp_faults++;
753         } else if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_MINOR) {
754                 uint8_t *area;
755                 int b;
756
757                 /*
758                  * Minor page faults
759                  *
760                  * To prove we can modify the original range for testing
761                  * purposes, we're going to bit flip this range before
762                  * continuing.
763                  *
764                  * Note that this requires all minor page fault tests operate on
765                  * area_dst (non-UFFD-registered) and area_dst_alias
766                  * (UFFD-registered).
767                  */
768
769                 area = (uint8_t *)(area_dst +
770                                    ((char *)msg->arg.pagefault.address -
771                                     area_dst_alias));
772                 for (b = 0; b < page_size; ++b)
773                         area[b] = ~area[b];
774                 continue_range(uffd, msg->arg.pagefault.address, page_size);
775                 stats->minor_faults++;
776         } else {
777                 /* Missing page faults */
778                 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
779                         err("unexpected write fault");
780
781                 offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
782                 offset &= ~(page_size-1);
783
784                 if (copy_page(uffd, offset))
785                         stats->missing_faults++;
786         }
787 }
788
789 static void *uffd_poll_thread(void *arg)
790 {
791         struct uffd_stats *stats = (struct uffd_stats *)arg;
792         unsigned long cpu = stats->cpu;
793         struct pollfd pollfd[2];
794         struct uffd_msg msg;
795         struct uffdio_register uffd_reg;
796         int ret;
797         char tmp_chr;
798
799         pollfd[0].fd = uffd;
800         pollfd[0].events = POLLIN;
801         pollfd[1].fd = pipefd[cpu*2];
802         pollfd[1].events = POLLIN;
803
804         for (;;) {
805                 ret = poll(pollfd, 2, -1);
806                 if (ret <= 0) {
807                         if (errno == EINTR || errno == EAGAIN)
808                                 continue;
809                         err("poll error: %d", ret);
810                 }
811                 if (pollfd[1].revents & POLLIN) {
812                         if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
813                                 err("read pipefd error");
814                         break;
815                 }
816                 if (!(pollfd[0].revents & POLLIN))
817                         err("pollfd[0].revents %d", pollfd[0].revents);
818                 if (uffd_read_msg(uffd, &msg))
819                         continue;
820                 switch (msg.event) {
821                 default:
822                         err("unexpected msg event %u\n", msg.event);
823                         break;
824                 case UFFD_EVENT_PAGEFAULT:
825                         uffd_handle_page_fault(&msg, stats);
826                         break;
827                 case UFFD_EVENT_FORK:
828                         close(uffd);
829                         uffd = msg.arg.fork.ufd;
830                         pollfd[0].fd = uffd;
831                         break;
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");
838                         break;
839                 case UFFD_EVENT_REMAP:
840                         area_remap = area_dst;  /* save for later unmap */
841                         area_dst = (char *)(unsigned long)msg.arg.remap.to;
842                         break;
843                 }
844         }
845
846         return NULL;
847 }
848
849 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
850
851 static void *uffd_read_thread(void *arg)
852 {
853         struct uffd_stats *stats = (struct uffd_stats *)arg;
854         struct uffd_msg msg;
855
856         pthread_mutex_unlock(&uffd_read_mutex);
857         /* from here cancellation is ok */
858
859         for (;;) {
860                 if (uffd_read_msg(uffd, &msg))
861                         continue;
862                 uffd_handle_page_fault(&msg, stats);
863         }
864
865         return NULL;
866 }
867
868 static void *background_thread(void *arg)
869 {
870         unsigned long cpu = (unsigned long) arg;
871         unsigned long page_nr, start_nr, mid_nr, end_nr;
872
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;
876
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);
880
881         /*
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
885          */
886         if (test_uffdio_wp)
887                 wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
888                         nr_pages_per_cpu * page_size, true);
889
890         /*
891          * Continue the 2nd half of the page copying, handling write
892          * protection faults if any
893          */
894         for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
895                 copy_page_retry(uffd, page_nr * page_size);
896
897         return NULL;
898 }
899
900 static int stress(struct uffd_stats *uffd_stats)
901 {
902         unsigned long cpu;
903         pthread_t locking_threads[nr_cpus];
904         pthread_t uffd_threads[nr_cpus];
905         pthread_t background_threads[nr_cpus];
906
907         finished = 0;
908         for (cpu = 0; cpu < nr_cpus; cpu++) {
909                 if (pthread_create(&locking_threads[cpu], &attr,
910                                    locking_thread, (void *)cpu))
911                         return 1;
912                 if (bounces & BOUNCE_POLL) {
913                         if (pthread_create(&uffd_threads[cpu], &attr,
914                                            uffd_poll_thread,
915                                            (void *)&uffd_stats[cpu]))
916                                 return 1;
917                 } else {
918                         if (pthread_create(&uffd_threads[cpu], &attr,
919                                            uffd_read_thread,
920                                            (void *)&uffd_stats[cpu]))
921                                 return 1;
922                         pthread_mutex_lock(&uffd_read_mutex);
923                 }
924                 if (pthread_create(&background_threads[cpu], &attr,
925                                    background_thread, (void *)cpu))
926                         return 1;
927         }
928         for (cpu = 0; cpu < nr_cpus; cpu++)
929                 if (pthread_join(background_threads[cpu], NULL))
930                         return 1;
931
932         /*
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).
940          */
941         uffd_test_ops->release_pages(area_src);
942
943         finished = 1;
944         for (cpu = 0; cpu < nr_cpus; cpu++)
945                 if (pthread_join(locking_threads[cpu], NULL))
946                         return 1;
947
948         for (cpu = 0; cpu < nr_cpus; cpu++) {
949                 char c;
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]))
955                                 return 1;
956                 } else {
957                         if (pthread_cancel(uffd_threads[cpu]))
958                                 return 1;
959                         if (pthread_join(uffd_threads[cpu], NULL))
960                                 return 1;
961                 }
962         }
963
964         return 0;
965 }
966
967 sigjmp_buf jbuf, *sigbuf;
968
969 static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
970 {
971         if (sig == SIGBUS) {
972                 if (sigbuf)
973                         siglongjmp(*sigbuf, 1);
974                 abort();
975         }
976 }
977
978 /*
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
982  * area.
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
987  * HUGETLB_TEST.
988  * The release of the pages currently generates event for shmem and
989  * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
990  * for hugetlb.
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.
998  */
999 static int faulting_process(int signal_test)
1000 {
1001         unsigned long nr;
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;
1007
1008         split_nr_pages = (nr_pages + 1) / 2;
1009
1010         if (signal_test) {
1011                 sigbuf = &jbuf;
1012                 memset(&act, 0, sizeof(act));
1013                 act.sa_sigaction = sighndl;
1014                 act.sa_flags = SA_SIGINFO;
1015                 if (sigaction(SIGBUS, &act, 0))
1016                         err("sigaction");
1017                 lastnr = (unsigned long)-1;
1018         }
1019
1020         for (nr = 0; nr < split_nr_pages; nr++) {
1021                 volatile int steps = 1;
1022                 unsigned long offset = nr * page_size;
1023
1024                 if (signal_test) {
1025                         if (sigsetjmp(*sigbuf, 1) != 0) {
1026                                 if (steps == 1 && nr == lastnr)
1027                                         err("Signal repeated");
1028
1029                                 lastnr = nr;
1030                                 if (signal_test == 1) {
1031                                         if (steps == 1) {
1032                                                 /* This is a MISSING request */
1033                                                 steps++;
1034                                                 if (copy_page(uffd, offset))
1035                                                         signalled++;
1036                                         } else {
1037                                                 /* This is a WP request */
1038                                                 assert(steps == 2);
1039                                                 wp_range(uffd,
1040                                                          (__u64)area_dst +
1041                                                          offset,
1042                                                          page_size, false);
1043                                         }
1044                                 } else {
1045                                         signalled++;
1046                                         continue;
1047                                 }
1048                         }
1049                 }
1050
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]);
1055                 /*
1056                  * Trigger write protection if there is by writing
1057                  * the same value back.
1058                  */
1059                 *area_count(area_dst, nr) = count;
1060         }
1061
1062         if (signal_test)
1063                 return signalled != split_nr_pages;
1064
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)
1068                 err("mremap");
1069         /* Reset area_src since we just clobbered it */
1070         area_src = NULL;
1071
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]);
1077                 }
1078                 /*
1079                  * Trigger write protection if there is by writing
1080                  * the same value back.
1081                  */
1082                 *area_count(area_dst, nr) = count;
1083         }
1084
1085         uffd_test_ops->release_pages(area_dst);
1086
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);
1090
1091         return 0;
1092 }
1093
1094 static void retry_uffdio_zeropage(int ufd,
1095                                   struct uffdio_zeropage *uffdio_zeropage,
1096                                   unsigned long offset)
1097 {
1098         uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
1099                                      uffdio_zeropage->range.len,
1100                                      offset);
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);
1105         } else {
1106                 err("UFFDIO_ZEROPAGE error: %"PRId64,
1107                     (int64_t)uffdio_zeropage->zeropage);
1108         }
1109 }
1110
1111 static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
1112 {
1113         struct uffdio_zeropage uffdio_zeropage;
1114         int ret;
1115         bool has_zeropage = get_expected_ioctls(0) & (1 << _UFFDIO_ZEROPAGE);
1116         __s64 res;
1117
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;
1125         if (ret) {
1126                 /* real retval in ufdio_zeropage.zeropage */
1127                 if (has_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");
1134                 } else {
1135                         if (test_uffdio_zeropage_eexist && retry) {
1136                                 test_uffdio_zeropage_eexist = false;
1137                                 retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1138                                                       offset);
1139                         }
1140                         return 1;
1141                 }
1142         } else
1143                 err("UFFDIO_ZEROPAGE succeeded");
1144
1145         return 0;
1146 }
1147
1148 static int uffdio_zeropage(int ufd, unsigned long offset)
1149 {
1150         return __uffdio_zeropage(ufd, offset, false);
1151 }
1152
1153 /* exercise UFFDIO_ZEROPAGE */
1154 static int userfaultfd_zeropage_test(void)
1155 {
1156         struct uffdio_register uffdio_register;
1157
1158         printf("testing UFFDIO_ZEROPAGE: ");
1159         fflush(stdout);
1160
1161         uffd_test_ctx_init(0);
1162
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;
1166         if (test_uffdio_wp)
1167                 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1168         if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1169                 err("register failure");
1170
1171         assert_expected_ioctls_present(
1172                 uffdio_register.mode, uffdio_register.ioctls);
1173
1174         if (uffdio_zeropage(uffd, 0))
1175                 if (my_bcmp(area_dst, zeropage, page_size))
1176                         err("zeropage is not zero");
1177
1178         printf("done.\n");
1179         return 0;
1180 }
1181
1182 static int userfaultfd_events_test(void)
1183 {
1184         struct uffdio_register uffdio_register;
1185         pthread_t uffd_mon;
1186         int err, features;
1187         pid_t pid;
1188         char c;
1189         struct uffd_stats stats = { 0 };
1190
1191         printf("testing events (fork, remap, remove): ");
1192         fflush(stdout);
1193
1194         features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1195                 UFFD_FEATURE_EVENT_REMOVE;
1196         uffd_test_ctx_init(features);
1197
1198         fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1199
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;
1203         if (test_uffdio_wp)
1204                 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1205         if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1206                 err("register failure");
1207
1208         assert_expected_ioctls_present(
1209                 uffdio_register.mode, uffdio_register.ioctls);
1210
1211         if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1212                 err("uffd_poll_thread create");
1213
1214         pid = fork();
1215         if (pid < 0)
1216                 err("fork");
1217
1218         if (!pid)
1219                 exit(faulting_process(0));
1220
1221         waitpid(pid, &err, 0);
1222         if (err)
1223                 err("faulting process failed");
1224         if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1225                 err("pipe write");
1226         if (pthread_join(uffd_mon, NULL))
1227                 return 1;
1228
1229         uffd_stats_report(&stats, 1);
1230
1231         return stats.missing_faults != nr_pages;
1232 }
1233
1234 static int userfaultfd_sig_test(void)
1235 {
1236         struct uffdio_register uffdio_register;
1237         unsigned long userfaults;
1238         pthread_t uffd_mon;
1239         int err, features;
1240         pid_t pid;
1241         char c;
1242         struct uffd_stats stats = { 0 };
1243
1244         printf("testing signal delivery: ");
1245         fflush(stdout);
1246
1247         features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1248         uffd_test_ctx_init(features);
1249
1250         fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1251
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;
1255         if (test_uffdio_wp)
1256                 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1257         if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1258                 err("register failure");
1259
1260         assert_expected_ioctls_present(
1261                 uffdio_register.mode, uffdio_register.ioctls);
1262
1263         if (faulting_process(1))
1264                 err("faulting process failed");
1265
1266         uffd_test_ops->release_pages(area_dst);
1267
1268         if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1269                 err("uffd_poll_thread create");
1270
1271         pid = fork();
1272         if (pid < 0)
1273                 err("fork");
1274
1275         if (!pid)
1276                 exit(faulting_process(2));
1277
1278         waitpid(pid, &err, 0);
1279         if (err)
1280                 err("faulting process failed");
1281         if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1282                 err("pipe write");
1283         if (pthread_join(uffd_mon, (void **)&userfaults))
1284                 return 1;
1285
1286         printf("done.\n");
1287         if (userfaults)
1288                 err("Signal test failed, userfaults: %ld", userfaults);
1289
1290         return userfaults != 0;
1291 }
1292
1293 void check_memory_contents(char *p)
1294 {
1295         unsigned long i;
1296         uint8_t expected_byte;
1297         void *expected_page;
1298
1299         if (posix_memalign(&expected_page, page_size, page_size))
1300                 err("out of memory");
1301
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");
1307         }
1308
1309         free(expected_page);
1310 }
1311
1312 static int userfaultfd_minor_test(void)
1313 {
1314         unsigned long p;
1315         struct uffdio_register uffdio_register;
1316         pthread_t uffd_mon;
1317         char c;
1318         struct uffd_stats stats = { 0 };
1319
1320         if (!test_uffdio_minor)
1321                 return 0;
1322
1323         printf("testing minor faults: ");
1324         fflush(stdout);
1325
1326         uffd_test_ctx_init(uffd_minor_feature());
1327
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");
1333
1334         assert_expected_ioctls_present(
1335                 uffdio_register.mode, uffdio_register.ioctls);
1336
1337         /*
1338          * After registering with UFFD, populate the non-UFFD-registered side of
1339          * the shared mapping. This should *not* trigger any UFFD minor faults.
1340          */
1341         for (p = 0; p < nr_pages; ++p) {
1342                 memset(area_dst + (p * page_size), p % ((uint8_t)-1),
1343                        page_size);
1344         }
1345
1346         if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1347                 err("uffd_poll_thread create");
1348
1349         /*
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.
1354          */
1355         check_memory_contents(area_dst_alias);
1356
1357         if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1358                 err("pipe write");
1359         if (pthread_join(uffd_mon, NULL))
1360                 return 1;
1361
1362         uffd_stats_report(&stats, 1);
1363
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,
1367                             MADV_COLLAPSE))
1368                         err("madvise(MADV_COLLAPSE)");
1369
1370                 uffd_test_ops->check_pmd_mapping(area_dst,
1371                                                  nr_pages * page_size /
1372                                                  hpage_size);
1373                 /*
1374                  * This won't cause uffd-fault - it purely just makes sure there
1375                  * was no corruption.
1376                  */
1377                 check_memory_contents(area_dst_alias);
1378                 printf(" done.\n");
1379         }
1380
1381         return stats.missing_faults != 0 || stats.minor_faults != nr_pages;
1382 }
1383
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)
1391
1392 static int pagemap_open(void)
1393 {
1394         int fd = open("/proc/self/pagemap", O_RDONLY);
1395
1396         if (fd < 0)
1397                 err("open pagemap");
1398
1399         return fd;
1400 }
1401
1402 static uint64_t pagemap_read_vaddr(int fd, void *vaddr)
1403 {
1404         uint64_t value;
1405         int ret;
1406
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");
1411
1412         return value;
1413 }
1414
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); \
1419         } while (0)
1420
1421 static int pagemap_test_fork(bool present)
1422 {
1423         pid_t child = fork();
1424         uint64_t value;
1425         int fd, result;
1426
1427         if (!child) {
1428                 /* Open the pagemap fd of the child itself */
1429                 fd = pagemap_open();
1430                 value = pagemap_read_vaddr(fd, area_dst);
1431                 /*
1432                  * After fork() uffd-wp bit should be gone as long as we're
1433                  * without UFFD_FEATURE_EVENT_FORK
1434                  */
1435                 pagemap_check_wp(value, false);
1436                 /* Succeed */
1437                 exit(0);
1438         }
1439         waitpid(child, &result, 0);
1440         return result;
1441 }
1442
1443 static void userfaultfd_pagemap_test(unsigned int test_pgsize)
1444 {
1445         struct uffdio_register uffdio_register;
1446         int pagemap_fd;
1447         uint64_t value;
1448
1449         /* Pagemap tests uffd-wp only */
1450         if (!test_uffdio_wp)
1451                 return;
1452
1453         /* Not enough memory to test this page size */
1454         if (test_pgsize > nr_pages * page_size)
1455                 return;
1456
1457         printf("testing uffd-wp with pagemap (pgsize=%u): ", test_pgsize);
1458         /* Flush so it doesn't flush twice in parent/child later */
1459         fflush(stdout);
1460
1461         uffd_test_ctx_init(0);
1462
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");
1471         }
1472
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");
1478
1479         pagemap_fd = pagemap_open();
1480
1481         /* Touch the page */
1482         *area_dst = 1;
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");
1489
1490         /* Exclusive required or PAGEOUT won't work */
1491         if (!(value & PM_MMAP_EXCLUSIVE))
1492                 err("multiple mapping detected: 0x%"PRIx64, value);
1493
1494         if (madvise(area_dst, test_pgsize, MADV_PAGEOUT))
1495                 err("madvise(MADV_PAGEOUT) failed");
1496
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");
1503
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);
1508
1509         /* Fault in the page from disk */
1510         *area_dst = 2;
1511         value = pagemap_read_vaddr(pagemap_fd, area_dst);
1512         pagemap_check_wp(value, false);
1513
1514         close(pagemap_fd);
1515         printf("done\n");
1516 }
1517
1518 static int userfaultfd_stress(void)
1519 {
1520         void *area;
1521         unsigned long nr;
1522         struct uffdio_register uffdio_register;
1523         struct uffd_stats uffd_stats[nr_cpus];
1524
1525         uffd_test_ctx_init(0);
1526
1527         if (posix_memalign(&area, page_size, page_size))
1528                 err("out of memory");
1529         zeropage = area;
1530         bzero(zeropage, page_size);
1531
1532         pthread_mutex_lock(&uffd_read_mutex);
1533
1534         pthread_attr_init(&attr);
1535         pthread_attr_setstacksize(&attr, 16*1024*1024);
1536
1537         while (bounces--) {
1538                 printf("bounces: %d, mode:", bounces);
1539                 if (bounces & BOUNCE_RANDOM)
1540                         printf(" rnd");
1541                 if (bounces & BOUNCE_RACINGFAULTS)
1542                         printf(" racing");
1543                 if (bounces & BOUNCE_VERIFY)
1544                         printf(" ver");
1545                 if (bounces & BOUNCE_POLL)
1546                         printf(" poll");
1547                 else
1548                         printf(" read");
1549                 printf(", ");
1550                 fflush(stdout);
1551
1552                 if (bounces & BOUNCE_POLL)
1553                         fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1554                 else
1555                         fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1556
1557                 /* register */
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;
1561                 if (test_uffdio_wp)
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);
1567
1568                 if (area_dst_alias) {
1569                         uffdio_register.range.start = (unsigned long)
1570                                 area_dst_alias;
1571                         if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1572                                 err("register failure alias");
1573                 }
1574
1575                 /*
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
1590                  * area_dst.
1591                  *
1592                  * Try to comment this out madvise to see the memory
1593                  * corruption being caught pretty quick.
1594                  *
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.
1598                  */
1599                 uffd_test_ops->release_pages(area_dst);
1600
1601                 uffd_stats_reset(uffd_stats, nr_cpus);
1602
1603                 /* bounce pass */
1604                 if (stress(uffd_stats))
1605                         return 1;
1606
1607                 /* Clear all the write protections if there is any */
1608                 if (test_uffdio_wp)
1609                         wp_range(uffd, (unsigned long)area_dst,
1610                                  nr_pages * page_size, false);
1611
1612                 /* unregister */
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");
1620                 }
1621
1622                 /* verification */
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);
1629
1630                 /* prepare next bounce */
1631                 swap(area_src, area_dst);
1632
1633                 swap(area_src_alias, area_dst_alias);
1634
1635                 uffd_stats_report(uffd_stats, nr_cpus);
1636         }
1637
1638         if (test_type == TEST_ANON) {
1639                 /*
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.
1644                  */
1645                 userfaultfd_pagemap_test(page_size);
1646                 /*
1647                  * Hard-code for x86_64 for now for 2M THP, as x86_64 is
1648                  * currently the only one that supports uffd-wp
1649                  */
1650                 userfaultfd_pagemap_test(page_size * 512);
1651         }
1652
1653         return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1654                 || userfaultfd_events_test() || userfaultfd_minor_test();
1655 }
1656
1657 /*
1658  * Copied from mlock2-tests.c
1659  */
1660 unsigned long default_huge_page_size(void)
1661 {
1662         unsigned long hps = 0;
1663         char *line = NULL;
1664         size_t linelen = 0;
1665         FILE *f = fopen("/proc/meminfo", "r");
1666
1667         if (!f)
1668                 return 0;
1669         while (getline(&line, &linelen, f) > 0) {
1670                 if (sscanf(line, "Hugepagesize:       %lu kB", &hps) == 1) {
1671                         hps <<= 10;
1672                         break;
1673                 }
1674         }
1675
1676         free(line);
1677         fclose(f);
1678         return hps;
1679 }
1680
1681 static void set_test_type(const char *type)
1682 {
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")) {
1690                 map_shared = true;
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")) {
1696                 map_shared = true;
1697                 test_type = TEST_SHMEM;
1698                 uffd_test_ops = &shmem_uffd_test_ops;
1699                 test_uffdio_minor = true;
1700         }
1701 }
1702
1703 static void parse_test_type_arg(const char *raw_type)
1704 {
1705         char *buf = strdup(raw_type);
1706         uint64_t features = UFFD_API_FEATURES;
1707
1708         while (buf) {
1709                 const char *token = strsep(&buf, ":");
1710
1711                 if (!test_type)
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;
1719                 else
1720                         err("unrecognized test mod '%s'", token);
1721         }
1722
1723         if (!test_type)
1724                 err("failed to parse test type argument: '%s'", raw_type);
1725
1726         if (test_collapse && test_type != TEST_SHMEM)
1727                 err("Unsupported test: %s", raw_type);
1728
1729         if (test_type == TEST_HUGETLB)
1730                 page_size = hpage_size;
1731         else
1732                 page_size = sysconf(_SC_PAGE_SIZE);
1733
1734         if (!page_size)
1735                 err("Unable to determine page size");
1736         if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1737             > page_size)
1738                 err("Impossible to run this test");
1739
1740         /*
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
1743          * feature.
1744          */
1745
1746         userfaultfd_open(&features);
1747
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());
1752
1753         close(uffd);
1754         uffd = -1;
1755 }
1756
1757 static void sigalrm(int sig)
1758 {
1759         if (sig != SIGALRM)
1760                 abort();
1761         test_uffdio_copy_eexist = true;
1762         test_uffdio_zeropage_eexist = true;
1763         alarm(ALARM_INTERVAL_SECS);
1764 }
1765
1766 int main(int argc, char **argv)
1767 {
1768         size_t bytes;
1769
1770         if (argc < 4)
1771                 usage();
1772
1773         if (signal(SIGALRM, sigalrm) == SIG_ERR)
1774                 err("failed to arm SIGALRM");
1775         alarm(ALARM_INTERVAL_SECS);
1776
1777         hpage_size = default_huge_page_size();
1778         parse_test_type_arg(argv[1]);
1779         bytes = atol(argv[2]) * 1024 * 1024;
1780
1781         if (test_collapse && bytes & (hpage_size - 1))
1782                 err("MiB must be multiple of %lu if :collapse mod set",
1783                     hpage_size >> 20);
1784
1785         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1786
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
1791                  * hpage_size.
1792                  *
1793                  * This means that nr_cpus must divide (N * (2 << (H-P))
1794                  * where:
1795                  *      bytes = hpage_size * N
1796                  *      hpage_size = 2 << H
1797                  *      page_size = 2 << P
1798                  *
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).
1805                  */
1806                 int x = factor_of_2(nr_cpus);
1807                 int y = factor_of_2(bytes / page_size);
1808
1809                 nr_cpus = x < y ? x : y;
1810         }
1811         nr_pages_per_cpu = bytes / page_size / nr_cpus;
1812         if (!nr_pages_per_cpu) {
1813                 _err("invalid MiB");
1814                 usage();
1815         }
1816
1817         bounces = atoi(argv[3]);
1818         if (bounces <= 0) {
1819                 _err("invalid bounces");
1820                 usage();
1821         }
1822         nr_pages = nr_pages_per_cpu * nr_cpus;
1823
1824         if (test_type == TEST_HUGETLB && map_shared) {
1825                 if (argc < 5)
1826                         usage();
1827                 huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1828                 if (huge_fd < 0)
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);
1834                 if (shm_fd < 0)
1835                         err("memfd_create");
1836                 if (ftruncate(shm_fd, nr_pages * page_size * 2))
1837                         err("ftruncate");
1838                 if (fallocate(shm_fd,
1839                               FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
1840                               nr_pages * page_size * 2))
1841                         err("fallocate");
1842         }
1843         printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1844                nr_pages, nr_pages_per_cpu);
1845         return userfaultfd_stress();
1846 }
1847
1848 #else /* __NR_userfaultfd */
1849
1850 #warning "missing __NR_userfaultfd definition"
1851
1852 int main(void)
1853 {
1854         printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1855         return KSFT_SKIP;
1856 }
1857
1858 #endif /* __NR_userfaultfd */