[PATCH v2 12/13] KVM: selftests: Verify that faulting in private guest_memfd memory fails

Sean Christopherson
2025-10-03T23:26:33Z

Add a guest_memfd testcase to verify that faulting in private memory gets
a SIGBUS. For now, test only the case where memory is private by default
since KVM doesn't yet support in-place conversion.

Deliberately run the CoW test with and without INIT_SHARED set as KVM
should disallow MAP_PRIVATE regardless of whether the memory itself is
private from a CoCo perspective.

Cc: Ackerley Tng <ackerleytng@google.com>
Reviewed-by: Fuad Tabba <tabba@google.com>
Tested-by: Fuad Tabba <tabba@google.com>
Reviewed-by: David Hildenbrand <david@redhat.com>
Reviewed-by: Ackerley Tng <ackerleytng@google.com>
Signed-off-by: Sean Christopherson <seanjc@google.com>
---
.../testing/selftests/kvm/guest_memfd_test.c | 26 +++++++++++++++----
1 file changed, 21 insertions(+), 5 deletions(-)

diff --git a/tools/testing/selftests/kvm/guest_memfd_test.c b/tools/testing/selftests/kvm/guest_memfd_test.c
index 73c2e54e7297..f5372fdf096d 100644
--- a/tools/testing/selftests/kvm/guest_memfd_test.c
+++ b/tools/testing/selftests/kvm/guest_memfd_test.c
@@ -75,9 +75,8 @@ static void test_mmap_supported(int fd, size_t total_size)
kvm_munmap(mem, total_size);
}

-static void test_fault_overflow(int fd, size_t total_size)
+static void test_fault_sigbus(int fd, size_t accessible_size, size_t map_size)
{
- size_t map_size = total_size * 4;
const char val = 0xaa;
char *mem;
size_t i;
@@ -86,12 +85,22 @@ static void test_fault_overflow(int fd, size_t total_size)

TEST_EXPECT_SIGBUS(memset(mem, val, map_size));

- for (i = 0; i < total_size; i++)
+ for (i = 0; i < accessible_size; i++)
TEST_ASSERT_EQ(READ_ONCE(mem[i]), val);

kvm_munmap(mem, map_size);
}

+static void test_fault_overflow(int fd, size_t total_size)
+{
+ test_fault_sigbus(fd, total_size, total_size * 4);
+}
+
+static void test_fault_private(int fd, size_t total_size)
+{
+ test_fault_sigbus(fd, 0, total_size);
+}
+
static void test_mmap_not_supported(int fd, size_t total_size)
{
char *mem;
@@ -260,9 +269,14 @@ static void __test_guest_memfd(struct kvm_vm *vm, uint64_t flags)
gmem_test(file_read_write, vm, flags);

if (flags & GUEST_MEMFD_FLAG_MMAP) {
- gmem_test(mmap_supported, vm, flags);
+ if (flags & GUEST_MEMFD_FLAG_INIT_SHARED) {
+ gmem_test(mmap_supported, vm, flags);
+ gmem_test(fault_overflow, vm, flags);
+ } else {
+ gmem_test(fault_private, vm, flags);
+ }
+
gmem_test(mmap_cow, vm, flags);
- gmem_test(fault_overflow, vm, flags);
} else {
gmem_test(mmap_not_supported, vm, flags);
}
@@ -282,6 +296,8 @@ static void test_guest_memfd(unsigned long vm_type)
__test_guest_memfd(vm, 0);

flags = vm_check_cap(vm, KVM_CAP_GUEST_MEMFD_FLAGS);
+ if (flags & GUEST_MEMFD_FLAG_MMAP)
+ __test_guest_memfd(vm, GUEST_MEMFD_FLAG_MMAP);

/* MMAP should always be supported if INIT_SHARED is supported. */
if (flags & GUEST_MEMFD_FLAG_INIT_SHARED)
--
2.51.0.618.g983fd99d29-goog