Path: blob/master/tools/testing/selftests/kvm/mmu_stress_test.c
38189 views
// SPDX-License-Identifier: GPL-2.01#include <stdio.h>2#include <stdlib.h>3#include <pthread.h>4#include <semaphore.h>5#include <sys/types.h>6#include <signal.h>7#include <errno.h>8#include <linux/bitmap.h>9#include <linux/bitops.h>10#include <linux/atomic.h>11#include <linux/sizes.h>1213#include "kvm_util.h"14#include "test_util.h"15#include "guest_modes.h"16#include "processor.h"17#include "ucall_common.h"1819static bool mprotect_ro_done;20static bool all_vcpus_hit_ro_fault;2122static void guest_code(uint64_t start_gpa, uint64_t end_gpa, uint64_t stride)23{24uint64_t gpa;25int i;2627for (i = 0; i < 2; i++) {28for (gpa = start_gpa; gpa < end_gpa; gpa += stride)29vcpu_arch_put_guest(*((volatile uint64_t *)gpa), gpa);30GUEST_SYNC(i);31}3233for (gpa = start_gpa; gpa < end_gpa; gpa += stride)34*((volatile uint64_t *)gpa);35GUEST_SYNC(2);3637/*38* Write to the region while mprotect(PROT_READ) is underway. Keep39* looping until the memory is guaranteed to be read-only and a fault40* has occurred, otherwise vCPUs may complete their writes and advance41* to the next stage prematurely.42*43* For architectures that support skipping the faulting instruction,44* generate the store via inline assembly to ensure the exact length45* of the instruction is known and stable (vcpu_arch_put_guest() on46* fixed-length architectures should work, but the cost of paranoia47* is low in this case). For x86, hand-code the exact opcode so that48* there is no room for variability in the generated instruction.49*/50do {51for (gpa = start_gpa; gpa < end_gpa; gpa += stride)52#ifdef __x86_64__53asm volatile(".byte 0x48,0x89,0x00" :: "a"(gpa) : "memory"); /* mov %rax, (%rax) */54#elif defined(__aarch64__)55asm volatile("str %0, [%0]" :: "r" (gpa) : "memory");56#else57vcpu_arch_put_guest(*((volatile uint64_t *)gpa), gpa);58#endif59} while (!READ_ONCE(mprotect_ro_done) || !READ_ONCE(all_vcpus_hit_ro_fault));6061/*62* Only architectures that write the entire range can explicitly sync,63* as other architectures will be stuck on the write fault.64*/65#if defined(__x86_64__) || defined(__aarch64__)66GUEST_SYNC(3);67#endif6869for (gpa = start_gpa; gpa < end_gpa; gpa += stride)70vcpu_arch_put_guest(*((volatile uint64_t *)gpa), gpa);71GUEST_SYNC(4);7273GUEST_ASSERT(0);74}7576struct vcpu_info {77struct kvm_vcpu *vcpu;78uint64_t start_gpa;79uint64_t end_gpa;80};8182static int nr_vcpus;83static atomic_t rendezvous;84static atomic_t nr_ro_faults;8586static void rendezvous_with_boss(void)87{88int orig = atomic_read(&rendezvous);8990if (orig > 0) {91atomic_dec_and_test(&rendezvous);92while (atomic_read(&rendezvous) > 0)93cpu_relax();94} else {95atomic_inc(&rendezvous);96while (atomic_read(&rendezvous) < 0)97cpu_relax();98}99}100101static void assert_sync_stage(struct kvm_vcpu *vcpu, int stage)102{103struct ucall uc;104105TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_SYNC);106TEST_ASSERT_EQ(uc.args[1], stage);107}108109static void run_vcpu(struct kvm_vcpu *vcpu, int stage)110{111vcpu_run(vcpu);112assert_sync_stage(vcpu, stage);113}114115static void *vcpu_worker(void *data)116{117struct kvm_sregs __maybe_unused sregs;118struct vcpu_info *info = data;119struct kvm_vcpu *vcpu = info->vcpu;120struct kvm_vm *vm = vcpu->vm;121int r;122123vcpu_args_set(vcpu, 3, info->start_gpa, info->end_gpa, vm->page_size);124125rendezvous_with_boss();126127/* Stage 0, write all of guest memory. */128run_vcpu(vcpu, 0);129rendezvous_with_boss();130#ifdef __x86_64__131vcpu_sregs_get(vcpu, &sregs);132/* Toggle CR0.WP to trigger a MMU context reset. */133sregs.cr0 ^= X86_CR0_WP;134vcpu_sregs_set(vcpu, &sregs);135#endif136rendezvous_with_boss();137138/* Stage 1, re-write all of guest memory. */139run_vcpu(vcpu, 1);140rendezvous_with_boss();141142/* Stage 2, read all of guest memory, which is now read-only. */143run_vcpu(vcpu, 2);144145/*146* Stage 3, write guest memory and verify KVM returns -EFAULT for once147* the mprotect(PROT_READ) lands. Only architectures that support148* validating *all* of guest memory sync for this stage, as vCPUs will149* be stuck on the faulting instruction for other architectures. Go to150* stage 3 without a rendezvous151*/152r = _vcpu_run(vcpu);153TEST_ASSERT(r == -1 && errno == EFAULT,154"Expected EFAULT on write to RO memory, got r = %d, errno = %d", r, errno);155156atomic_inc(&nr_ro_faults);157if (atomic_read(&nr_ro_faults) == nr_vcpus) {158WRITE_ONCE(all_vcpus_hit_ro_fault, true);159sync_global_to_guest(vm, all_vcpus_hit_ro_fault);160}161162#if defined(__x86_64__) || defined(__aarch64__)163/*164* Verify *all* writes from the guest hit EFAULT due to the VMA now165* being read-only. x86 and arm64 only at this time as skipping the166* instruction that hits the EFAULT requires advancing the program167* counter, which is arch specific and relies on inline assembly.168*/169#ifdef __x86_64__170vcpu->run->kvm_valid_regs = KVM_SYNC_X86_REGS;171#endif172for (;;) {173r = _vcpu_run(vcpu);174if (!r)175break;176TEST_ASSERT_EQ(errno, EFAULT);177#if defined(__x86_64__)178WRITE_ONCE(vcpu->run->kvm_dirty_regs, KVM_SYNC_X86_REGS);179vcpu->run->s.regs.regs.rip += 3;180#elif defined(__aarch64__)181vcpu_set_reg(vcpu, ARM64_CORE_REG(regs.pc),182vcpu_get_reg(vcpu, ARM64_CORE_REG(regs.pc)) + 4);183#endif184185}186assert_sync_stage(vcpu, 3);187#endif /* __x86_64__ || __aarch64__ */188rendezvous_with_boss();189190/*191* Stage 4. Run to completion, waiting for mprotect(PROT_WRITE) to192* make the memory writable again.193*/194do {195r = _vcpu_run(vcpu);196} while (r && errno == EFAULT);197TEST_ASSERT_EQ(r, 0);198assert_sync_stage(vcpu, 4);199rendezvous_with_boss();200201return NULL;202}203204static pthread_t *spawn_workers(struct kvm_vm *vm, struct kvm_vcpu **vcpus,205uint64_t start_gpa, uint64_t end_gpa)206{207struct vcpu_info *info;208uint64_t gpa, nr_bytes;209pthread_t *threads;210int i;211212threads = malloc(nr_vcpus * sizeof(*threads));213TEST_ASSERT(threads, "Failed to allocate vCPU threads");214215info = malloc(nr_vcpus * sizeof(*info));216TEST_ASSERT(info, "Failed to allocate vCPU gpa ranges");217218nr_bytes = ((end_gpa - start_gpa) / nr_vcpus) &219~((uint64_t)vm->page_size - 1);220TEST_ASSERT(nr_bytes, "C'mon, no way you have %d CPUs", nr_vcpus);221222for (i = 0, gpa = start_gpa; i < nr_vcpus; i++, gpa += nr_bytes) {223info[i].vcpu = vcpus[i];224info[i].start_gpa = gpa;225info[i].end_gpa = gpa + nr_bytes;226pthread_create(&threads[i], NULL, vcpu_worker, &info[i]);227}228return threads;229}230231static void rendezvous_with_vcpus(struct timespec *time, const char *name)232{233int i, rendezvoused;234235pr_info("Waiting for vCPUs to finish %s...\n", name);236237rendezvoused = atomic_read(&rendezvous);238for (i = 0; abs(rendezvoused) != 1; i++) {239usleep(100);240if (!(i & 0x3f))241pr_info("\r%d vCPUs haven't rendezvoused...",242abs(rendezvoused) - 1);243rendezvoused = atomic_read(&rendezvous);244}245246clock_gettime(CLOCK_MONOTONIC, time);247248/* Release the vCPUs after getting the time of the previous action. */249pr_info("\rAll vCPUs finished %s, releasing...\n", name);250if (rendezvoused > 0)251atomic_set(&rendezvous, -nr_vcpus - 1);252else253atomic_set(&rendezvous, nr_vcpus + 1);254}255256static void calc_default_nr_vcpus(void)257{258cpu_set_t possible_mask;259int r;260261r = sched_getaffinity(0, sizeof(possible_mask), &possible_mask);262TEST_ASSERT(!r, "sched_getaffinity failed, errno = %d (%s)",263errno, strerror(errno));264265nr_vcpus = CPU_COUNT(&possible_mask);266TEST_ASSERT(nr_vcpus > 0, "Uh, no CPUs?");267if (nr_vcpus >= 2)268nr_vcpus = nr_vcpus * 3/4;269}270271int main(int argc, char *argv[])272{273/*274* Skip the first 4gb and slot0. slot0 maps <1gb and is used to back275* the guest's code, stack, and page tables. Because selftests creates276* an IRQCHIP, a.k.a. a local APIC, KVM creates an internal memslot277* just below the 4gb boundary. This test could create memory at278* 1gb-3gb,but it's simpler to skip straight to 4gb.279*/280const uint64_t start_gpa = SZ_4G;281const int first_slot = 1;282283struct timespec time_start, time_run1, time_reset, time_run2, time_ro, time_rw;284uint64_t max_gpa, gpa, slot_size, max_mem, i;285int max_slots, slot, opt, fd;286bool hugepages = false;287struct kvm_vcpu **vcpus;288pthread_t *threads;289struct kvm_vm *vm;290void *mem;291292/*293* Default to 2gb so that maxing out systems with MAXPHADDR=46, which294* are quite common for x86, requires changing only max_mem (KVM allows295* 32k memslots, 32k * 2gb == ~64tb of guest memory).296*/297slot_size = SZ_2G;298299max_slots = kvm_check_cap(KVM_CAP_NR_MEMSLOTS);300TEST_ASSERT(max_slots > first_slot, "KVM is broken");301302/* All KVM MMUs should be able to survive a 128gb guest. */303max_mem = 128ull * SZ_1G;304305calc_default_nr_vcpus();306307while ((opt = getopt(argc, argv, "c:h:m:s:H")) != -1) {308switch (opt) {309case 'c':310nr_vcpus = atoi_positive("Number of vCPUs", optarg);311break;312case 'm':313max_mem = 1ull * atoi_positive("Memory size", optarg) * SZ_1G;314break;315case 's':316slot_size = 1ull * atoi_positive("Slot size", optarg) * SZ_1G;317break;318case 'H':319hugepages = true;320break;321case 'h':322default:323printf("usage: %s [-c nr_vcpus] [-m max_mem_in_gb] [-s slot_size_in_gb] [-H]\n", argv[0]);324exit(1);325}326}327328vcpus = malloc(nr_vcpus * sizeof(*vcpus));329TEST_ASSERT(vcpus, "Failed to allocate vCPU array");330331vm = __vm_create_with_vcpus(VM_SHAPE_DEFAULT, nr_vcpus,332#ifdef __x86_64__333max_mem / SZ_1G,334#else335max_mem / vm_guest_mode_params[VM_MODE_DEFAULT].page_size,336#endif337guest_code, vcpus);338339max_gpa = vm->max_gfn << vm->page_shift;340TEST_ASSERT(max_gpa > (4 * slot_size), "MAXPHYADDR <4gb ");341342fd = kvm_memfd_alloc(slot_size, hugepages);343mem = kvm_mmap(slot_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd);344345TEST_ASSERT(!madvise(mem, slot_size, MADV_NOHUGEPAGE), "madvise() failed");346347/* Pre-fault the memory to avoid taking mmap_sem on guest page faults. */348for (i = 0; i < slot_size; i += vm->page_size)349((uint8_t *)mem)[i] = 0xaa;350351gpa = 0;352for (slot = first_slot; slot < max_slots; slot++) {353gpa = start_gpa + ((slot - first_slot) * slot_size);354if (gpa + slot_size > max_gpa)355break;356357if ((gpa - start_gpa) >= max_mem)358break;359360vm_set_user_memory_region(vm, slot, 0, gpa, slot_size, mem);361362#ifdef __x86_64__363/* Identity map memory in the guest using 1gb pages. */364virt_map_level(vm, gpa, gpa, slot_size, PG_LEVEL_1G);365#else366virt_map(vm, gpa, gpa, slot_size >> vm->page_shift);367#endif368}369370atomic_set(&rendezvous, nr_vcpus + 1);371threads = spawn_workers(vm, vcpus, start_gpa, gpa);372373free(vcpus);374vcpus = NULL;375376pr_info("Running with %lugb of guest memory and %u vCPUs\n",377(gpa - start_gpa) / SZ_1G, nr_vcpus);378379rendezvous_with_vcpus(&time_start, "spawning");380rendezvous_with_vcpus(&time_run1, "run 1");381rendezvous_with_vcpus(&time_reset, "reset");382rendezvous_with_vcpus(&time_run2, "run 2");383384mprotect(mem, slot_size, PROT_READ);385mprotect_ro_done = true;386sync_global_to_guest(vm, mprotect_ro_done);387388rendezvous_with_vcpus(&time_ro, "mprotect RO");389mprotect(mem, slot_size, PROT_READ | PROT_WRITE);390rendezvous_with_vcpus(&time_rw, "mprotect RW");391392time_rw = timespec_sub(time_rw, time_ro);393time_ro = timespec_sub(time_ro, time_run2);394time_run2 = timespec_sub(time_run2, time_reset);395time_reset = timespec_sub(time_reset, time_run1);396time_run1 = timespec_sub(time_run1, time_start);397398pr_info("run1 = %ld.%.9lds, reset = %ld.%.9lds, run2 = %ld.%.9lds, "399"ro = %ld.%.9lds, rw = %ld.%.9lds\n",400time_run1.tv_sec, time_run1.tv_nsec,401time_reset.tv_sec, time_reset.tv_nsec,402time_run2.tv_sec, time_run2.tv_nsec,403time_ro.tv_sec, time_ro.tv_nsec,404time_rw.tv_sec, time_rw.tv_nsec);405406/*407* Delete even numbered slots (arbitrary) and unmap the first half of408* the backing (also arbitrary) to verify KVM correctly drops all409* references to the removed regions.410*/411for (slot = (slot - 1) & ~1ull; slot >= first_slot; slot -= 2)412vm_set_user_memory_region(vm, slot, 0, 0, 0, NULL);413414kvm_munmap(mem, slot_size / 2);415416/* Sanity check that the vCPUs actually ran. */417for (i = 0; i < nr_vcpus; i++)418pthread_join(threads[i], NULL);419420/*421* Deliberately exit without deleting the remaining memslots or closing422* kvm_fd to test cleanup via mmu_notifier.release.423*/424}425426427