diff mbox series

[2/2] KVM: selftests: Add assertion for mem_size in vm_mem_add()

Message ID 20240424224434.14166-2-dongsheng.x.zhang@intel.com (mailing list archive)
State New
Headers show
Series [1/2] KVM: selftests: Fix nx_huge_pages_test for default_hugepagesz=1G | expand

Commit Message

Zhang, Dongsheng X April 24, 2024, 10:44 p.m. UTC
From: donsheng <dongsheng.x.zhang@intel.com>

If mmap() is called with MAP_HUGETLB and the requested mapping size is
not a multiple of the underlying hugetlb page size, kernel will automatically
align the mmap size, but munmap() will fail if you specify the size you asked
for rather than the size that was assigned by Linux kernel mmap().

To avoid munmap() failure, add sanity check for mem_size in vm_mem_add() to
ensure that mem_size is aligned to page size of the underlying hugetlb backing src.

This assertion helps to ensure that vm_mem_add() is called with aligned mapping size,
especially when vm_mem_add() is called to add guest memory backed by
VM_MEM_SRC_ANONYMOUS_HUGETLB which relies on the default hugetlb page size.

Signed-off-by: donsheng <dongsheng.x.zhang@intel.com>
---
 tools/testing/selftests/kvm/lib/kvm_util.c | 5 +++++
 1 file changed, 5 insertions(+)
diff mbox series

Patch

diff --git a/tools/testing/selftests/kvm/lib/kvm_util.c b/tools/testing/selftests/kvm/lib/kvm_util.c
index b2262b5fad9e..827bb3d57815 100644
--- a/tools/testing/selftests/kvm/lib/kvm_util.c
+++ b/tools/testing/selftests/kvm/lib/kvm_util.c
@@ -985,6 +985,11 @@  void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type,
 		"  vm->max_gfn: 0x%lx vm->page_size: 0x%x",
 		guest_paddr, npages, vm->max_gfn, vm->page_size);
 
+	TEST_ASSERT(!(is_backing_src_hugetlb(src_type) &&
+		(mem_size & (backing_src_pagesz - 1))),
+		"mem_size 0x%lx is not aligned to backing src %s's page size 0x%lx",
+		mem_size, vm_mem_backing_src_alias(src_type)->name, backing_src_pagesz);
+
 	/*
 	 * Confirm a mem region with an overlapping address doesn't
 	 * already exist.