Linux Audio

Check our new training course

Loading...
Note: File does not exist in v3.5.6.
   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 */