Loading...
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
68static 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)
74static int bounces;
75
76#define TEST_ANON 1
77#define TEST_HUGETLB 2
78#define TEST_SHMEM 3
79static 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) */
86static bool test_dev_userfaultfd;
87
88/* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
89#define ALARM_INTERVAL_SECS 10
90static volatile bool test_uffdio_copy_eexist = true;
91static volatile bool test_uffdio_zeropage_eexist = true;
92/* Whether to test uffd write-protection */
93static bool test_uffdio_wp = true;
94/* Whether to test uffd minor faults */
95static bool test_uffdio_minor = false;
96static bool map_shared;
97static int mem_fd;
98static unsigned long long *count_verify;
99static int uffd = -1;
100static int uffd_flags, finished, *pipefd;
101static char *area_src, *area_src_alias, *area_dst, *area_dst_alias, *area_remap;
102static char *zeropage;
103pthread_attr_t attr;
104static bool test_collapse;
105
106/* Userfaultfd test statistics */
107struct uffd_stats {
108 int cpu;
109 unsigned long missing_faults;
110 unsigned long wp_faults;
111 unsigned long minor_faults;
112};
113
114/* pthread_mutex_t starts at page offset 0 */
115#define area_mutex(___area, ___nr) \
116 ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
117/*
118 * count is placed in the page after pthread_mutex_t naturally aligned
119 * to avoid non alignment faults on non-x86 archs.
120 */
121#define area_count(___area, ___nr) \
122 ((volatile unsigned long long *) ((unsigned long) \
123 ((___area) + (___nr)*page_size + \
124 sizeof(pthread_mutex_t) + \
125 sizeof(unsigned long long) - 1) & \
126 ~(unsigned long)(sizeof(unsigned long long) \
127 - 1)))
128
129#define swap(a, b) \
130 do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
131
132#define factor_of_2(x) ((x) ^ ((x) & ((x) - 1)))
133
134const char *examples =
135 "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
136 "./userfaultfd anon 100 99999\n\n"
137 "# Run the same anonymous memory test, but using /dev/userfaultfd:\n"
138 "./userfaultfd anon:dev 100 99999\n\n"
139 "# Run share memory test on 1GiB region with 99 bounces:\n"
140 "./userfaultfd shmem 1000 99\n\n"
141 "# Run hugetlb memory test on 256MiB region with 50 bounces:\n"
142 "./userfaultfd hugetlb 256 50\n\n"
143 "# Run the same hugetlb test but using shared file:\n"
144 "./userfaultfd hugetlb_shared 256 50\n\n"
145 "# 10MiB-~6GiB 999 bounces anonymous test, "
146 "continue forever unless an error triggers\n"
147 "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
148
149static void usage(void)
150{
151 fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
152 "[hugetlbfs_file]\n\n");
153 fprintf(stderr, "Supported <test type>: anon, hugetlb, "
154 "hugetlb_shared, shmem\n\n");
155 fprintf(stderr, "'Test mods' can be joined to the test type string with a ':'. "
156 "Supported mods:\n");
157 fprintf(stderr, "\tsyscall - Use userfaultfd(2) (default)\n");
158 fprintf(stderr, "\tdev - Use /dev/userfaultfd instead of userfaultfd(2)\n");
159 fprintf(stderr, "\tcollapse - Test MADV_COLLAPSE of UFFDIO_REGISTER_MODE_MINOR\n"
160 "memory\n");
161 fprintf(stderr, "\nExample test mod usage:\n");
162 fprintf(stderr, "# Run anonymous memory test with /dev/userfaultfd:\n");
163 fprintf(stderr, "./userfaultfd anon:dev 100 99999\n\n");
164
165 fprintf(stderr, "Examples:\n\n");
166 fprintf(stderr, "%s", examples);
167 exit(1);
168}
169
170#define _err(fmt, ...) \
171 do { \
172 int ret = errno; \
173 fprintf(stderr, "ERROR: " fmt, ##__VA_ARGS__); \
174 fprintf(stderr, " (errno=%d, line=%d)\n", \
175 ret, __LINE__); \
176 } while (0)
177
178#define errexit(exitcode, fmt, ...) \
179 do { \
180 _err(fmt, ##__VA_ARGS__); \
181 exit(exitcode); \
182 } while (0)
183
184#define err(fmt, ...) errexit(1, fmt, ##__VA_ARGS__)
185
186static void uffd_stats_reset(struct uffd_stats *uffd_stats,
187 unsigned long n_cpus)
188{
189 int i;
190
191 for (i = 0; i < n_cpus; i++) {
192 uffd_stats[i].cpu = i;
193 uffd_stats[i].missing_faults = 0;
194 uffd_stats[i].wp_faults = 0;
195 uffd_stats[i].minor_faults = 0;
196 }
197}
198
199static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
200{
201 int i;
202 unsigned long long miss_total = 0, wp_total = 0, minor_total = 0;
203
204 for (i = 0; i < n_cpus; i++) {
205 miss_total += stats[i].missing_faults;
206 wp_total += stats[i].wp_faults;
207 minor_total += stats[i].minor_faults;
208 }
209
210 printf("userfaults: ");
211 if (miss_total) {
212 printf("%llu missing (", miss_total);
213 for (i = 0; i < n_cpus; i++)
214 printf("%lu+", stats[i].missing_faults);
215 printf("\b) ");
216 }
217 if (wp_total) {
218 printf("%llu wp (", wp_total);
219 for (i = 0; i < n_cpus; i++)
220 printf("%lu+", stats[i].wp_faults);
221 printf("\b) ");
222 }
223 if (minor_total) {
224 printf("%llu minor (", minor_total);
225 for (i = 0; i < n_cpus; i++)
226 printf("%lu+", stats[i].minor_faults);
227 printf("\b)");
228 }
229 printf("\n");
230}
231
232static void anon_release_pages(char *rel_area)
233{
234 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
235 err("madvise(MADV_DONTNEED) failed");
236}
237
238static void anon_allocate_area(void **alloc_area, bool is_src)
239{
240 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
241 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
242}
243
244static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
245{
246}
247
248static void hugetlb_release_pages(char *rel_area)
249{
250 if (!map_shared) {
251 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED))
252 err("madvise(MADV_DONTNEED) failed");
253 } else {
254 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
255 err("madvise(MADV_REMOVE) failed");
256 }
257}
258
259static void hugetlb_allocate_area(void **alloc_area, bool is_src)
260{
261 off_t size = nr_pages * page_size;
262 off_t offset = is_src ? 0 : size;
263 void *area_alias = NULL;
264 char **alloc_area_alias;
265
266 *alloc_area = mmap(NULL, size, PROT_READ | PROT_WRITE,
267 (map_shared ? MAP_SHARED : MAP_PRIVATE) |
268 (is_src ? 0 : MAP_NORESERVE),
269 mem_fd, offset);
270 if (*alloc_area == MAP_FAILED)
271 err("mmap of hugetlbfs file failed");
272
273 if (map_shared) {
274 area_alias = mmap(NULL, size, PROT_READ | PROT_WRITE,
275 MAP_SHARED, mem_fd, offset);
276 if (area_alias == MAP_FAILED)
277 err("mmap of hugetlb file alias failed");
278 }
279
280 if (is_src) {
281 alloc_area_alias = &area_src_alias;
282 } else {
283 alloc_area_alias = &area_dst_alias;
284 }
285 if (area_alias)
286 *alloc_area_alias = area_alias;
287}
288
289static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
290{
291 if (!map_shared)
292 return;
293
294 *start = (unsigned long) area_dst_alias + offset;
295}
296
297static void shmem_release_pages(char *rel_area)
298{
299 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE))
300 err("madvise(MADV_REMOVE) failed");
301}
302
303static void shmem_allocate_area(void **alloc_area, bool is_src)
304{
305 void *area_alias = NULL;
306 size_t bytes = nr_pages * page_size;
307 unsigned long offset = is_src ? 0 : bytes;
308 char *p = NULL, *p_alias = NULL;
309
310 if (test_collapse) {
311 p = BASE_PMD_ADDR;
312 if (!is_src)
313 /* src map + alias + interleaved hpages */
314 p += 2 * (bytes + hpage_size);
315 p_alias = p;
316 p_alias += bytes;
317 p_alias += hpage_size; /* Prevent src/dst VMA merge */
318 }
319
320 *alloc_area = mmap(p, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
321 mem_fd, offset);
322 if (*alloc_area == MAP_FAILED)
323 err("mmap of memfd failed");
324 if (test_collapse && *alloc_area != p)
325 err("mmap of memfd failed at %p", p);
326
327 area_alias = mmap(p_alias, bytes, PROT_READ | PROT_WRITE, MAP_SHARED,
328 mem_fd, offset);
329 if (area_alias == MAP_FAILED)
330 err("mmap of memfd alias failed");
331 if (test_collapse && area_alias != p_alias)
332 err("mmap of anonymous memory failed at %p", p_alias);
333
334 if (is_src)
335 area_src_alias = area_alias;
336 else
337 area_dst_alias = area_alias;
338}
339
340static void shmem_alias_mapping(__u64 *start, size_t len, unsigned long offset)
341{
342 *start = (unsigned long)area_dst_alias + offset;
343}
344
345static void shmem_check_pmd_mapping(void *p, int expect_nr_hpages)
346{
347 if (!check_huge_shmem(area_dst_alias, expect_nr_hpages, hpage_size))
348 err("Did not find expected %d number of hugepages",
349 expect_nr_hpages);
350}
351
352struct uffd_test_ops {
353 void (*allocate_area)(void **alloc_area, bool is_src);
354 void (*release_pages)(char *rel_area);
355 void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
356 void (*check_pmd_mapping)(void *p, int expect_nr_hpages);
357};
358
359static struct uffd_test_ops anon_uffd_test_ops = {
360 .allocate_area = anon_allocate_area,
361 .release_pages = anon_release_pages,
362 .alias_mapping = noop_alias_mapping,
363 .check_pmd_mapping = NULL,
364};
365
366static struct uffd_test_ops shmem_uffd_test_ops = {
367 .allocate_area = shmem_allocate_area,
368 .release_pages = shmem_release_pages,
369 .alias_mapping = shmem_alias_mapping,
370 .check_pmd_mapping = shmem_check_pmd_mapping,
371};
372
373static struct uffd_test_ops hugetlb_uffd_test_ops = {
374 .allocate_area = hugetlb_allocate_area,
375 .release_pages = hugetlb_release_pages,
376 .alias_mapping = hugetlb_alias_mapping,
377 .check_pmd_mapping = NULL,
378};
379
380static struct uffd_test_ops *uffd_test_ops;
381
382static inline uint64_t uffd_minor_feature(void)
383{
384 if (test_type == TEST_HUGETLB && map_shared)
385 return UFFD_FEATURE_MINOR_HUGETLBFS;
386 else if (test_type == TEST_SHMEM)
387 return UFFD_FEATURE_MINOR_SHMEM;
388 else
389 return 0;
390}
391
392static uint64_t get_expected_ioctls(uint64_t mode)
393{
394 uint64_t ioctls = UFFD_API_RANGE_IOCTLS;
395
396 if (test_type == TEST_HUGETLB)
397 ioctls &= ~(1 << _UFFDIO_ZEROPAGE);
398
399 if (!((mode & UFFDIO_REGISTER_MODE_WP) && test_uffdio_wp))
400 ioctls &= ~(1 << _UFFDIO_WRITEPROTECT);
401
402 if (!((mode & UFFDIO_REGISTER_MODE_MINOR) && test_uffdio_minor))
403 ioctls &= ~(1 << _UFFDIO_CONTINUE);
404
405 return ioctls;
406}
407
408static void assert_expected_ioctls_present(uint64_t mode, uint64_t ioctls)
409{
410 uint64_t expected = get_expected_ioctls(mode);
411 uint64_t actual = ioctls & expected;
412
413 if (actual != expected) {
414 err("missing ioctl(s): expected %"PRIx64" actual: %"PRIx64,
415 expected, actual);
416 }
417}
418
419static int __userfaultfd_open_dev(void)
420{
421 int fd, _uffd;
422
423 fd = open("/dev/userfaultfd", O_RDWR | O_CLOEXEC);
424 if (fd < 0)
425 errexit(KSFT_SKIP, "opening /dev/userfaultfd failed");
426
427 _uffd = ioctl(fd, USERFAULTFD_IOC_NEW, UFFD_FLAGS);
428 if (_uffd < 0)
429 errexit(errno == ENOTTY ? KSFT_SKIP : 1,
430 "creating userfaultfd failed");
431 close(fd);
432 return _uffd;
433}
434
435static void userfaultfd_open(uint64_t *features)
436{
437 struct uffdio_api uffdio_api;
438
439 if (test_dev_userfaultfd)
440 uffd = __userfaultfd_open_dev();
441 else {
442 uffd = syscall(__NR_userfaultfd, UFFD_FLAGS);
443 if (uffd < 0)
444 errexit(errno == ENOSYS ? KSFT_SKIP : 1,
445 "creating userfaultfd failed");
446 }
447 uffd_flags = fcntl(uffd, F_GETFD, NULL);
448
449 uffdio_api.api = UFFD_API;
450 uffdio_api.features = *features;
451 if (ioctl(uffd, UFFDIO_API, &uffdio_api))
452 err("UFFDIO_API failed.\nPlease make sure to "
453 "run with either root or ptrace capability.");
454 if (uffdio_api.api != UFFD_API)
455 err("UFFDIO_API error: %" PRIu64, (uint64_t)uffdio_api.api);
456
457 *features = uffdio_api.features;
458}
459
460static inline void munmap_area(void **area)
461{
462 if (*area)
463 if (munmap(*area, nr_pages * page_size))
464 err("munmap");
465
466 *area = NULL;
467}
468
469static void uffd_test_ctx_clear(void)
470{
471 size_t i;
472
473 if (pipefd) {
474 for (i = 0; i < nr_cpus * 2; ++i) {
475 if (close(pipefd[i]))
476 err("close pipefd");
477 }
478 free(pipefd);
479 pipefd = NULL;
480 }
481
482 if (count_verify) {
483 free(count_verify);
484 count_verify = NULL;
485 }
486
487 if (uffd != -1) {
488 if (close(uffd))
489 err("close uffd");
490 uffd = -1;
491 }
492
493 munmap_area((void **)&area_src);
494 munmap_area((void **)&area_src_alias);
495 munmap_area((void **)&area_dst);
496 munmap_area((void **)&area_dst_alias);
497 munmap_area((void **)&area_remap);
498}
499
500static void uffd_test_ctx_init(uint64_t features)
501{
502 unsigned long nr, cpu;
503
504 uffd_test_ctx_clear();
505
506 uffd_test_ops->allocate_area((void **)&area_src, true);
507 uffd_test_ops->allocate_area((void **)&area_dst, false);
508
509 userfaultfd_open(&features);
510
511 count_verify = malloc(nr_pages * sizeof(unsigned long long));
512 if (!count_verify)
513 err("count_verify");
514
515 for (nr = 0; nr < nr_pages; nr++) {
516 *area_mutex(area_src, nr) =
517 (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
518 count_verify[nr] = *area_count(area_src, nr) = 1;
519 /*
520 * In the transition between 255 to 256, powerpc will
521 * read out of order in my_bcmp and see both bytes as
522 * zero, so leave a placeholder below always non-zero
523 * after the count, to avoid my_bcmp to trigger false
524 * positives.
525 */
526 *(area_count(area_src, nr) + 1) = 1;
527 }
528
529 /*
530 * After initialization of area_src, we must explicitly release pages
531 * for area_dst to make sure it's fully empty. Otherwise we could have
532 * some area_dst pages be errornously initialized with zero pages,
533 * hence we could hit memory corruption later in the test.
534 *
535 * One example is when THP is globally enabled, above allocate_area()
536 * calls could have the two areas merged into a single VMA (as they
537 * will have the same VMA flags so they're mergeable). When we
538 * initialize the area_src above, it's possible that some part of
539 * area_dst could have been faulted in via one huge THP that will be
540 * shared between area_src and area_dst. It could cause some of the
541 * area_dst won't be trapped by missing userfaults.
542 *
543 * This release_pages() will guarantee even if that happened, we'll
544 * proactively split the thp and drop any accidentally initialized
545 * pages within area_dst.
546 */
547 uffd_test_ops->release_pages(area_dst);
548
549 pipefd = malloc(sizeof(int) * nr_cpus * 2);
550 if (!pipefd)
551 err("pipefd");
552 for (cpu = 0; cpu < nr_cpus; cpu++)
553 if (pipe2(&pipefd[cpu * 2], O_CLOEXEC | O_NONBLOCK))
554 err("pipe");
555}
556
557static int my_bcmp(char *str1, char *str2, size_t n)
558{
559 unsigned long i;
560 for (i = 0; i < n; i++)
561 if (str1[i] != str2[i])
562 return 1;
563 return 0;
564}
565
566static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
567{
568 struct uffdio_writeprotect prms;
569
570 /* Write protection page faults */
571 prms.range.start = start;
572 prms.range.len = len;
573 /* Undo write-protect, do wakeup after that */
574 prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
575
576 if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
577 err("clear WP failed: address=0x%"PRIx64, (uint64_t)start);
578}
579
580static void continue_range(int ufd, __u64 start, __u64 len)
581{
582 struct uffdio_continue req;
583 int ret;
584
585 req.range.start = start;
586 req.range.len = len;
587 req.mode = 0;
588
589 if (ioctl(ufd, UFFDIO_CONTINUE, &req))
590 err("UFFDIO_CONTINUE failed for address 0x%" PRIx64,
591 (uint64_t)start);
592
593 /*
594 * Error handling within the kernel for continue is subtly different
595 * from copy or zeropage, so it may be a source of bugs. Trigger an
596 * error (-EEXIST) on purpose, to verify doing so doesn't cause a BUG.
597 */
598 req.mapped = 0;
599 ret = ioctl(ufd, UFFDIO_CONTINUE, &req);
600 if (ret >= 0 || req.mapped != -EEXIST)
601 err("failed to exercise UFFDIO_CONTINUE error handling, ret=%d, mapped=%" PRId64,
602 ret, (int64_t) req.mapped);
603}
604
605static void *locking_thread(void *arg)
606{
607 unsigned long cpu = (unsigned long) arg;
608 unsigned long page_nr;
609 unsigned long long count;
610
611 if (!(bounces & BOUNCE_RANDOM)) {
612 page_nr = -bounces;
613 if (!(bounces & BOUNCE_RACINGFAULTS))
614 page_nr += cpu * nr_pages_per_cpu;
615 }
616
617 while (!finished) {
618 if (bounces & BOUNCE_RANDOM) {
619 if (getrandom(&page_nr, sizeof(page_nr), 0) != sizeof(page_nr))
620 err("getrandom failed");
621 } else
622 page_nr += 1;
623 page_nr %= nr_pages;
624 pthread_mutex_lock(area_mutex(area_dst, page_nr));
625 count = *area_count(area_dst, page_nr);
626 if (count != count_verify[page_nr])
627 err("page_nr %lu memory corruption %llu %llu",
628 page_nr, count, count_verify[page_nr]);
629 count++;
630 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
631 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
632 }
633
634 return NULL;
635}
636
637static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
638 unsigned long offset)
639{
640 uffd_test_ops->alias_mapping(&uffdio_copy->dst,
641 uffdio_copy->len,
642 offset);
643 if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
644 /* real retval in ufdio_copy.copy */
645 if (uffdio_copy->copy != -EEXIST)
646 err("UFFDIO_COPY retry error: %"PRId64,
647 (int64_t)uffdio_copy->copy);
648 } else {
649 err("UFFDIO_COPY retry unexpected: %"PRId64,
650 (int64_t)uffdio_copy->copy);
651 }
652}
653
654static void wake_range(int ufd, unsigned long addr, unsigned long len)
655{
656 struct uffdio_range uffdio_wake;
657
658 uffdio_wake.start = addr;
659 uffdio_wake.len = len;
660
661 if (ioctl(ufd, UFFDIO_WAKE, &uffdio_wake))
662 fprintf(stderr, "error waking %lu\n",
663 addr), exit(1);
664}
665
666static int __copy_page(int ufd, unsigned long offset, bool retry)
667{
668 struct uffdio_copy uffdio_copy;
669
670 if (offset >= nr_pages * page_size)
671 err("unexpected offset %lu\n", offset);
672 uffdio_copy.dst = (unsigned long) area_dst + offset;
673 uffdio_copy.src = (unsigned long) area_src + offset;
674 uffdio_copy.len = page_size;
675 if (test_uffdio_wp)
676 uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
677 else
678 uffdio_copy.mode = 0;
679 uffdio_copy.copy = 0;
680 if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
681 /* real retval in ufdio_copy.copy */
682 if (uffdio_copy.copy != -EEXIST)
683 err("UFFDIO_COPY error: %"PRId64,
684 (int64_t)uffdio_copy.copy);
685 wake_range(ufd, uffdio_copy.dst, page_size);
686 } else if (uffdio_copy.copy != page_size) {
687 err("UFFDIO_COPY error: %"PRId64, (int64_t)uffdio_copy.copy);
688 } else {
689 if (test_uffdio_copy_eexist && retry) {
690 test_uffdio_copy_eexist = false;
691 retry_copy_page(ufd, &uffdio_copy, offset);
692 }
693 return 1;
694 }
695 return 0;
696}
697
698static int copy_page_retry(int ufd, unsigned long offset)
699{
700 return __copy_page(ufd, offset, true);
701}
702
703static int copy_page(int ufd, unsigned long offset)
704{
705 return __copy_page(ufd, offset, false);
706}
707
708static int uffd_read_msg(int ufd, struct uffd_msg *msg)
709{
710 int ret = read(uffd, msg, sizeof(*msg));
711
712 if (ret != sizeof(*msg)) {
713 if (ret < 0) {
714 if (errno == EAGAIN || errno == EINTR)
715 return 1;
716 err("blocking read error");
717 } else {
718 err("short read");
719 }
720 }
721
722 return 0;
723}
724
725static void uffd_handle_page_fault(struct uffd_msg *msg,
726 struct uffd_stats *stats)
727{
728 unsigned long offset;
729
730 if (msg->event != UFFD_EVENT_PAGEFAULT)
731 err("unexpected msg event %u", msg->event);
732
733 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
734 /* Write protect page faults */
735 wp_range(uffd, msg->arg.pagefault.address, page_size, false);
736 stats->wp_faults++;
737 } else if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_MINOR) {
738 uint8_t *area;
739 int b;
740
741 /*
742 * Minor page faults
743 *
744 * To prove we can modify the original range for testing
745 * purposes, we're going to bit flip this range before
746 * continuing.
747 *
748 * Note that this requires all minor page fault tests operate on
749 * area_dst (non-UFFD-registered) and area_dst_alias
750 * (UFFD-registered).
751 */
752
753 area = (uint8_t *)(area_dst +
754 ((char *)msg->arg.pagefault.address -
755 area_dst_alias));
756 for (b = 0; b < page_size; ++b)
757 area[b] = ~area[b];
758 continue_range(uffd, msg->arg.pagefault.address, page_size);
759 stats->minor_faults++;
760 } else {
761 /*
762 * Missing page faults.
763 *
764 * Here we force a write check for each of the missing mode
765 * faults. It's guaranteed because the only threads that
766 * will trigger uffd faults are the locking threads, and
767 * their first instruction to touch the missing page will
768 * always be pthread_mutex_lock().
769 *
770 * Note that here we relied on an NPTL glibc impl detail to
771 * always read the lock type at the entry of the lock op
772 * (pthread_mutex_t.__data.__type, offset 0x10) before
773 * doing any locking operations to guarantee that. It's
774 * actually not good to rely on this impl detail because
775 * logically a pthread-compatible lib can implement the
776 * locks without types and we can fail when linking with
777 * them. However since we used to find bugs with this
778 * strict check we still keep it around. Hopefully this
779 * could be a good hint when it fails again. If one day
780 * it'll break on some other impl of glibc we'll revisit.
781 */
782 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
783 err("unexpected write fault");
784
785 offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
786 offset &= ~(page_size-1);
787
788 if (copy_page(uffd, offset))
789 stats->missing_faults++;
790 }
791}
792
793static void *uffd_poll_thread(void *arg)
794{
795 struct uffd_stats *stats = (struct uffd_stats *)arg;
796 unsigned long cpu = stats->cpu;
797 struct pollfd pollfd[2];
798 struct uffd_msg msg;
799 struct uffdio_register uffd_reg;
800 int ret;
801 char tmp_chr;
802
803 pollfd[0].fd = uffd;
804 pollfd[0].events = POLLIN;
805 pollfd[1].fd = pipefd[cpu*2];
806 pollfd[1].events = POLLIN;
807
808 for (;;) {
809 ret = poll(pollfd, 2, -1);
810 if (ret <= 0) {
811 if (errno == EINTR || errno == EAGAIN)
812 continue;
813 err("poll error: %d", ret);
814 }
815 if (pollfd[1].revents & POLLIN) {
816 if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
817 err("read pipefd error");
818 break;
819 }
820 if (!(pollfd[0].revents & POLLIN))
821 err("pollfd[0].revents %d", pollfd[0].revents);
822 if (uffd_read_msg(uffd, &msg))
823 continue;
824 switch (msg.event) {
825 default:
826 err("unexpected msg event %u\n", msg.event);
827 break;
828 case UFFD_EVENT_PAGEFAULT:
829 uffd_handle_page_fault(&msg, stats);
830 break;
831 case UFFD_EVENT_FORK:
832 close(uffd);
833 uffd = msg.arg.fork.ufd;
834 pollfd[0].fd = uffd;
835 break;
836 case UFFD_EVENT_REMOVE:
837 uffd_reg.range.start = msg.arg.remove.start;
838 uffd_reg.range.len = msg.arg.remove.end -
839 msg.arg.remove.start;
840 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
841 err("remove failure");
842 break;
843 case UFFD_EVENT_REMAP:
844 area_remap = area_dst; /* save for later unmap */
845 area_dst = (char *)(unsigned long)msg.arg.remap.to;
846 break;
847 }
848 }
849
850 return NULL;
851}
852
853pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
854
855static void *uffd_read_thread(void *arg)
856{
857 struct uffd_stats *stats = (struct uffd_stats *)arg;
858 struct uffd_msg msg;
859
860 pthread_mutex_unlock(&uffd_read_mutex);
861 /* from here cancellation is ok */
862
863 for (;;) {
864 if (uffd_read_msg(uffd, &msg))
865 continue;
866 uffd_handle_page_fault(&msg, stats);
867 }
868
869 return NULL;
870}
871
872static void *background_thread(void *arg)
873{
874 unsigned long cpu = (unsigned long) arg;
875 unsigned long page_nr, start_nr, mid_nr, end_nr;
876
877 start_nr = cpu * nr_pages_per_cpu;
878 end_nr = (cpu+1) * nr_pages_per_cpu;
879 mid_nr = (start_nr + end_nr) / 2;
880
881 /* Copy the first half of the pages */
882 for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
883 copy_page_retry(uffd, page_nr * page_size);
884
885 /*
886 * If we need to test uffd-wp, set it up now. Then we'll have
887 * at least the first half of the pages mapped already which
888 * can be write-protected for testing
889 */
890 if (test_uffdio_wp)
891 wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
892 nr_pages_per_cpu * page_size, true);
893
894 /*
895 * Continue the 2nd half of the page copying, handling write
896 * protection faults if any
897 */
898 for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
899 copy_page_retry(uffd, page_nr * page_size);
900
901 return NULL;
902}
903
904static int stress(struct uffd_stats *uffd_stats)
905{
906 unsigned long cpu;
907 pthread_t locking_threads[nr_cpus];
908 pthread_t uffd_threads[nr_cpus];
909 pthread_t background_threads[nr_cpus];
910
911 finished = 0;
912 for (cpu = 0; cpu < nr_cpus; cpu++) {
913 if (pthread_create(&locking_threads[cpu], &attr,
914 locking_thread, (void *)cpu))
915 return 1;
916 if (bounces & BOUNCE_POLL) {
917 if (pthread_create(&uffd_threads[cpu], &attr,
918 uffd_poll_thread,
919 (void *)&uffd_stats[cpu]))
920 return 1;
921 } else {
922 if (pthread_create(&uffd_threads[cpu], &attr,
923 uffd_read_thread,
924 (void *)&uffd_stats[cpu]))
925 return 1;
926 pthread_mutex_lock(&uffd_read_mutex);
927 }
928 if (pthread_create(&background_threads[cpu], &attr,
929 background_thread, (void *)cpu))
930 return 1;
931 }
932 for (cpu = 0; cpu < nr_cpus; cpu++)
933 if (pthread_join(background_threads[cpu], NULL))
934 return 1;
935
936 /*
937 * Be strict and immediately zap area_src, the whole area has
938 * been transferred already by the background treads. The
939 * area_src could then be faulted in a racy way by still
940 * running uffdio_threads reading zeropages after we zapped
941 * area_src (but they're guaranteed to get -EEXIST from
942 * UFFDIO_COPY without writing zero pages into area_dst
943 * because the background threads already completed).
944 */
945 uffd_test_ops->release_pages(area_src);
946
947 finished = 1;
948 for (cpu = 0; cpu < nr_cpus; cpu++)
949 if (pthread_join(locking_threads[cpu], NULL))
950 return 1;
951
952 for (cpu = 0; cpu < nr_cpus; cpu++) {
953 char c;
954 if (bounces & BOUNCE_POLL) {
955 if (write(pipefd[cpu*2+1], &c, 1) != 1)
956 err("pipefd write error");
957 if (pthread_join(uffd_threads[cpu],
958 (void *)&uffd_stats[cpu]))
959 return 1;
960 } else {
961 if (pthread_cancel(uffd_threads[cpu]))
962 return 1;
963 if (pthread_join(uffd_threads[cpu], NULL))
964 return 1;
965 }
966 }
967
968 return 0;
969}
970
971sigjmp_buf jbuf, *sigbuf;
972
973static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
974{
975 if (sig == SIGBUS) {
976 if (sigbuf)
977 siglongjmp(*sigbuf, 1);
978 abort();
979 }
980}
981
982/*
983 * For non-cooperative userfaultfd test we fork() a process that will
984 * generate pagefaults, will mremap the area monitored by the
985 * userfaultfd and at last this process will release the monitored
986 * area.
987 * For the anonymous and shared memory the area is divided into two
988 * parts, the first part is accessed before mremap, and the second
989 * part is accessed after mremap. Since hugetlbfs does not support
990 * mremap, the entire monitored area is accessed in a single pass for
991 * HUGETLB_TEST.
992 * The release of the pages currently generates event for shmem and
993 * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
994 * for hugetlb.
995 * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
996 * monitored area, generate pagefaults and test that signal is delivered.
997 * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
998 * test robustness use case - we release monitored area, fork a process
999 * that will generate pagefaults and verify signal is generated.
1000 * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
1001 * feature. Using monitor thread, verify no userfault events are generated.
1002 */
1003static int faulting_process(int signal_test)
1004{
1005 unsigned long nr;
1006 unsigned long long count;
1007 unsigned long split_nr_pages;
1008 unsigned long lastnr;
1009 struct sigaction act;
1010 volatile unsigned long signalled = 0;
1011
1012 split_nr_pages = (nr_pages + 1) / 2;
1013
1014 if (signal_test) {
1015 sigbuf = &jbuf;
1016 memset(&act, 0, sizeof(act));
1017 act.sa_sigaction = sighndl;
1018 act.sa_flags = SA_SIGINFO;
1019 if (sigaction(SIGBUS, &act, 0))
1020 err("sigaction");
1021 lastnr = (unsigned long)-1;
1022 }
1023
1024 for (nr = 0; nr < split_nr_pages; nr++) {
1025 volatile int steps = 1;
1026 unsigned long offset = nr * page_size;
1027
1028 if (signal_test) {
1029 if (sigsetjmp(*sigbuf, 1) != 0) {
1030 if (steps == 1 && nr == lastnr)
1031 err("Signal repeated");
1032
1033 lastnr = nr;
1034 if (signal_test == 1) {
1035 if (steps == 1) {
1036 /* This is a MISSING request */
1037 steps++;
1038 if (copy_page(uffd, offset))
1039 signalled++;
1040 } else {
1041 /* This is a WP request */
1042 assert(steps == 2);
1043 wp_range(uffd,
1044 (__u64)area_dst +
1045 offset,
1046 page_size, false);
1047 }
1048 } else {
1049 signalled++;
1050 continue;
1051 }
1052 }
1053 }
1054
1055 count = *area_count(area_dst, nr);
1056 if (count != count_verify[nr])
1057 err("nr %lu memory corruption %llu %llu\n",
1058 nr, count, count_verify[nr]);
1059 /*
1060 * Trigger write protection if there is by writing
1061 * the same value back.
1062 */
1063 *area_count(area_dst, nr) = count;
1064 }
1065
1066 if (signal_test)
1067 return signalled != split_nr_pages;
1068
1069 area_dst = mremap(area_dst, nr_pages * page_size, nr_pages * page_size,
1070 MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
1071 if (area_dst == MAP_FAILED)
1072 err("mremap");
1073 /* Reset area_src since we just clobbered it */
1074 area_src = NULL;
1075
1076 for (; nr < nr_pages; nr++) {
1077 count = *area_count(area_dst, nr);
1078 if (count != count_verify[nr]) {
1079 err("nr %lu memory corruption %llu %llu\n",
1080 nr, count, count_verify[nr]);
1081 }
1082 /*
1083 * Trigger write protection if there is by writing
1084 * the same value back.
1085 */
1086 *area_count(area_dst, nr) = count;
1087 }
1088
1089 uffd_test_ops->release_pages(area_dst);
1090
1091 for (nr = 0; nr < nr_pages; nr++)
1092 if (my_bcmp(area_dst + nr * page_size, zeropage, page_size))
1093 err("nr %lu is not zero", nr);
1094
1095 return 0;
1096}
1097
1098static void retry_uffdio_zeropage(int ufd,
1099 struct uffdio_zeropage *uffdio_zeropage,
1100 unsigned long offset)
1101{
1102 uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
1103 uffdio_zeropage->range.len,
1104 offset);
1105 if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
1106 if (uffdio_zeropage->zeropage != -EEXIST)
1107 err("UFFDIO_ZEROPAGE error: %"PRId64,
1108 (int64_t)uffdio_zeropage->zeropage);
1109 } else {
1110 err("UFFDIO_ZEROPAGE error: %"PRId64,
1111 (int64_t)uffdio_zeropage->zeropage);
1112 }
1113}
1114
1115static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
1116{
1117 struct uffdio_zeropage uffdio_zeropage;
1118 int ret;
1119 bool has_zeropage = get_expected_ioctls(0) & (1 << _UFFDIO_ZEROPAGE);
1120 __s64 res;
1121
1122 if (offset >= nr_pages * page_size)
1123 err("unexpected offset %lu", offset);
1124 uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
1125 uffdio_zeropage.range.len = page_size;
1126 uffdio_zeropage.mode = 0;
1127 ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
1128 res = uffdio_zeropage.zeropage;
1129 if (ret) {
1130 /* real retval in ufdio_zeropage.zeropage */
1131 if (has_zeropage)
1132 err("UFFDIO_ZEROPAGE error: %"PRId64, (int64_t)res);
1133 else if (res != -EINVAL)
1134 err("UFFDIO_ZEROPAGE not -EINVAL");
1135 } else if (has_zeropage) {
1136 if (res != page_size) {
1137 err("UFFDIO_ZEROPAGE unexpected size");
1138 } else {
1139 if (test_uffdio_zeropage_eexist && retry) {
1140 test_uffdio_zeropage_eexist = false;
1141 retry_uffdio_zeropage(ufd, &uffdio_zeropage,
1142 offset);
1143 }
1144 return 1;
1145 }
1146 } else
1147 err("UFFDIO_ZEROPAGE succeeded");
1148
1149 return 0;
1150}
1151
1152static int uffdio_zeropage(int ufd, unsigned long offset)
1153{
1154 return __uffdio_zeropage(ufd, offset, false);
1155}
1156
1157/* exercise UFFDIO_ZEROPAGE */
1158static int userfaultfd_zeropage_test(void)
1159{
1160 struct uffdio_register uffdio_register;
1161
1162 printf("testing UFFDIO_ZEROPAGE: ");
1163 fflush(stdout);
1164
1165 uffd_test_ctx_init(0);
1166
1167 uffdio_register.range.start = (unsigned long) area_dst;
1168 uffdio_register.range.len = nr_pages * page_size;
1169 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1170 if (test_uffdio_wp)
1171 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1172 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1173 err("register failure");
1174
1175 assert_expected_ioctls_present(
1176 uffdio_register.mode, uffdio_register.ioctls);
1177
1178 if (uffdio_zeropage(uffd, 0))
1179 if (my_bcmp(area_dst, zeropage, page_size))
1180 err("zeropage is not zero");
1181
1182 printf("done.\n");
1183 return 0;
1184}
1185
1186static int userfaultfd_events_test(void)
1187{
1188 struct uffdio_register uffdio_register;
1189 pthread_t uffd_mon;
1190 int err, features;
1191 pid_t pid;
1192 char c;
1193 struct uffd_stats stats = { 0 };
1194
1195 printf("testing events (fork, remap, remove): ");
1196 fflush(stdout);
1197
1198 features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1199 UFFD_FEATURE_EVENT_REMOVE;
1200 uffd_test_ctx_init(features);
1201
1202 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1203
1204 uffdio_register.range.start = (unsigned long) area_dst;
1205 uffdio_register.range.len = nr_pages * page_size;
1206 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1207 if (test_uffdio_wp)
1208 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1209 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1210 err("register failure");
1211
1212 assert_expected_ioctls_present(
1213 uffdio_register.mode, uffdio_register.ioctls);
1214
1215 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1216 err("uffd_poll_thread create");
1217
1218 pid = fork();
1219 if (pid < 0)
1220 err("fork");
1221
1222 if (!pid)
1223 exit(faulting_process(0));
1224
1225 waitpid(pid, &err, 0);
1226 if (err)
1227 err("faulting process failed");
1228 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1229 err("pipe write");
1230 if (pthread_join(uffd_mon, NULL))
1231 return 1;
1232
1233 uffd_stats_report(&stats, 1);
1234
1235 return stats.missing_faults != nr_pages;
1236}
1237
1238static int userfaultfd_sig_test(void)
1239{
1240 struct uffdio_register uffdio_register;
1241 unsigned long userfaults;
1242 pthread_t uffd_mon;
1243 int err, features;
1244 pid_t pid;
1245 char c;
1246 struct uffd_stats stats = { 0 };
1247
1248 printf("testing signal delivery: ");
1249 fflush(stdout);
1250
1251 features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1252 uffd_test_ctx_init(features);
1253
1254 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1255
1256 uffdio_register.range.start = (unsigned long) area_dst;
1257 uffdio_register.range.len = nr_pages * page_size;
1258 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1259 if (test_uffdio_wp)
1260 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1261 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1262 err("register failure");
1263
1264 assert_expected_ioctls_present(
1265 uffdio_register.mode, uffdio_register.ioctls);
1266
1267 if (faulting_process(1))
1268 err("faulting process failed");
1269
1270 uffd_test_ops->release_pages(area_dst);
1271
1272 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1273 err("uffd_poll_thread create");
1274
1275 pid = fork();
1276 if (pid < 0)
1277 err("fork");
1278
1279 if (!pid)
1280 exit(faulting_process(2));
1281
1282 waitpid(pid, &err, 0);
1283 if (err)
1284 err("faulting process failed");
1285 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1286 err("pipe write");
1287 if (pthread_join(uffd_mon, (void **)&userfaults))
1288 return 1;
1289
1290 printf("done.\n");
1291 if (userfaults)
1292 err("Signal test failed, userfaults: %ld", userfaults);
1293
1294 return userfaults != 0;
1295}
1296
1297void check_memory_contents(char *p)
1298{
1299 unsigned long i;
1300 uint8_t expected_byte;
1301 void *expected_page;
1302
1303 if (posix_memalign(&expected_page, page_size, page_size))
1304 err("out of memory");
1305
1306 for (i = 0; i < nr_pages; ++i) {
1307 expected_byte = ~((uint8_t)(i % ((uint8_t)-1)));
1308 memset(expected_page, expected_byte, page_size);
1309 if (my_bcmp(expected_page, p + (i * page_size), page_size))
1310 err("unexpected page contents after minor fault");
1311 }
1312
1313 free(expected_page);
1314}
1315
1316static int userfaultfd_minor_test(void)
1317{
1318 unsigned long p;
1319 struct uffdio_register uffdio_register;
1320 pthread_t uffd_mon;
1321 char c;
1322 struct uffd_stats stats = { 0 };
1323
1324 if (!test_uffdio_minor)
1325 return 0;
1326
1327 printf("testing minor faults: ");
1328 fflush(stdout);
1329
1330 uffd_test_ctx_init(uffd_minor_feature());
1331
1332 uffdio_register.range.start = (unsigned long)area_dst_alias;
1333 uffdio_register.range.len = nr_pages * page_size;
1334 uffdio_register.mode = UFFDIO_REGISTER_MODE_MINOR;
1335 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1336 err("register failure");
1337
1338 assert_expected_ioctls_present(
1339 uffdio_register.mode, uffdio_register.ioctls);
1340
1341 /*
1342 * After registering with UFFD, populate the non-UFFD-registered side of
1343 * the shared mapping. This should *not* trigger any UFFD minor faults.
1344 */
1345 for (p = 0; p < nr_pages; ++p) {
1346 memset(area_dst + (p * page_size), p % ((uint8_t)-1),
1347 page_size);
1348 }
1349
1350 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1351 err("uffd_poll_thread create");
1352
1353 /*
1354 * Read each of the pages back using the UFFD-registered mapping. We
1355 * expect that the first time we touch a page, it will result in a minor
1356 * fault. uffd_poll_thread will resolve the fault by bit-flipping the
1357 * page's contents, and then issuing a CONTINUE ioctl.
1358 */
1359 check_memory_contents(area_dst_alias);
1360
1361 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1362 err("pipe write");
1363 if (pthread_join(uffd_mon, NULL))
1364 return 1;
1365
1366 uffd_stats_report(&stats, 1);
1367
1368 if (test_collapse) {
1369 printf("testing collapse of uffd memory into PMD-mapped THPs:");
1370 if (madvise(area_dst_alias, nr_pages * page_size,
1371 MADV_COLLAPSE))
1372 err("madvise(MADV_COLLAPSE)");
1373
1374 uffd_test_ops->check_pmd_mapping(area_dst,
1375 nr_pages * page_size /
1376 hpage_size);
1377 /*
1378 * This won't cause uffd-fault - it purely just makes sure there
1379 * was no corruption.
1380 */
1381 check_memory_contents(area_dst_alias);
1382 printf(" done.\n");
1383 }
1384
1385 return stats.missing_faults != 0 || stats.minor_faults != nr_pages;
1386}
1387
1388#define BIT_ULL(nr) (1ULL << (nr))
1389#define PM_SOFT_DIRTY BIT_ULL(55)
1390#define PM_MMAP_EXCLUSIVE BIT_ULL(56)
1391#define PM_UFFD_WP BIT_ULL(57)
1392#define PM_FILE BIT_ULL(61)
1393#define PM_SWAP BIT_ULL(62)
1394#define PM_PRESENT BIT_ULL(63)
1395
1396static int pagemap_open(void)
1397{
1398 int fd = open("/proc/self/pagemap", O_RDONLY);
1399
1400 if (fd < 0)
1401 err("open pagemap");
1402
1403 return fd;
1404}
1405
1406static uint64_t pagemap_read_vaddr(int fd, void *vaddr)
1407{
1408 uint64_t value;
1409 int ret;
1410
1411 ret = pread(fd, &value, sizeof(uint64_t),
1412 ((uint64_t)vaddr >> 12) * sizeof(uint64_t));
1413 if (ret != sizeof(uint64_t))
1414 err("pread() on pagemap failed");
1415
1416 return value;
1417}
1418
1419/* This macro let __LINE__ works in err() */
1420#define pagemap_check_wp(value, wp) do { \
1421 if (!!(value & PM_UFFD_WP) != wp) \
1422 err("pagemap uffd-wp bit error: 0x%"PRIx64, value); \
1423 } while (0)
1424
1425static int pagemap_test_fork(bool present)
1426{
1427 pid_t child = fork();
1428 uint64_t value;
1429 int fd, result;
1430
1431 if (!child) {
1432 /* Open the pagemap fd of the child itself */
1433 fd = pagemap_open();
1434 value = pagemap_read_vaddr(fd, area_dst);
1435 /*
1436 * After fork() uffd-wp bit should be gone as long as we're
1437 * without UFFD_FEATURE_EVENT_FORK
1438 */
1439 pagemap_check_wp(value, false);
1440 /* Succeed */
1441 exit(0);
1442 }
1443 waitpid(child, &result, 0);
1444 return result;
1445}
1446
1447static void userfaultfd_pagemap_test(unsigned int test_pgsize)
1448{
1449 struct uffdio_register uffdio_register;
1450 int pagemap_fd;
1451 uint64_t value;
1452
1453 /* Pagemap tests uffd-wp only */
1454 if (!test_uffdio_wp)
1455 return;
1456
1457 /* Not enough memory to test this page size */
1458 if (test_pgsize > nr_pages * page_size)
1459 return;
1460
1461 printf("testing uffd-wp with pagemap (pgsize=%u): ", test_pgsize);
1462 /* Flush so it doesn't flush twice in parent/child later */
1463 fflush(stdout);
1464
1465 uffd_test_ctx_init(0);
1466
1467 if (test_pgsize > page_size) {
1468 /* This is a thp test */
1469 if (madvise(area_dst, nr_pages * page_size, MADV_HUGEPAGE))
1470 err("madvise(MADV_HUGEPAGE) failed");
1471 } else if (test_pgsize == page_size) {
1472 /* This is normal page test; force no thp */
1473 if (madvise(area_dst, nr_pages * page_size, MADV_NOHUGEPAGE))
1474 err("madvise(MADV_NOHUGEPAGE) failed");
1475 }
1476
1477 uffdio_register.range.start = (unsigned long) area_dst;
1478 uffdio_register.range.len = nr_pages * page_size;
1479 uffdio_register.mode = UFFDIO_REGISTER_MODE_WP;
1480 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1481 err("register failed");
1482
1483 pagemap_fd = pagemap_open();
1484
1485 /* Touch the page */
1486 *area_dst = 1;
1487 wp_range(uffd, (uint64_t)area_dst, test_pgsize, true);
1488 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1489 pagemap_check_wp(value, true);
1490 /* Make sure uffd-wp bit dropped when fork */
1491 if (pagemap_test_fork(true))
1492 err("Detected stall uffd-wp bit in child");
1493
1494 /* Exclusive required or PAGEOUT won't work */
1495 if (!(value & PM_MMAP_EXCLUSIVE))
1496 err("multiple mapping detected: 0x%"PRIx64, value);
1497
1498 if (madvise(area_dst, test_pgsize, MADV_PAGEOUT))
1499 err("madvise(MADV_PAGEOUT) failed");
1500
1501 /* Uffd-wp should persist even swapped out */
1502 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1503 pagemap_check_wp(value, true);
1504 /* Make sure uffd-wp bit dropped when fork */
1505 if (pagemap_test_fork(false))
1506 err("Detected stall uffd-wp bit in child");
1507
1508 /* Unprotect; this tests swap pte modifications */
1509 wp_range(uffd, (uint64_t)area_dst, page_size, false);
1510 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1511 pagemap_check_wp(value, false);
1512
1513 /* Fault in the page from disk */
1514 *area_dst = 2;
1515 value = pagemap_read_vaddr(pagemap_fd, area_dst);
1516 pagemap_check_wp(value, false);
1517
1518 close(pagemap_fd);
1519 printf("done\n");
1520}
1521
1522static int userfaultfd_stress(void)
1523{
1524 void *area;
1525 unsigned long nr;
1526 struct uffdio_register uffdio_register;
1527 struct uffd_stats uffd_stats[nr_cpus];
1528
1529 uffd_test_ctx_init(0);
1530
1531 if (posix_memalign(&area, page_size, page_size))
1532 err("out of memory");
1533 zeropage = area;
1534 bzero(zeropage, page_size);
1535
1536 pthread_mutex_lock(&uffd_read_mutex);
1537
1538 pthread_attr_init(&attr);
1539 pthread_attr_setstacksize(&attr, 16*1024*1024);
1540
1541 while (bounces--) {
1542 printf("bounces: %d, mode:", bounces);
1543 if (bounces & BOUNCE_RANDOM)
1544 printf(" rnd");
1545 if (bounces & BOUNCE_RACINGFAULTS)
1546 printf(" racing");
1547 if (bounces & BOUNCE_VERIFY)
1548 printf(" ver");
1549 if (bounces & BOUNCE_POLL)
1550 printf(" poll");
1551 else
1552 printf(" read");
1553 printf(", ");
1554 fflush(stdout);
1555
1556 if (bounces & BOUNCE_POLL)
1557 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1558 else
1559 fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1560
1561 /* register */
1562 uffdio_register.range.start = (unsigned long) area_dst;
1563 uffdio_register.range.len = nr_pages * page_size;
1564 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1565 if (test_uffdio_wp)
1566 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1567 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1568 err("register failure");
1569 assert_expected_ioctls_present(
1570 uffdio_register.mode, uffdio_register.ioctls);
1571
1572 if (area_dst_alias) {
1573 uffdio_register.range.start = (unsigned long)
1574 area_dst_alias;
1575 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1576 err("register failure alias");
1577 }
1578
1579 /*
1580 * The madvise done previously isn't enough: some
1581 * uffd_thread could have read userfaults (one of
1582 * those already resolved by the background thread)
1583 * and it may be in the process of calling
1584 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1585 * area_src and it would map a zero page in it (of
1586 * course such a UFFDIO_COPY is perfectly safe as it'd
1587 * return -EEXIST). The problem comes at the next
1588 * bounce though: that racing UFFDIO_COPY would
1589 * generate zeropages in the area_src, so invalidating
1590 * the previous MADV_DONTNEED. Without this additional
1591 * MADV_DONTNEED those zeropages leftovers in the
1592 * area_src would lead to -EEXIST failure during the
1593 * next bounce, effectively leaving a zeropage in the
1594 * area_dst.
1595 *
1596 * Try to comment this out madvise to see the memory
1597 * corruption being caught pretty quick.
1598 *
1599 * khugepaged is also inhibited to collapse THP after
1600 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1601 * required to MADV_DONTNEED here.
1602 */
1603 uffd_test_ops->release_pages(area_dst);
1604
1605 uffd_stats_reset(uffd_stats, nr_cpus);
1606
1607 /* bounce pass */
1608 if (stress(uffd_stats))
1609 return 1;
1610
1611 /* Clear all the write protections if there is any */
1612 if (test_uffdio_wp)
1613 wp_range(uffd, (unsigned long)area_dst,
1614 nr_pages * page_size, false);
1615
1616 /* unregister */
1617 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range))
1618 err("unregister failure");
1619 if (area_dst_alias) {
1620 uffdio_register.range.start = (unsigned long) area_dst;
1621 if (ioctl(uffd, UFFDIO_UNREGISTER,
1622 &uffdio_register.range))
1623 err("unregister failure alias");
1624 }
1625
1626 /* verification */
1627 if (bounces & BOUNCE_VERIFY)
1628 for (nr = 0; nr < nr_pages; nr++)
1629 if (*area_count(area_dst, nr) != count_verify[nr])
1630 err("error area_count %llu %llu %lu\n",
1631 *area_count(area_src, nr),
1632 count_verify[nr], nr);
1633
1634 /* prepare next bounce */
1635 swap(area_src, area_dst);
1636
1637 swap(area_src_alias, area_dst_alias);
1638
1639 uffd_stats_report(uffd_stats, nr_cpus);
1640 }
1641
1642 if (test_type == TEST_ANON) {
1643 /*
1644 * shmem/hugetlb won't be able to run since they have different
1645 * behavior on fork() (file-backed memory normally drops ptes
1646 * directly when fork), meanwhile the pagemap test will verify
1647 * pgtable entry of fork()ed child.
1648 */
1649 userfaultfd_pagemap_test(page_size);
1650 /*
1651 * Hard-code for x86_64 for now for 2M THP, as x86_64 is
1652 * currently the only one that supports uffd-wp
1653 */
1654 userfaultfd_pagemap_test(page_size * 512);
1655 }
1656
1657 return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1658 || userfaultfd_events_test() || userfaultfd_minor_test();
1659}
1660
1661/*
1662 * Copied from mlock2-tests.c
1663 */
1664unsigned long default_huge_page_size(void)
1665{
1666 unsigned long hps = 0;
1667 char *line = NULL;
1668 size_t linelen = 0;
1669 FILE *f = fopen("/proc/meminfo", "r");
1670
1671 if (!f)
1672 return 0;
1673 while (getline(&line, &linelen, f) > 0) {
1674 if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) {
1675 hps <<= 10;
1676 break;
1677 }
1678 }
1679
1680 free(line);
1681 fclose(f);
1682 return hps;
1683}
1684
1685static void set_test_type(const char *type)
1686{
1687 if (!strcmp(type, "anon")) {
1688 test_type = TEST_ANON;
1689 uffd_test_ops = &anon_uffd_test_ops;
1690 } else if (!strcmp(type, "hugetlb")) {
1691 test_type = TEST_HUGETLB;
1692 uffd_test_ops = &hugetlb_uffd_test_ops;
1693 } else if (!strcmp(type, "hugetlb_shared")) {
1694 map_shared = true;
1695 test_type = TEST_HUGETLB;
1696 uffd_test_ops = &hugetlb_uffd_test_ops;
1697 /* Minor faults require shared hugetlb; only enable here. */
1698 test_uffdio_minor = true;
1699 } else if (!strcmp(type, "shmem")) {
1700 map_shared = true;
1701 test_type = TEST_SHMEM;
1702 uffd_test_ops = &shmem_uffd_test_ops;
1703 test_uffdio_minor = true;
1704 }
1705}
1706
1707static void parse_test_type_arg(const char *raw_type)
1708{
1709 char *buf = strdup(raw_type);
1710 uint64_t features = UFFD_API_FEATURES;
1711
1712 while (buf) {
1713 const char *token = strsep(&buf, ":");
1714
1715 if (!test_type)
1716 set_test_type(token);
1717 else if (!strcmp(token, "dev"))
1718 test_dev_userfaultfd = true;
1719 else if (!strcmp(token, "syscall"))
1720 test_dev_userfaultfd = false;
1721 else if (!strcmp(token, "collapse"))
1722 test_collapse = true;
1723 else
1724 err("unrecognized test mod '%s'", token);
1725 }
1726
1727 if (!test_type)
1728 err("failed to parse test type argument: '%s'", raw_type);
1729
1730 if (test_collapse && test_type != TEST_SHMEM)
1731 err("Unsupported test: %s", raw_type);
1732
1733 if (test_type == TEST_HUGETLB)
1734 page_size = hpage_size;
1735 else
1736 page_size = sysconf(_SC_PAGE_SIZE);
1737
1738 if (!page_size)
1739 err("Unable to determine page size");
1740 if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1741 > page_size)
1742 err("Impossible to run this test");
1743
1744 /*
1745 * Whether we can test certain features depends not just on test type,
1746 * but also on whether or not this particular kernel supports the
1747 * feature.
1748 */
1749
1750 userfaultfd_open(&features);
1751
1752 test_uffdio_wp = test_uffdio_wp &&
1753 (features & UFFD_FEATURE_PAGEFAULT_FLAG_WP);
1754 test_uffdio_minor = test_uffdio_minor &&
1755 (features & uffd_minor_feature());
1756
1757 close(uffd);
1758 uffd = -1;
1759}
1760
1761static void sigalrm(int sig)
1762{
1763 if (sig != SIGALRM)
1764 abort();
1765 test_uffdio_copy_eexist = true;
1766 test_uffdio_zeropage_eexist = true;
1767 alarm(ALARM_INTERVAL_SECS);
1768}
1769
1770int main(int argc, char **argv)
1771{
1772 size_t bytes;
1773
1774 if (argc < 4)
1775 usage();
1776
1777 if (signal(SIGALRM, sigalrm) == SIG_ERR)
1778 err("failed to arm SIGALRM");
1779 alarm(ALARM_INTERVAL_SECS);
1780
1781 hpage_size = default_huge_page_size();
1782 parse_test_type_arg(argv[1]);
1783 bytes = atol(argv[2]) * 1024 * 1024;
1784
1785 if (test_collapse && bytes & (hpage_size - 1))
1786 err("MiB must be multiple of %lu if :collapse mod set",
1787 hpage_size >> 20);
1788
1789 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1790
1791 if (test_collapse) {
1792 /* nr_cpus must divide (bytes / page_size), otherwise,
1793 * area allocations of (nr_pages * paze_size) won't be a
1794 * multiple of hpage_size, even if bytes is a multiple of
1795 * hpage_size.
1796 *
1797 * This means that nr_cpus must divide (N * (2 << (H-P))
1798 * where:
1799 * bytes = hpage_size * N
1800 * hpage_size = 2 << H
1801 * page_size = 2 << P
1802 *
1803 * And we want to chose nr_cpus to be the largest value
1804 * satisfying this constraint, not larger than the number
1805 * of online CPUs. Unfortunately, prime factorization of
1806 * N and nr_cpus may be arbitrary, so have to search for it.
1807 * Instead, just use the highest power of 2 dividing both
1808 * nr_cpus and (bytes / page_size).
1809 */
1810 int x = factor_of_2(nr_cpus);
1811 int y = factor_of_2(bytes / page_size);
1812
1813 nr_cpus = x < y ? x : y;
1814 }
1815 nr_pages_per_cpu = bytes / page_size / nr_cpus;
1816 if (!nr_pages_per_cpu) {
1817 _err("invalid MiB");
1818 usage();
1819 }
1820
1821 bounces = atoi(argv[3]);
1822 if (bounces <= 0) {
1823 _err("invalid bounces");
1824 usage();
1825 }
1826 nr_pages = nr_pages_per_cpu * nr_cpus;
1827
1828 if (test_type == TEST_SHMEM || test_type == TEST_HUGETLB) {
1829 unsigned int memfd_flags = 0;
1830
1831 if (test_type == TEST_HUGETLB)
1832 memfd_flags = MFD_HUGETLB;
1833 mem_fd = memfd_create(argv[0], memfd_flags);
1834 if (mem_fd < 0)
1835 err("memfd_create");
1836 if (ftruncate(mem_fd, nr_pages * page_size * 2))
1837 err("ftruncate");
1838 if (fallocate(mem_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
1852int main(void)
1853{
1854 printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1855 return KSFT_SKIP;
1856}
1857
1858#endif /* __NR_userfaultfd */
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 <sys/mman.h>
50#include <sys/syscall.h>
51#include <sys/ioctl.h>
52#include <sys/wait.h>
53#include <pthread.h>
54#include <linux/userfaultfd.h>
55#include <setjmp.h>
56#include <stdbool.h>
57#include <assert.h>
58
59#include "../kselftest.h"
60
61#ifdef __NR_userfaultfd
62
63static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size;
64
65#define BOUNCE_RANDOM (1<<0)
66#define BOUNCE_RACINGFAULTS (1<<1)
67#define BOUNCE_VERIFY (1<<2)
68#define BOUNCE_POLL (1<<3)
69static int bounces;
70
71#define TEST_ANON 1
72#define TEST_HUGETLB 2
73#define TEST_SHMEM 3
74static int test_type;
75
76/* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
77#define ALARM_INTERVAL_SECS 10
78static volatile bool test_uffdio_copy_eexist = true;
79static volatile bool test_uffdio_zeropage_eexist = true;
80/* Whether to test uffd write-protection */
81static bool test_uffdio_wp = false;
82
83static bool map_shared;
84static int huge_fd;
85static char *huge_fd_off0;
86static unsigned long long *count_verify;
87static int uffd, uffd_flags, finished, *pipefd;
88static char *area_src, *area_src_alias, *area_dst, *area_dst_alias;
89static char *zeropage;
90pthread_attr_t attr;
91
92/* Userfaultfd test statistics */
93struct uffd_stats {
94 int cpu;
95 unsigned long missing_faults;
96 unsigned long wp_faults;
97};
98
99/* pthread_mutex_t starts at page offset 0 */
100#define area_mutex(___area, ___nr) \
101 ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
102/*
103 * count is placed in the page after pthread_mutex_t naturally aligned
104 * to avoid non alignment faults on non-x86 archs.
105 */
106#define area_count(___area, ___nr) \
107 ((volatile unsigned long long *) ((unsigned long) \
108 ((___area) + (___nr)*page_size + \
109 sizeof(pthread_mutex_t) + \
110 sizeof(unsigned long long) - 1) & \
111 ~(unsigned long)(sizeof(unsigned long long) \
112 - 1)))
113
114const char *examples =
115 "# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
116 "./userfaultfd anon 100 99999\n\n"
117 "# Run share memory test on 1GiB region with 99 bounces:\n"
118 "./userfaultfd shmem 1000 99\n\n"
119 "# Run hugetlb memory test on 256MiB region with 50 bounces (using /dev/hugepages/hugefile):\n"
120 "./userfaultfd hugetlb 256 50 /dev/hugepages/hugefile\n\n"
121 "# Run the same hugetlb test but using shmem:\n"
122 "./userfaultfd hugetlb_shared 256 50 /dev/hugepages/hugefile\n\n"
123 "# 10MiB-~6GiB 999 bounces anonymous test, "
124 "continue forever unless an error triggers\n"
125 "while ./userfaultfd anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
126
127static void usage(void)
128{
129 fprintf(stderr, "\nUsage: ./userfaultfd <test type> <MiB> <bounces> "
130 "[hugetlbfs_file]\n\n");
131 fprintf(stderr, "Supported <test type>: anon, hugetlb, "
132 "hugetlb_shared, shmem\n\n");
133 fprintf(stderr, "Examples:\n\n");
134 fprintf(stderr, "%s", examples);
135 exit(1);
136}
137
138static void uffd_stats_reset(struct uffd_stats *uffd_stats,
139 unsigned long n_cpus)
140{
141 int i;
142
143 for (i = 0; i < n_cpus; i++) {
144 uffd_stats[i].cpu = i;
145 uffd_stats[i].missing_faults = 0;
146 uffd_stats[i].wp_faults = 0;
147 }
148}
149
150static void uffd_stats_report(struct uffd_stats *stats, int n_cpus)
151{
152 int i;
153 unsigned long long miss_total = 0, wp_total = 0;
154
155 for (i = 0; i < n_cpus; i++) {
156 miss_total += stats[i].missing_faults;
157 wp_total += stats[i].wp_faults;
158 }
159
160 printf("userfaults: %llu missing (", miss_total);
161 for (i = 0; i < n_cpus; i++)
162 printf("%lu+", stats[i].missing_faults);
163 printf("\b), %llu wp (", wp_total);
164 for (i = 0; i < n_cpus; i++)
165 printf("%lu+", stats[i].wp_faults);
166 printf("\b)\n");
167}
168
169static int anon_release_pages(char *rel_area)
170{
171 int ret = 0;
172
173 if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED)) {
174 perror("madvise");
175 ret = 1;
176 }
177
178 return ret;
179}
180
181static void anon_allocate_area(void **alloc_area)
182{
183 if (posix_memalign(alloc_area, page_size, nr_pages * page_size)) {
184 fprintf(stderr, "out of memory\n");
185 *alloc_area = NULL;
186 }
187}
188
189static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
190{
191}
192
193/* HugeTLB memory */
194static int hugetlb_release_pages(char *rel_area)
195{
196 int ret = 0;
197
198 if (fallocate(huge_fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
199 rel_area == huge_fd_off0 ? 0 :
200 nr_pages * page_size,
201 nr_pages * page_size)) {
202 perror("fallocate");
203 ret = 1;
204 }
205
206 return ret;
207}
208
209
210static void hugetlb_allocate_area(void **alloc_area)
211{
212 void *area_alias = NULL;
213 char **alloc_area_alias;
214 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
215 (map_shared ? MAP_SHARED : MAP_PRIVATE) |
216 MAP_HUGETLB,
217 huge_fd, *alloc_area == area_src ? 0 :
218 nr_pages * page_size);
219 if (*alloc_area == MAP_FAILED) {
220 fprintf(stderr, "mmap of hugetlbfs file failed\n");
221 *alloc_area = NULL;
222 }
223
224 if (map_shared) {
225 area_alias = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
226 MAP_SHARED | MAP_HUGETLB,
227 huge_fd, *alloc_area == area_src ? 0 :
228 nr_pages * page_size);
229 if (area_alias == MAP_FAILED) {
230 if (munmap(*alloc_area, nr_pages * page_size) < 0)
231 perror("hugetlb munmap"), exit(1);
232 *alloc_area = NULL;
233 return;
234 }
235 }
236 if (*alloc_area == area_src) {
237 huge_fd_off0 = *alloc_area;
238 alloc_area_alias = &area_src_alias;
239 } else {
240 alloc_area_alias = &area_dst_alias;
241 }
242 if (area_alias)
243 *alloc_area_alias = area_alias;
244}
245
246static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
247{
248 if (!map_shared)
249 return;
250 /*
251 * We can't zap just the pagetable with hugetlbfs because
252 * MADV_DONTEED won't work. So exercise -EEXIST on a alias
253 * mapping where the pagetables are not established initially,
254 * this way we'll exercise the -EEXEC at the fs level.
255 */
256 *start = (unsigned long) area_dst_alias + offset;
257}
258
259/* Shared memory */
260static int shmem_release_pages(char *rel_area)
261{
262 int ret = 0;
263
264 if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE)) {
265 perror("madvise");
266 ret = 1;
267 }
268
269 return ret;
270}
271
272static void shmem_allocate_area(void **alloc_area)
273{
274 *alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
275 MAP_ANONYMOUS | MAP_SHARED, -1, 0);
276 if (*alloc_area == MAP_FAILED) {
277 fprintf(stderr, "shared memory mmap failed\n");
278 *alloc_area = NULL;
279 }
280}
281
282struct uffd_test_ops {
283 unsigned long expected_ioctls;
284 void (*allocate_area)(void **alloc_area);
285 int (*release_pages)(char *rel_area);
286 void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
287};
288
289#define SHMEM_EXPECTED_IOCTLS ((1 << _UFFDIO_WAKE) | \
290 (1 << _UFFDIO_COPY) | \
291 (1 << _UFFDIO_ZEROPAGE))
292
293#define ANON_EXPECTED_IOCTLS ((1 << _UFFDIO_WAKE) | \
294 (1 << _UFFDIO_COPY) | \
295 (1 << _UFFDIO_ZEROPAGE) | \
296 (1 << _UFFDIO_WRITEPROTECT))
297
298static struct uffd_test_ops anon_uffd_test_ops = {
299 .expected_ioctls = ANON_EXPECTED_IOCTLS,
300 .allocate_area = anon_allocate_area,
301 .release_pages = anon_release_pages,
302 .alias_mapping = noop_alias_mapping,
303};
304
305static struct uffd_test_ops shmem_uffd_test_ops = {
306 .expected_ioctls = SHMEM_EXPECTED_IOCTLS,
307 .allocate_area = shmem_allocate_area,
308 .release_pages = shmem_release_pages,
309 .alias_mapping = noop_alias_mapping,
310};
311
312static struct uffd_test_ops hugetlb_uffd_test_ops = {
313 .expected_ioctls = UFFD_API_RANGE_IOCTLS_BASIC,
314 .allocate_area = hugetlb_allocate_area,
315 .release_pages = hugetlb_release_pages,
316 .alias_mapping = hugetlb_alias_mapping,
317};
318
319static struct uffd_test_ops *uffd_test_ops;
320
321static int my_bcmp(char *str1, char *str2, size_t n)
322{
323 unsigned long i;
324 for (i = 0; i < n; i++)
325 if (str1[i] != str2[i])
326 return 1;
327 return 0;
328}
329
330static void wp_range(int ufd, __u64 start, __u64 len, bool wp)
331{
332 struct uffdio_writeprotect prms = { 0 };
333
334 /* Write protection page faults */
335 prms.range.start = start;
336 prms.range.len = len;
337 /* Undo write-protect, do wakeup after that */
338 prms.mode = wp ? UFFDIO_WRITEPROTECT_MODE_WP : 0;
339
340 if (ioctl(ufd, UFFDIO_WRITEPROTECT, &prms))
341 fprintf(stderr, "clear WP failed for address 0x%Lx\n",
342 start), exit(1);
343}
344
345static void *locking_thread(void *arg)
346{
347 unsigned long cpu = (unsigned long) arg;
348 struct random_data rand;
349 unsigned long page_nr = *(&(page_nr)); /* uninitialized warning */
350 int32_t rand_nr;
351 unsigned long long count;
352 char randstate[64];
353 unsigned int seed;
354 time_t start;
355
356 if (bounces & BOUNCE_RANDOM) {
357 seed = (unsigned int) time(NULL) - bounces;
358 if (!(bounces & BOUNCE_RACINGFAULTS))
359 seed += cpu;
360 bzero(&rand, sizeof(rand));
361 bzero(&randstate, sizeof(randstate));
362 if (initstate_r(seed, randstate, sizeof(randstate), &rand))
363 fprintf(stderr, "srandom_r error\n"), exit(1);
364 } else {
365 page_nr = -bounces;
366 if (!(bounces & BOUNCE_RACINGFAULTS))
367 page_nr += cpu * nr_pages_per_cpu;
368 }
369
370 while (!finished) {
371 if (bounces & BOUNCE_RANDOM) {
372 if (random_r(&rand, &rand_nr))
373 fprintf(stderr, "random_r 1 error\n"), exit(1);
374 page_nr = rand_nr;
375 if (sizeof(page_nr) > sizeof(rand_nr)) {
376 if (random_r(&rand, &rand_nr))
377 fprintf(stderr, "random_r 2 error\n"), exit(1);
378 page_nr |= (((unsigned long) rand_nr) << 16) <<
379 16;
380 }
381 } else
382 page_nr += 1;
383 page_nr %= nr_pages;
384
385 start = time(NULL);
386 if (bounces & BOUNCE_VERIFY) {
387 count = *area_count(area_dst, page_nr);
388 if (!count)
389 fprintf(stderr,
390 "page_nr %lu wrong count %Lu %Lu\n",
391 page_nr, count,
392 count_verify[page_nr]), exit(1);
393
394
395 /*
396 * We can't use bcmp (or memcmp) because that
397 * returns 0 erroneously if the memory is
398 * changing under it (even if the end of the
399 * page is never changing and always
400 * different).
401 */
402#if 1
403 if (!my_bcmp(area_dst + page_nr * page_size, zeropage,
404 page_size))
405 fprintf(stderr,
406 "my_bcmp page_nr %lu wrong count %Lu %Lu\n",
407 page_nr, count,
408 count_verify[page_nr]), exit(1);
409#else
410 unsigned long loops;
411
412 loops = 0;
413 /* uncomment the below line to test with mutex */
414 /* pthread_mutex_lock(area_mutex(area_dst, page_nr)); */
415 while (!bcmp(area_dst + page_nr * page_size, zeropage,
416 page_size)) {
417 loops += 1;
418 if (loops > 10)
419 break;
420 }
421 /* uncomment below line to test with mutex */
422 /* pthread_mutex_unlock(area_mutex(area_dst, page_nr)); */
423 if (loops) {
424 fprintf(stderr,
425 "page_nr %lu all zero thread %lu %p %lu\n",
426 page_nr, cpu, area_dst + page_nr * page_size,
427 loops);
428 if (loops > 10)
429 exit(1);
430 }
431#endif
432 }
433
434 pthread_mutex_lock(area_mutex(area_dst, page_nr));
435 count = *area_count(area_dst, page_nr);
436 if (count != count_verify[page_nr]) {
437 fprintf(stderr,
438 "page_nr %lu memory corruption %Lu %Lu\n",
439 page_nr, count,
440 count_verify[page_nr]), exit(1);
441 }
442 count++;
443 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
444 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
445
446 if (time(NULL) - start > 1)
447 fprintf(stderr,
448 "userfault too slow %ld "
449 "possible false positive with overcommit\n",
450 time(NULL) - start);
451 }
452
453 return NULL;
454}
455
456static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
457 unsigned long offset)
458{
459 uffd_test_ops->alias_mapping(&uffdio_copy->dst,
460 uffdio_copy->len,
461 offset);
462 if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
463 /* real retval in ufdio_copy.copy */
464 if (uffdio_copy->copy != -EEXIST)
465 fprintf(stderr, "UFFDIO_COPY retry error %Ld\n",
466 uffdio_copy->copy), exit(1);
467 } else {
468 fprintf(stderr, "UFFDIO_COPY retry unexpected %Ld\n",
469 uffdio_copy->copy), exit(1);
470 }
471}
472
473static int __copy_page(int ufd, unsigned long offset, bool retry)
474{
475 struct uffdio_copy uffdio_copy;
476
477 if (offset >= nr_pages * page_size)
478 fprintf(stderr, "unexpected offset %lu\n",
479 offset), exit(1);
480 uffdio_copy.dst = (unsigned long) area_dst + offset;
481 uffdio_copy.src = (unsigned long) area_src + offset;
482 uffdio_copy.len = page_size;
483 if (test_uffdio_wp)
484 uffdio_copy.mode = UFFDIO_COPY_MODE_WP;
485 else
486 uffdio_copy.mode = 0;
487 uffdio_copy.copy = 0;
488 if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
489 /* real retval in ufdio_copy.copy */
490 if (uffdio_copy.copy != -EEXIST)
491 fprintf(stderr, "UFFDIO_COPY error %Ld\n",
492 uffdio_copy.copy), exit(1);
493 } else if (uffdio_copy.copy != page_size) {
494 fprintf(stderr, "UFFDIO_COPY unexpected copy %Ld\n",
495 uffdio_copy.copy), exit(1);
496 } else {
497 if (test_uffdio_copy_eexist && retry) {
498 test_uffdio_copy_eexist = false;
499 retry_copy_page(ufd, &uffdio_copy, offset);
500 }
501 return 1;
502 }
503 return 0;
504}
505
506static int copy_page_retry(int ufd, unsigned long offset)
507{
508 return __copy_page(ufd, offset, true);
509}
510
511static int copy_page(int ufd, unsigned long offset)
512{
513 return __copy_page(ufd, offset, false);
514}
515
516static int uffd_read_msg(int ufd, struct uffd_msg *msg)
517{
518 int ret = read(uffd, msg, sizeof(*msg));
519
520 if (ret != sizeof(*msg)) {
521 if (ret < 0) {
522 if (errno == EAGAIN)
523 return 1;
524 else
525 perror("blocking read error"), exit(1);
526 } else {
527 fprintf(stderr, "short read\n"), exit(1);
528 }
529 }
530
531 return 0;
532}
533
534static void uffd_handle_page_fault(struct uffd_msg *msg,
535 struct uffd_stats *stats)
536{
537 unsigned long offset;
538
539 if (msg->event != UFFD_EVENT_PAGEFAULT)
540 fprintf(stderr, "unexpected msg event %u\n",
541 msg->event), exit(1);
542
543 if (msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP) {
544 wp_range(uffd, msg->arg.pagefault.address, page_size, false);
545 stats->wp_faults++;
546 } else {
547 /* Missing page faults */
548 if (bounces & BOUNCE_VERIFY &&
549 msg->arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
550 fprintf(stderr, "unexpected write fault\n"), exit(1);
551
552 offset = (char *)(unsigned long)msg->arg.pagefault.address - area_dst;
553 offset &= ~(page_size-1);
554
555 if (copy_page(uffd, offset))
556 stats->missing_faults++;
557 }
558}
559
560static void *uffd_poll_thread(void *arg)
561{
562 struct uffd_stats *stats = (struct uffd_stats *)arg;
563 unsigned long cpu = stats->cpu;
564 struct pollfd pollfd[2];
565 struct uffd_msg msg;
566 struct uffdio_register uffd_reg;
567 int ret;
568 char tmp_chr;
569
570 pollfd[0].fd = uffd;
571 pollfd[0].events = POLLIN;
572 pollfd[1].fd = pipefd[cpu*2];
573 pollfd[1].events = POLLIN;
574
575 for (;;) {
576 ret = poll(pollfd, 2, -1);
577 if (!ret)
578 fprintf(stderr, "poll error %d\n", ret), exit(1);
579 if (ret < 0)
580 perror("poll"), exit(1);
581 if (pollfd[1].revents & POLLIN) {
582 if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
583 fprintf(stderr, "read pipefd error\n"),
584 exit(1);
585 break;
586 }
587 if (!(pollfd[0].revents & POLLIN))
588 fprintf(stderr, "pollfd[0].revents %d\n",
589 pollfd[0].revents), exit(1);
590 if (uffd_read_msg(uffd, &msg))
591 continue;
592 switch (msg.event) {
593 default:
594 fprintf(stderr, "unexpected msg event %u\n",
595 msg.event), exit(1);
596 break;
597 case UFFD_EVENT_PAGEFAULT:
598 uffd_handle_page_fault(&msg, stats);
599 break;
600 case UFFD_EVENT_FORK:
601 close(uffd);
602 uffd = msg.arg.fork.ufd;
603 pollfd[0].fd = uffd;
604 break;
605 case UFFD_EVENT_REMOVE:
606 uffd_reg.range.start = msg.arg.remove.start;
607 uffd_reg.range.len = msg.arg.remove.end -
608 msg.arg.remove.start;
609 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
610 fprintf(stderr, "remove failure\n"), exit(1);
611 break;
612 case UFFD_EVENT_REMAP:
613 area_dst = (char *)(unsigned long)msg.arg.remap.to;
614 break;
615 }
616 }
617
618 return NULL;
619}
620
621pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
622
623static void *uffd_read_thread(void *arg)
624{
625 struct uffd_stats *stats = (struct uffd_stats *)arg;
626 struct uffd_msg msg;
627
628 pthread_mutex_unlock(&uffd_read_mutex);
629 /* from here cancellation is ok */
630
631 for (;;) {
632 if (uffd_read_msg(uffd, &msg))
633 continue;
634 uffd_handle_page_fault(&msg, stats);
635 }
636
637 return NULL;
638}
639
640static void *background_thread(void *arg)
641{
642 unsigned long cpu = (unsigned long) arg;
643 unsigned long page_nr, start_nr, mid_nr, end_nr;
644
645 start_nr = cpu * nr_pages_per_cpu;
646 end_nr = (cpu+1) * nr_pages_per_cpu;
647 mid_nr = (start_nr + end_nr) / 2;
648
649 /* Copy the first half of the pages */
650 for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
651 copy_page_retry(uffd, page_nr * page_size);
652
653 /*
654 * If we need to test uffd-wp, set it up now. Then we'll have
655 * at least the first half of the pages mapped already which
656 * can be write-protected for testing
657 */
658 if (test_uffdio_wp)
659 wp_range(uffd, (unsigned long)area_dst + start_nr * page_size,
660 nr_pages_per_cpu * page_size, true);
661
662 /*
663 * Continue the 2nd half of the page copying, handling write
664 * protection faults if any
665 */
666 for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
667 copy_page_retry(uffd, page_nr * page_size);
668
669 return NULL;
670}
671
672static int stress(struct uffd_stats *uffd_stats)
673{
674 unsigned long cpu;
675 pthread_t locking_threads[nr_cpus];
676 pthread_t uffd_threads[nr_cpus];
677 pthread_t background_threads[nr_cpus];
678
679 finished = 0;
680 for (cpu = 0; cpu < nr_cpus; cpu++) {
681 if (pthread_create(&locking_threads[cpu], &attr,
682 locking_thread, (void *)cpu))
683 return 1;
684 if (bounces & BOUNCE_POLL) {
685 if (pthread_create(&uffd_threads[cpu], &attr,
686 uffd_poll_thread,
687 (void *)&uffd_stats[cpu]))
688 return 1;
689 } else {
690 if (pthread_create(&uffd_threads[cpu], &attr,
691 uffd_read_thread,
692 (void *)&uffd_stats[cpu]))
693 return 1;
694 pthread_mutex_lock(&uffd_read_mutex);
695 }
696 if (pthread_create(&background_threads[cpu], &attr,
697 background_thread, (void *)cpu))
698 return 1;
699 }
700 for (cpu = 0; cpu < nr_cpus; cpu++)
701 if (pthread_join(background_threads[cpu], NULL))
702 return 1;
703
704 /*
705 * Be strict and immediately zap area_src, the whole area has
706 * been transferred already by the background treads. The
707 * area_src could then be faulted in in a racy way by still
708 * running uffdio_threads reading zeropages after we zapped
709 * area_src (but they're guaranteed to get -EEXIST from
710 * UFFDIO_COPY without writing zero pages into area_dst
711 * because the background threads already completed).
712 */
713 if (uffd_test_ops->release_pages(area_src))
714 return 1;
715
716
717 finished = 1;
718 for (cpu = 0; cpu < nr_cpus; cpu++)
719 if (pthread_join(locking_threads[cpu], NULL))
720 return 1;
721
722 for (cpu = 0; cpu < nr_cpus; cpu++) {
723 char c;
724 if (bounces & BOUNCE_POLL) {
725 if (write(pipefd[cpu*2+1], &c, 1) != 1) {
726 fprintf(stderr, "pipefd write error\n");
727 return 1;
728 }
729 if (pthread_join(uffd_threads[cpu],
730 (void *)&uffd_stats[cpu]))
731 return 1;
732 } else {
733 if (pthread_cancel(uffd_threads[cpu]))
734 return 1;
735 if (pthread_join(uffd_threads[cpu], NULL))
736 return 1;
737 }
738 }
739
740 return 0;
741}
742
743static int userfaultfd_open(int features)
744{
745 struct uffdio_api uffdio_api;
746
747 uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
748 if (uffd < 0) {
749 fprintf(stderr,
750 "userfaultfd syscall not available in this kernel\n");
751 return 1;
752 }
753 uffd_flags = fcntl(uffd, F_GETFD, NULL);
754
755 uffdio_api.api = UFFD_API;
756 uffdio_api.features = features;
757 if (ioctl(uffd, UFFDIO_API, &uffdio_api)) {
758 fprintf(stderr, "UFFDIO_API\n");
759 return 1;
760 }
761 if (uffdio_api.api != UFFD_API) {
762 fprintf(stderr, "UFFDIO_API error %Lu\n", uffdio_api.api);
763 return 1;
764 }
765
766 return 0;
767}
768
769sigjmp_buf jbuf, *sigbuf;
770
771static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
772{
773 if (sig == SIGBUS) {
774 if (sigbuf)
775 siglongjmp(*sigbuf, 1);
776 abort();
777 }
778}
779
780/*
781 * For non-cooperative userfaultfd test we fork() a process that will
782 * generate pagefaults, will mremap the area monitored by the
783 * userfaultfd and at last this process will release the monitored
784 * area.
785 * For the anonymous and shared memory the area is divided into two
786 * parts, the first part is accessed before mremap, and the second
787 * part is accessed after mremap. Since hugetlbfs does not support
788 * mremap, the entire monitored area is accessed in a single pass for
789 * HUGETLB_TEST.
790 * The release of the pages currently generates event for shmem and
791 * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
792 * for hugetlb.
793 * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
794 * monitored area, generate pagefaults and test that signal is delivered.
795 * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
796 * test robustness use case - we release monitored area, fork a process
797 * that will generate pagefaults and verify signal is generated.
798 * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
799 * feature. Using monitor thread, verify no userfault events are generated.
800 */
801static int faulting_process(int signal_test)
802{
803 unsigned long nr;
804 unsigned long long count;
805 unsigned long split_nr_pages;
806 unsigned long lastnr;
807 struct sigaction act;
808 unsigned long signalled = 0;
809
810 if (test_type != TEST_HUGETLB)
811 split_nr_pages = (nr_pages + 1) / 2;
812 else
813 split_nr_pages = nr_pages;
814
815 if (signal_test) {
816 sigbuf = &jbuf;
817 memset(&act, 0, sizeof(act));
818 act.sa_sigaction = sighndl;
819 act.sa_flags = SA_SIGINFO;
820 if (sigaction(SIGBUS, &act, 0)) {
821 perror("sigaction");
822 return 1;
823 }
824 lastnr = (unsigned long)-1;
825 }
826
827 for (nr = 0; nr < split_nr_pages; nr++) {
828 int steps = 1;
829 unsigned long offset = nr * page_size;
830
831 if (signal_test) {
832 if (sigsetjmp(*sigbuf, 1) != 0) {
833 if (steps == 1 && nr == lastnr) {
834 fprintf(stderr, "Signal repeated\n");
835 return 1;
836 }
837
838 lastnr = nr;
839 if (signal_test == 1) {
840 if (steps == 1) {
841 /* This is a MISSING request */
842 steps++;
843 if (copy_page(uffd, offset))
844 signalled++;
845 } else {
846 /* This is a WP request */
847 assert(steps == 2);
848 wp_range(uffd,
849 (__u64)area_dst +
850 offset,
851 page_size, false);
852 }
853 } else {
854 signalled++;
855 continue;
856 }
857 }
858 }
859
860 count = *area_count(area_dst, nr);
861 if (count != count_verify[nr]) {
862 fprintf(stderr,
863 "nr %lu memory corruption %Lu %Lu\n",
864 nr, count,
865 count_verify[nr]);
866 }
867 /*
868 * Trigger write protection if there is by writting
869 * the same value back.
870 */
871 *area_count(area_dst, nr) = count;
872 }
873
874 if (signal_test)
875 return signalled != split_nr_pages;
876
877 if (test_type == TEST_HUGETLB)
878 return 0;
879
880 area_dst = mremap(area_dst, nr_pages * page_size, nr_pages * page_size,
881 MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
882 if (area_dst == MAP_FAILED)
883 perror("mremap"), exit(1);
884
885 for (; nr < nr_pages; nr++) {
886 count = *area_count(area_dst, nr);
887 if (count != count_verify[nr]) {
888 fprintf(stderr,
889 "nr %lu memory corruption %Lu %Lu\n",
890 nr, count,
891 count_verify[nr]), exit(1);
892 }
893 /*
894 * Trigger write protection if there is by writting
895 * the same value back.
896 */
897 *area_count(area_dst, nr) = count;
898 }
899
900 if (uffd_test_ops->release_pages(area_dst))
901 return 1;
902
903 for (nr = 0; nr < nr_pages; nr++) {
904 if (my_bcmp(area_dst + nr * page_size, zeropage, page_size))
905 fprintf(stderr, "nr %lu is not zero\n", nr), exit(1);
906 }
907
908 return 0;
909}
910
911static void retry_uffdio_zeropage(int ufd,
912 struct uffdio_zeropage *uffdio_zeropage,
913 unsigned long offset)
914{
915 uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
916 uffdio_zeropage->range.len,
917 offset);
918 if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
919 if (uffdio_zeropage->zeropage != -EEXIST)
920 fprintf(stderr, "UFFDIO_ZEROPAGE retry error %Ld\n",
921 uffdio_zeropage->zeropage), exit(1);
922 } else {
923 fprintf(stderr, "UFFDIO_ZEROPAGE retry unexpected %Ld\n",
924 uffdio_zeropage->zeropage), exit(1);
925 }
926}
927
928static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
929{
930 struct uffdio_zeropage uffdio_zeropage;
931 int ret;
932 unsigned long has_zeropage;
933
934 has_zeropage = uffd_test_ops->expected_ioctls & (1 << _UFFDIO_ZEROPAGE);
935
936 if (offset >= nr_pages * page_size)
937 fprintf(stderr, "unexpected offset %lu\n",
938 offset), exit(1);
939 uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
940 uffdio_zeropage.range.len = page_size;
941 uffdio_zeropage.mode = 0;
942 ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
943 if (ret) {
944 /* real retval in ufdio_zeropage.zeropage */
945 if (has_zeropage) {
946 if (uffdio_zeropage.zeropage == -EEXIST)
947 fprintf(stderr, "UFFDIO_ZEROPAGE -EEXIST\n"),
948 exit(1);
949 else
950 fprintf(stderr, "UFFDIO_ZEROPAGE error %Ld\n",
951 uffdio_zeropage.zeropage), exit(1);
952 } else {
953 if (uffdio_zeropage.zeropage != -EINVAL)
954 fprintf(stderr,
955 "UFFDIO_ZEROPAGE not -EINVAL %Ld\n",
956 uffdio_zeropage.zeropage), exit(1);
957 }
958 } else if (has_zeropage) {
959 if (uffdio_zeropage.zeropage != page_size) {
960 fprintf(stderr, "UFFDIO_ZEROPAGE unexpected %Ld\n",
961 uffdio_zeropage.zeropage), exit(1);
962 } else {
963 if (test_uffdio_zeropage_eexist && retry) {
964 test_uffdio_zeropage_eexist = false;
965 retry_uffdio_zeropage(ufd, &uffdio_zeropage,
966 offset);
967 }
968 return 1;
969 }
970 } else {
971 fprintf(stderr,
972 "UFFDIO_ZEROPAGE succeeded %Ld\n",
973 uffdio_zeropage.zeropage), exit(1);
974 }
975
976 return 0;
977}
978
979static int uffdio_zeropage(int ufd, unsigned long offset)
980{
981 return __uffdio_zeropage(ufd, offset, false);
982}
983
984/* exercise UFFDIO_ZEROPAGE */
985static int userfaultfd_zeropage_test(void)
986{
987 struct uffdio_register uffdio_register;
988 unsigned long expected_ioctls;
989
990 printf("testing UFFDIO_ZEROPAGE: ");
991 fflush(stdout);
992
993 if (uffd_test_ops->release_pages(area_dst))
994 return 1;
995
996 if (userfaultfd_open(0) < 0)
997 return 1;
998 uffdio_register.range.start = (unsigned long) area_dst;
999 uffdio_register.range.len = nr_pages * page_size;
1000 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1001 if (test_uffdio_wp)
1002 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1003 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1004 fprintf(stderr, "register failure\n"), exit(1);
1005
1006 expected_ioctls = uffd_test_ops->expected_ioctls;
1007 if ((uffdio_register.ioctls & expected_ioctls) !=
1008 expected_ioctls)
1009 fprintf(stderr,
1010 "unexpected missing ioctl for anon memory\n"),
1011 exit(1);
1012
1013 if (uffdio_zeropage(uffd, 0)) {
1014 if (my_bcmp(area_dst, zeropage, page_size))
1015 fprintf(stderr, "zeropage is not zero\n"), exit(1);
1016 }
1017
1018 close(uffd);
1019 printf("done.\n");
1020 return 0;
1021}
1022
1023static int userfaultfd_events_test(void)
1024{
1025 struct uffdio_register uffdio_register;
1026 unsigned long expected_ioctls;
1027 pthread_t uffd_mon;
1028 int err, features;
1029 pid_t pid;
1030 char c;
1031 struct uffd_stats stats = { 0 };
1032
1033 printf("testing events (fork, remap, remove): ");
1034 fflush(stdout);
1035
1036 if (uffd_test_ops->release_pages(area_dst))
1037 return 1;
1038
1039 features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
1040 UFFD_FEATURE_EVENT_REMOVE;
1041 if (userfaultfd_open(features) < 0)
1042 return 1;
1043 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1044
1045 uffdio_register.range.start = (unsigned long) area_dst;
1046 uffdio_register.range.len = nr_pages * page_size;
1047 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1048 if (test_uffdio_wp)
1049 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1050 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1051 fprintf(stderr, "register failure\n"), exit(1);
1052
1053 expected_ioctls = uffd_test_ops->expected_ioctls;
1054 if ((uffdio_register.ioctls & expected_ioctls) !=
1055 expected_ioctls)
1056 fprintf(stderr,
1057 "unexpected missing ioctl for anon memory\n"),
1058 exit(1);
1059
1060 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1061 perror("uffd_poll_thread create"), exit(1);
1062
1063 pid = fork();
1064 if (pid < 0)
1065 perror("fork"), exit(1);
1066
1067 if (!pid)
1068 return faulting_process(0);
1069
1070 waitpid(pid, &err, 0);
1071 if (err)
1072 fprintf(stderr, "faulting process failed\n"), exit(1);
1073
1074 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1075 perror("pipe write"), exit(1);
1076 if (pthread_join(uffd_mon, NULL))
1077 return 1;
1078
1079 close(uffd);
1080
1081 uffd_stats_report(&stats, 1);
1082
1083 return stats.missing_faults != nr_pages;
1084}
1085
1086static int userfaultfd_sig_test(void)
1087{
1088 struct uffdio_register uffdio_register;
1089 unsigned long expected_ioctls;
1090 unsigned long userfaults;
1091 pthread_t uffd_mon;
1092 int err, features;
1093 pid_t pid;
1094 char c;
1095 struct uffd_stats stats = { 0 };
1096
1097 printf("testing signal delivery: ");
1098 fflush(stdout);
1099
1100 if (uffd_test_ops->release_pages(area_dst))
1101 return 1;
1102
1103 features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
1104 if (userfaultfd_open(features) < 0)
1105 return 1;
1106 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1107
1108 uffdio_register.range.start = (unsigned long) area_dst;
1109 uffdio_register.range.len = nr_pages * page_size;
1110 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1111 if (test_uffdio_wp)
1112 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1113 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
1114 fprintf(stderr, "register failure\n"), exit(1);
1115
1116 expected_ioctls = uffd_test_ops->expected_ioctls;
1117 if ((uffdio_register.ioctls & expected_ioctls) !=
1118 expected_ioctls)
1119 fprintf(stderr,
1120 "unexpected missing ioctl for anon memory\n"),
1121 exit(1);
1122
1123 if (faulting_process(1))
1124 fprintf(stderr, "faulting process failed\n"), exit(1);
1125
1126 if (uffd_test_ops->release_pages(area_dst))
1127 return 1;
1128
1129 if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, &stats))
1130 perror("uffd_poll_thread create"), exit(1);
1131
1132 pid = fork();
1133 if (pid < 0)
1134 perror("fork"), exit(1);
1135
1136 if (!pid)
1137 exit(faulting_process(2));
1138
1139 waitpid(pid, &err, 0);
1140 if (err)
1141 fprintf(stderr, "faulting process failed\n"), exit(1);
1142
1143 if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1144 perror("pipe write"), exit(1);
1145 if (pthread_join(uffd_mon, (void **)&userfaults))
1146 return 1;
1147
1148 printf("done.\n");
1149 if (userfaults)
1150 fprintf(stderr, "Signal test failed, userfaults: %ld\n",
1151 userfaults);
1152 close(uffd);
1153 return userfaults != 0;
1154}
1155
1156static int userfaultfd_stress(void)
1157{
1158 void *area;
1159 char *tmp_area;
1160 unsigned long nr;
1161 struct uffdio_register uffdio_register;
1162 unsigned long cpu;
1163 int err;
1164 struct uffd_stats uffd_stats[nr_cpus];
1165
1166 uffd_test_ops->allocate_area((void **)&area_src);
1167 if (!area_src)
1168 return 1;
1169 uffd_test_ops->allocate_area((void **)&area_dst);
1170 if (!area_dst)
1171 return 1;
1172
1173 if (userfaultfd_open(0) < 0)
1174 return 1;
1175
1176 count_verify = malloc(nr_pages * sizeof(unsigned long long));
1177 if (!count_verify) {
1178 perror("count_verify");
1179 return 1;
1180 }
1181
1182 for (nr = 0; nr < nr_pages; nr++) {
1183 *area_mutex(area_src, nr) = (pthread_mutex_t)
1184 PTHREAD_MUTEX_INITIALIZER;
1185 count_verify[nr] = *area_count(area_src, nr) = 1;
1186 /*
1187 * In the transition between 255 to 256, powerpc will
1188 * read out of order in my_bcmp and see both bytes as
1189 * zero, so leave a placeholder below always non-zero
1190 * after the count, to avoid my_bcmp to trigger false
1191 * positives.
1192 */
1193 *(area_count(area_src, nr) + 1) = 1;
1194 }
1195
1196 pipefd = malloc(sizeof(int) * nr_cpus * 2);
1197 if (!pipefd) {
1198 perror("pipefd");
1199 return 1;
1200 }
1201 for (cpu = 0; cpu < nr_cpus; cpu++) {
1202 if (pipe2(&pipefd[cpu*2], O_CLOEXEC | O_NONBLOCK)) {
1203 perror("pipe");
1204 return 1;
1205 }
1206 }
1207
1208 if (posix_memalign(&area, page_size, page_size)) {
1209 fprintf(stderr, "out of memory\n");
1210 return 1;
1211 }
1212 zeropage = area;
1213 bzero(zeropage, page_size);
1214
1215 pthread_mutex_lock(&uffd_read_mutex);
1216
1217 pthread_attr_init(&attr);
1218 pthread_attr_setstacksize(&attr, 16*1024*1024);
1219
1220 err = 0;
1221 while (bounces--) {
1222 unsigned long expected_ioctls;
1223
1224 printf("bounces: %d, mode:", bounces);
1225 if (bounces & BOUNCE_RANDOM)
1226 printf(" rnd");
1227 if (bounces & BOUNCE_RACINGFAULTS)
1228 printf(" racing");
1229 if (bounces & BOUNCE_VERIFY)
1230 printf(" ver");
1231 if (bounces & BOUNCE_POLL)
1232 printf(" poll");
1233 printf(", ");
1234 fflush(stdout);
1235
1236 if (bounces & BOUNCE_POLL)
1237 fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1238 else
1239 fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1240
1241 /* register */
1242 uffdio_register.range.start = (unsigned long) area_dst;
1243 uffdio_register.range.len = nr_pages * page_size;
1244 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1245 if (test_uffdio_wp)
1246 uffdio_register.mode |= UFFDIO_REGISTER_MODE_WP;
1247 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1248 fprintf(stderr, "register failure\n");
1249 return 1;
1250 }
1251 expected_ioctls = uffd_test_ops->expected_ioctls;
1252 if ((uffdio_register.ioctls & expected_ioctls) !=
1253 expected_ioctls) {
1254 fprintf(stderr,
1255 "unexpected missing ioctl for anon memory\n");
1256 return 1;
1257 }
1258
1259 if (area_dst_alias) {
1260 uffdio_register.range.start = (unsigned long)
1261 area_dst_alias;
1262 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1263 fprintf(stderr, "register failure alias\n");
1264 return 1;
1265 }
1266 }
1267
1268 /*
1269 * The madvise done previously isn't enough: some
1270 * uffd_thread could have read userfaults (one of
1271 * those already resolved by the background thread)
1272 * and it may be in the process of calling
1273 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1274 * area_src and it would map a zero page in it (of
1275 * course such a UFFDIO_COPY is perfectly safe as it'd
1276 * return -EEXIST). The problem comes at the next
1277 * bounce though: that racing UFFDIO_COPY would
1278 * generate zeropages in the area_src, so invalidating
1279 * the previous MADV_DONTNEED. Without this additional
1280 * MADV_DONTNEED those zeropages leftovers in the
1281 * area_src would lead to -EEXIST failure during the
1282 * next bounce, effectively leaving a zeropage in the
1283 * area_dst.
1284 *
1285 * Try to comment this out madvise to see the memory
1286 * corruption being caught pretty quick.
1287 *
1288 * khugepaged is also inhibited to collapse THP after
1289 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1290 * required to MADV_DONTNEED here.
1291 */
1292 if (uffd_test_ops->release_pages(area_dst))
1293 return 1;
1294
1295 uffd_stats_reset(uffd_stats, nr_cpus);
1296
1297 /* bounce pass */
1298 if (stress(uffd_stats))
1299 return 1;
1300
1301 /* Clear all the write protections if there is any */
1302 if (test_uffdio_wp)
1303 wp_range(uffd, (unsigned long)area_dst,
1304 nr_pages * page_size, false);
1305
1306 /* unregister */
1307 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range)) {
1308 fprintf(stderr, "unregister failure\n");
1309 return 1;
1310 }
1311 if (area_dst_alias) {
1312 uffdio_register.range.start = (unsigned long) area_dst;
1313 if (ioctl(uffd, UFFDIO_UNREGISTER,
1314 &uffdio_register.range)) {
1315 fprintf(stderr, "unregister failure alias\n");
1316 return 1;
1317 }
1318 }
1319
1320 /* verification */
1321 if (bounces & BOUNCE_VERIFY) {
1322 for (nr = 0; nr < nr_pages; nr++) {
1323 if (*area_count(area_dst, nr) != count_verify[nr]) {
1324 fprintf(stderr,
1325 "error area_count %Lu %Lu %lu\n",
1326 *area_count(area_src, nr),
1327 count_verify[nr],
1328 nr);
1329 err = 1;
1330 bounces = 0;
1331 }
1332 }
1333 }
1334
1335 /* prepare next bounce */
1336 tmp_area = area_src;
1337 area_src = area_dst;
1338 area_dst = tmp_area;
1339
1340 tmp_area = area_src_alias;
1341 area_src_alias = area_dst_alias;
1342 area_dst_alias = tmp_area;
1343
1344 uffd_stats_report(uffd_stats, nr_cpus);
1345 }
1346
1347 if (err)
1348 return err;
1349
1350 close(uffd);
1351 return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1352 || userfaultfd_events_test();
1353}
1354
1355/*
1356 * Copied from mlock2-tests.c
1357 */
1358unsigned long default_huge_page_size(void)
1359{
1360 unsigned long hps = 0;
1361 char *line = NULL;
1362 size_t linelen = 0;
1363 FILE *f = fopen("/proc/meminfo", "r");
1364
1365 if (!f)
1366 return 0;
1367 while (getline(&line, &linelen, f) > 0) {
1368 if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) {
1369 hps <<= 10;
1370 break;
1371 }
1372 }
1373
1374 free(line);
1375 fclose(f);
1376 return hps;
1377}
1378
1379static void set_test_type(const char *type)
1380{
1381 if (!strcmp(type, "anon")) {
1382 test_type = TEST_ANON;
1383 uffd_test_ops = &anon_uffd_test_ops;
1384 /* Only enable write-protect test for anonymous test */
1385 test_uffdio_wp = true;
1386 } else if (!strcmp(type, "hugetlb")) {
1387 test_type = TEST_HUGETLB;
1388 uffd_test_ops = &hugetlb_uffd_test_ops;
1389 } else if (!strcmp(type, "hugetlb_shared")) {
1390 map_shared = true;
1391 test_type = TEST_HUGETLB;
1392 uffd_test_ops = &hugetlb_uffd_test_ops;
1393 } else if (!strcmp(type, "shmem")) {
1394 map_shared = true;
1395 test_type = TEST_SHMEM;
1396 uffd_test_ops = &shmem_uffd_test_ops;
1397 } else {
1398 fprintf(stderr, "Unknown test type: %s\n", type), exit(1);
1399 }
1400
1401 if (test_type == TEST_HUGETLB)
1402 page_size = default_huge_page_size();
1403 else
1404 page_size = sysconf(_SC_PAGE_SIZE);
1405
1406 if (!page_size)
1407 fprintf(stderr, "Unable to determine page size\n"),
1408 exit(2);
1409 if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1410 > page_size)
1411 fprintf(stderr, "Impossible to run this test\n"), exit(2);
1412}
1413
1414static void sigalrm(int sig)
1415{
1416 if (sig != SIGALRM)
1417 abort();
1418 test_uffdio_copy_eexist = true;
1419 test_uffdio_zeropage_eexist = true;
1420 alarm(ALARM_INTERVAL_SECS);
1421}
1422
1423int main(int argc, char **argv)
1424{
1425 if (argc < 4)
1426 usage();
1427
1428 if (signal(SIGALRM, sigalrm) == SIG_ERR)
1429 fprintf(stderr, "failed to arm SIGALRM"), exit(1);
1430 alarm(ALARM_INTERVAL_SECS);
1431
1432 set_test_type(argv[1]);
1433
1434 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1435 nr_pages_per_cpu = atol(argv[2]) * 1024*1024 / page_size /
1436 nr_cpus;
1437 if (!nr_pages_per_cpu) {
1438 fprintf(stderr, "invalid MiB\n");
1439 usage();
1440 }
1441
1442 bounces = atoi(argv[3]);
1443 if (bounces <= 0) {
1444 fprintf(stderr, "invalid bounces\n");
1445 usage();
1446 }
1447 nr_pages = nr_pages_per_cpu * nr_cpus;
1448
1449 if (test_type == TEST_HUGETLB) {
1450 if (argc < 5)
1451 usage();
1452 huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1453 if (huge_fd < 0) {
1454 fprintf(stderr, "Open of %s failed", argv[3]);
1455 perror("open");
1456 exit(1);
1457 }
1458 if (ftruncate(huge_fd, 0)) {
1459 fprintf(stderr, "ftruncate %s to size 0 failed", argv[3]);
1460 perror("ftruncate");
1461 exit(1);
1462 }
1463 }
1464 printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1465 nr_pages, nr_pages_per_cpu);
1466 return userfaultfd_stress();
1467}
1468
1469#else /* __NR_userfaultfd */
1470
1471#warning "missing __NR_userfaultfd definition"
1472
1473int main(void)
1474{
1475 printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1476 return KSFT_SKIP;
1477}
1478
1479#endif /* __NR_userfaultfd */