Linux Audio

Check our new training course

Loading...
v6.2
   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 */
v4.17
 
   1/*
   2 * Stress userfaultfd syscall.
   3 *
   4 *  Copyright (C) 2015  Red Hat, Inc.
   5 *
   6 *  This work is licensed under the terms of the GNU GPL, version 2. See
   7 *  the COPYING file in the top-level directory.
   8 *
   9 * This test allocates two virtual areas and bounces the physical
  10 * memory across the two virtual areas (from area_src to area_dst)
  11 * using userfaultfd.
  12 *
  13 * There are three threads running per CPU:
  14 *
  15 * 1) one per-CPU thread takes a per-page pthread_mutex in a random
  16 *    page of the area_dst (while the physical page may still be in
  17 *    area_src), and increments a per-page counter in the same page,
  18 *    and checks its value against a verification region.
  19 *
  20 * 2) another per-CPU thread handles the userfaults generated by
  21 *    thread 1 above. userfaultfd blocking reads or poll() modes are
  22 *    exercised interleaved.
  23 *
  24 * 3) one last per-CPU thread transfers the memory in the background
  25 *    at maximum bandwidth (if not already transferred by thread
  26 *    2). Each cpu thread takes cares of transferring a portion of the
  27 *    area.
  28 *
  29 * When all threads of type 3 completed the transfer, one bounce is
  30 * complete. area_src and area_dst are then swapped. All threads are
  31 * respawned and so the bounce is immediately restarted in the
  32 * opposite direction.
  33 *
  34 * per-CPU threads 1 by triggering userfaults inside
  35 * pthread_mutex_lock will also verify the atomicity of the memory
  36 * transfer (UFFDIO_COPY).
  37 *
  38 * The program takes two parameters: the amounts of physical memory in
  39 * megabytes (MiB) of the area and the number of bounces to execute.
  40 *
  41 * # 100MiB 99999 bounces
  42 * ./userfaultfd 100 99999
  43 *
  44 * # 1GiB 99 bounces
  45 * ./userfaultfd 1000 99
  46 *
  47 * # 10MiB-~6GiB 999 bounces, continue forever unless an error triggers
  48 * while ./userfaultfd $[RANDOM % 6000 + 10] 999; do true; done
  49 */
  50
  51#define _GNU_SOURCE
  52#include <stdio.h>
  53#include <errno.h>
  54#include <unistd.h>
  55#include <stdlib.h>
  56#include <sys/types.h>
  57#include <sys/stat.h>
  58#include <fcntl.h>
  59#include <time.h>
  60#include <signal.h>
  61#include <poll.h>
  62#include <string.h>
 
  63#include <sys/mman.h>
  64#include <sys/syscall.h>
  65#include <sys/ioctl.h>
  66#include <sys/wait.h>
  67#include <pthread.h>
  68#include <linux/userfaultfd.h>
  69#include <setjmp.h>
  70#include <stdbool.h>
 
 
 
 
 
 
 
  71
  72#ifdef __NR_userfaultfd
  73
  74static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size;
  75
  76#define BOUNCE_RANDOM		(1<<0)
  77#define BOUNCE_RACINGFAULTS	(1<<1)
  78#define BOUNCE_VERIFY		(1<<2)
  79#define BOUNCE_POLL		(1<<3)
  80static int bounces;
  81
  82#define TEST_ANON	1
  83#define TEST_HUGETLB	2
  84#define TEST_SHMEM	3
  85static int test_type;
  86
 
 
 
 
 
 
 
  87/* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
  88#define ALARM_INTERVAL_SECS 10
  89static volatile bool test_uffdio_copy_eexist = true;
  90static volatile bool test_uffdio_zeropage_eexist = true;
  91
 
 
 
  92static bool map_shared;
  93static int huge_fd;
  94static char *huge_fd_off0;
  95static unsigned long long *count_verify;
  96static int uffd, uffd_flags, finished, *pipefd;
  97static char *area_src, *area_src_alias, *area_dst, *area_dst_alias;
 
  98static char *zeropage;
  99pthread_attr_t attr;
 
 
 
 
 
 
 
 
 
 100
 101/* pthread_mutex_t starts at page offset 0 */
 102#define area_mutex(___area, ___nr)					\
 103	((pthread_mutex_t *) ((___area) + (___nr)*page_size))
 104/*
 105 * count is placed in the page after pthread_mutex_t naturally aligned
 106 * to avoid non alignment faults on non-x86 archs.
 107 */
 108#define area_count(___area, ___nr)					\
 109	((volatile unsigned long long *) ((unsigned long)		\
 110				 ((___area) + (___nr)*page_size +	\
 111				  sizeof(pthread_mutex_t) +		\
 112				  sizeof(unsigned long long) - 1) &	\
 113				 ~(unsigned long)(sizeof(unsigned long long) \
 114						  -  1)))
 115
 116static int anon_release_pages(char *rel_area)
 117{
 118	int ret = 0;
 
 119
 120	if (madvise(rel_area, nr_pages * page_size, MADV_DONTNEED)) {
 121		perror("madvise");
 122		ret = 1;
 123	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 124
 125	return ret;
 
 
 
 126}
 127
 128static void anon_allocate_area(void **alloc_area)
 129{
 130	if (posix_memalign(alloc_area, page_size, nr_pages * page_size)) {
 131		fprintf(stderr, "out of memory\n");
 132		*alloc_area = NULL;
 133	}
 134}
 135
 136static void noop_alias_mapping(__u64 *start, size_t len, unsigned long offset)
 137{
 138}
 139
 140/* HugeTLB memory */
 141static int hugetlb_release_pages(char *rel_area)
 142{
 143	int ret = 0;
 144
 145	if (fallocate(huge_fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
 146				rel_area == huge_fd_off0 ? 0 :
 147				nr_pages * page_size,
 148				nr_pages * page_size)) {
 149		perror("fallocate");
 150		ret = 1;
 151	}
 152
 153	return ret;
 154}
 155
 156
 157static void hugetlb_allocate_area(void **alloc_area)
 158{
 
 
 159	void *area_alias = NULL;
 160	char **alloc_area_alias;
 161	*alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
 
 162			   (map_shared ? MAP_SHARED : MAP_PRIVATE) |
 163			   MAP_HUGETLB,
 164			   huge_fd, *alloc_area == area_src ? 0 :
 165			   nr_pages * page_size);
 166	if (*alloc_area == MAP_FAILED) {
 167		fprintf(stderr, "mmap of hugetlbfs file failed\n");
 168		*alloc_area = NULL;
 169	}
 170
 171	if (map_shared) {
 172		area_alias = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
 173				  MAP_SHARED | MAP_HUGETLB,
 174				  huge_fd, *alloc_area == area_src ? 0 :
 175				  nr_pages * page_size);
 176		if (area_alias == MAP_FAILED) {
 177			if (munmap(*alloc_area, nr_pages * page_size) < 0)
 178				perror("hugetlb munmap"), exit(1);
 179			*alloc_area = NULL;
 180			return;
 181		}
 182	}
 183	if (*alloc_area == area_src) {
 184		huge_fd_off0 = *alloc_area;
 185		alloc_area_alias = &area_src_alias;
 186	} else {
 187		alloc_area_alias = &area_dst_alias;
 188	}
 189	if (area_alias)
 190		*alloc_area_alias = area_alias;
 191}
 192
 193static void hugetlb_alias_mapping(__u64 *start, size_t len, unsigned long offset)
 194{
 195	if (!map_shared)
 196		return;
 197	/*
 198	 * We can't zap just the pagetable with hugetlbfs because
 199	 * MADV_DONTEED won't work. So exercise -EEXIST on a alias
 200	 * mapping where the pagetables are not established initially,
 201	 * this way we'll exercise the -EEXEC at the fs level.
 202	 */
 203	*start = (unsigned long) area_dst_alias + offset;
 204}
 205
 206/* Shared memory */
 207static int shmem_release_pages(char *rel_area)
 
 
 
 
 
 208{
 209	int ret = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 210
 211	if (madvise(rel_area, nr_pages * page_size, MADV_REMOVE)) {
 212		perror("madvise");
 213		ret = 1;
 214	}
 
 215
 216	return ret;
 
 
 217}
 218
 219static void shmem_allocate_area(void **alloc_area)
 220{
 221	*alloc_area = mmap(NULL, nr_pages * page_size, PROT_READ | PROT_WRITE,
 222			   MAP_ANONYMOUS | MAP_SHARED, -1, 0);
 223	if (*alloc_area == MAP_FAILED) {
 224		fprintf(stderr, "shared memory mmap failed\n");
 225		*alloc_area = NULL;
 226	}
 227}
 228
 229struct uffd_test_ops {
 230	unsigned long expected_ioctls;
 231	void (*allocate_area)(void **alloc_area);
 232	int (*release_pages)(char *rel_area);
 233	void (*alias_mapping)(__u64 *start, size_t len, unsigned long offset);
 
 234};
 235
 236#define ANON_EXPECTED_IOCTLS		((1 << _UFFDIO_WAKE) | \
 237					 (1 << _UFFDIO_COPY) | \
 238					 (1 << _UFFDIO_ZEROPAGE))
 239
 240static struct uffd_test_ops anon_uffd_test_ops = {
 241	.expected_ioctls = ANON_EXPECTED_IOCTLS,
 242	.allocate_area	= anon_allocate_area,
 243	.release_pages	= anon_release_pages,
 244	.alias_mapping = noop_alias_mapping,
 
 245};
 246
 247static struct uffd_test_ops shmem_uffd_test_ops = {
 248	.expected_ioctls = ANON_EXPECTED_IOCTLS,
 249	.allocate_area	= shmem_allocate_area,
 250	.release_pages	= shmem_release_pages,
 251	.alias_mapping = noop_alias_mapping,
 
 252};
 253
 254static struct uffd_test_ops hugetlb_uffd_test_ops = {
 255	.expected_ioctls = UFFD_API_RANGE_IOCTLS_BASIC,
 256	.allocate_area	= hugetlb_allocate_area,
 257	.release_pages	= hugetlb_release_pages,
 258	.alias_mapping = hugetlb_alias_mapping,
 
 259};
 260
 261static struct uffd_test_ops *uffd_test_ops;
 262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 263static int my_bcmp(char *str1, char *str2, size_t n)
 264{
 265	unsigned long i;
 266	for (i = 0; i < n; i++)
 267		if (str1[i] != str2[i])
 268			return 1;
 269	return 0;
 270}
 271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 272static void *locking_thread(void *arg)
 273{
 274	unsigned long cpu = (unsigned long) arg;
 275	struct random_data rand;
 276	unsigned long page_nr = *(&(page_nr)); /* uninitialized warning */
 277	int32_t rand_nr;
 278	unsigned long long count;
 279	char randstate[64];
 280	unsigned int seed;
 281	time_t start;
 282
 283	if (bounces & BOUNCE_RANDOM) {
 284		seed = (unsigned int) time(NULL) - bounces;
 285		if (!(bounces & BOUNCE_RACINGFAULTS))
 286			seed += cpu;
 287		bzero(&rand, sizeof(rand));
 288		bzero(&randstate, sizeof(randstate));
 289		if (initstate_r(seed, randstate, sizeof(randstate), &rand))
 290			fprintf(stderr, "srandom_r error\n"), exit(1);
 291	} else {
 292		page_nr = -bounces;
 293		if (!(bounces & BOUNCE_RACINGFAULTS))
 294			page_nr += cpu * nr_pages_per_cpu;
 295	}
 296
 297	while (!finished) {
 298		if (bounces & BOUNCE_RANDOM) {
 299			if (random_r(&rand, &rand_nr))
 300				fprintf(stderr, "random_r 1 error\n"), exit(1);
 301			page_nr = rand_nr;
 302			if (sizeof(page_nr) > sizeof(rand_nr)) {
 303				if (random_r(&rand, &rand_nr))
 304					fprintf(stderr, "random_r 2 error\n"), exit(1);
 305				page_nr |= (((unsigned long) rand_nr) << 16) <<
 306					   16;
 307			}
 308		} else
 309			page_nr += 1;
 310		page_nr %= nr_pages;
 311
 312		start = time(NULL);
 313		if (bounces & BOUNCE_VERIFY) {
 314			count = *area_count(area_dst, page_nr);
 315			if (!count)
 316				fprintf(stderr,
 317					"page_nr %lu wrong count %Lu %Lu\n",
 318					page_nr, count,
 319					count_verify[page_nr]), exit(1);
 320
 321
 322			/*
 323			 * We can't use bcmp (or memcmp) because that
 324			 * returns 0 erroneously if the memory is
 325			 * changing under it (even if the end of the
 326			 * page is never changing and always
 327			 * different).
 328			 */
 329#if 1
 330			if (!my_bcmp(area_dst + page_nr * page_size, zeropage,
 331				     page_size))
 332				fprintf(stderr,
 333					"my_bcmp page_nr %lu wrong count %Lu %Lu\n",
 334					page_nr, count,
 335					count_verify[page_nr]), exit(1);
 336#else
 337			unsigned long loops;
 338
 339			loops = 0;
 340			/* uncomment the below line to test with mutex */
 341			/* pthread_mutex_lock(area_mutex(area_dst, page_nr)); */
 342			while (!bcmp(area_dst + page_nr * page_size, zeropage,
 343				     page_size)) {
 344				loops += 1;
 345				if (loops > 10)
 346					break;
 347			}
 348			/* uncomment below line to test with mutex */
 349			/* pthread_mutex_unlock(area_mutex(area_dst, page_nr)); */
 350			if (loops) {
 351				fprintf(stderr,
 352					"page_nr %lu all zero thread %lu %p %lu\n",
 353					page_nr, cpu, area_dst + page_nr * page_size,
 354					loops);
 355				if (loops > 10)
 356					exit(1);
 357			}
 358#endif
 359		}
 360
 361		pthread_mutex_lock(area_mutex(area_dst, page_nr));
 362		count = *area_count(area_dst, page_nr);
 363		if (count != count_verify[page_nr]) {
 364			fprintf(stderr,
 365				"page_nr %lu memory corruption %Lu %Lu\n",
 366				page_nr, count,
 367				count_verify[page_nr]), exit(1);
 368		}
 369		count++;
 370		*area_count(area_dst, page_nr) = count_verify[page_nr] = count;
 371		pthread_mutex_unlock(area_mutex(area_dst, page_nr));
 372
 373		if (time(NULL) - start > 1)
 374			fprintf(stderr,
 375				"userfault too slow %ld "
 376				"possible false positive with overcommit\n",
 377				time(NULL) - start);
 378	}
 379
 380	return NULL;
 381}
 382
 383static void retry_copy_page(int ufd, struct uffdio_copy *uffdio_copy,
 384			    unsigned long offset)
 385{
 386	uffd_test_ops->alias_mapping(&uffdio_copy->dst,
 387				     uffdio_copy->len,
 388				     offset);
 389	if (ioctl(ufd, UFFDIO_COPY, uffdio_copy)) {
 390		/* real retval in ufdio_copy.copy */
 391		if (uffdio_copy->copy != -EEXIST)
 392			fprintf(stderr, "UFFDIO_COPY retry error %Ld\n",
 393				uffdio_copy->copy), exit(1);
 394	} else {
 395		fprintf(stderr,	"UFFDIO_COPY retry unexpected %Ld\n",
 396			uffdio_copy->copy), exit(1);
 397	}
 398}
 399
 
 
 
 
 
 
 
 
 
 
 
 
 400static int __copy_page(int ufd, unsigned long offset, bool retry)
 401{
 402	struct uffdio_copy uffdio_copy;
 403
 404	if (offset >= nr_pages * page_size)
 405		fprintf(stderr, "unexpected offset %lu\n",
 406			offset), exit(1);
 407	uffdio_copy.dst = (unsigned long) area_dst + offset;
 408	uffdio_copy.src = (unsigned long) area_src + offset;
 409	uffdio_copy.len = page_size;
 410	uffdio_copy.mode = 0;
 
 
 
 411	uffdio_copy.copy = 0;
 412	if (ioctl(ufd, UFFDIO_COPY, &uffdio_copy)) {
 413		/* real retval in ufdio_copy.copy */
 414		if (uffdio_copy.copy != -EEXIST)
 415			fprintf(stderr, "UFFDIO_COPY error %Ld\n",
 416				uffdio_copy.copy), exit(1);
 
 417	} else if (uffdio_copy.copy != page_size) {
 418		fprintf(stderr, "UFFDIO_COPY unexpected copy %Ld\n",
 419			uffdio_copy.copy), exit(1);
 420	} else {
 421		if (test_uffdio_copy_eexist && retry) {
 422			test_uffdio_copy_eexist = false;
 423			retry_copy_page(ufd, &uffdio_copy, offset);
 424		}
 425		return 1;
 426	}
 427	return 0;
 428}
 429
 430static int copy_page_retry(int ufd, unsigned long offset)
 431{
 432	return __copy_page(ufd, offset, true);
 433}
 434
 435static int copy_page(int ufd, unsigned long offset)
 436{
 437	return __copy_page(ufd, offset, false);
 438}
 439
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 440static void *uffd_poll_thread(void *arg)
 441{
 442	unsigned long cpu = (unsigned long) arg;
 
 443	struct pollfd pollfd[2];
 444	struct uffd_msg msg;
 445	struct uffdio_register uffd_reg;
 446	int ret;
 447	unsigned long offset;
 448	char tmp_chr;
 449	unsigned long userfaults = 0;
 450
 451	pollfd[0].fd = uffd;
 452	pollfd[0].events = POLLIN;
 453	pollfd[1].fd = pipefd[cpu*2];
 454	pollfd[1].events = POLLIN;
 455
 456	for (;;) {
 457		ret = poll(pollfd, 2, -1);
 458		if (!ret)
 459			fprintf(stderr, "poll error %d\n", ret), exit(1);
 460		if (ret < 0)
 461			perror("poll"), exit(1);
 
 462		if (pollfd[1].revents & POLLIN) {
 463			if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
 464				fprintf(stderr, "read pipefd error\n"),
 465					exit(1);
 466			break;
 467		}
 468		if (!(pollfd[0].revents & POLLIN))
 469			fprintf(stderr, "pollfd[0].revents %d\n",
 470				pollfd[0].revents), exit(1);
 471		ret = read(uffd, &msg, sizeof(msg));
 472		if (ret < 0) {
 473			if (errno == EAGAIN)
 474				continue;
 475			perror("nonblocking read error"), exit(1);
 476		}
 477		switch (msg.event) {
 478		default:
 479			fprintf(stderr, "unexpected msg event %u\n",
 480				msg.event), exit(1);
 481			break;
 482		case UFFD_EVENT_PAGEFAULT:
 483			if (msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
 484				fprintf(stderr, "unexpected write fault\n"), exit(1);
 485			offset = (char *)(unsigned long)msg.arg.pagefault.address -
 486				area_dst;
 487			offset &= ~(page_size-1);
 488			if (copy_page(uffd, offset))
 489				userfaults++;
 490			break;
 491		case UFFD_EVENT_FORK:
 492			close(uffd);
 493			uffd = msg.arg.fork.ufd;
 494			pollfd[0].fd = uffd;
 495			break;
 496		case UFFD_EVENT_REMOVE:
 497			uffd_reg.range.start = msg.arg.remove.start;
 498			uffd_reg.range.len = msg.arg.remove.end -
 499				msg.arg.remove.start;
 500			if (ioctl(uffd, UFFDIO_UNREGISTER, &uffd_reg.range))
 501				fprintf(stderr, "remove failure\n"), exit(1);
 502			break;
 503		case UFFD_EVENT_REMAP:
 
 504			area_dst = (char *)(unsigned long)msg.arg.remap.to;
 505			break;
 506		}
 507	}
 508	return (void *)userfaults;
 
 509}
 510
 511pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
 512
 513static void *uffd_read_thread(void *arg)
 514{
 515	unsigned long *this_cpu_userfaults;
 516	struct uffd_msg msg;
 517	unsigned long offset;
 518	int ret;
 519
 520	this_cpu_userfaults = (unsigned long *) arg;
 521	*this_cpu_userfaults = 0;
 522
 523	pthread_mutex_unlock(&uffd_read_mutex);
 524	/* from here cancellation is ok */
 525
 526	for (;;) {
 527		ret = read(uffd, &msg, sizeof(msg));
 528		if (ret != sizeof(msg)) {
 529			if (ret < 0)
 530				perror("blocking read error"), exit(1);
 531			else
 532				fprintf(stderr, "short read\n"), exit(1);
 533		}
 534		if (msg.event != UFFD_EVENT_PAGEFAULT)
 535			fprintf(stderr, "unexpected msg event %u\n",
 536				msg.event), exit(1);
 537		if (bounces & BOUNCE_VERIFY &&
 538		    msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
 539			fprintf(stderr, "unexpected write fault\n"), exit(1);
 540		offset = (char *)(unsigned long)msg.arg.pagefault.address -
 541			 area_dst;
 542		offset &= ~(page_size-1);
 543		if (copy_page(uffd, offset))
 544			(*this_cpu_userfaults)++;
 545	}
 546	return (void *)NULL;
 
 547}
 548
 549static void *background_thread(void *arg)
 550{
 551	unsigned long cpu = (unsigned long) arg;
 552	unsigned long page_nr;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 553
 554	for (page_nr = cpu * nr_pages_per_cpu;
 555	     page_nr < (cpu+1) * nr_pages_per_cpu;
 556	     page_nr++)
 
 
 557		copy_page_retry(uffd, page_nr * page_size);
 558
 559	return NULL;
 560}
 561
 562static int stress(unsigned long *userfaults)
 563{
 564	unsigned long cpu;
 565	pthread_t locking_threads[nr_cpus];
 566	pthread_t uffd_threads[nr_cpus];
 567	pthread_t background_threads[nr_cpus];
 568	void **_userfaults = (void **) userfaults;
 569
 570	finished = 0;
 571	for (cpu = 0; cpu < nr_cpus; cpu++) {
 572		if (pthread_create(&locking_threads[cpu], &attr,
 573				   locking_thread, (void *)cpu))
 574			return 1;
 575		if (bounces & BOUNCE_POLL) {
 576			if (pthread_create(&uffd_threads[cpu], &attr,
 577					   uffd_poll_thread, (void *)cpu))
 
 578				return 1;
 579		} else {
 580			if (pthread_create(&uffd_threads[cpu], &attr,
 581					   uffd_read_thread,
 582					   &_userfaults[cpu]))
 583				return 1;
 584			pthread_mutex_lock(&uffd_read_mutex);
 585		}
 586		if (pthread_create(&background_threads[cpu], &attr,
 587				   background_thread, (void *)cpu))
 588			return 1;
 589	}
 590	for (cpu = 0; cpu < nr_cpus; cpu++)
 591		if (pthread_join(background_threads[cpu], NULL))
 592			return 1;
 593
 594	/*
 595	 * Be strict and immediately zap area_src, the whole area has
 596	 * been transferred already by the background treads. The
 597	 * area_src could then be faulted in in a racy way by still
 598	 * running uffdio_threads reading zeropages after we zapped
 599	 * area_src (but they're guaranteed to get -EEXIST from
 600	 * UFFDIO_COPY without writing zero pages into area_dst
 601	 * because the background threads already completed).
 602	 */
 603	if (uffd_test_ops->release_pages(area_src))
 604		return 1;
 
 
 
 
 605
 606	for (cpu = 0; cpu < nr_cpus; cpu++) {
 607		char c;
 608		if (bounces & BOUNCE_POLL) {
 609			if (write(pipefd[cpu*2+1], &c, 1) != 1) {
 610				fprintf(stderr, "pipefd write error\n");
 611				return 1;
 612			}
 613			if (pthread_join(uffd_threads[cpu], &_userfaults[cpu]))
 614				return 1;
 615		} else {
 616			if (pthread_cancel(uffd_threads[cpu]))
 617				return 1;
 618			if (pthread_join(uffd_threads[cpu], NULL))
 619				return 1;
 620		}
 621	}
 622
 623	finished = 1;
 624	for (cpu = 0; cpu < nr_cpus; cpu++)
 625		if (pthread_join(locking_threads[cpu], NULL))
 626			return 1;
 627
 628	return 0;
 629}
 630
 631static int userfaultfd_open(int features)
 632{
 633	struct uffdio_api uffdio_api;
 634
 635	uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
 636	if (uffd < 0) {
 637		fprintf(stderr,
 638			"userfaultfd syscall not available in this kernel\n");
 639		return 1;
 640	}
 641	uffd_flags = fcntl(uffd, F_GETFD, NULL);
 642
 643	uffdio_api.api = UFFD_API;
 644	uffdio_api.features = features;
 645	if (ioctl(uffd, UFFDIO_API, &uffdio_api)) {
 646		fprintf(stderr, "UFFDIO_API\n");
 647		return 1;
 648	}
 649	if (uffdio_api.api != UFFD_API) {
 650		fprintf(stderr, "UFFDIO_API error %Lu\n", uffdio_api.api);
 651		return 1;
 652	}
 653
 654	return 0;
 655}
 656
 657sigjmp_buf jbuf, *sigbuf;
 658
 659static void sighndl(int sig, siginfo_t *siginfo, void *ptr)
 660{
 661	if (sig == SIGBUS) {
 662		if (sigbuf)
 663			siglongjmp(*sigbuf, 1);
 664		abort();
 665	}
 666}
 667
 668/*
 669 * For non-cooperative userfaultfd test we fork() a process that will
 670 * generate pagefaults, will mremap the area monitored by the
 671 * userfaultfd and at last this process will release the monitored
 672 * area.
 673 * For the anonymous and shared memory the area is divided into two
 674 * parts, the first part is accessed before mremap, and the second
 675 * part is accessed after mremap. Since hugetlbfs does not support
 676 * mremap, the entire monitored area is accessed in a single pass for
 677 * HUGETLB_TEST.
 678 * The release of the pages currently generates event for shmem and
 679 * anonymous memory (UFFD_EVENT_REMOVE), hence it is not checked
 680 * for hugetlb.
 681 * For signal test(UFFD_FEATURE_SIGBUS), signal_test = 1, we register
 682 * monitored area, generate pagefaults and test that signal is delivered.
 683 * Use UFFDIO_COPY to allocate missing page and retry. For signal_test = 2
 684 * test robustness use case - we release monitored area, fork a process
 685 * that will generate pagefaults and verify signal is generated.
 686 * This also tests UFFD_FEATURE_EVENT_FORK event along with the signal
 687 * feature. Using monitor thread, verify no userfault events are generated.
 688 */
 689static int faulting_process(int signal_test)
 690{
 691	unsigned long nr;
 692	unsigned long long count;
 693	unsigned long split_nr_pages;
 694	unsigned long lastnr;
 695	struct sigaction act;
 696	unsigned long signalled = 0;
 697
 698	if (test_type != TEST_HUGETLB)
 699		split_nr_pages = (nr_pages + 1) / 2;
 700	else
 701		split_nr_pages = nr_pages;
 702
 703	if (signal_test) {
 704		sigbuf = &jbuf;
 705		memset(&act, 0, sizeof(act));
 706		act.sa_sigaction = sighndl;
 707		act.sa_flags = SA_SIGINFO;
 708		if (sigaction(SIGBUS, &act, 0)) {
 709			perror("sigaction");
 710			return 1;
 711		}
 712		lastnr = (unsigned long)-1;
 713	}
 714
 715	for (nr = 0; nr < split_nr_pages; nr++) {
 
 
 
 716		if (signal_test) {
 717			if (sigsetjmp(*sigbuf, 1) != 0) {
 718				if (nr == lastnr) {
 719					fprintf(stderr, "Signal repeated\n");
 720					return 1;
 721				}
 722
 723				lastnr = nr;
 724				if (signal_test == 1) {
 725					if (copy_page(uffd, nr * page_size))
 726						signalled++;
 
 
 
 
 
 
 
 
 
 
 
 727				} else {
 728					signalled++;
 729					continue;
 730				}
 731			}
 732		}
 733
 734		count = *area_count(area_dst, nr);
 735		if (count != count_verify[nr]) {
 736			fprintf(stderr,
 737				"nr %lu memory corruption %Lu %Lu\n",
 738				nr, count,
 739				count_verify[nr]), exit(1);
 740		}
 
 
 741	}
 742
 743	if (signal_test)
 744		return signalled != split_nr_pages;
 745
 746	if (test_type == TEST_HUGETLB)
 747		return 0;
 748
 749	area_dst = mremap(area_dst, nr_pages * page_size,  nr_pages * page_size,
 750			  MREMAP_MAYMOVE | MREMAP_FIXED, area_src);
 751	if (area_dst == MAP_FAILED)
 752		perror("mremap"), exit(1);
 
 
 753
 754	for (; nr < nr_pages; nr++) {
 755		count = *area_count(area_dst, nr);
 756		if (count != count_verify[nr]) {
 757			fprintf(stderr,
 758				"nr %lu memory corruption %Lu %Lu\n",
 759				nr, count,
 760				count_verify[nr]), exit(1);
 761		}
 
 
 
 
 
 762	}
 763
 764	if (uffd_test_ops->release_pages(area_dst))
 765		return 1;
 766
 767	for (nr = 0; nr < nr_pages; nr++) {
 768		if (my_bcmp(area_dst + nr * page_size, zeropage, page_size))
 769			fprintf(stderr, "nr %lu is not zero\n", nr), exit(1);
 770	}
 771
 772	return 0;
 773}
 774
 775static void retry_uffdio_zeropage(int ufd,
 776				  struct uffdio_zeropage *uffdio_zeropage,
 777				  unsigned long offset)
 778{
 779	uffd_test_ops->alias_mapping(&uffdio_zeropage->range.start,
 780				     uffdio_zeropage->range.len,
 781				     offset);
 782	if (ioctl(ufd, UFFDIO_ZEROPAGE, uffdio_zeropage)) {
 783		if (uffdio_zeropage->zeropage != -EEXIST)
 784			fprintf(stderr, "UFFDIO_ZEROPAGE retry error %Ld\n",
 785				uffdio_zeropage->zeropage), exit(1);
 786	} else {
 787		fprintf(stderr, "UFFDIO_ZEROPAGE retry unexpected %Ld\n",
 788			uffdio_zeropage->zeropage), exit(1);
 789	}
 790}
 791
 792static int __uffdio_zeropage(int ufd, unsigned long offset, bool retry)
 793{
 794	struct uffdio_zeropage uffdio_zeropage;
 795	int ret;
 796	unsigned long has_zeropage;
 797
 798	has_zeropage = uffd_test_ops->expected_ioctls & (1 << _UFFDIO_ZEROPAGE);
 799
 800	if (offset >= nr_pages * page_size)
 801		fprintf(stderr, "unexpected offset %lu\n",
 802			offset), exit(1);
 803	uffdio_zeropage.range.start = (unsigned long) area_dst + offset;
 804	uffdio_zeropage.range.len = page_size;
 805	uffdio_zeropage.mode = 0;
 806	ret = ioctl(ufd, UFFDIO_ZEROPAGE, &uffdio_zeropage);
 
 807	if (ret) {
 808		/* real retval in ufdio_zeropage.zeropage */
 809		if (has_zeropage) {
 810			if (uffdio_zeropage.zeropage == -EEXIST)
 811				fprintf(stderr, "UFFDIO_ZEROPAGE -EEXIST\n"),
 812					exit(1);
 813			else
 814				fprintf(stderr, "UFFDIO_ZEROPAGE error %Ld\n",
 815					uffdio_zeropage.zeropage), exit(1);
 816		} else {
 817			if (uffdio_zeropage.zeropage != -EINVAL)
 818				fprintf(stderr,
 819					"UFFDIO_ZEROPAGE not -EINVAL %Ld\n",
 820					uffdio_zeropage.zeropage), exit(1);
 821		}
 822	} else if (has_zeropage) {
 823		if (uffdio_zeropage.zeropage != page_size) {
 824			fprintf(stderr, "UFFDIO_ZEROPAGE unexpected %Ld\n",
 825				uffdio_zeropage.zeropage), exit(1);
 826		} else {
 827			if (test_uffdio_zeropage_eexist && retry) {
 828				test_uffdio_zeropage_eexist = false;
 829				retry_uffdio_zeropage(ufd, &uffdio_zeropage,
 830						      offset);
 831			}
 832			return 1;
 833		}
 834	} else {
 835		fprintf(stderr,
 836			"UFFDIO_ZEROPAGE succeeded %Ld\n",
 837			uffdio_zeropage.zeropage), exit(1);
 838	}
 839
 840	return 0;
 841}
 842
 843static int uffdio_zeropage(int ufd, unsigned long offset)
 844{
 845	return __uffdio_zeropage(ufd, offset, false);
 846}
 847
 848/* exercise UFFDIO_ZEROPAGE */
 849static int userfaultfd_zeropage_test(void)
 850{
 851	struct uffdio_register uffdio_register;
 852	unsigned long expected_ioctls;
 853
 854	printf("testing UFFDIO_ZEROPAGE: ");
 855	fflush(stdout);
 856
 857	if (uffd_test_ops->release_pages(area_dst))
 858		return 1;
 859
 860	if (userfaultfd_open(0) < 0)
 861		return 1;
 862	uffdio_register.range.start = (unsigned long) area_dst;
 863	uffdio_register.range.len = nr_pages * page_size;
 864	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
 
 
 865	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
 866		fprintf(stderr, "register failure\n"), exit(1);
 867
 868	expected_ioctls = uffd_test_ops->expected_ioctls;
 869	if ((uffdio_register.ioctls & expected_ioctls) !=
 870	    expected_ioctls)
 871		fprintf(stderr,
 872			"unexpected missing ioctl for anon memory\n"),
 873			exit(1);
 874
 875	if (uffdio_zeropage(uffd, 0)) {
 876		if (my_bcmp(area_dst, zeropage, page_size))
 877			fprintf(stderr, "zeropage is not zero\n"), exit(1);
 878	}
 879
 880	close(uffd);
 881	printf("done.\n");
 882	return 0;
 883}
 884
 885static int userfaultfd_events_test(void)
 886{
 887	struct uffdio_register uffdio_register;
 888	unsigned long expected_ioctls;
 889	unsigned long userfaults;
 890	pthread_t uffd_mon;
 891	int err, features;
 892	pid_t pid;
 893	char c;
 
 894
 895	printf("testing events (fork, remap, remove): ");
 896	fflush(stdout);
 897
 898	if (uffd_test_ops->release_pages(area_dst))
 899		return 1;
 900
 901	features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP |
 902		UFFD_FEATURE_EVENT_REMOVE;
 903	if (userfaultfd_open(features) < 0)
 904		return 1;
 905	fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
 906
 907	uffdio_register.range.start = (unsigned long) area_dst;
 908	uffdio_register.range.len = nr_pages * page_size;
 909	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
 
 
 910	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
 911		fprintf(stderr, "register failure\n"), exit(1);
 912
 913	expected_ioctls = uffd_test_ops->expected_ioctls;
 914	if ((uffdio_register.ioctls & expected_ioctls) !=
 915	    expected_ioctls)
 916		fprintf(stderr,
 917			"unexpected missing ioctl for anon memory\n"),
 918			exit(1);
 919
 920	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, NULL))
 921		perror("uffd_poll_thread create"), exit(1);
 922
 923	pid = fork();
 924	if (pid < 0)
 925		perror("fork"), exit(1);
 926
 927	if (!pid)
 928		return faulting_process(0);
 929
 930	waitpid(pid, &err, 0);
 931	if (err)
 932		fprintf(stderr, "faulting process failed\n"), exit(1);
 933
 934	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
 935		perror("pipe write"), exit(1);
 936	if (pthread_join(uffd_mon, (void **)&userfaults))
 937		return 1;
 938
 939	close(uffd);
 940	printf("userfaults: %ld\n", userfaults);
 941
 942	return userfaults != nr_pages;
 943}
 944
 945static int userfaultfd_sig_test(void)
 946{
 947	struct uffdio_register uffdio_register;
 948	unsigned long expected_ioctls;
 949	unsigned long userfaults;
 950	pthread_t uffd_mon;
 951	int err, features;
 952	pid_t pid;
 953	char c;
 
 954
 955	printf("testing signal delivery: ");
 956	fflush(stdout);
 957
 958	if (uffd_test_ops->release_pages(area_dst))
 959		return 1;
 960
 961	features = UFFD_FEATURE_EVENT_FORK|UFFD_FEATURE_SIGBUS;
 962	if (userfaultfd_open(features) < 0)
 963		return 1;
 964	fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
 965
 966	uffdio_register.range.start = (unsigned long) area_dst;
 967	uffdio_register.range.len = nr_pages * page_size;
 968	uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
 
 
 969	if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register))
 970		fprintf(stderr, "register failure\n"), exit(1);
 971
 972	expected_ioctls = uffd_test_ops->expected_ioctls;
 973	if ((uffdio_register.ioctls & expected_ioctls) !=
 974	    expected_ioctls)
 975		fprintf(stderr,
 976			"unexpected missing ioctl for anon memory\n"),
 977			exit(1);
 978
 979	if (faulting_process(1))
 980		fprintf(stderr, "faulting process failed\n"), exit(1);
 981
 982	if (uffd_test_ops->release_pages(area_dst))
 983		return 1;
 984
 985	if (pthread_create(&uffd_mon, &attr, uffd_poll_thread, NULL))
 986		perror("uffd_poll_thread create"), exit(1);
 987
 988	pid = fork();
 989	if (pid < 0)
 990		perror("fork"), exit(1);
 991
 992	if (!pid)
 993		exit(faulting_process(2));
 994
 995	waitpid(pid, &err, 0);
 996	if (err)
 997		fprintf(stderr, "faulting process failed\n"), exit(1);
 998
 999	if (write(pipefd[1], &c, sizeof(c)) != sizeof(c))
1000		perror("pipe write"), exit(1);
1001	if (pthread_join(uffd_mon, (void **)&userfaults))
1002		return 1;
1003
1004	printf("done.\n");
1005	if (userfaults)
1006		fprintf(stderr, "Signal test failed, userfaults: %ld\n",
1007			userfaults);
1008	close(uffd);
1009	return userfaults != 0;
1010}
1011static int userfaultfd_stress(void)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1012{
1013	void *area;
1014	char *tmp_area;
1015	unsigned long nr;
1016	struct uffdio_register uffdio_register;
1017	unsigned long cpu;
1018	int err;
1019	unsigned long userfaults[nr_cpus];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1020
1021	uffd_test_ops->allocate_area((void **)&area_src);
1022	if (!area_src)
1023		return 1;
1024	uffd_test_ops->allocate_area((void **)&area_dst);
1025	if (!area_dst)
1026		return 1;
1027
1028	if (userfaultfd_open(0) < 0)
1029		return 1;
 
 
 
 
 
1030
1031	count_verify = malloc(nr_pages * sizeof(unsigned long long));
1032	if (!count_verify) {
1033		perror("count_verify");
1034		return 1;
 
 
 
 
 
1035	}
1036
1037	for (nr = 0; nr < nr_pages; nr++) {
1038		*area_mutex(area_src, nr) = (pthread_mutex_t)
1039			PTHREAD_MUTEX_INITIALIZER;
1040		count_verify[nr] = *area_count(area_src, nr) = 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1041		/*
1042		 * In the transition between 255 to 256, powerpc will
1043		 * read out of order in my_bcmp and see both bytes as
1044		 * zero, so leave a placeholder below always non-zero
1045		 * after the count, to avoid my_bcmp to trigger false
1046		 * positives.
1047		 */
1048		*(area_count(area_src, nr) + 1) = 1;
 
 
1049	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1050
1051	pipefd = malloc(sizeof(int) * nr_cpus * 2);
1052	if (!pipefd) {
1053		perror("pipefd");
1054		return 1;
1055	}
1056	for (cpu = 0; cpu < nr_cpus; cpu++) {
1057		if (pipe2(&pipefd[cpu*2], O_CLOEXEC | O_NONBLOCK)) {
1058			perror("pipe");
1059			return 1;
1060		}
1061	}
1062
1063	if (posix_memalign(&area, page_size, page_size)) {
1064		fprintf(stderr, "out of memory\n");
1065		return 1;
1066	}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1067	zeropage = area;
1068	bzero(zeropage, page_size);
1069
1070	pthread_mutex_lock(&uffd_read_mutex);
1071
1072	pthread_attr_init(&attr);
1073	pthread_attr_setstacksize(&attr, 16*1024*1024);
1074
1075	err = 0;
1076	while (bounces--) {
1077		unsigned long expected_ioctls;
1078
1079		printf("bounces: %d, mode:", bounces);
1080		if (bounces & BOUNCE_RANDOM)
1081			printf(" rnd");
1082		if (bounces & BOUNCE_RACINGFAULTS)
1083			printf(" racing");
1084		if (bounces & BOUNCE_VERIFY)
1085			printf(" ver");
1086		if (bounces & BOUNCE_POLL)
1087			printf(" poll");
 
 
1088		printf(", ");
1089		fflush(stdout);
1090
1091		if (bounces & BOUNCE_POLL)
1092			fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
1093		else
1094			fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
1095
1096		/* register */
1097		uffdio_register.range.start = (unsigned long) area_dst;
1098		uffdio_register.range.len = nr_pages * page_size;
1099		uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
1100		if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1101			fprintf(stderr, "register failure\n");
1102			return 1;
1103		}
1104		expected_ioctls = uffd_test_ops->expected_ioctls;
1105		if ((uffdio_register.ioctls & expected_ioctls) !=
1106		    expected_ioctls) {
1107			fprintf(stderr,
1108				"unexpected missing ioctl for anon memory\n");
1109			return 1;
1110		}
1111
1112		if (area_dst_alias) {
1113			uffdio_register.range.start = (unsigned long)
1114				area_dst_alias;
1115			if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
1116				fprintf(stderr, "register failure alias\n");
1117				return 1;
1118			}
1119		}
1120
1121		/*
1122		 * The madvise done previously isn't enough: some
1123		 * uffd_thread could have read userfaults (one of
1124		 * those already resolved by the background thread)
1125		 * and it may be in the process of calling
1126		 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
1127		 * area_src and it would map a zero page in it (of
1128		 * course such a UFFDIO_COPY is perfectly safe as it'd
1129		 * return -EEXIST). The problem comes at the next
1130		 * bounce though: that racing UFFDIO_COPY would
1131		 * generate zeropages in the area_src, so invalidating
1132		 * the previous MADV_DONTNEED. Without this additional
1133		 * MADV_DONTNEED those zeropages leftovers in the
1134		 * area_src would lead to -EEXIST failure during the
1135		 * next bounce, effectively leaving a zeropage in the
1136		 * area_dst.
1137		 *
1138		 * Try to comment this out madvise to see the memory
1139		 * corruption being caught pretty quick.
1140		 *
1141		 * khugepaged is also inhibited to collapse THP after
1142		 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
1143		 * required to MADV_DONTNEED here.
1144		 */
1145		if (uffd_test_ops->release_pages(area_dst))
1146			return 1;
 
1147
1148		/* bounce pass */
1149		if (stress(userfaults))
1150			return 1;
1151
 
 
 
 
 
1152		/* unregister */
1153		if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range)) {
1154			fprintf(stderr, "unregister failure\n");
1155			return 1;
1156		}
1157		if (area_dst_alias) {
1158			uffdio_register.range.start = (unsigned long) area_dst;
1159			if (ioctl(uffd, UFFDIO_UNREGISTER,
1160				  &uffdio_register.range)) {
1161				fprintf(stderr, "unregister failure alias\n");
1162				return 1;
1163			}
1164		}
1165
1166		/* verification */
1167		if (bounces & BOUNCE_VERIFY) {
1168			for (nr = 0; nr < nr_pages; nr++) {
1169				if (*area_count(area_dst, nr) != count_verify[nr]) {
1170					fprintf(stderr,
1171						"error area_count %Lu %Lu %lu\n",
1172						*area_count(area_src, nr),
1173						count_verify[nr],
1174						nr);
1175					err = 1;
1176					bounces = 0;
1177				}
1178			}
1179		}
1180
1181		/* prepare next bounce */
1182		tmp_area = area_src;
1183		area_src = area_dst;
1184		area_dst = tmp_area;
1185
1186		tmp_area = area_src_alias;
1187		area_src_alias = area_dst_alias;
1188		area_dst_alias = tmp_area;
1189
1190		printf("userfaults:");
1191		for (cpu = 0; cpu < nr_cpus; cpu++)
1192			printf(" %lu", userfaults[cpu]);
1193		printf("\n");
1194	}
1195
1196	if (err)
1197		return err;
 
 
 
 
 
 
 
 
 
 
 
 
1198
1199	close(uffd);
1200	return userfaultfd_zeropage_test() || userfaultfd_sig_test()
1201		|| userfaultfd_events_test();
1202}
1203
1204/*
1205 * Copied from mlock2-tests.c
1206 */
1207unsigned long default_huge_page_size(void)
1208{
1209	unsigned long hps = 0;
1210	char *line = NULL;
1211	size_t linelen = 0;
1212	FILE *f = fopen("/proc/meminfo", "r");
1213
1214	if (!f)
1215		return 0;
1216	while (getline(&line, &linelen, f) > 0) {
1217		if (sscanf(line, "Hugepagesize:       %lu kB", &hps) == 1) {
1218			hps <<= 10;
1219			break;
1220		}
1221	}
1222
1223	free(line);
1224	fclose(f);
1225	return hps;
1226}
1227
1228static void set_test_type(const char *type)
1229{
1230	if (!strcmp(type, "anon")) {
1231		test_type = TEST_ANON;
1232		uffd_test_ops = &anon_uffd_test_ops;
1233	} else if (!strcmp(type, "hugetlb")) {
1234		test_type = TEST_HUGETLB;
1235		uffd_test_ops = &hugetlb_uffd_test_ops;
1236	} else if (!strcmp(type, "hugetlb_shared")) {
1237		map_shared = true;
1238		test_type = TEST_HUGETLB;
1239		uffd_test_ops = &hugetlb_uffd_test_ops;
 
 
1240	} else if (!strcmp(type, "shmem")) {
1241		map_shared = true;
1242		test_type = TEST_SHMEM;
1243		uffd_test_ops = &shmem_uffd_test_ops;
1244	} else {
1245		fprintf(stderr, "Unknown test type: %s\n", type), exit(1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1246	}
1247
 
 
 
 
 
 
1248	if (test_type == TEST_HUGETLB)
1249		page_size = default_huge_page_size();
1250	else
1251		page_size = sysconf(_SC_PAGE_SIZE);
1252
1253	if (!page_size)
1254		fprintf(stderr, "Unable to determine page size\n"),
1255				exit(2);
1256	if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) * 2
1257	    > page_size)
1258		fprintf(stderr, "Impossible to run this test\n"), exit(2);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1259}
1260
1261static void sigalrm(int sig)
1262{
1263	if (sig != SIGALRM)
1264		abort();
1265	test_uffdio_copy_eexist = true;
1266	test_uffdio_zeropage_eexist = true;
1267	alarm(ALARM_INTERVAL_SECS);
1268}
1269
1270int main(int argc, char **argv)
1271{
 
 
1272	if (argc < 4)
1273		fprintf(stderr, "Usage: <test type> <MiB> <bounces> [hugetlbfs_file]\n"),
1274				exit(1);
1275
1276	if (signal(SIGALRM, sigalrm) == SIG_ERR)
1277		fprintf(stderr, "failed to arm SIGALRM"), exit(1);
1278	alarm(ALARM_INTERVAL_SECS);
1279
1280	set_test_type(argv[1]);
 
 
 
 
 
 
1281
1282	nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
1283	nr_pages_per_cpu = atol(argv[2]) * 1024*1024 / page_size /
1284		nr_cpus;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1285	if (!nr_pages_per_cpu) {
1286		fprintf(stderr, "invalid MiB\n");
1287		fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
1288	}
1289
1290	bounces = atoi(argv[3]);
1291	if (bounces <= 0) {
1292		fprintf(stderr, "invalid bounces\n");
1293		fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
1294	}
1295	nr_pages = nr_pages_per_cpu * nr_cpus;
1296
1297	if (test_type == TEST_HUGETLB) {
1298		if (argc < 5)
1299			fprintf(stderr, "Usage: hugetlb <MiB> <bounces> <hugetlbfs_file>\n"),
1300				exit(1);
1301		huge_fd = open(argv[4], O_CREAT | O_RDWR, 0755);
1302		if (huge_fd < 0) {
1303			fprintf(stderr, "Open of %s failed", argv[3]);
1304			perror("open");
1305			exit(1);
1306		}
1307		if (ftruncate(huge_fd, 0)) {
1308			fprintf(stderr, "ftruncate %s to size 0 failed", argv[3]);
1309			perror("ftruncate");
1310			exit(1);
1311		}
1312	}
1313	printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
1314	       nr_pages, nr_pages_per_cpu);
1315	return userfaultfd_stress();
1316}
1317
1318#else /* __NR_userfaultfd */
1319
1320#warning "missing __NR_userfaultfd definition"
1321
1322int main(void)
1323{
1324	printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
1325	return 0;
1326}
1327
1328#endif /* __NR_userfaultfd */