Back the ucall MMIO address with a read-only region in slot 1 when KVM_CAP_READONLY_MEM is available. Writes still exit as MMIO, while overlapping memslot creation is rejected. Start test memslots at slot 2, leaving slot 1 reserved by convention even when read-only memory is unsupported. Signed-off-by: Tharit Tangkijwanichakul --- .../testing/selftests/kvm/include/kvm_util.h | 2 +- tools/testing/selftests/kvm/lib/kvm_util.c | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/tools/testing/selftests/kvm/include/kvm_util.h b/tools/testing/selftests/kvm/include/kvm_util.h index 759d604d44ce..4dbb2ef332fc 100644 --- a/tools/testing/selftests/kvm/include/kvm_util.h +++ b/tools/testing/selftests/kvm/include/kvm_util.h @@ -30,7 +30,7 @@ #define KVM_DEV_PATH "/dev/kvm" #define KVM_MAX_VCPUS 512 -#define TEST_MEM_SLOT_BASE 1 +#define TEST_MEM_SLOT_BASE 2 #define NSEC_PER_SEC 1000000000L diff --git a/tools/testing/selftests/kvm/lib/kvm_util.c b/tools/testing/selftests/kvm/lib/kvm_util.c index 9ddc047d5c27..73e28814a226 100644 --- a/tools/testing/selftests/kvm/lib/kvm_util.c +++ b/tools/testing/selftests/kvm/lib/kvm_util.c @@ -20,6 +20,7 @@ #include #define KVM_UTIL_MIN_PFN 2 +#define KVM_UCALL_MEMSLOT 1 u32 kvm_random_seed; struct kvm_random_state kvm_rng; @@ -492,6 +493,7 @@ struct kvm_vm *__vm_create(struct vm_shape shape, u32 nr_runnable_vcpus, struct userspace_mem_region *slot0; struct kvm_vm *vm; int i, flags; + gpa_t mmio_gpa; kvm_set_files_rlimit(nr_runnable_vcpus); @@ -514,14 +516,19 @@ struct kvm_vm *__vm_create(struct vm_shape shape, u32 nr_runnable_vcpus, kvm_vm_elf_load(vm, program_invocation_name); - /* - * TODO: Add proper defines to protect the library's memslots, and then - * carve out memslot1 for the ucall MMIO address. KVM treats writes to - * read-only memslots as MMIO, and creating a read-only memslot for the - * MMIO region would prevent silently clobbering the MMIO region. + /* KVM treats writes to read-only memslots as MMIO, and creating + * a read-only memslot for the MMIO region would prevent silently + * clobbering the MMIO region. */ slot0 = memslot2region(vm, 0); - ucall_init(vm, slot0->region.guest_phys_addr + slot0->region.memory_size); + mmio_gpa = slot0->region.guest_phys_addr + slot0->region.memory_size; + ucall_init(vm, mmio_gpa); + + if (vm_check_cap(vm, KVM_CAP_READONLY_MEM)) + vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, + mmio_gpa, KVM_UCALL_MEMSLOT, + vm_adjust_num_guest_pages(vm->mode, 1), + KVM_MEM_READONLY); if (kvm_random_seed != last_kvm_seed) kvm_seed_rng(kvm_random_seed); -- 2.53.0