1 // SPDX-License-Identifier: GPL-2.0
3 * KVM demand paging test
4 * Adapted from dirty_log_test.c
6 * Copyright (C) 2018, Red Hat, Inc.
7 * Copyright (C) 2019, Google, Inc.
10 #define _GNU_SOURCE /* for program_invocation_name */
14 #include <sys/syscall.h>
16 #include <asm/unistd.h>
20 #include <linux/bitmap.h>
21 #include <linux/bitops.h>
22 #include <linux/userfaultfd.h>
24 #include "test_util.h"
26 #include "processor.h"
28 #ifdef __NR_userfaultfd
30 /* The memory slot index demand page */
31 #define TEST_MEM_SLOT_INDEX 1
33 /* Default guest test virtual memory offset */
34 #define DEFAULT_GUEST_TEST_MEM 0xc0000000
36 #define DEFAULT_GUEST_TEST_MEM_SIZE (1 << 30) /* 1G */
38 #ifdef PRINT_PER_PAGE_UPDATES
39 #define PER_PAGE_DEBUG(...) printf(__VA_ARGS__)
41 #define PER_PAGE_DEBUG(...) _no_printf(__VA_ARGS__)
44 #ifdef PRINT_PER_VCPU_UPDATES
45 #define PER_VCPU_DEBUG(...) printf(__VA_ARGS__)
47 #define PER_VCPU_DEBUG(...) _no_printf(__VA_ARGS__)
53 * Guest/Host shared variables. Ensure addr_gva2hva() and/or
54 * sync_global_to/from_guest() are used when accessing from
55 * the host. READ/WRITE_ONCE() should also be used with anything
58 static uint64_t host_page_size;
59 static uint64_t guest_page_size;
61 static char *guest_data_prototype;
64 * Guest physical memory offset of the testing memory slot.
65 * This will be set to the topmost valid physical address minus
66 * the test memory size.
68 static uint64_t guest_test_phys_mem;
71 * Guest virtual memory offset of the testing memory slot.
72 * Must not conflict with identity mapped test code.
74 static uint64_t guest_test_virt_mem = DEFAULT_GUEST_TEST_MEM;
80 /* Only used by the host userspace part of the vCPU thread */
85 static struct vcpu_args vcpu_args[MAX_VCPUS];
88 * Continuously write to the first 8 bytes of each page in the demand paging
91 static void guest_code(uint32_t vcpu_id)
97 /* Make sure vCPU args data structure is not corrupt. */
98 GUEST_ASSERT(vcpu_args[vcpu_id].vcpu_id == vcpu_id);
100 gva = vcpu_args[vcpu_id].gva;
101 pages = vcpu_args[vcpu_id].pages;
103 for (i = 0; i < pages; i++) {
104 uint64_t addr = gva + (i * guest_page_size);
106 addr &= ~(host_page_size - 1);
107 *(uint64_t *)addr = 0x0123456789ABCDEF;
113 static void *vcpu_worker(void *data)
116 struct vcpu_args *args = (struct vcpu_args *)data;
117 struct kvm_vm *vm = args->vm;
118 int vcpu_id = args->vcpu_id;
120 struct timespec start;
123 vcpu_args_set(vm, vcpu_id, 1, vcpu_id);
124 run = vcpu_state(vm, vcpu_id);
126 clock_gettime(CLOCK_MONOTONIC, &start);
128 /* Let the guest access its memory */
129 ret = _vcpu_run(vm, vcpu_id);
130 TEST_ASSERT(ret == 0, "vcpu_run failed: %d\n", ret);
131 if (get_ucall(vm, vcpu_id, NULL) != UCALL_SYNC) {
133 "Invalid guest sync status: exit_reason=%s\n",
134 exit_reason_str(run->exit_reason));
137 clock_gettime(CLOCK_MONOTONIC, &end);
138 PER_VCPU_DEBUG("vCPU %d execution time: %lld.%.9lds\n", vcpu_id,
139 (long long)(timespec_diff(start, end).tv_sec),
140 timespec_diff(start, end).tv_nsec);
145 #define PAGE_SHIFT_4K 12
146 #define PTES_PER_4K_PT 512
148 static struct kvm_vm *create_vm(enum vm_guest_mode mode, int vcpus,
149 uint64_t vcpu_memory_bytes)
152 uint64_t pages = DEFAULT_GUEST_PHY_PAGES;
154 /* Account for a few pages per-vCPU for stacks */
155 pages += DEFAULT_STACK_PGS * vcpus;
158 * Reserve twice the ammount of memory needed to map the test region and
159 * the page table / stacks region, at 4k, for page tables. Do the
160 * calculation with 4K page size: the smallest of all archs. (e.g., 64K
161 * page size guest will need even less memory for page tables).
163 pages += (2 * pages) / PTES_PER_4K_PT;
164 pages += ((2 * vcpus * vcpu_memory_bytes) >> PAGE_SHIFT_4K) /
166 pages = vm_adjust_num_guest_pages(mode, pages);
168 pr_info("Testing guest mode: %s\n", vm_guest_mode_string(mode));
170 vm = _vm_create(mode, pages, O_RDWR);
171 kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
173 vm_create_irqchip(vm);
178 static int handle_uffd_page_request(int uffd, uint64_t addr)
181 struct timespec start;
183 struct uffdio_copy copy;
186 tid = syscall(__NR_gettid);
188 copy.src = (uint64_t)guest_data_prototype;
190 copy.len = host_page_size;
193 clock_gettime(CLOCK_MONOTONIC, &start);
195 r = ioctl(uffd, UFFDIO_COPY, ©);
197 pr_info("Failed Paged in 0x%lx from thread %d with errno: %d\n",
202 clock_gettime(CLOCK_MONOTONIC, &end);
204 PER_PAGE_DEBUG("UFFDIO_COPY %d \t%lld ns\n", tid,
205 (long long)timespec_to_ns(timespec_diff(start, end)));
206 PER_PAGE_DEBUG("Paged in %ld bytes at 0x%lx from thread %d\n",
207 host_page_size, addr, tid);
212 bool quit_uffd_thread;
214 struct uffd_handler_args {
220 static void *uffd_handler_thread_fn(void *arg)
222 struct uffd_handler_args *uffd_args = (struct uffd_handler_args *)arg;
223 int uffd = uffd_args->uffd;
224 int pipefd = uffd_args->pipefd;
225 useconds_t delay = uffd_args->delay;
227 struct timespec start;
230 clock_gettime(CLOCK_MONOTONIC, &start);
231 while (!quit_uffd_thread) {
233 struct pollfd pollfd[2];
239 pollfd[0].events = POLLIN;
240 pollfd[1].fd = pipefd;
241 pollfd[1].events = POLLIN;
243 r = poll(pollfd, 2, -1);
253 pr_info("Polling uffd returned %d", r);
257 if (pollfd[0].revents & POLLERR) {
258 pr_info("uffd revents has POLLERR");
262 if (pollfd[1].revents & POLLIN) {
263 r = read(pollfd[1].fd, &tmp_chr, 1);
265 "Error reading pipefd in UFFD thread\n");
269 if (!pollfd[0].revents & POLLIN)
272 r = read(uffd, &msg, sizeof(msg));
276 pr_info("Read of uffd gor errno %d", errno);
280 if (r != sizeof(msg)) {
281 pr_info("Read on uffd returned unexpected size: %d bytes", r);
285 if (!(msg.event & UFFD_EVENT_PAGEFAULT))
290 addr = msg.arg.pagefault.address;
291 r = handle_uffd_page_request(uffd, addr);
297 clock_gettime(CLOCK_MONOTONIC, &end);
298 PER_VCPU_DEBUG("userfaulted %ld pages over %lld.%.9lds. (%f/sec)\n",
299 pages, (long long)(timespec_diff(start, end).tv_sec),
300 timespec_diff(start, end).tv_nsec, pages /
301 ((double)timespec_diff(start, end).tv_sec +
302 (double)timespec_diff(start, end).tv_nsec / 100000000.0));
307 static int setup_demand_paging(struct kvm_vm *vm,
308 pthread_t *uffd_handler_thread, int pipefd,
309 useconds_t uffd_delay,
310 struct uffd_handler_args *uffd_args,
311 void *hva, uint64_t len)
314 struct uffdio_api uffdio_api;
315 struct uffdio_register uffdio_register;
317 uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
319 pr_info("uffd creation failed\n");
323 uffdio_api.api = UFFD_API;
324 uffdio_api.features = 0;
325 if (ioctl(uffd, UFFDIO_API, &uffdio_api) == -1) {
326 pr_info("ioctl uffdio_api failed\n");
330 uffdio_register.range.start = (uint64_t)hva;
331 uffdio_register.range.len = len;
332 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
333 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register) == -1) {
334 pr_info("ioctl uffdio_register failed\n");
338 if ((uffdio_register.ioctls & UFFD_API_RANGE_IOCTLS) !=
339 UFFD_API_RANGE_IOCTLS) {
340 pr_info("unexpected userfaultfd ioctl set\n");
344 uffd_args->uffd = uffd;
345 uffd_args->pipefd = pipefd;
346 uffd_args->delay = uffd_delay;
347 pthread_create(uffd_handler_thread, NULL, uffd_handler_thread_fn,
350 PER_VCPU_DEBUG("Created uffd thread for HVA range [%p, %p)\n",
356 static void run_test(enum vm_guest_mode mode, bool use_uffd,
357 useconds_t uffd_delay, int vcpus,
358 uint64_t vcpu_memory_bytes)
360 pthread_t *vcpu_threads;
361 pthread_t *uffd_handler_threads = NULL;
362 struct uffd_handler_args *uffd_args = NULL;
365 uint64_t guest_num_pages;
368 struct timespec start;
371 vm = create_vm(mode, vcpus, vcpu_memory_bytes);
373 guest_page_size = vm_get_page_size(vm);
375 TEST_ASSERT(vcpu_memory_bytes % guest_page_size == 0,
376 "Guest memory size is not guest page size aligned.");
378 guest_num_pages = (vcpus * vcpu_memory_bytes) / guest_page_size;
379 guest_num_pages = vm_adjust_num_guest_pages(mode, guest_num_pages);
382 * If there should be more memory in the guest test region than there
383 * can be pages in the guest, it will definitely cause problems.
385 TEST_ASSERT(guest_num_pages < vm_get_max_gfn(vm),
386 "Requested more guest memory than address space allows.\n"
387 " guest pages: %lx max gfn: %x vcpus: %d wss: %lx]\n",
388 guest_num_pages, vm_get_max_gfn(vm), vcpus,
391 host_page_size = getpagesize();
392 TEST_ASSERT(vcpu_memory_bytes % host_page_size == 0,
393 "Guest memory size is not host page size aligned.");
395 guest_test_phys_mem = (vm_get_max_gfn(vm) - guest_num_pages) *
397 guest_test_phys_mem &= ~(host_page_size - 1);
400 /* Align to 1M (segment size) */
401 guest_test_phys_mem &= ~((1 << 20) - 1);
404 pr_info("guest physical test memory offset: 0x%lx\n", guest_test_phys_mem);
406 /* Add an extra memory slot for testing demand paging */
407 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
412 /* Do mapping for the demand paging memory slot */
413 virt_map(vm, guest_test_virt_mem, guest_test_phys_mem,
414 guest_num_pages * guest_page_size, 0);
416 ucall_init(vm, NULL);
418 guest_data_prototype = malloc(host_page_size);
419 TEST_ASSERT(guest_data_prototype,
420 "Failed to allocate buffer for guest data pattern");
421 memset(guest_data_prototype, 0xAB, host_page_size);
423 vcpu_threads = malloc(vcpus * sizeof(*vcpu_threads));
424 TEST_ASSERT(vcpu_threads, "Memory allocation failed");
427 uffd_handler_threads =
428 malloc(vcpus * sizeof(*uffd_handler_threads));
429 TEST_ASSERT(uffd_handler_threads, "Memory allocation failed");
431 uffd_args = malloc(vcpus * sizeof(*uffd_args));
432 TEST_ASSERT(uffd_args, "Memory allocation failed");
434 pipefds = malloc(sizeof(int) * vcpus * 2);
435 TEST_ASSERT(pipefds, "Unable to allocate memory for pipefd");
438 for (vcpu_id = 0; vcpu_id < vcpus; vcpu_id++) {
442 vm_vcpu_add_default(vm, vcpu_id, guest_code);
444 vcpu_gpa = guest_test_phys_mem + (vcpu_id * vcpu_memory_bytes);
445 PER_VCPU_DEBUG("Added VCPU %d with test mem gpa [%lx, %lx)\n",
446 vcpu_id, vcpu_gpa, vcpu_gpa + vcpu_memory_bytes);
448 /* Cache the HVA pointer of the region */
449 vcpu_hva = addr_gpa2hva(vm, vcpu_gpa);
453 * Set up user fault fd to handle demand paging
456 r = pipe2(&pipefds[vcpu_id * 2],
457 O_CLOEXEC | O_NONBLOCK);
458 TEST_ASSERT(!r, "Failed to set up pipefd");
460 r = setup_demand_paging(vm,
461 &uffd_handler_threads[vcpu_id],
462 pipefds[vcpu_id * 2],
463 uffd_delay, &uffd_args[vcpu_id],
464 vcpu_hva, vcpu_memory_bytes);
470 vcpu_set_cpuid(vm, vcpu_id, kvm_get_supported_cpuid());
473 vcpu_args[vcpu_id].vm = vm;
474 vcpu_args[vcpu_id].vcpu_id = vcpu_id;
475 vcpu_args[vcpu_id].gva = guest_test_virt_mem +
476 (vcpu_id * vcpu_memory_bytes);
477 vcpu_args[vcpu_id].pages = vcpu_memory_bytes / guest_page_size;
480 /* Export the shared variables to the guest */
481 sync_global_to_guest(vm, host_page_size);
482 sync_global_to_guest(vm, guest_page_size);
483 sync_global_to_guest(vm, vcpu_args);
485 pr_info("Finished creating vCPUs and starting uffd threads\n");
487 clock_gettime(CLOCK_MONOTONIC, &start);
489 for (vcpu_id = 0; vcpu_id < vcpus; vcpu_id++) {
490 pthread_create(&vcpu_threads[vcpu_id], NULL, vcpu_worker,
491 &vcpu_args[vcpu_id]);
494 pr_info("Started all vCPUs\n");
496 /* Wait for the vcpu threads to quit */
497 for (vcpu_id = 0; vcpu_id < vcpus; vcpu_id++) {
498 pthread_join(vcpu_threads[vcpu_id], NULL);
499 PER_VCPU_DEBUG("Joined thread for vCPU %d\n", vcpu_id);
502 pr_info("All vCPU threads joined\n");
504 clock_gettime(CLOCK_MONOTONIC, &end);
509 /* Tell the user fault fd handler threads to quit */
510 for (vcpu_id = 0; vcpu_id < vcpus; vcpu_id++) {
511 r = write(pipefds[vcpu_id * 2 + 1], &c, 1);
512 TEST_ASSERT(r == 1, "Unable to write to pipefd");
514 pthread_join(uffd_handler_threads[vcpu_id], NULL);
518 pr_info("Total guest execution time: %lld.%.9lds\n",
519 (long long)(timespec_diff(start, end).tv_sec),
520 timespec_diff(start, end).tv_nsec);
521 pr_info("Overall demand paging rate: %f pgs/sec\n",
522 guest_num_pages / ((double)timespec_diff(start, end).tv_sec +
523 (double)timespec_diff(start, end).tv_nsec / 100000000.0));
528 free(guest_data_prototype);
531 free(uffd_handler_threads);
541 static struct guest_mode guest_modes[NUM_VM_MODES];
543 #define guest_mode_init(mode, supported, enabled) ({ \
544 guest_modes[mode] = (struct guest_mode){ supported, enabled }; \
547 static void help(char *name)
552 printf("usage: %s [-h] [-m mode] [-u] [-d uffd_delay_usec]\n"
553 " [-b memory] [-v vcpus]\n", name);
554 printf(" -m: specify the guest mode ID to test\n"
555 " (default: test all supported modes)\n"
556 " This option may be used multiple times.\n"
557 " Guest mode IDs:\n");
558 for (i = 0; i < NUM_VM_MODES; ++i) {
559 printf(" %d: %s%s\n", i, vm_guest_mode_string(i),
560 guest_modes[i].supported ? " (supported)" : "");
562 printf(" -u: use User Fault FD to handle vCPU page\n"
564 printf(" -d: add a delay in usec to the User Fault\n"
565 " FD handler to simulate demand paging\n"
566 " overheads. Ignored without -u.\n");
567 printf(" -b: specify the size of the memory region which should be\n"
568 " demand paged by each vCPU. e.g. 10M or 3G.\n"
570 printf(" -v: specify the number of vCPUs to run.\n");
575 int main(int argc, char *argv[])
577 bool mode_selected = false;
578 uint64_t vcpu_memory_bytes = DEFAULT_GUEST_TEST_MEM_SIZE;
582 bool use_uffd = false;
583 useconds_t uffd_delay = 0;
586 guest_mode_init(VM_MODE_PXXV48_4K, true, true);
589 guest_mode_init(VM_MODE_P40V48_4K, true, true);
590 guest_mode_init(VM_MODE_P40V48_64K, true, true);
592 unsigned int limit = kvm_check_cap(KVM_CAP_ARM_VM_IPA_SIZE);
595 guest_mode_init(VM_MODE_P52V48_64K, true, true);
597 guest_mode_init(VM_MODE_P48V48_4K, true, true);
598 guest_mode_init(VM_MODE_P48V48_64K, true, true);
603 guest_mode_init(VM_MODE_P40V48_4K, true, true);
606 while ((opt = getopt(argc, argv, "hm:ud:b:v:")) != -1) {
609 if (!mode_selected) {
610 for (i = 0; i < NUM_VM_MODES; ++i)
611 guest_modes[i].enabled = false;
612 mode_selected = true;
614 mode = strtoul(optarg, NULL, 10);
615 TEST_ASSERT(mode < NUM_VM_MODES,
616 "Guest mode ID %d too big", mode);
617 guest_modes[mode].enabled = true;
623 uffd_delay = strtoul(optarg, NULL, 0);
624 TEST_ASSERT(uffd_delay >= 0,
625 "A negative UFFD delay is not supported.");
628 vcpu_memory_bytes = parse_size(optarg);
631 vcpus = atoi(optarg);
632 TEST_ASSERT(vcpus > 0,
633 "Must have a positive number of vCPUs");
634 TEST_ASSERT(vcpus <= MAX_VCPUS,
635 "This test does not currently support\n"
636 "more than %d vCPUs.", MAX_VCPUS);
645 for (i = 0; i < NUM_VM_MODES; ++i) {
646 if (!guest_modes[i].enabled)
648 TEST_ASSERT(guest_modes[i].supported,
649 "Guest mode ID %d (%s) not supported.",
650 i, vm_guest_mode_string(i));
651 run_test(i, use_uffd, uffd_delay, vcpus, vcpu_memory_bytes);
657 #else /* __NR_userfaultfd */
659 #warning "missing __NR_userfaultfd definition"
663 printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
667 #endif /* __NR_userfaultfd */