From 0a380f4e11973eeae0690256d94240a4f81e05b4 Mon Sep 17 00:00:00 2001 From: Patrick Roy Date: Wed, 5 Feb 2025 16:59:39 +0000 Subject: [PATCH] fix: stop `dup(2)`-ing fds when setting up guest memory Currently, when backing guest memory by memfd or when mmaping a snapshot file, we duplicate the file descriptor once per memslot. This is not necessary: KVM will happily accept the same fd into multiple memslots, and even rust-vmm supports APIs for this (by storing `Arc` instead of just `File` in `FileOffset`, we can actually share the same `File` reference between multiple memory regions). So let's make use of this capability. Signed-off-by: Patrick Roy --- src/vmm/src/vstate/memory.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/vmm/src/vstate/memory.rs b/src/vmm/src/vstate/memory.rs index a9e16a8c2e6..b89de3453c2 100644 --- a/src/vmm/src/vstate/memory.rs +++ b/src/vmm/src/vstate/memory.rs @@ -7,6 +7,7 @@ use std::fs::File; use std::io::SeekFrom; +use std::sync::Arc; use libc::c_int; use serde::{Deserialize, Serialize}; @@ -35,8 +36,6 @@ pub type GuestMmapRegion = vm_memory::MmapRegion>; /// Errors associated with dumping guest memory to file. #[derive(Debug, thiserror::Error, displaydoc::Display)] pub enum MemoryError { - /// Cannot access file: {0} - FileError(std::io::Error), /// Cannot create memory: {0} CreateMemory(VmMemoryError), /// Cannot create memory region: {0} @@ -173,6 +172,7 @@ impl GuestMemoryExtension for GuestMemoryMmap { track_dirty_pages: bool, ) -> Result { let mut offset = 0; + let file = file.map(Arc::new); let regions = regions .map(|(start, size)| { let mut builder = MmapRegionBuilder::new_with_bitmap( @@ -183,8 +183,7 @@ impl GuestMemoryExtension for GuestMemoryMmap { .with_mmap_flags(libc::MAP_NORESERVE | mmap_flags); if let Some(ref file) = file { - let file_offset = - FileOffset::new(file.try_clone().map_err(MemoryError::FileError)?, offset); + let file_offset = FileOffset::from_arc(Arc::clone(file), offset); builder = builder.with_file_offset(file_offset); }