Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
255 changes: 155 additions & 100 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/clippy-tracing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ bench = false

[dependencies]
clap = { version = "4.6.1", features = ["derive"] }
itertools = "0.14.0"
itertools = "0.15.0"
proc-macro2 = { version = "1.0.106", features = ["span-locations"] }
quote = "1.0.45"
syn = { version = "2.0.117", features = ["full", "extra-traits", "visit", "visit-mut", "printing"] }
Expand Down
2 changes: 1 addition & 1 deletion src/firecracker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ serde = { version = "1.0.228" }
serde_json = "1.0.149"

[dev-dependencies]
cargo_toml = "0.22.3"
cargo_toml = "1.0.0"
libc = "0.2.186"
regex = { version = "1.12.3", default-features = false, features = [
"std",
Expand Down
2 changes: 2 additions & 0 deletions src/firecracker/src/api_server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ mod tests {
snapshot_type: SnapshotType::Diff,
snapshot_path: PathBuf::new(),
mem_file_path: PathBuf::new(),
vmstate_only: false,
})),
start_time_us,
);
Expand All @@ -290,6 +291,7 @@ mod tests {
snapshot_type: SnapshotType::Diff,
snapshot_path: PathBuf::new(),
mem_file_path: PathBuf::new(),
vmstate_only: false,
})),
start_time_us,
);
Expand Down
24 changes: 24 additions & 0 deletions src/firecracker/src/api_server/request/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ fn parse_put_snapshot_load(body: &Body) -> Result<ParsedRequest, RequestError> {
network_overrides: snapshot_config.network_overrides,
vsock_override: snapshot_config.vsock_override,
clock_realtime: snapshot_config.clock_realtime,
uffd_base_file: snapshot_config.uffd_base_file,
};

// Construct the `ParsedRequest` object.
Expand Down Expand Up @@ -147,6 +148,7 @@ mod tests {
snapshot_type: SnapshotType::Diff,
snapshot_path: PathBuf::from("foo"),
mem_file_path: PathBuf::from("bar"),
vmstate_only: false,
};
assert_eq!(
vmm_action_from_request(parse_put_snapshot(&Body::new(body), Some("create")).unwrap()),
Expand All @@ -161,6 +163,23 @@ mod tests {
snapshot_type: SnapshotType::Full,
snapshot_path: PathBuf::from("foo"),
mem_file_path: PathBuf::from("bar"),
vmstate_only: false,
};
assert_eq!(
vmm_action_from_request(parse_put_snapshot(&Body::new(body), Some("create")).unwrap()),
VmmAction::CreateSnapshot(expected_config)
);

let body = r#"{
"snapshot_path": "foo",
"mem_file_path": "bar",
"vmstate_only": true
}"#;
let expected_config = CreateSnapshotParams {
snapshot_type: SnapshotType::Full,
snapshot_path: PathBuf::from("foo"),
mem_file_path: PathBuf::from("bar"),
vmstate_only: true,
};
assert_eq!(
vmm_action_from_request(parse_put_snapshot(&Body::new(body), Some("create")).unwrap()),
Expand Down Expand Up @@ -191,6 +210,7 @@ mod tests {
network_overrides: vec![],
vsock_override: None,
clock_realtime: false,
uffd_base_file: None,
};
let mut parsed_request = parse_put_snapshot(&Body::new(body), Some("load")).unwrap();
assert!(
Expand Down Expand Up @@ -223,6 +243,7 @@ mod tests {
network_overrides: vec![],
vsock_override: None,
clock_realtime: false,
uffd_base_file: None,
};
let mut parsed_request = parse_put_snapshot(&Body::new(body), Some("load")).unwrap();
assert!(
Expand Down Expand Up @@ -255,6 +276,7 @@ mod tests {
network_overrides: vec![],
vsock_override: None,
clock_realtime: false,
uffd_base_file: None,
};
let mut parsed_request = parse_put_snapshot(&Body::new(body), Some("load")).unwrap();
assert!(
Expand Down Expand Up @@ -296,6 +318,7 @@ mod tests {
}],
vsock_override: None,
clock_realtime: false,
uffd_base_file: None,
};
let mut parsed_request = parse_put_snapshot(&Body::new(body), Some("load")).unwrap();
assert!(
Expand Down Expand Up @@ -325,6 +348,7 @@ mod tests {
network_overrides: vec![],
vsock_override: None,
clock_realtime: false,
uffd_base_file: None,
};
let parsed_request = parse_put_snapshot(&Body::new(body), Some("load")).unwrap();
assert_eq!(
Expand Down
15 changes: 15 additions & 0 deletions src/firecracker/swagger/firecracker.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1624,6 +1624,11 @@ definitions:
description:
Type of snapshot to create. It is optional and by default, a full
snapshot is created.
vmstate_only:
type: boolean
description:
Write only the microVM state file and skip the guest-memory leg
entirely (mem_file_path is ignored). Optional and defaults to false.

NetworkOverride:
type: object
Expand Down Expand Up @@ -1710,6 +1715,16 @@ definitions:
elapsed since the snapshot was taken. When false (default), kvmclock resumes
from where it was at snapshot time. This option may be extended to other clock
sources and CPU architectures in the future."
uffd_base_file:
type: string
description:
Unified-memory-substrate base backing (engrams ADR 0045 v2b). When set
with the Uffd memory backend, guest memory is created as MAP_PRIVATE of
this shmem file instead of anonymous, and the UFFD registration uses
MISSING|MINOR. The external handler resolves base-identical pages with
UFFDIO_CONTINUE (page-cache sharing across same-template microVMs) and
divergent pages with UFFDIO_COPY; guest writes COW natively. Invalid
with the File backend. Optional.


TokenBucket:
Expand Down
5 changes: 3 additions & 2 deletions src/vmm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ serde = { version = "1.0.228", features = ["derive", "rc"] }
serde_json = "1.0.149"
slab = "0.4.12"
thiserror = "2.0.18"
userfaultfd = "0.9.0"
# linux5_13: RegisterMode::MINOR for the ADR 0045 substrate (v2b) registration.
userfaultfd = { version = "0.9.0", features = ["linux5_13"] }
utils = { path = "../utils" }
uuid = "1.23.1"
vhost = { version = "0.15.0", features = ["vhost-user-frontend"] }
Expand All @@ -65,7 +66,7 @@ vm-fdt = "0.3.0"
[dev-dependencies]
criterion = { version = "0.8.2", default-features = false }
device_tree = "1.1.0"
itertools = "0.14.0"
itertools = "0.15.0"
proptest = { version = "1.11.0", default-features = false, features = ["std"] }

[[bench]]
Expand Down
134 changes: 117 additions & 17 deletions src/vmm/src/persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::sync::{Arc, Mutex};

use semver::Version;
use serde::{Deserialize, Serialize};
use userfaultfd::{FeatureFlags, Uffd, UffdBuilder};
use userfaultfd::{FeatureFlags, RegisterMode, Uffd, UffdBuilder};
use vmm_sys_util::sock_ctrl_msg::ScmSocket;

#[cfg(target_arch = "aarch64")]
Expand Down Expand Up @@ -174,18 +174,23 @@ pub fn create_snapshot(

snapshot_state_to_file(&microvm_state, &params.snapshot_path)?;

let kvm_vm = vmm.vm.as_kvm().ok_or_else(|| {
CreateSnapshotError::MicrovmState(MicrovmStateError::NotAllowed(
"snapshot requires KVM".into(),
))
})?;
kvm_vm.snapshot_memory_to_file(&params.mem_file_path, params.snapshot_type)?;

// We need to mark queues as dirty again for all activated devices. The reason we
// do it here is that we don't mark pages as dirty during runtime
// for queue objects.
vmm.device_manager
.mark_virtio_queue_memory_dirty(kvm_vm.guest_memory());
// engram v3 (ADR 0045 C2): vmstate-only capture for post-copy live
// migration — skip the memory leg (and its dirty-queue correction, which
// only compensates for the memory dump) entirely.
if !params.vmstate_only {
let kvm_vm = vmm.vm.as_kvm().ok_or_else(|| {
CreateSnapshotError::MicrovmState(MicrovmStateError::NotAllowed(
"snapshot requires KVM".into(),
))
})?;
kvm_vm.snapshot_memory_to_file(&params.mem_file_path, params.snapshot_type)?;

// We need to mark queues as dirty again for all activated devices. The reason we
// do it here is that we don't mark pages as dirty during runtime
// for queue objects.
vmm.device_manager
.mark_virtio_queue_memory_dirty(kvm_vm.guest_memory());
}

Ok(())
}
Expand Down Expand Up @@ -448,6 +453,12 @@ pub fn restore_from_snapshot(
)
.into());
}
if params.uffd_base_file.is_some() {
return Err(RestoreFromSnapshotGuestMemoryError::Uffd(
GuestMemoryFromUffdError::BaseFileRequiresUffdBackend,
)
.into());
}
(
guest_memory_from_file(mem_backend_path, mem_state, track_dirty_pages)
.map_err(RestoreFromSnapshotGuestMemoryError::File)?,
Expand All @@ -459,6 +470,7 @@ pub fn restore_from_snapshot(
mem_state,
track_dirty_pages,
vm_resources.machine_config.huge_pages,
params.uffd_base_file.as_deref(),
)
.map_err(RestoreFromSnapshotGuestMemoryError::Uffd)?,
};
Expand Down Expand Up @@ -531,16 +543,25 @@ pub enum GuestMemoryFromUffdError {
Connect(#[from] std::io::Error),
/// Failed to sends file descriptor: {0}
Send(#[from] vmm_sys_util::errno::Error),
/// `uffd_base_file` is only supported with the Uffd memory backend.
BaseFileRequiresUffdBackend,
/// `uffd_base_file` is not supported with hugetlbfs-backed snapshots (UFFD minor faults are shmem-only here).
BaseFileHugetlbfs,
/// Failed to open uffd_base_file: {0}
OpenBaseFile(std::io::Error),
/// Failed to map guest memory from uffd_base_file: {0}
BaseFileMap(MemoryError),
}

fn guest_memory_from_uffd(
mem_uds_path: &Path,
mem_state: &GuestMemoryState,
track_dirty_pages: bool,
huge_pages: HugePageConfig,
base_file: Option<&Path>,
) -> Result<(Vec<GuestRegionMmap>, Option<Uffd>), GuestMemoryFromUffdError> {
let (guest_memory, backend_mappings) =
create_guest_memory(mem_state, track_dirty_pages, huge_pages)?;
create_guest_memory(mem_state, track_dirty_pages, huge_pages, base_file)?;

let mut uffd_builder = UffdBuilder::new();

Expand All @@ -557,8 +578,17 @@ fn guest_memory_from_uffd(
.create()
.map_err(GuestMemoryFromUffdError::Create)?;

// ADR 0045 substrate v2b: with a base file backing, register MISSING|MINOR
// so the handler can resolve base-identical pages with UFFDIO_CONTINUE
// (shared page cache) and divergent pages with UFFDIO_COPY (private).
// Without it, the stock MISSING-only registration is byte-identical.
let register_mode = if base_file.is_some() {
RegisterMode::MISSING | RegisterMode::MINOR
} else {
RegisterMode::MISSING
};
for mem_region in guest_memory.iter() {
uffd.register(mem_region.as_ptr().cast(), mem_region.size() as _)
uffd.register_with_mode(mem_region.as_ptr().cast(), mem_region.size() as _, register_mode)
.map_err(GuestMemoryFromUffdError::Register)?;
}

Expand All @@ -571,8 +601,22 @@ fn create_guest_memory(
mem_state: &GuestMemoryState,
track_dirty_pages: bool,
huge_pages: HugePageConfig,
base_file: Option<&Path>,
) -> Result<(Vec<GuestRegionMmap>, Vec<GuestRegionUffdMapping>), GuestMemoryFromUffdError> {
let guest_memory = memory::anonymous(mem_state.regions(), track_dirty_pages, huge_pages)?;
let guest_memory = match base_file {
Some(path) => {
// ADR 0045 substrate v2b: MAP_PRIVATE of the shared base shm file.
// Read-only fd is enough — guest writes COW to private anon pages;
// only the external handler ever writes the base (by path).
if huge_pages.is_hugetlbfs() {
return Err(GuestMemoryFromUffdError::BaseFileHugetlbfs);
}
let file = std::fs::File::open(path).map_err(GuestMemoryFromUffdError::OpenBaseFile)?;
memory::snapshot_file(file, mem_state.regions(), track_dirty_pages)
.map_err(GuestMemoryFromUffdError::BaseFileMap)?
}
None => memory::anonymous(mem_state.regions(), track_dirty_pages, huge_pages)?,
};
let mut backend_mappings = Vec::with_capacity(guest_memory.len());
let mut offset = 0;
for mem_region in guest_memory.iter() {
Expand Down Expand Up @@ -777,14 +821,70 @@ mod tests {
};

let (_, uffd_regions) =
create_guest_memory(&mem_state, false, HugePageConfig::None).unwrap();
create_guest_memory(&mem_state, false, HugePageConfig::None, None).unwrap();

assert_eq!(uffd_regions.len(), 1);
assert_eq!(uffd_regions[0].size, 0x20000);
assert_eq!(uffd_regions[0].offset, 0);
assert_eq!(uffd_regions[0].page_size, HugePageConfig::None.page_size());
}

/// ADR 0045 substrate v2b: guest memory created over a base file maps it
/// MAP_PRIVATE — content reads through from the file (page-cache shared),
/// guest-side writes COW privately and never reach the file, and the
/// backend mappings carry the same sequential file offsets as the
/// anonymous path.
#[test]
fn test_create_guest_memory_with_base_file() {
use std::io::Write;

let region_size: usize = 0x20000;
let base = TempFile::new().unwrap();
let pattern: Vec<u8> = (0..region_size).map(|i| (i % 251) as u8).collect();
base.as_file().write_all(&pattern).unwrap();

let mem_state = GuestMemoryState {
regions: vec![GuestMemoryRegionState {
base_address: 0,
size: region_size,
region_type: GuestRegionType::Dram,
plugged: vec![true],
}],
};

let (guest_memory, uffd_regions) =
create_guest_memory(&mem_state, false, HugePageConfig::None, Some(base.as_path()))
.unwrap();
assert_eq!(uffd_regions.len(), 1);
assert_eq!(uffd_regions[0].size, region_size);
assert_eq!(uffd_regions[0].offset, 0);

// Content reads through from the base file (no uffd registered yet, so
// plain page-cache faults serve these).
let ptr = guest_memory[0].as_ptr();
// SAFETY: ptr covers region_size bytes of the mapping we just created.
let view = unsafe { std::slice::from_raw_parts_mut(ptr, region_size) };
assert_eq!(&view[..64], &pattern[..64]);
assert_eq!(view[0x10000], pattern[0x10000]);

// A write COWs privately: visible through the mapping, absent from the file.
view[0x10000] = 0xEE;
assert_eq!(view[0x10000], 0xEE);
let mut on_disk = vec![0u8; 4];
std::os::unix::fs::FileExt::read_exact_at(base.as_file(), &mut on_disk, 0x10000).unwrap();
assert_eq!(on_disk[0], pattern[0x10000], "guest write leaked into the base file");

// Hugetlbfs + base file is rejected.
let err = create_guest_memory(
&mem_state,
false,
HugePageConfig::Hugetlbfs2M,
Some(base.as_path()),
)
.unwrap_err();
assert!(matches!(err, GuestMemoryFromUffdError::BaseFileHugetlbfs));
}

#[test]
fn test_send_uffd_handshake() {
#[allow(deprecated)]
Expand Down
2 changes: 2 additions & 0 deletions src/vmm/src/rpc_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1240,6 +1240,7 @@ mod tests {
snapshot_type: SnapshotType::Full,
snapshot_path: PathBuf::new(),
mem_file_path: PathBuf::new(),
vmstate_only: false,
},
)));
#[cfg(target_arch = "x86_64")]
Expand Down Expand Up @@ -1331,6 +1332,7 @@ mod tests {
network_overrides: vec![],
vsock_override: None,
clock_realtime: false,
uffd_base_file: None,
},
)));
check_unsupported(runtime_request(VmmAction::SetEntropyDevice(
Expand Down
Loading
Loading