diff --git a/Cargo.lock b/Cargo.lock index f1d41733ce9..b87a2ac1a62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -624,6 +624,7 @@ dependencies = [ "closeable_mutex", "parking_lot", "range_map_vec", + "test_with_tracing", "thiserror 2.0.16", "tracing", ] @@ -649,6 +650,7 @@ dependencies = [ "closeable_mutex", "parking_lot", "range_map_vec", + "test_with_tracing", "tracing", ] diff --git a/Guide/src/reference/devices/virtio/virtio-fs.md b/Guide/src/reference/devices/virtio/virtio-fs.md index 05f5605d58c..536f73a37af 100644 --- a/Guide/src/reference/devices/virtio/virtio-fs.md +++ b/Guide/src/reference/devices/virtio/virtio-fs.md @@ -377,6 +377,12 @@ without being followed, and an alias whose ancestor has become a link fails restore. A handle that the guest held open for writing must still be on a writable path. +Capture checks those identities first, rather than save a snapshot that +cannot restore: it fails while the guest holds an object whose name the host +has given to another object, as host software does when it renames a new file +over a file that the guest holds open, until the guest kernel releases that +object, as it does once the guest closes the file. + A snapshot of an aggregate records each child's name, canonical host path, root identity, access mode, and denied, allowed, and writable paths, and the attachment's identity is the SHA-256 of the children's names and root diff --git a/vm/chipset_arc_mutex_device/Cargo.toml b/vm/chipset_arc_mutex_device/Cargo.toml index 031d212dcaa..11565e360d3 100644 --- a/vm/chipset_arc_mutex_device/Cargo.toml +++ b/vm/chipset_arc_mutex_device/Cargo.toml @@ -17,5 +17,8 @@ parking_lot.workspace = true thiserror.workspace = true tracing.workspace = true +[dev-dependencies] +test_with_tracing.workspace = true + [lints] workspace = true diff --git a/vm/chipset_arc_mutex_device/src/test_chipset.rs b/vm/chipset_arc_mutex_device/src/test_chipset.rs index e94b4de28aa..e95e2d9ad2e 100644 --- a/vm/chipset_arc_mutex_device/src/test_chipset.rs +++ b/vm/chipset_arc_mutex_device/src/test_chipset.rs @@ -84,10 +84,11 @@ impl ControlMmioIntercept for TestDeviceRange { fn offset_of(&self, addr: u64) -> Option { let base = self.addr?; - - (base..(base + self.len)) - .contains(&addr) - .then(|| addr - base) + // Compare the offset with the length: the exclusive end of a region + // that ends at the top of the address space does not fit in the + // address type. + let offset = addr.checked_sub(base)?; + (offset < self.len).then_some(offset) } } @@ -190,6 +191,7 @@ impl MmioInterceptServices for TestChipsetServicesImpl<'_> { #[cfg(test)] mod tests { use super::*; + use test_with_tracing::test; mod sample_dev { use super::*; @@ -262,4 +264,26 @@ mod tests { Ok(()) } + + #[test] + fn mmio_region_ending_at_the_top_finds_its_offsets() { + let mut mapper = TestMmioRangeMapper { + dev: Weak::>::new(), + map: Default::default(), + }; + let mut region = mapper.new_io_region("top", 0x1000); + let base = u64::MAX - 0xfff; + assert_eq!(region.offset_of(u64::MAX), None); + region.map(base); + assert_eq!(region.addr(), Some(base)); + assert_eq!(region.offset_of(base - 1), None); + assert_eq!(region.offset_of(base), Some(0)); + assert_eq!(region.offset_of(u64::MAX), Some(0xfff)); + region.map(base - 1); + assert_eq!(region.offset_of(base - 1), Some(0)); + assert_eq!(region.offset_of(u64::MAX - 1), Some(0xfff)); + assert_eq!(region.offset_of(u64::MAX), None); + region.unmap(); + assert_eq!(region.offset_of(base), None); + } } diff --git a/vm/chipset_device_fuzz/Cargo.toml b/vm/chipset_device_fuzz/Cargo.toml index 351768119d3..2c44f19f03a 100644 --- a/vm/chipset_device_fuzz/Cargo.toml +++ b/vm/chipset_device_fuzz/Cargo.toml @@ -18,5 +18,8 @@ arbitrary = { workspace = true, features = ["derive"] } parking_lot.workspace = true tracing.workspace = true +[dev-dependencies] +test_with_tracing.workspace = true + [lints] workspace = true diff --git a/vm/chipset_device_fuzz/src/lib.rs b/vm/chipset_device_fuzz/src/lib.rs index 0a7aa540554..25085f40b4f 100644 --- a/vm/chipset_device_fuzz/src/lib.rs +++ b/vm/chipset_device_fuzz/src/lib.rs @@ -489,10 +489,11 @@ macro_rules! impl_intercept { fn offset_of(&self, addr: $usize) -> Option<$usize> { let base = self.addr?; - - (base..(base + self.len)) - .contains(&addr) - .then(|| addr - base) + // Compare the offset with the length: the exclusive end of a + // region that ends at the top of the address space does not + // fit in the address type. + let offset = addr.checked_sub(base)?; + (offset < self.len).then_some(offset) } } }; @@ -628,3 +629,55 @@ impl PollDeviceServices for FuzzChipsetServicesImpl<'_> { self.took_poll.get() } } + +#[cfg(test)] +mod tests { + use super::*; + use test_with_tracing::test; + + enum NoDevice {} + + impl ChipsetDevice for NoDevice {} + + fn mapper() -> FuzzRegisterIntercept { + FuzzRegisterIntercept { + dev: Weak::>::new(), + map: Default::default(), + } + } + + #[test] + fn pio_region_ending_at_the_top_finds_its_offsets() { + let mut region = mapper::().new_io_region("top", 2); + assert_eq!(region.offset_of(0xffff), None); + region.map(0xfffe); + assert_eq!(region.addr(), Some(0xfffe)); + assert_eq!(region.offset_of(0xfffd), None); + assert_eq!(region.offset_of(0xfffe), Some(0)); + assert_eq!(region.offset_of(0xffff), Some(1)); + region.map(0xfffd); + assert_eq!(region.offset_of(0xfffd), Some(0)); + assert_eq!(region.offset_of(0xfffe), Some(1)); + assert_eq!(region.offset_of(0xffff), None); + region.unmap(); + assert_eq!(region.offset_of(0xfffe), None); + } + + #[test] + fn mmio_region_ending_at_the_top_finds_its_offsets() { + let mut region = mapper::().new_io_region("top", 0x1000); + let base = u64::MAX - 0xfff; + assert_eq!(region.offset_of(u64::MAX), None); + region.map(base); + assert_eq!(region.addr(), Some(base)); + assert_eq!(region.offset_of(base - 1), None); + assert_eq!(region.offset_of(base), Some(0)); + assert_eq!(region.offset_of(u64::MAX), Some(0xfff)); + region.map(base - 1); + assert_eq!(region.offset_of(base - 1), Some(0)); + assert_eq!(region.offset_of(u64::MAX - 1), Some(0xfff)); + assert_eq!(region.offset_of(u64::MAX), None); + region.unmap(); + assert_eq!(region.offset_of(base), None); + } +} diff --git a/vm/devices/virtio/virtiofs/src/inode.rs b/vm/devices/virtio/virtiofs/src/inode.rs index 48d58c74bca..c5e3780c2e8 100644 --- a/vm/devices/virtio/virtiofs/src/inode.rs +++ b/vm/devices/virtio/virtiofs/src/inode.rs @@ -365,18 +365,20 @@ impl VirtioFsInode { *path = new_path; } - /// Increments the lookup count without updating the path, saturating at `u64::MAX`. + /// Increments the lookup count without updating the path, saturating at `u64::MAX`, and + /// returns whether the count changed. /// /// This is used when returning an existing inode in a FUSE reply (e.g., for hard links) /// where the kernel will track the reference and later send a forget. /// /// A count that wrapped to zero would let the next forget evict an inode that the guest /// still references, so the count stops at `u64::MAX` instead. - pub fn inc_lookup(&self) { + pub fn inc_lookup(&self) -> bool { self.lookup_count .update(Ordering::AcqRel, Ordering::Acquire, |count| { count.saturating_add(1) - }); + }) + != u64::MAX } /// Decrements the lookup count, and returns the new count. diff --git a/vm/devices/virtio/virtiofs/src/lib.rs b/vm/devices/virtio/virtiofs/src/lib.rs index 97a6a7fe4ac..9677b92da21 100644 --- a/vm/devices/virtio/virtiofs/src/lib.rs +++ b/vm/devices/virtio/virtiofs/src/lib.rs @@ -268,13 +268,7 @@ impl Fuse for VirtioFs { } // This must be done under lock so an inode can't be resurrected between the lookup count // reaching zero and removing it from the list. - let mut inodes = self.inner.inodes.write(); - if let Some(inode) = inodes.get(node_id) { - if inode.forget(node_id, lookup_count) == 0 { - tracing::trace!(node_id, "Removing inode"); - inodes.remove(node_id); - } - } + self.inner.inodes.write().forget(node_id, lookup_count); } fn open(&self, request: &Request, flags: u32) -> lx::Result { @@ -413,7 +407,12 @@ impl Fuse for VirtioFs { return Err(lx::Error::EROFS); } let inode = self.get_inode(request.node_id())?; - let target_inode = self.get_inode(target)?; + // The reply hands the guest a lookup reference to the target node. + // Take it now, while the inode map holds the node, so that a FORGET + // on another queue cannot remove the node before the reply returns + // it. A link that fails releases the reference. + let target_reference = self.reference_inode(target)?; + let target_inode = target_reference.inode(); // Like Linux's linkat, which reports a read-only destination before a // link across filesystems, check where the link would go first. self.check_writable(&inode)?; @@ -429,13 +428,11 @@ impl Fuse for VirtioFs { if target_inode.readonly() { return Err(lx::Error::EXDEV); } - self.preflight_alias_add(&target_inode, &alias)?; - let attr = inode.link(name, &target_inode)?; + self.preflight_alias_add(target_inode, &alias)?; + let attr = inode.link(name, target_inode)?; target_inode.add_alias(alias); - - // Increment the lookup count since we're returning an entry for this inode. - // The kernel will send a forget for this entry later. - target_inode.inc_lookup(); + // The kernel will send a forget for the reply's reference later. + target_reference.keep(); // Use the target inode as the reply, with refreshed attributes. Ok(fuse_entry_out::new( @@ -882,10 +879,19 @@ impl VirtioFs { Ok(inode) } - /// Insert a new inode, and returns the assigned node ID as well as a reference to the inode. + /// Inserts `inode`, and returns the inode that the map holds for its host + /// object, with that inode's node ID. /// - /// If the file system supports stable inode numbers and an inode already existed with this - /// device and inode number, the existing inode is returned, not the passed in one. + /// An inode already in the map is a candidate for the object only if it + /// belongs to the volume of `inode` (see [`DedupKey`]). On a volume with + /// stable file IDs, the host device and inode numbers of `inode` identify + /// a candidate within that volume; the pair is not a key across volumes, + /// so a host object that two children of an aggregate reach gets a node + /// in each. On a volume without stable file IDs, the path of `inode` + /// identifies a candidate instead. A candidate of the same file type takes + /// the new name and one more lookup, and is returned, not the passed in + /// one; one of another file type held an object that the host has since + /// replaced, so `inode` gets a node of its own. fn insert_inode(&self, inode: VirtioFsInode) -> lx::Result<(Arc, u64)> { let mut inodes = self.inner.inodes.write(); microvm::fs::insert_inode(self, &mut inodes, inode) @@ -907,6 +913,40 @@ impl VirtioFs { }) } + /// Takes a lookup reference to the node `node_id` for a reply that + /// returns the node to the guest, as [`Self::insert_inode`] takes one when + /// a lookup finds a node that the inode map holds. + /// + /// A FORGET removes a node under the inode map's lock once the guest holds + /// no reference to it, so this takes the reference under that lock too: + /// either the FORGET removed the node first, and this fails with `EINVAL`, + /// as a request about any unknown node does, or the node stays in the map + /// until the guest forgets this reference as well. Dropping the reference + /// releases it, as a FORGET of it would, unless the request keeps it for + /// its reply (see [`LookupReference::keep`]). Like a lookup's, the + /// reference adds nothing to a count that stopped at `u64::MAX` (see + /// [`VirtioFsInode::inc_lookup`]), so dropping it then releases nothing. + fn reference_inode(&self, node_id: u64) -> lx::Result> { + let reference = { + let inodes = self.inner.inodes.read(); + let inode = inodes.get(node_id).ok_or_else(|| { + tracelimit::warn_ratelimited!(node_id, "request for unknown inode"); + lx::Error::EINVAL + })?; + // A FORGET takes the write lock, so the read lock keeps it out + // while the count, which changes atomically, goes up. + let release = inode.inc_lookup(); + LookupReference { + inodes: &self.inner.inodes, + node_id, + inode, + release, + } + }; + reference.inode.validate_confined_object()?; + Ok(reference) + } + /// Retrieves the open file `fh` of a request about the node `node_id`. /// /// The handle must have been opened on that node, and the guest must still @@ -993,6 +1033,48 @@ impl Drop for InodeReservation<'_> { } } +/// A lookup reference to a node that a request takes for a reply that +/// returns the node to the guest (see [`VirtioFs::reference_inode`]). +struct LookupReference<'a> { + inodes: &'a RwLock, + node_id: u64, + inode: Arc, + /// Whether dropping the reference releases it: taking it added to the + /// node's lookup count, which stops at `u64::MAX`, and the request has + /// not kept it. + release: bool, +} + +impl LookupReference<'_> { + /// Returns the node's inode. + fn inode(&self) -> &Arc { + &self.inode + } + + /// Keeps the reference for the reply, which hands it to the guest. + fn keep(mut self) { + self.release = false; + } +} + +impl Drop for LookupReference<'_> { + fn drop(&mut self) { + if !self.release { + return; + } + let mut inodes = self.inodes.write(); + // Since the reference was taken, a FUSE_DESTROY may have emptied the + // map, or a FORGET of more references than the guest held may have + // removed the node. + if inodes + .get(self.node_id) + .is_some_and(|inode| Arc::ptr_eq(&inode, &self.inode)) + { + inodes.forget(self.node_id, 1); + } + } +} + struct FileReservation<'a> { files: &'a RwLock>>, reservation: HandleReservation, @@ -1164,7 +1246,7 @@ impl HandleMap { } } -/// Assigns node IDs to inodes, and keeps track of in-use inodes by their actual inode number. +/// Assigns node IDs to inodes, and indexes the inodes that insertions may reuse by [`DedupKey`]. /// /// We cannot use the real inode number as the FUSE node ID: /// - FUSE node ID 1 is reserved for the root, so this would break if a file system used that inode @@ -1304,6 +1386,21 @@ impl InodeMap { .filter(|existing| Self::reuses(existing, inode)) } + /// Drops `lookup_count` of the guest's lookup references to the node + /// `node_id`, and removes the node once it has none left. + /// + /// The caller holds the map's lock, so no request can take another + /// reference to the node between its count reaching zero and its removal. + pub fn forget(&mut self, node_id: u64, lookup_count: u64) { + let Some(inode) = self.get(node_id) else { + return; + }; + if inode.forget(node_id, lookup_count) == 0 { + tracing::trace!(node_id, "Removing inode"); + self.remove(node_id); + } + } + /// Remove an inode with the specified FUSE node ID from the map. pub fn remove(&mut self, node_id: u64) { let Some(inode) = self.inodes_by_node_id.remove(node_id) else { @@ -1411,6 +1508,9 @@ impl InodeMap { mod tests { use super::HandleMap; use super::VirtioFs; + use super::profile::MICROVM_ATTACHMENT_ID; + use super::profile::MicroVmVirtioFsProfile; + use super::profile::microvm_root_identity; use fuse::Fuse; use fuse::Request; use fuse::protocol::*; @@ -2058,6 +2158,117 @@ mod tests { assert!(fs.get_inode(FUSE_ROOT_ID).is_ok()); } + /// Returns a direct file system of `root`, or a writable microVM one if + /// `microvm`, whose root holds the regular file `file`, which the guest + /// has looked up once, with the file's node ID. + fn fs_with_a_looked_up_file(root: &Path, microvm: bool) -> (VirtioFs, u64) { + std::fs::write(root.join("file"), b"data").unwrap(); + let fs = if microvm { + let profile = MicroVmVirtioFsProfile::from_attachment( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root).unwrap(), + false, + Vec::new(), + ) + .unwrap(); + VirtioFs::new_microvm(root, profile).unwrap() + } else { + VirtioFs::new(root, None).unwrap() + }; + let node_id = fs + .lookup(&request(FUSE_ROOT_ID), "file".as_ref()) + .unwrap() + .nodeid; + (fs, node_id) + } + + /// A successful LINK hands the guest a lookup reference to its target + /// node, so the node must stay in the inode table until the guest forgets + /// that reference too, even when a FORGET, which the guest sends on + /// another queue, drops every other reference while the LINK runs. + #[test] + fn link_keeps_its_node_through_a_concurrent_forget() { + for microvm in [false, true] { + let root = tempfile::tempdir().unwrap(); + let (fs, node_id) = fs_with_a_looked_up_file(root.path(), microvm); + let target = fs.get_inode(node_id).unwrap(); + // The FORGET below finds the node by its inode number, without + // the path that the test holds. + assert!(target.volume.supports_stable_file_id()); + + // A LINK records the new name after its host link, under the + // target's alias lock and then its path lock, so while the test + // holds the path, the LINK stops there, before it replies. + let path = target.path.read(); + std::thread::scope(|scope| { + let link = + scope.spawn(|| fs.link(&request(FUSE_ROOT_ID), "link".as_ref(), node_id)); + while !target.aliases.is_locked_exclusive() && !link.is_finished() { + std::thread::yield_now(); + } + fs.forget(node_id, 1); + drop(path); + assert_eq!(link.join().unwrap().unwrap().nodeid, node_id); + }); + + fs.get_attr(&request(node_id), 0, 0).unwrap(); + fs.forget(node_id, 1); + assert_eq!( + fs.get_attr(&request(node_id), 0, 0).unwrap_err(), + lx::Error::EINVAL + ); + } + } + + /// A LINK that fails, whether before or at its host link, hands the guest + /// no reference to its target node, so the node leaves the inode table + /// once the guest forgets the references that it holds. + #[test] + fn failed_link_retains_no_reference() { + for microvm in [false, true] { + let root = tempfile::tempdir().unwrap(); + let (fs, node_id) = fs_with_a_looked_up_file(root.path(), microvm); + std::fs::write(root.path().join("existing"), b"other").unwrap(); + + assert_eq!( + fs.link(&request(node_id), "link".as_ref(), node_id) + .unwrap_err(), + lx::Error::ENOTDIR + ); + assert_eq!( + fs.link(&request(FUSE_ROOT_ID), "existing".as_ref(), node_id) + .unwrap_err(), + lx::Error::EEXIST + ); + + fs.forget(node_id, 1); + assert_eq!( + fs.get_attr(&request(node_id), 0, 0).unwrap_err(), + lx::Error::EINVAL + ); + } + } + + /// A LINK takes the reference that its reply hands the guest before it + /// links on the host, so a FORGET of the guest's other references to the + /// target node meanwhile leaves the node in the inode table. A LINK that + /// then fails releases the reference as a FORGET of it would, which + /// removes the node, since the guest holds no reference to it. + #[test] + fn released_link_reference_removes_a_forgotten_node() { + let root = tempfile::tempdir().unwrap(); + let (fs, node_id) = fs_with_a_looked_up_file(root.path(), false); + + let reference = fs.reference_inode(node_id).unwrap(); + fs.forget(node_id, 1); + fs.get_attr(&request(node_id), 0, 0).unwrap(); + drop(reference); + assert_eq!( + fs.get_attr(&request(node_id), 0, 0).unwrap_err(), + lx::Error::EINVAL + ); + } + #[test] #[should_panic(expected = "root inode ID changed during clear")] fn clear_rejects_corrupt_root_allocator() { diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs.rs b/vm/devices/virtio/virtiofs/src/microvm/fs.rs index 08d644422d2..700a319f5b5 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs.rs @@ -32,7 +32,6 @@ use super::state::validate_identity; use super::state::validate_microvm_state; use super::state::validate_relative_path; use super::state::validate_reopenable_alias; -use super::state::validate_saved_identity; use crate::ATTRIBUTE_TIMEOUT; use crate::ENTRY_TIMEOUT; use crate::FuseNegotiation; @@ -293,6 +292,21 @@ fn open_microvm_volume( Ok((volume, root_inode, root_stat)) } +/// Returns the error of a save whose nodes `first` and `second` share a name or +/// the dedup key of one host object in one volume, which a restore cannot tell +/// apart, as after the host gave the inode number of an object that the guest +/// holds to an object of another type, and then to one of the held object's +/// type again, while the guest looked up each. +fn nodes_of_one_object(first: u64, second: u64) -> anyhow::Error { + anyhow::anyhow!( + "nodes {} and {} name one host object, as after the host replaced an object that \ + the guest holds by one with its inode number; the guest must release one of them \ + before a save", + first.min(second), + first.max(second) + ) +} + impl VirtioFs { /// Creates a filesystem attachment for the fixed microVM profile. /// @@ -521,6 +535,10 @@ impl VirtioFs { let mut node_ids = HashMap::with_capacity(inodes.inodes_by_node_id.values.len()); let mut alias_count = 0usize; let mut alias_bytes = 0usize; + // A restore keys the nodes of each volume by their names and by + // their dedup keys, so no two nodes of one volume may share either. + let mut alias_nodes = HashMap::new(); + let mut object_nodes = HashMap::new(); for (&node_id, inode) in &inodes.inodes_by_node_id.values { let aliases = inode.aliases(); anyhow::ensure!( @@ -532,20 +550,30 @@ impl VirtioFs { .context("saved alias count overflow")?; anyhow::ensure!(alias_count <= MAX_ALIASES, "saved alias table is too large"); let volume = inode.volume(); + // A restore binds the node only to its own object, which the + // node's guest inode number numbers, so every name must still + // reach that object rather than one that the host has put in + // its place. + let object_identity = inode.object_identity(); let mut relative_aliases = Vec::with_capacity(aliases.len()); - let mut object_identity = None; for alias in aliases { validate_relative_path(&alias, true) .map_err(anyhow::Error::from) .context("inode has an unsafe relative alias")?; let stat = validate_reopenable_alias(&volume, &alias) .context("inode alias cannot be revalidated for save")?; - let identity = saved_identity(&stat); - if let Some(expected) = &object_identity { - validate_saved_identity(&identity, expected) - .context("inode aliases identify different objects")?; - } else { - object_identity = Some(identity); + validate_identity(&stat, &object_identity).with_context(|| { + format!( + "node {node_id} (guest inode {}) has a name that reaches another \ + host object, as after the host replaced an object that the \ + guest holds; the guest must release the object before a save", + inode.guest_inode_nr() + ) + })?; + if let Some(other) = + alias_nodes.insert((inode.volume_id(), alias.clone()), node_id) + { + return Err(nodes_of_one_object(other, node_id)); } let alias = encode_relative_path(&alias)?; alias_bytes = alias_bytes @@ -557,13 +585,16 @@ impl VirtioFs { ); relative_aliases.push(alias); } + if let Some(other) = object_nodes.insert(inode.dedup_key(), node_id) { + return Err(nodes_of_one_object(other, node_id)); + } saved.push(SavedInode { node_id, volume_id: inode.volume_id(), relative_aliases, lookup_count: inode.lookup_count(), guest_inode_id: inode.guest_inode_nr(), - object_identity: object_identity.context("inode has no aliases")?, + object_identity, }); anyhow::ensure!( node_ids @@ -589,6 +620,15 @@ impl VirtioFs { .object_stat() .map_err(anyhow::Error::from) .context("open handle cannot be revalidated for save")?; + // A restore reopens the handle by its node's names, which reach + // the node's own object. + validate_identity(&stat, &file.inode().object_identity()).with_context(|| { + format!( + "handle {handle_id} of node {node_id} reaches another host object than \ + the node, as after the guest opened the node while the host had \ + replaced its object; the guest must close the handle before a save" + ) + })?; let snapshot_entries = file.directory_entries(); let directory_snapshot_built = file.directory_snapshot_built(); anyhow::ensure!( diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs index 2090e421afa..0e4fb1e2f3e 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs @@ -3,7 +3,11 @@ //! Tests for microVM filesystem persistence and limits. +use super::policy_tests::lookup; use super::policy_tests::name; +use super::policy_tests::open; +use super::policy_tests::read_node; +use super::policy_tests::release; use super::policy_tests::request; use super::profile::MICROVM_ATTACHMENT_ID; use super::profile::MICROVM_FUSE_MAJOR; @@ -1313,6 +1317,166 @@ fn hard_link_aliases_restore_and_reject_missing_or_replaced_names() { ); } +/// Host software often replaces a file by renaming a new file over its name. +/// When the guest holds the old file open, the file's node keeps the name, +/// which now reaches the new file, and a lookup of the name gives the new file +/// a node of its own. A restore could reopen the held file by none of its +/// names, and must not bind its node to the new file, so a save must fail, +/// and say why, rather than save a snapshot that cannot restore, whether or +/// not the guest has looked the new file up. The guest's handle still reads +/// the old file. Once the guest releases the old file, a save succeeds, and +/// its restore binds the name to the new file, at the new file's node if the +/// guest has one. A snapshot saved before the replacement no longer restores, +/// since the held node's name reaches another object. +#[test] +fn a_held_file_that_the_host_replaces_fails_the_save_until_released() { + for look_up_replacement in [false, true] { + let case = format!("look_up_replacement={look_up_replacement}"); + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + std::fs::write(root_path.join("file"), b"old").unwrap(); + let profile = profile(root_path); + let fs = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let held = lookup(&fs, "file").unwrap(); + let fh = open(&fs, held, lx::O_RDONLY).unwrap(); + let saved_before = fs + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + let restore = |state| { + let destination = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(destination.clone()); + destination + .restore_microvm_state(&profile, state, &session) + .map(|()| destination) + }; + + std::fs::write(root_path.join("new"), b"new").unwrap(); + std::fs::rename(root_path.join("new"), root_path.join("file")).unwrap(); + let replacement = look_up_replacement.then(|| lookup(&fs, "file").unwrap()); + assert_ne!(replacement, Some(held), "{case}"); + + let Err(error) = fs.save_microvm_state(&profile, SessionState::default()) else { + panic!("{case}: a save succeeded while the guest held a replaced file"); + }; + let message = format!("{error:#}"); + assert!( + message.contains(&format!("node {held} ")) + && message.contains("has a name that reaches another host object"), + "{case}: {message}" + ); + let mut read = fuse_read_in::new_zeroed(); + read.fh = fh; + read.size = 64; + assert_eq!(fs.read(&request(held), &read).unwrap(), b"old", "{case}"); + let Err(error) = restore(saved_before) else { + panic!("{case}: a restore bound the held node to the new file"); + }; + assert!( + format!("{error:#}").contains("saved inode identity does not match the attachment"), + "{case}: {error:#}" + ); + + release(&fs, held, fh); + fs.forget(held, 1); + let state = fs + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + let destination = restore(state).unwrap(); + assert_eq!( + destination.get_attr(&request(held), 0, 0).err(), + Some(lx::Error::EINVAL), + "{case}" + ); + let node = lookup(&destination, "file").unwrap(); + if let Some(replacement) = replacement { + assert_eq!(node, replacement, "{case}"); + assert_eq!( + destination.get_attr(&request(node), 0, 0).unwrap().attr.ino, + fs.get_attr(&request(replacement), 0, 0).unwrap().attr.ino, + "{case}" + ); + } + assert_eq!(read_node(&destination, node), b"new", "{case}"); + } +} + +/// A host can give the inode number of a removed object to a new object of +/// another file type, and then to an object of the removed object's type +/// again, while the guest holds a node of each: each gets a node of its own +/// (see `InodeMap::dedup_entry`). Once the guest forgets the second, the nodes +/// of the first and the last object both name an object of that inode number +/// and type, by one name or by two names of it, which a restore cannot tell +/// apart, so a save must fail rather than save a snapshot that cannot restore. +#[test] +fn nodes_that_name_one_object_fail_the_save() { + for path in ["file", "link"] { + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + let (fs, file, node_id) = microvm_with_a_tracked_file(root_path); + std::fs::hard_link(root_path.join("file"), root_path.join("link")).unwrap(); + let (_, directory) = fs + .insert_inode(directory_with_the_inode_number_of(&file, "file")) + .unwrap(); + let stat = file.volume().lstat(file.clone_path()).unwrap(); + let (_, other) = fs + .insert_inode(VirtioFsInode::with_attr( + file.volume(), + PathBuf::from(path), + &stat, + )) + .unwrap(); + assert_ne!(other, node_id, "{path}"); + fs.forget(directory, 1); + + let Err(error) = fs.save_microvm_state(&profile(root_path), SessionState::default()) else { + panic!("{path}: a save succeeded with two nodes of one object"); + }; + let message = format!("{error:#}"); + assert!( + message.contains(&format!("nodes {node_id} and {other} name one host object")), + "{path}: {message}" + ); + fs.forget(other, 1); + fs.save_microvm_state(&profile(root_path), SessionState::default()) + .unwrap(); + } +} + +/// The guest can open a node after the host has replaced its object, as Linux +/// does when a program reopens a file that it holds through `/proc/self/fd`, +/// and the host can then give the node's name its object back. The node's +/// names then reach its object, but its handle reaches the replacement, which +/// a restore, which reopens each handle by its node's names, cannot reach, so +/// a save must fail rather than save a snapshot that cannot restore. +#[test] +fn a_handle_of_another_object_than_its_node_fails_the_save() { + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + std::fs::write(root_path.join("file"), b"old").unwrap(); + let profile = profile(root_path); + let fs = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let node = lookup(&fs, "file").unwrap(); + std::fs::rename(root_path.join("file"), root_path.join("kept")).unwrap(); + std::fs::write(root_path.join("file"), b"new").unwrap(); + let fh = open(&fs, node, lx::O_RDONLY).unwrap(); + std::fs::rename(root_path.join("file"), root_path.join("replacement")).unwrap(); + std::fs::rename(root_path.join("kept"), root_path.join("file")).unwrap(); + + let Err(error) = fs.save_microvm_state(&profile, SessionState::default()) else { + panic!("a save succeeded with a handle of another object than its node"); + }; + let message = format!("{error:#}"); + assert!( + message.contains(&format!( + "handle {fh} of node {node} reaches another host object" + )), + "{message}" + ); + release(&fs, node, fh); + fs.save_microvm_state(&profile, SessionState::default()) + .unwrap(); +} + /// Objects with one inode number on two devices, as `/proc` and `/sys` are, /// save as two inodes and restore as two. #[cfg(target_os = "linux")] diff --git a/vm/devices/virtio/virtiofs/src/microvm/inode.rs b/vm/devices/virtio/virtiofs/src/microvm/inode.rs index 32c1ea8844d..7259307c05b 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/inode.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/inode.rs @@ -6,6 +6,7 @@ use super::policy::PathVisibility; use super::policy::SubtreePolicy; use super::saved_state::MAX_PATH_BYTES; +use super::saved_state::SavedObjectIdentity; use super::state::relative_path_encoded_len; use super::state::validate_relative_path; use crate::inode::VirtioFsInode; @@ -147,6 +148,18 @@ impl VirtioFsInode { Ok(inode) } + /// Returns the identity of this inode's own object, which a snapshot + /// records for the inode: the object that the guest reached when it got + /// the node, or that a restore bound the node to, which the node's guest + /// inode number numbers. + pub(crate) fn object_identity(&self) -> SavedObjectIdentity { + SavedObjectIdentity { + device_id: self.device_nr(), + inode_id: self.inode_nr(), + kind: self.file_type(), + } + } + /// Checks that a microVM inode used as a directory is reached without /// crossing a symbolic link, including at its final component. /// diff --git a/vm/devices/virtio/virtiofs/src/microvm/state.rs b/vm/devices/virtio/virtiofs/src/microvm/state.rs index 99699680df7..1a1d7ddbab7 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/state.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/state.rs @@ -163,19 +163,6 @@ pub(crate) fn validate_identity( Ok(()) } -pub(crate) fn validate_saved_identity( - actual: &SavedObjectIdentity, - expected: &SavedObjectIdentity, -) -> anyhow::Result<()> { - anyhow::ensure!( - actual.kind == expected.kind - && actual.device_id == expected.device_id - && actual.inode_id == expected.inode_id, - "object identity changed between aliases" - ); - Ok(()) -} - pub(crate) fn validate_reopenable_alias( volume: &VirtioFsVolume, path: &Path,