Skip to content

Commit df2c3ac

Browse files
committed
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<File>` 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 <[email protected]>
1 parent c862760 commit df2c3ac

File tree

1 file changed

+3
-4
lines changed

1 file changed

+3
-4
lines changed

src/vmm/src/vstate/memory.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
use std::fs::File;
99
use std::io::SeekFrom;
10+
use std::sync::Arc;
1011

1112
use libc::c_int;
1213
use serde::{Deserialize, Serialize};
@@ -35,8 +36,6 @@ pub type GuestMmapRegion = vm_memory::MmapRegion<Option<AtomicBitmap>>;
3536
/// Errors associated with dumping guest memory to file.
3637
#[derive(Debug, thiserror::Error, displaydoc::Display)]
3738
pub enum MemoryError {
38-
/// Cannot access file: {0}
39-
FileError(std::io::Error),
4039
/// Cannot create memory: {0}
4140
CreateMemory(VmMemoryError),
4241
/// Cannot create memory region: {0}
@@ -173,6 +172,7 @@ impl GuestMemoryExtension for GuestMemoryMmap {
173172
track_dirty_pages: bool,
174173
) -> Result<Self, MemoryError> {
175174
let mut offset = 0;
175+
let file = file.map(Arc::new);
176176
let regions = regions
177177
.map(|(start, size)| {
178178
let mut builder = MmapRegionBuilder::new_with_bitmap(
@@ -183,8 +183,7 @@ impl GuestMemoryExtension for GuestMemoryMmap {
183183
.with_mmap_flags(libc::MAP_NORESERVE | mmap_flags);
184184

185185
if let Some(ref file) = file {
186-
let file_offset =
187-
FileOffset::new(file.try_clone().map_err(MemoryError::FileError)?, offset);
186+
let file_offset = FileOffset::from_arc(Arc::clone(file), offset);
188187

189188
builder = builder.with_file_offset(file_offset);
190189
}

0 commit comments

Comments
 (0)