[PATCH guest_memfd] KVM: selftests: Add a memory region subtest to validate invalid flags
From: Sean Christopherson
Date: Mon Oct 30 2023 - 20:20:59 EST
Add a subtest to set_memory_region_test to verify that KVM rejects invalid
flags and combinations with -EINVAL.
Signed-off-by: Sean Christopherson <seanjc@xxxxxxxxxx>
---
Selftest that *tries* to detect cases where KVM allows v2 flags for
KVM_SET_USER_MEMORY_REGION. It's kinda worthless because KVM will likely fail
with EINVAL anyways, but maybe it'll provide meaningful coverage in concert
with a sanitizer?
.../selftests/kvm/set_memory_region_test.c | 49 +++++++++++++++++++
1 file changed, 49 insertions(+)
diff --git a/tools/testing/selftests/kvm/set_memory_region_test.c b/tools/testing/selftests/kvm/set_memory_region_test.c
index ca83e3307a98..268baf853bd6 100644
--- a/tools/testing/selftests/kvm/set_memory_region_test.c
+++ b/tools/testing/selftests/kvm/set_memory_region_test.c
@@ -326,6 +326,53 @@ static void test_zero_memory_regions(void)
}
#endif /* __x86_64__ */
+static void test_invalid_memory_region_flags(void)
+{
+ uint32_t supported_flags = KVM_MEM_LOG_DIRTY_PAGES;
+ const uint32_t v2_only_flags = KVM_MEM_PRIVATE;
+ struct kvm_vm *vm;
+ int r, i;
+
+#ifdef __x86_64__
+ supported_flags |= KVM_MEM_READONLY;
+
+ if (kvm_check_cap(KVM_CAP_VM_TYPES) & BIT(KVM_X86_SW_PROTECTED_VM))
+ vm = vm_create_barebones_protected_vm();
+ else
+#endif
+ vm = vm_create_barebones();
+
+ if (kvm_check_cap(KVM_CAP_MEMORY_ATTRIBUTES) & KVM_MEMORY_ATTRIBUTE_PRIVATE)
+ supported_flags |= KVM_MEM_PRIVATE;
+
+ for (i = 0; i < 32; i++) {
+ if ((supported_flags & BIT(i)) && !(v2_only_flags & BIT(i)))
+ continue;
+
+ r = __vm_set_user_memory_region(vm, MEM_REGION_SLOT, BIT(i),
+ MEM_REGION_GPA, MEM_REGION_SIZE, NULL);
+
+ TEST_ASSERT(r && errno == EINVAL,
+ "KVM_SET_USER_MEMORY_REGION should have failed on v2 only flag 0x%lx", BIT(i));
+
+ if (supported_flags & BIT(i))
+ continue;
+
+ r = __vm_set_user_memory_region2(vm, MEM_REGION_SLOT, BIT(i),
+ MEM_REGION_GPA, MEM_REGION_SIZE, NULL, 0, 0);
+ TEST_ASSERT(r && errno == EINVAL,
+ "KVM_SET_USER_MEMORY_REGION2 should have failed on unsupported flag 0x%lx", BIT(i));
+ }
+
+ if (supported_flags & KVM_MEM_PRIVATE) {
+ r = __vm_set_user_memory_region2(vm, MEM_REGION_SLOT,
+ KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_PRIVATE,
+ MEM_REGION_GPA, MEM_REGION_SIZE, NULL, 0, 0);
+ TEST_ASSERT(r && errno == EINVAL,
+ "KVM_SET_USER_MEMORY_REGION2 should have failed, dirty logging private memory is unsupported");
+ }
+}
+
/*
* Test it can be added memory slots up to KVM_CAP_NR_MEMSLOTS, then any
* tentative to add further slots should fail.
@@ -491,6 +538,8 @@ int main(int argc, char *argv[])
test_zero_memory_regions();
#endif
+ test_invalid_memory_region_flags();
+
test_add_max_memory_regions();
if (kvm_has_cap(KVM_CAP_GUEST_MEMFD) &&
base-commit: 881375a408c0f4ea451ff14545b59216d2923881
--
2.42.0.820.g83a721a137-goog