From 6f258f93c5ca3f9fb1fa288dae843dafed428c30 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 9 Jun 2026 16:53:30 -0700 Subject: [PATCH 1/2] chore(fc-fork): bump to substrate-v2 (uffd_base_file + MISSING|MINOR) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Picks up cortexapps/firecracker#4 — the ADR 0045 D1 fork surface: an optional uffd_base_file load param backing Uffd-restored guest memory MAP_PRIVATE on a shmem base file with MISSING|MINOR registration. Inert in this binary: engrams never sends the field yet (that's the D2 wiring PR), and the default path is byte-identical to the current fork (R2 guard verifies). The fleet roll this triggers ships a drop-in. Co-Authored-By: Claude Fable 5 --- third_party/firecracker | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/firecracker b/third_party/firecracker index 5ca2fba47..4a9636d06 160000 --- a/third_party/firecracker +++ b/third_party/firecracker @@ -1 +1 @@ -Subproject commit 5ca2fba475aebfbfbd47e76f35cfa5fb6320df21 +Subproject commit 4a9636d06620897647e649c6fb6f3df94ebfaa50 From d43748220f3bff836f3328518cc307bf6f2e6917 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 9 Jun 2026 17:29:41 -0700 Subject: [PATCH 2/2] =?UTF-8?q?feat(ADR=200045=20D2):=20substrate=20v2b=20?= =?UTF-8?q?wiring=20=E2=80=94=20shared=20base=20shm=20+=20CONTINUE=20arm?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engrams half of the unified memory substrate, dark behind ENGRAM_FC_UFFD_BASE_DIR (unset everywhere; D3/D4 parity gates flip it on and retire the knob): - client: SnapshotLoadBody grows uffd_base_file (skip_serializing_if — bodies stay byte-identical to stock when off). - engram-sandbox-firecracker: FirecrackerConfig.uffd_base_dir; the Uffd restore leg derives /-v.base through one helper for both the handler spawn (--base-shm) and the FC load, so the two can't diverge. - engram-uffd-handler: a BaseShm module (create+size before the UDS binds — FC's open is ordered after wait_for_socket; SEEK_HOLE populated-probe; idempotent canonical pwrites) and the substrate resolution: ResolvedPage::Canonical → ensure-base-populated + UFFDIO_CONTINUE over the chunk range (one page-cache copy shared by every same-template VM; the populated fast path skips the chunk fetch entirely), ResolvedPage::Chunk → UFFDIO_COPY as today, zero chunks → ZEROPAGE with COPY-of-zeros fallback. The prefault path routes canonical positions through the shared install too — a prefault COPY would privately duplicate exactly the hot pages the substrate shares. - host-agent env + Tiltfile plumbing. - tests/substrate_uffd_base.rs (fork-gated like stock_fork_snapshot_compat, wired into ci.yml): restore round-trips on the forked FC, the base shm is created/sized/populated by the handler, and a sibling restores against the already-warm base — green on engram-dev real KVM (21s). snapshot_uffd (stock path, base off) stays green; Linux clippy clean. Rides the fc-fork-substrate-v2-bump gitlink (cortexapps/firecracker#4). Co-Authored-By: Claude Fable 5 --- .github/workflows/ci.yml | 1 + Tiltfile | 6 + crates/engram-host-agent/src/live_attach.rs | 1 + crates/engram-host-agent/src/main.rs | 7 + .../engram-sandbox-firecracker/src/client.rs | 45 ++- crates/engram-sandbox-firecracker/src/lib.rs | 61 +++++ .../tests/substrate_uffd_base.rs | 259 ++++++++++++++++++ crates/engram-uffd-handler/Cargo.toml | 4 +- crates/engram-uffd-handler/src/base_shm.rs | 139 ++++++++++ crates/engram-uffd-handler/src/lib.rs | 2 + crates/engram-uffd-handler/src/main.rs | 34 ++- crates/engram-uffd-handler/src/runtime.rs | 189 ++++++++++++- 12 files changed, 736 insertions(+), 12 deletions(-) create mode 100644 crates/engram-sandbox-firecracker/tests/substrate_uffd_base.rs create mode 100644 crates/engram-uffd-handler/src/base_shm.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 818fb7e55..930a8edf1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -626,6 +626,7 @@ jobs: --test file_restore_shared_rss \ --test stock_fork_snapshot_compat \ --test substrate_kernel_capabilities \ + --test substrate_uffd_base \ --run-ignored ignored-only \ --no-fail-fast \ --test-threads=1 diff --git a/Tiltfile b/Tiltfile index c49096b5e..80b2105e7 100644 --- a/Tiltfile +++ b/Tiltfile @@ -397,6 +397,12 @@ def host_agent_resource(name, grpc_port, metrics_port, work_dir, nbd_csv): # where the handler is present. (Base-create stays code-default # `file`, which needs no handler.) 'ENGRAM_FC_RESTORE_MODE': env_or('ENGRAM_FC_RESTORE_MODE', 'file'), + # ADR 0045 substrate (v2b): point at a tmpfs dir (e.g. + # /dev/shm/engram) to back Uffd restores with a shared + # per-template base shm. Empty = off (stock anonymous Uffd). + # Must be listed here: the host-agent runs under sudo + # --preserve-env=, which scrubs unlisted vars. + 'ENGRAM_FC_UFFD_BASE_DIR': env_or('ENGRAM_FC_UFFD_BASE_DIR', ''), # gRPC plumbing — coord dials advertise, host-agent listens on # bind. Same machine in dev, so loopback works for both. 'ENGRAM_GRPC_LISTEN_ADDR': '127.0.0.1:' + grpc_port, diff --git a/crates/engram-host-agent/src/live_attach.rs b/crates/engram-host-agent/src/live_attach.rs index f71ae81ac..7cf66cdd5 100644 --- a/crates/engram-host-agent/src/live_attach.rs +++ b/crates/engram-host-agent/src/live_attach.rs @@ -271,6 +271,7 @@ mod tests { guest_otel_endpoint: None, firecracker_bin: PathBuf::from("/nonexistent/firecracker"), uffd_handler_bin: PathBuf::from("/nonexistent/engram-uffd-handler"), + uffd_base_dir: None, restore_mode: engram_sandbox_firecracker::RestoreMode::File, base_restore_mode: None, track_dirty_pages: false, diff --git a/crates/engram-host-agent/src/main.rs b/crates/engram-host-agent/src/main.rs index 6a0a6809f..e7e31f9ab 100644 --- a/crates/engram-host-agent/src/main.rs +++ b/crates/engram-host-agent/src/main.rs @@ -331,6 +331,13 @@ async fn main() -> Result<(), HostAgentError> { if let Ok(p) = std::env::var("ENGRAM_FC_UFFD_HANDLER_BIN") { fc_cfg.uffd_handler_bin = p.into(); } + // ADR 0045 unified memory substrate (v2b): when + // ENGRAM_FC_UFFD_BASE_DIR points at a tmpfs dir, Uffd-mode + // restores back guest memory MAP_PRIVATE on a per-template + // base shm file there — canonical pages become one shared + // page-cache copy per host (the D2 rollout gate; D3/D4 + // parity flips retire the knob). + fc_cfg.uffd_base_dir = engram_sandbox_firecracker::uffd_base_dir_from_env(); // ADR 0014 M1.12: each FC host maintains a 16 MiB empty // ext4 stub harness that warm-pool restore points the // harness symlink at. Content-identical to the one the diff --git a/crates/engram-sandbox-firecracker/src/client.rs b/crates/engram-sandbox-firecracker/src/client.rs index 31fa833ad..a2dda66e2 100644 --- a/crates/engram-sandbox-firecracker/src/client.rs +++ b/crates/engram-sandbox-firecracker/src/client.rs @@ -283,6 +283,8 @@ impl FirecrackerClient { }, enable_diff_snapshots, resume_vm, + // Substrate base backing is a Uffd-mode concept (ADR 0045 v2b). + uffd_base_file: None, }; self.put("/snapshot/load", &body).await } @@ -300,8 +302,14 @@ impl FirecrackerClient { state_path: &Path, uffd_uds_path: &Path, ) -> Result<(), SandboxError> { - self.load_snapshot_uffd_inner(state_path, uffd_uds_path, /*resume_vm=*/ true, false) - .await + self.load_snapshot_uffd_inner( + state_path, + uffd_uds_path, + /*resume_vm=*/ true, + false, + None, + ) + .await } /// UFFD-backed load that leaves the VM paused. Caller must @@ -316,8 +324,14 @@ impl FirecrackerClient { state_path: &Path, uffd_uds_path: &Path, ) -> Result<(), SandboxError> { - self.load_snapshot_uffd_inner(state_path, uffd_uds_path, /*resume_vm=*/ false, false) - .await + self.load_snapshot_uffd_inner( + state_path, + uffd_uds_path, + /*resume_vm=*/ false, + false, + None, + ) + .await } /// UFFD-backed load with explicit `resume_vm` / @@ -329,9 +343,16 @@ impl FirecrackerClient { uffd_uds_path: &Path, resume_vm: bool, enable_diff_snapshots: bool, + uffd_base_file: Option<&Path>, ) -> Result<(), SandboxError> { - self.load_snapshot_uffd_inner(state_path, uffd_uds_path, resume_vm, enable_diff_snapshots) - .await + self.load_snapshot_uffd_inner( + state_path, + uffd_uds_path, + resume_vm, + enable_diff_snapshots, + uffd_base_file, + ) + .await } async fn load_snapshot_uffd_inner( @@ -340,6 +361,7 @@ impl FirecrackerClient { uffd_uds_path: &Path, resume_vm: bool, enable_diff_snapshots: bool, + uffd_base_file: Option<&Path>, ) -> Result<(), SandboxError> { let body = SnapshotLoadBody { snapshot_path: state_path.to_string_lossy().into_owned(), @@ -349,6 +371,7 @@ impl FirecrackerClient { }, enable_diff_snapshots, resume_vm, + uffd_base_file: uffd_base_file.map(|p| p.to_string_lossy().into_owned()), }; self.put("/snapshot/load", &body).await } @@ -703,6 +726,15 @@ struct SnapshotLoadBody { /// `true` makes Firecracker resume the guest immediately after /// load (no separate `PATCH /vm Resumed` needed). resume_vm: bool, + /// ADR 0045 substrate (v2b): when set with the Uffd backend, the + /// forked FC creates guest memory as `MAP_PRIVATE` of this shmem + /// base file and registers UFFD `MISSING|MINOR`, letting the + /// handler share base-identical pages across same-template VMs via + /// `UFFDIO_CONTINUE`. `skip_serializing_if` keeps the body + /// byte-identical to stock when unset (stock FC and pre-v2 forks + /// `deny_unknown_fields` this struct). + #[serde(skip_serializing_if = "Option::is_none")] + uffd_base_file: Option, } /// How memory is supplied during snapshot load. @@ -1120,6 +1152,7 @@ mod tests { }, enable_diff_snapshots: false, resume_vm: true, + uffd_base_file: None, }; let v: serde_json::Value = serde_json::to_value(&body).unwrap(); assert_eq!(v["snapshot_path"], "/snap/state.bin"); diff --git a/crates/engram-sandbox-firecracker/src/lib.rs b/crates/engram-sandbox-firecracker/src/lib.rs index 39cef7ca6..5f4a3bda6 100644 --- a/crates/engram-sandbox-firecracker/src/lib.rs +++ b/crates/engram-sandbox-firecracker/src/lib.rs @@ -208,6 +208,15 @@ pub struct FirecrackerConfig { /// when `restore_mode == Uffd`. Defaults to `engram-uffd-handler` /// (resolved via PATH). pub uffd_handler_bin: PathBuf, + /// ADR 0045 unified memory substrate (v2b). When set, Uffd-mode + /// restores back guest memory `MAP_PRIVATE` on a per-template base + /// shm file under this directory (`/-v.base`, + /// created + lazily populated by the handler), registered + /// `MISSING|MINOR` by the forked FC — base-identical pages are + /// then shared page-cache across same-template VMs via + /// `UFFDIO_CONTINUE`. MUST point at a tmpfs/shmem mount (MINOR + /// faults are shmem-only). `None` ⇒ stock anonymous Uffd restore. + pub uffd_base_dir: Option, /// How to wire memory on snapshot restore. File mode synchronously /// reads memory.bin (slow, simple, no extra processes). Uffd mode /// spawns engram-uffd-handler and serves pages on demand (fast, @@ -406,6 +415,20 @@ pub fn base_restore_mode_from_env() -> Option { } } +/// ADR 0045 substrate (v2b): per-template base-shm directory for +/// Uffd-mode restores from `ENGRAM_FC_UFFD_BASE_DIR`. Unset/empty ⇒ +/// `None` (stock anonymous Uffd restore — the D2 rollout gate; the +/// D3/D4 parity flips make this the one path and retire the knob). +/// The directory must live on tmpfs/shmem (e.g. `/dev/shm/engram` on +/// the dev VM, the node-prep tmpfs in prod) — UFFD minor faults are +/// shmem-only. +pub fn uffd_base_dir_from_env() -> Option { + match std::env::var("ENGRAM_FC_UFFD_BASE_DIR") { + Ok(s) if !s.trim().is_empty() => Some(PathBuf::from(s)), + _ => None, + } +} + /// ADR 0009 §6 errors from `FirecrackerBackend::reattach_sandbox`. /// Distinct from `SandboxError` so the live-attach driver can /// distinguish "FC truly gone, fall through to path 2" from "operator @@ -507,6 +530,7 @@ impl FirecrackerConfig { guest_otel_endpoint: None, firecracker_bin: PathBuf::from("firecracker"), uffd_handler_bin: PathBuf::from("engram-uffd-handler"), + uffd_base_dir: None, restore_mode: RestoreMode::File, // ADR 0022: inherit `restore_mode` for base-create until prod // opts in via ENGRAM_FC_BASE_RESTORE_MODE. @@ -1502,6 +1526,22 @@ impl FirecrackerBackend { /// Returns the live `Child` so the caller can hold it for the /// VM's lifetime. #[allow(clippy::too_many_arguments)] + /// ADR 0045 substrate (v2b): the per-template base shm path for a + /// canonical manifest, or `None` when the substrate is off. Both the + /// handler spawn (creates + populates it) and the FC load (maps it + /// `MAP_PRIVATE`) derive the path through here so they can't diverge. + fn uffd_base_path( + &self, + canonical_ref: &engram_core::types::manifest::ManifestRef, + ) -> Option { + self.config.uffd_base_dir.as_ref().map(|dir| { + dir.join(format!( + "{}-v{}.base", + canonical_ref.manifest_id, canonical_ref.version + )) + }) + } + #[tracing::instrument(name = "fc.spawn_uffd_handler", skip_all)] async fn spawn_uffd_handler( &self, @@ -1545,6 +1585,19 @@ impl FirecrackerBackend { if let Some(cache_root) = self.config.uffd_cache_root.as_ref() { cmd.arg("--cache-root").arg(cache_root); } + // ADR 0045 substrate (v2b): the handler creates + sizes the base + // shm file (it knows total_bytes from the canonical manifest) + // BEFORE binding the UDS, and `wait_for_socket` below orders the + // FC load after that — so FC's O_RDONLY open of the same path + // always sees a fully-sized file. + if let Some(base) = self.uffd_base_path(&canonical_ref) { + if let Some(dir) = base.parent() { + tokio::fs::create_dir_all(dir) + .await + .map_err(|e| vm_err(format!("create uffd base dir {}: {e}", dir.display())))?; + } + cmd.arg("--base-shm").arg(&base); + } if let Some(host) = prefault_trace_host { cmd.arg("--prefault-trace").arg(host.to_string()); } @@ -2550,6 +2603,12 @@ impl FirecrackerBackend { .await?; } Some((_handler, uffd_uds)) => { + // ADR 0045 substrate (v2b): same canonical ref as the + // handler spawn (canonical == session, ADR 0015 M5), + // so the derived base path matches the handler's. + let base = manifest + .memory_manifest + .and_then(|r| self.uffd_base_path(&r)); tracing::Instrument::instrument( async { api.load_snapshot_uffd_opts( @@ -2557,6 +2616,7 @@ impl FirecrackerBackend { uffd_uds, /*resume_vm=*/ aux_swap_plan.is_empty(), self.config.track_dirty_pages, + base.as_deref(), ) .await }, @@ -4435,6 +4495,7 @@ mod tests { guest_otel_endpoint: None, firecracker_bin: PathBuf::from("/nonexistent/firecracker"), uffd_handler_bin: PathBuf::from("/nonexistent/engram-uffd-handler"), + uffd_base_dir: None, restore_mode: RestoreMode::File, base_restore_mode: None, track_dirty_pages: false, diff --git a/crates/engram-sandbox-firecracker/tests/substrate_uffd_base.rs b/crates/engram-sandbox-firecracker/tests/substrate_uffd_base.rs new file mode 100644 index 000000000..fe91842cf --- /dev/null +++ b/crates/engram-sandbox-firecracker/tests/substrate_uffd_base.rs @@ -0,0 +1,259 @@ +//! ADR 0045 unified memory substrate (v2b) — end-to-end over real FC. +//! +//! Same shape as `tests/snapshot_uffd.rs`, but with `uffd_base_dir` set: +//! the restore sends `uffd_base_file` to the FORKED Firecracker, which +//! maps guest memory `MAP_PRIVATE` on the per-template base shm file and +//! registers UFFD `MISSING|MINOR`; the handler populates the base with +//! canonical chunks and resolves faults via `UFFDIO_CONTINUE` (shared) +//! instead of `UFFDIO_COPY` (private). +//! +//! Asserts: +//! - the restore round-trips and the restored VM is alive +//! - the base shm file exists at the derived path, is sized to the +//! manifest, and is PARTIALLY POPULATED (the handler pwrote canonical +//! chunks into it — `SEEK_DATA` finds extents) +//! - a SECOND sibling restored from the same snapshot works against the +//! same (already-populated) base file +//! +//! Density (PSS) parity is the ADR 0045 D3/D4 gate, measured separately — +//! this test is the D2 correctness gate. +//! +//! Needs the FORKED firecracker (`uffd_base_file` is a fork-only load +//! param; stock FC `deny_unknown_fields`-rejects it): set +//! `ENGRAM_FC_FORK_BIN`, as for `stock_fork_snapshot_compat`. Skips +//! cleanly when unset. +//! +//! ```sh +//! eval "$(bash crates/engram-sandbox-firecracker/scripts/fetch-fc-test-artifacts.sh)" +//! cargo build -p engram-uffd-handler +//! export ENGRAM_FC_FORK_BIN=/path/to/forked/firecracker +//! cargo test -p engram-sandbox-firecracker --test substrate_uffd_base -- --ignored --nocapture +//! ``` + +#![cfg(target_os = "linux")] + +mod common; + +use std::collections::HashMap; +use std::os::fd::AsRawFd; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use engram_chunk_store::{ChunkStore, ManifestKind}; +use engram_core::traits::sandbox::SandboxBackend; +use engram_core::traits::BlobStorage; +use engram_core::types::manifest::ManifestRef; +use engram_core::types::sandbox::{CpuLimit, DiskLimit, MemoryLimit, SandboxSpec}; +use engram_sandbox_firecracker::{FirecrackerBackend, FirecrackerConfig, RestoreMode}; +use engram_storage_local::LocalBlobStorage; + +/// First data extent at-or-after `offset`, or `None` if all-hole from +/// there. Used to prove the handler actually populated the base file. +fn first_data_at(file: &std::fs::File, offset: u64) -> Option { + // SAFETY: plain lseek on an owned fd. + let r = unsafe { libc::lseek64(file.as_raw_fd(), offset as libc::off64_t, libc::SEEK_DATA) }; + (r >= 0).then_some(r as u64) +} + +#[tokio::test] +#[ignore = "requires Linux + KVM + ENGRAM_FC_FORK_BIN + built engram-uffd-handler"] +async fn substrate_base_shm_restore_round_trips_and_shares() { + let env = match common::fc_preflight() { + Some(e) => e, + None => return, + }; + let fork_bin = match std::env::var("ENGRAM_FC_FORK_BIN") { + Ok(p) if !p.is_empty() => PathBuf::from(p), + _ => { + eprintln!("SKIP: ENGRAM_FC_FORK_BIN not set (uffd_base_file is a fork-only param)"); + return; + } + }; + + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"); + let target_root = Path::new(&manifest_dir) + .join("..") + .join("..") + .join("target"); + let handler = target_root.join("debug").join("engram-uffd-handler"); + if !handler.exists() { + eprintln!( + "SKIP: engram-uffd-handler not built at {} — run `cargo build -p engram-uffd-handler`", + handler.display() + ); + return; + } + + // The base dir MUST be tmpfs/shmem (UFFD MINOR is shmem-only). + let base_dir = PathBuf::from(format!( + "/dev/shm/engram-substrate-test-{}", + std::process::id() + )); + std::fs::create_dir_all(&base_dir).expect("create base dir on /dev/shm"); + + let work = tempfile::tempdir().expect("tempdir"); + let local_rootfs = work.path().join("rootfs.ext4"); + tokio::fs::copy(&env.rootfs, &local_rootfs) + .await + .expect("clone rootfs into tempdir"); + + let mut cfg = FirecrackerConfig::with_kernel(env.kernel); + cfg.net_pool = None; + cfg.firecracker_bin = fork_bin; + cfg.uffd_handler_bin = handler; + cfg.restore_mode = RestoreMode::Uffd; + cfg.uffd_base_dir = Some(base_dir.clone()); + cfg.default_boot_args = "console=ttyS0 reboot=k panic=1 pci=off init=/bin/bash".into(); + let backend = FirecrackerBackend::new(work.path(), cfg); + + let spec = SandboxSpec { + image: "fc-substrate-test".into(), + rootfs_source: Some(local_rootfs), + image_uri: None, + rootfs_manifest: None, + cpu: CpuLimit { vcpus: 1 }, + memory: MemoryLimit { max_mib: 128 }, + disk: DiskLimit { max_gib: 1 }, + ttl: None, + env: HashMap::new(), + workdir: None, + network: Default::default(), + aux_ro_drives: Vec::new(), + }; + + let original_id = backend.create(spec).await.expect("create"); + tokio::time::sleep(Duration::from_secs(2)).await; + let metadata = backend.snapshot(original_id).await.expect("snapshot"); + let snap_dir = backend.snapshot_path_for(metadata.id); + + // Inline the PooledBackend memory-chunking wrap (see snapshot_uffd.rs + // for the full rationale — a host-agent dep here would be circular). + let local_path = work.path().join("local-state"); + let blobs_dir = local_path.join("blobs"); + std::env::set_var("ENGRAM_BLOB_BACKEND", "local"); + std::env::set_var("ENGRAM_LOCAL_PATH", &local_path); + let blob: Arc = Arc::new(LocalBlobStorage::new(blobs_dir)); + let cs = ChunkStore::new(blob); + let memory_bin = snap_dir.join("memory.bin"); + let chunked = cs + .chunk_file(&memory_bin, ManifestKind::Memory, None) + .await + .expect("chunk memory.bin"); + let manifest_ref = ManifestRef::new(); + cs.put_manifest(manifest_ref, &chunked) + .await + .expect("put memory manifest"); + let manifest_json = snap_dir.join("manifest.json"); + let mut value: serde_json::Value = + serde_json::from_slice(&tokio::fs::read(&manifest_json).await.expect("read mj")) + .expect("parse mj"); + value.as_object_mut().expect("mj root is an object").insert( + "memory_manifest".into(), + serde_json::to_value(manifest_ref).expect("serialize mref"), + ); + tokio::fs::write( + &manifest_json, + serde_json::to_vec_pretty(&value).expect("re-serialize mj"), + ) + .await + .expect("write patched mj"); + + backend + .destroy(original_id) + .await + .expect("destroy original"); + std::env::set_var("ENGRAM_FC_KEEP_JAIL_ON_FAILURE", "1"); + + let restore_metadata = engram_core::types::snapshot::SnapshotMetadata { + id: metadata.id, + size_bytes: metadata.size_bytes, + created_at: metadata.created_at, + image_version: metadata.image_version.clone(), + disk_manifest: metadata.disk_manifest, + memory_manifest: Some(manifest_ref), + source_sandbox_id: metadata.source_sandbox_id, + state_blob_key: metadata.state_blob_key.clone(), + sidecar_blob_key: metadata.sidecar_blob_key.clone(), + rootfs_blob_key: metadata.rootfs_blob_key.clone(), + working_set_blob_key: metadata.working_set_blob_key.clone(), + aux_bundles: metadata.aux_bundles.clone(), + }; + + let dump_logs_and_panic = |what: &str, e: String, work_path: &Path| -> ! { + for entry in std::fs::read_dir(work_path).into_iter().flatten().flatten() { + if !entry.path().is_dir() { + continue; + } + for log_name in &["firecracker.log", "uffd-handler.log"] { + let log = entry.path().join(log_name); + if log.exists() { + let content = std::fs::read_to_string(&log).unwrap_or_default(); + eprintln!("--- {} ---\n{content}", log.display()); + } + } + } + panic!("{what}: {e}"); + }; + + let restored_id = match backend.restore(restore_metadata.clone()).await { + Ok(id) => id, + Err(e) => dump_logs_and_panic("restore #1", format!("{e:?}"), work.path()), + }; + + // The substrate's derived base path: /-v.base. + let base_path = base_dir.join(format!( + "{}-v{}.base", + manifest_ref.manifest_id, manifest_ref.version + )); + assert!( + base_path.exists(), + "handler should have created the base shm at {}", + base_path.display() + ); + let base_file = std::fs::File::open(&base_path).expect("open base shm"); + assert_eq!( + base_file.metadata().expect("stat base").len(), + 128 * 1024 * 1024, + "base shm sized to guest memory" + ); + + // Give the guest a moment to fault pages through the handler, then + // prove the handler populated the base (canonical chunks pwritten — + // the shared-install path, not private COPYs). + tokio::time::sleep(Duration::from_secs(2)).await; + assert!( + first_data_at(&base_file, 0).is_some(), + "base shm has no data extents — canonical faults did not go through \ + the shared install path" + ); + + // Handler log sanity: substrate mode announced itself. + let restored_jail = work.path().join(restored_id.to_string()); + let log_content = + std::fs::read_to_string(restored_jail.join("uffd-handler.log")).unwrap_or_default(); + assert!( + log_content.contains("substrate base shm ready"), + "expected substrate-mode startup line in handler log, got: {log_content}" + ); + + // Sibling restore from the same snapshot: exercises the + // already-populated base (SEEK_HOLE fast path + shared CONTINUE). + let sibling_id = match backend.restore(restore_metadata).await { + Ok(id) => id, + Err(e) => dump_logs_and_panic("restore #2 (sibling)", format!("{e:?}"), work.path()), + }; + tokio::time::sleep(Duration::from_secs(1)).await; + let mut listed = backend.list().await.expect("list"); + listed.sort(); + let mut expect = vec![restored_id, sibling_id]; + expect.sort(); + assert_eq!(listed, expect, "both substrate-backed VMs alive"); + + backend.destroy(sibling_id).await.expect("destroy sibling"); + backend + .destroy(restored_id) + .await + .expect("destroy restored"); + let _ = std::fs::remove_dir_all(&base_dir); +} diff --git a/crates/engram-uffd-handler/Cargo.toml b/crates/engram-uffd-handler/Cargo.toml index fe7ef344f..fb8d6f575 100644 --- a/crates/engram-uffd-handler/Cargo.toml +++ b/crates/engram-uffd-handler/Cargo.toml @@ -58,7 +58,9 @@ workspace-hack = { version = "0.1", path = "../../workspace-hack" } # itself doesn't gate by target_os; we do here so a workspace-wide # `cargo check` on macOS doesn't try to build it. [target.'cfg(target_os = "linux")'.dependencies] -userfaultfd = "0.9" +# linux5_13: Uffd::continue_ (UFFDIO_CONTINUE) for the ADR 0045 substrate's +# shared-base installs (MINOR-fault resolution against the base shm file). +userfaultfd = { version = "0.9", features = ["linux5_13"] } [dev-dependencies] tempfile = "3" diff --git a/crates/engram-uffd-handler/src/base_shm.rs b/crates/engram-uffd-handler/src/base_shm.rs new file mode 100644 index 000000000..5b5afbe56 --- /dev/null +++ b/crates/engram-uffd-handler/src/base_shm.rs @@ -0,0 +1,139 @@ +//! ADR 0045 unified memory substrate (v2b): the per-template base shm file. +//! +//! Guest memory is `MAP_PRIVATE` of this file (the forked FC maps it; +//! registration is `MISSING|MINOR`). This handler lazily populates it with +//! *canonical* chunk bytes — one copy per host, shared by every +//! same-template microVM through the page cache via `UFFDIO_CONTINUE` — +//! and NEVER writes session-divergent bytes here (those install privately +//! via `UFFDIO_COPY`). Guest writes COW in the kernel and never reach +//! this file either, so its content is canonical by construction. +//! +//! Concurrency: several handlers (one per sibling VM) populate the same +//! file. That's safe without coordination — every writer writes the same +//! canonical bytes at the same offsets (idempotent), and the +//! populated-probe (`SEEK_HOLE`) only skips work that some sibling has +//! already completed. A racing CONTINUE against a half-written chunk +//! cannot happen for the *faulting* sandbox because we always pwrite the +//! full range before CONTINUE-ing it; a sibling that observes the range +//! as populated observes it post-`pwrite` (shmem pwrite publishes whole +//! pages). + +use std::fs::File; +use std::os::fd::AsRawFd; +use std::os::unix::fs::FileExt; +use std::path::{Path, PathBuf}; + +#[derive(Debug)] +pub enum BaseShmError { + Open { + path: PathBuf, + source: std::io::Error, + }, + SetLen { + path: PathBuf, + len: u64, + source: std::io::Error, + }, + Write { + offset: u64, + source: std::io::Error, + }, +} + +impl std::fmt::Display for BaseShmError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Open { path, source } => { + write!(f, "open/create base shm {}: {source}", path.display()) + } + Self::SetLen { path, len, source } => { + write!(f, "size base shm {} to {len}: {source}", path.display()) + } + Self::Write { offset, source } => write!(f, "pwrite base shm at {offset}: {source}"), + } + } +} + +impl std::error::Error for BaseShmError {} + +#[derive(Debug)] +pub struct BaseShm { + file: File, + path: PathBuf, + total_bytes: u64, +} + +impl BaseShm { + /// Open-or-create the base file and size it to the canonical + /// manifest's `total_bytes`. Must run before the UDS listener binds: + /// the forked FC `open(O_RDONLY)` + `mmap`s this exact size at load, + /// which the caller orders after the socket appears. + pub fn open(path: &Path, total_bytes: u64) -> Result { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path) + .map_err(|source| BaseShmError::Open { + path: path.to_path_buf(), + source, + })?; + let cur = file + .metadata() + .map_err(|source| BaseShmError::Open { + path: path.to_path_buf(), + source, + })? + .len(); + // Grow-only: a sibling may have created it already at the same + // size; never shrink a file FC processes may be mapping. + if cur < total_bytes { + file.set_len(total_bytes) + .map_err(|source| BaseShmError::SetLen { + path: path.to_path_buf(), + len: total_bytes, + source, + })?; + } + Ok(Self { + file, + path: path.to_path_buf(), + total_bytes, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Is `[offset, offset+len)` fully populated (no holes)? A cheap + /// `lseek(SEEK_HOLE)` probe: if the first hole at-or-after `offset` + /// sits at-or-past the range end, every page in range is present in + /// the page cache and `UFFDIO_CONTINUE` can map it without a fetch. + pub fn is_populated(&self, offset: u64, len: u64) -> bool { + let end = offset.saturating_add(len).min(self.total_bytes); + // SAFETY: plain lseek on an fd we own; no memory is touched. + let hole = unsafe { + libc::lseek64( + self.file.as_raw_fd(), + offset as libc::off64_t, + libc::SEEK_HOLE, + ) + }; + if hole < 0 { + // ENXIO = offset past EOF (shouldn't happen — sized at open); + // any error ⇒ treat as unpopulated and let pwrite repair. + return false; + } + (hole as u64) >= end + } + + /// Write canonical chunk bytes at `offset`. Idempotent across + /// concurrent sibling handlers (same bytes, same offset). + pub fn write_chunk(&self, offset: u64, bytes: &[u8]) -> Result<(), BaseShmError> { + self.file + .write_all_at(bytes, offset) + .map_err(|source| BaseShmError::Write { offset, source }) + } +} diff --git a/crates/engram-uffd-handler/src/lib.rs b/crates/engram-uffd-handler/src/lib.rs index bdc5181b1..6fd5a535a 100644 --- a/crates/engram-uffd-handler/src/lib.rs +++ b/crates/engram-uffd-handler/src/lib.rs @@ -40,6 +40,8 @@ pub mod chunked; pub mod proto; pub mod working_set; +#[cfg(target_os = "linux")] +pub mod base_shm; #[cfg(target_os = "linux")] pub mod runtime; diff --git a/crates/engram-uffd-handler/src/main.rs b/crates/engram-uffd-handler/src/main.rs index 41e295005..d1ac38ad2 100644 --- a/crates/engram-uffd-handler/src/main.rs +++ b/crates/engram-uffd-handler/src/main.rs @@ -153,6 +153,12 @@ mod linux { pub cache_root: PathBuf, pub cache_budget_bytes: u64, pub recorder_window: Duration, + /// ADR 0045 substrate (v2b): the per-template base shm file this + /// handler creates, sizes, and lazily populates with canonical + /// chunks. The forked FC maps it MAP_PRIVATE and registers + /// MISSING|MINOR; canonical faults resolve via UFFDIO_CONTINUE + /// (shared), divergent via UFFDIO_COPY (private). Off when unset. + pub base_shm: Option, } pub fn parse_args() -> Result { @@ -166,6 +172,7 @@ mod linux { let mut cache_root: Option = None; let mut cache_budget_bytes: u64 = DEFAULT_CACHE_BUDGET_BYTES; let mut recorder_window_ms: u64 = DEFAULT_RECORDER_WINDOW_MS; + let mut base_shm: Option = None; let mut argv = std::env::args().skip(1); while let Some(arg) = argv.next() { @@ -229,6 +236,12 @@ mod linux { .parse::() .map_err(|e| format!("--cache-budget-bytes {v:?}: {e}"))?; } + "--base-shm" => { + base_shm = Some(PathBuf::from( + argv.next() + .ok_or_else(|| "--base-shm requires a value".to_string())?, + )); + } "--recorder-window-ms" => { let v = argv .next() @@ -263,6 +276,7 @@ mod linux { cache_root, cache_budget_bytes, recorder_window: Duration::from_millis(recorder_window_ms), + base_shm, }) } @@ -354,6 +368,24 @@ mod linux { None }; + // ADR 0045 substrate (v2b): create + size the base shm file NOW — + // before run_listener binds the UDS. The host-agent orders FC's + // load (which open(O_RDONLY)s + mmaps this file) after the socket + // appears, so the file is always fully sized by then. + let base_shm = match args.base_shm.as_ref() { + Some(path) => { + let b = engram_uffd_handler::base_shm::BaseShm::open(path, backend.total_bytes()) + .map_err(|e| format!("base shm: {e}"))?; + tracing::info!( + path = %path.display(), + total_bytes = backend.total_bytes(), + "substrate base shm ready (canonical -> CONTINUE, divergent -> COPY)" + ); + Some(b) + } + None => None, + }; + let result = tokio::task::spawn_blocking({ let handle = handle.clone(); let listen = args.listen.clone(); @@ -362,7 +394,7 @@ mod linux { let trace_out = args.trace_output.clone(); move || { engram_uffd_handler::runtime::run_listener( - listen, backend, handle, prefault, window, trace_out, + listen, backend, handle, prefault, window, trace_out, base_shm, ) } }) diff --git a/crates/engram-uffd-handler/src/runtime.rs b/crates/engram-uffd-handler/src/runtime.rs index 1d3bb3c06..e1c449d84 100644 --- a/crates/engram-uffd-handler/src/runtime.rs +++ b/crates/engram-uffd-handler/src/runtime.rs @@ -93,6 +93,8 @@ pub enum HandlerError { mappings_total: u64, manifest_total: u64, }, + /// ADR 0045 substrate: the base shm file couldn't be written/probed. + BaseShm(crate::base_shm::BaseShmError), } impl std::fmt::Display for HandlerError { @@ -116,6 +118,7 @@ impl std::fmt::Display for HandlerError { "FC mappings sum to {mappings_total} bytes; manifests describe \ {manifest_total} bytes — refusing to serve a mismatched memory layout" ), + Self::BaseShm(e) => write!(f, "base shm: {e}"), } } } @@ -226,6 +229,19 @@ pub struct Runtime { /// even if the run loop hangs on a stale userfaultfd that the /// kernel never closes after FC dies. trace_output: Option, + /// ADR 0045 unified memory substrate (v2b). When set, guest memory + /// is `MAP_PRIVATE` of this per-template base shm file (registered + /// `MISSING|MINOR` by the forked FC) and canonical chunks install + /// via populate-the-base + `UFFDIO_CONTINUE` — one page-cache copy + /// shared by every same-template VM on the host — instead of a + /// private `UFFDIO_COPY`. Session-divergent chunks keep COPY. + /// `None` ⇒ stock Route-B behavior, byte-identical. + base_shm: Option, + /// Whether `UFFDIO_ZEROPAGE` works on the substrate's MAP_PRIVATE + /// file-backed mapping (kernel-version dependent). Starts `true`; + /// flips to `false` on the first EINVAL and zero chunks fall back + /// to a private COPY of a zeroed buffer. + zeropage_ok: std::sync::atomic::AtomicBool, } impl Runtime { @@ -242,6 +258,7 @@ impl Runtime { backend: Arc, handle: TokioHandle, recorder_window: Duration, + base_shm: Option, ) -> Result { let mappings_total: u64 = mappings.iter().map(|m| m.size as u64).sum(); if mappings_total != backend.total_bytes() { @@ -272,6 +289,8 @@ impl Runtime { installed: Mutex::new(vec![false; chunk_count]), page_size, trace_output: None, + base_shm, + zeropage_ok: std::sync::atomic::AtomicBool::new(true), }) } @@ -334,6 +353,29 @@ impl Runtime { skipped += 1; continue; } + // ADR 0045 substrate: canonical positions must install via the + // shared base + CONTINUE — a prefault COPY here would privately + // duplicate exactly the hot pages the substrate exists to share. + if let Some(base) = self.base_shm.as_ref() { + for byte_offset in positions { + let shared = matches!( + self.backend.resolve(byte_offset), + Some(ResolvedPage::Canonical { canonical_offset }) + if self.backend.canonical_chunk_hash(canonical_offset) + == Some(*hash) + ); + let did = if shared { + self.install_canonical_shared(base, byte_offset, *hash, false)? + } else { + let bytes = self.handle.block_on(self.backend.fetch_chunk(*hash))?; + self.install_chunk_at(byte_offset, bytes, false)? + }; + if did { + installed += 1; + } + } + continue; + } let bytes = self.handle.block_on(self.backend.fetch_chunk(*hash))?; for byte_offset in positions { if self.install_chunk_at(byte_offset, bytes.clone(), false)? { @@ -442,6 +484,129 @@ impl Runtime { Ok(true) } + /// ADR 0045 substrate (v2b): install a canonical chunk by ensuring the + /// base shm file holds its bytes, then `UFFDIO_CONTINUE`-ing the range — + /// the kernel maps the base file's page-cache pages (write-protected + /// MAP_PRIVATE; guest writes COW), so every same-template VM on the host + /// shares one physical copy. The fetch is skipped entirely when a + /// sibling already populated the range (`SEEK_HOLE` probe). + fn install_canonical_shared( + &self, + base: &crate::base_shm::BaseShm, + byte_offset: u64, + hash: engram_chunk_store::ChunkHash, + wake: bool, + ) -> Result { + let chunk_size = self.backend.chunk_size(); + let chunk_idx = (byte_offset / chunk_size) as usize; + { + let mut installed = self.installed.lock().expect("installed bitmap poisoned"); + if let Some(slot) = installed.get_mut(chunk_idx) { + if *slot { + return Ok(false); + } + *slot = true; + } + } + + let (_m, host_va, room_to_eom) = locate_offset(&self.mappings, byte_offset) + .ok_or(HandlerError::AddressOutsideRegions(byte_offset))?; + let populate_len = std::cmp::min( + chunk_size, + self.backend.total_bytes().saturating_sub(byte_offset), + ); + if !base.is_populated(byte_offset, populate_len) { + let bytes = self.handle.block_on(self.backend.fetch_chunk(hash))?; + base.write_chunk(byte_offset, &bytes) + .map_err(HandlerError::BaseShm)?; + } + + let install_len = + std::cmp::min(std::cmp::min(chunk_size, room_to_eom), populate_len) as usize; + debug_assert!(install_len.is_multiple_of(self.page_size as usize)); + // CONTINUE the whole range in one ioctl; the kernel may map a prefix + // and return EAGAIN-with-progress (surfaced by the crate as + // Ok(mapped < len)) — loop the remainder. EEXIST means a racing + // prefault/fault already mapped a page; treat as installed. + let mut done: u64 = 0; + while (done as usize) < install_len { + let start = host_va + done; + let len = install_len as u64 - done; + // (`Uffd::continue` is a safe wrapper — the range lies inside a + // UFFD-registered region whose backing pages we just ensured + // are present in the base file's page cache.) + match self + .uffd + .r#continue(start as *mut std::ffi::c_void, len as usize, wake) + { + Ok(0) => break, // defensive: no progress + Ok(mapped) => done += mapped, + Err(userfaultfd::Error::SystemError(e)) if e as i32 == libc::EEXIST => { + // Page(s) already mapped (racing fault). The kernel + // stops at the first conflict without reporting + // progress; skip one page and keep going. + done += self.page_size; + } + Err(e) => return Err(HandlerError::Uffd(e)), + } + } + Ok(true) + } + + /// ADR 0045 substrate (v2b): zero canonical chunks. Try + /// `UFFDIO_ZEROPAGE` (maps the kernel zero page — zero RAM until the + /// guest writes); some kernels reject it on MAP_PRIVATE file-backed + /// mappings, in which case fall back to a private COPY of a zeroed + /// buffer (correct, costs one private page per touched page). + fn install_zero_substrate(&self, byte_offset: u64, wake: bool) -> Result { + let chunk_size = self.backend.chunk_size(); + let chunk_idx = (byte_offset / chunk_size) as usize; + { + let mut installed = self.installed.lock().expect("installed bitmap poisoned"); + if let Some(slot) = installed.get_mut(chunk_idx) { + if *slot { + return Ok(false); + } + *slot = true; + } + } + let (_m, host_va, room_to_eom) = locate_offset(&self.mappings, byte_offset) + .ok_or(HandlerError::AddressOutsideRegions(byte_offset))?; + let install_len = std::cmp::min(chunk_size, room_to_eom) as usize; + + use std::sync::atomic::Ordering; + if self.zeropage_ok.load(Ordering::Relaxed) { + // SAFETY: range is inside a registered region (as above). + match unsafe { + self.uffd + .zeropage(host_va as *mut std::ffi::c_void, install_len, wake) + } { + Ok(_) => return Ok(true), + Err(userfaultfd::Error::ZeropageFailed(errno)) + if errno as i32 == libc::EINVAL || errno as i32 == libc::EOPNOTSUPP => + { + self.zeropage_ok.store(false, Ordering::Relaxed); + tracing::info!( + "UFFDIO_ZEROPAGE unsupported on the substrate mapping; falling back to COPY-of-zeros" + ); + } + Err(e) => return Err(HandlerError::Uffd(e)), + } + } + let zeros = bytes::Bytes::from(vec![0u8; install_len]); + // SAFETY: zeroed buffer of install_len; same contract as + // install_chunk_at's copy. + unsafe { + self.uffd.copy( + zeros.as_ptr() as *const _, + host_va as *mut std::ffi::c_void, + install_len, + wake, + )?; + } + Ok(true) + } + /// Run forever, draining events from the UFFD and serving each /// page fault. Returns `Ok(())` cleanly when the UFFD is closed /// (Firecracker exited / sandbox destroyed). @@ -520,8 +685,18 @@ impl Runtime { r.observe(hash); } } - let bytes = self.handle.block_on(self.backend.fetch_chunk(hash))?; - let installed = self.install_chunk_at(chunk_byte_offset, bytes, true)?; + let installed = match self.base_shm.as_ref() { + // ADR 0045 substrate: shared install via the + // base shm + CONTINUE (one physical copy per + // host); guest writes COW privately. + Some(base) => { + self.install_canonical_shared(base, chunk_byte_offset, hash, true)? + } + None => { + let bytes = self.handle.block_on(self.backend.fetch_chunk(hash))?; + self.install_chunk_at(chunk_byte_offset, bytes, true)? + } + }; if !installed { // Already installed: wake the vCPU since the // kernel may have queued the fault before our @@ -530,7 +705,11 @@ impl Runtime { } } None => { - let installed = self.install_zero_at(chunk_byte_offset, true)?; + let installed = if self.base_shm.is_some() { + self.install_zero_substrate(chunk_byte_offset, true)? + } else { + self.install_zero_at(chunk_byte_offset, true)? + }; if !installed { self.wake_page(page_aligned, page_size)?; } @@ -604,6 +783,7 @@ pub fn run_listener( prefault_trace: Option, recorder_window: Duration, trace_output: Option, + base_shm: Option, ) -> Result { let pid = std::process::id(); let _ = std::fs::remove_file(&listen); @@ -622,7 +802,7 @@ pub fn run_listener( total_bytes = total, "handshake complete", ); - let mut rt = Runtime::new(mappings, uffd, backend, handle, recorder_window)?; + let mut rt = Runtime::new(mappings, uffd, backend, handle, recorder_window, base_shm)?; if let Some(path) = trace_output { rt.set_trace_output(path); } @@ -775,6 +955,7 @@ mod tests { backend, tokio::runtime::Handle::current(), Duration::ZERO, + None, ) .unwrap(), );