From 9a1b7317995aee01522a9df5ab433da1476ce1a0 Mon Sep 17 00:00:00 2001 From: Egor Lazarchuk Date: Tue, 2 Dec 2025 17:09:11 +0000 Subject: [PATCH] feat(virtio-pmem): add a Drop implementation Event though during Firecracker normal run pmem devices are never removed, so there is no need to unmap memory, it is important for fuzzer runs, as otherwise it runs out of virtual memory. Additionally make `mmap_backing_file` private since it is only called from within Pmem device. Signed-off-by: Egor Lazarchuk --- src/vmm/src/devices/virtio/pmem/device.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/vmm/src/devices/virtio/pmem/device.rs b/src/vmm/src/devices/virtio/pmem/device.rs index 8ac150fb894..49e79096391 100644 --- a/src/vmm/src/devices/virtio/pmem/device.rs +++ b/src/vmm/src/devices/virtio/pmem/device.rs @@ -95,6 +95,17 @@ pub struct Pmem { pub config: PmemConfig, } +impl Drop for Pmem { + fn drop(&mut self) { + let mmap_len = align_up(self.file_len, Self::ALIGNMENT); + // SAFETY: `mmap_ptr` is a valid pointer since Pmem can only be created with `new*` methods. + // Mapping size calculation is same for original mmap call. + unsafe { + _ = libc::munmap(self.mmap_ptr as *mut libc::c_void, u64_to_usize(mmap_len)); + } + } +} + impl Pmem { // Pmem devices need to have address and size to be // a multiple of 2MB @@ -130,10 +141,7 @@ impl Pmem { }) } - pub fn mmap_backing_file( - path: &str, - read_only: bool, - ) -> Result<(File, u64, u64, u64), PmemError> { + fn mmap_backing_file(path: &str, read_only: bool) -> Result<(File, u64, u64, u64), PmemError> { let file = OpenOptions::new() .read(true) .write(!read_only)