The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(vmm): add dynamic virtio-fs exports (#2749)
Vitusb6d6f3e5d5fb
diff --git a/src/boxlite/resources/seccomp/x86_64-unknown-linux-gnu.json b/src/boxlite/resources/seccomp/x86_64-unknown-linux-gnu.jsonindex d28fc498e..1ee67c79d 100644--- a/src/boxlite/resources/seccomp/x86_64-unknown-linux-gnu.json+++ b/src/boxlite/resources/seccomp/x86_64-unknown-linux-gnu.json@@ -542,6 +542,10 @@"syscall": "openat","comment": "libkrun: glibc 2.26+ maps open() to openat(AT_FDCWD, ...). Required at steady-state."},+ {+ "syscall": "openat2",+ "comment": "M6 virtio-fs: guest path resolution uses openat2(RESOLVE_BENEATH) confinement"+ },{"syscall": "newfstatat","comment": "libkrun: glibc 2.33+ maps stat/fstat to newfstatat. Required at steady-state."diff --git a/src/boxlite/resources/seccomp/x86_64-unknown-linux-musl.json b/src/boxlite/resources/seccomp/x86_64-unknown-linux-musl.jsonindex 048de5b62..e024c98c3 100644--- a/src/boxlite/resources/seccomp/x86_64-unknown-linux-musl.json+++ b/src/boxlite/resources/seccomp/x86_64-unknown-linux-musl.json@@ -526,6 +526,10 @@"syscall": "openat","comment": "libkrun: glibc 2.26+ maps open() to openat(AT_FDCWD, ...)"},+ {+ "syscall": "openat2",+ "comment": "M6 virtio-fs: guest path resolution uses openat2(RESOLVE_BENEATH) confinement"+ },{"syscall": "newfstatat","comment": "libkrun: glibc 2.33+ maps stat/fstat to newfstatat"diff --git a/src/vmm/README.md b/src/vmm/README.mdindex 0d9f34c37..247057202 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -47,7 +47,28 @@ boxlite-vmmThe Linux x86_64 native engine composes disks, reporting balloon, aggregatevirtio-fs, Unix-backed vsock, gvproxy stream networking and virtio-console.The adapter maps the runtime specification into `VmConfig`; optional devices-are omitted when not requested. Disk order remains `vda` (container) then+are omitted when not requested.++The aggregate virtio-fs device is runtime-extensible: `insert_aggregate`+publishes a live device by tag when it enters the transport, and+`lookup_aggregate` returns its filesystem to host-side consumers. VM shutdown+removes the registration, rejects mutations through cached handles, and clears+the guest session. Device drop performs the same cleanup if shutdown did not run.+Retained filesystem handles pin export roots until their final reference drops.+`AggregateFs::register_fd` registers directory descriptors, and `remove` retires+per-directory exports.+A retired export's name stops resolving while its in-use nodes, handles and+in-flight requests retain their backend; a re-registered name has a new identity+and independent read-only policy.+Registration validates that the supplied descriptor refers to a directory;+host read/write permissions are checked by the kernel for each operation.+A writable export may modify an existing writable file in a non-writable+directory, while creating files there still fails with EACCES. The export's+read-only policy separately rejects mutations with EROFS.+Guest LOOKUP and accepted READDIRPLUS entries retain root inodes independently+of open handles. FORGET releases those references; rejected READDIRPLUS entries+and plain READDIR create no persistent lookup ownership.+Disk order remains `vda` (container) then`vdb` (read-only guest root). The guest runs as PID 1, reports readiness overvsock and receives aggregate mount instructions before container startup.Linux arm64 and macOS arm64 remain separate M2 qualification gates; x86_64diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rsindex 6ce1639c1..38712b2a5 100644--- a/src/vmm/src/lib.rs+++ b/src/vmm/src/lib.rs@@ -89,6 +89,8 @@ pub use config::{pub use control::VmControl;pub use error::{Error, Result};pub use memory::ReclaimPolicy;+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]+pub use virtio::fs::{AggregateFs, Share, insert_aggregate, lookup_aggregate};pub use vm::{StopHandle, Vm, VmExit};/// A recording hypervisor backend shared by the crate's unit tests. Testdiff --git a/src/vmm/src/virtio/fs/aggregate.rs b/src/vmm/src/virtio/fs/aggregate.rsindex e2cbc621e..4e9c029b2 100644--- a/src/vmm/src/virtio/fs/aggregate.rs+++ b/src/vmm/src/virtio/fs/aggregate.rs@@ -11,9 +11,11 @@use std::collections::BTreeMap;use std::ffi::{CStr, CString};+use std::fs::File;use std::io;use std::mem;use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;@@ -31,32 +33,45 @@ const INTERNAL: Context = Context {pid: 0,};-pub(crate) struct Share {- pub(crate) name: String,- pub(crate) path: PathBuf,- pub(crate) read_only: bool,+#[derive(Debug)]+pub struct Share {+ pub name: String,+ pub path: PathBuf,+ pub read_only: bool,}struct Export {name: CString,root: u64,+ identity: u64,backend: Arc<PassthroughFs>,read_only: bool,}+impl Drop for Export {+ fn drop(&mut self) {+ // The last aggregate reference releases the backend's descriptors.+ // destroy is idempotent, so a reset-cycle destroy first is harmless.+ self.backend.destroy();+ }+}+struct Node {global: u64,identity: u64,- share: usize,+ // The export Arc keeps a removed share's backend alive for this node.+ export: Arc<Export>,local: u64,- backend: Arc<PassthroughFs>,root: bool,+ // Retired roots release their backend reference when their final guest+ // lookup, handle, and in-flight request have finished.+ retired: AtomicBool,}impl Drop for Node {fn drop(&mut self) {- if !self.root {- self.backend.forget(INTERNAL, self.local, 1);+ if !self.root || self.retired.load(Ordering::Acquire) {+ self.export.backend.forget(INTERNAL, self.local, 1);}}}@@ -81,10 +96,11 @@ impl Drop for Handle {// Removing a guest handle prevents new requests. Its last owned Arc// releases the backend handle only after existing requests finish.let result = if self.directory {- node.backend+ node.export+ .backend.releasedir(INTERNAL, node.local, self.flags, self.local)} else {- node.backend.release(+ node.export.backend.release(INTERNAL, node.local, self.flags, self.local, false, false, None,)};@@ -98,17 +114,31 @@ impl Drop for Handle {#[derive(Default)]struct State {nodes: BTreeMap<u64, NodeRecord>,- local_ids: BTreeMap<(usize, u64), u64>,+ // (export root, backend-local inode) -> global node. The export root is+ // the export identity: never reused, so a re-registered name is a new key.+ local_ids: BTreeMap<(u64, u64), u64>,// Scalar identities survive node reclamation, without retaining backend FDs.- identities: BTreeMap<(usize, InodeAltKey), u64>,+ identities: BTreeMap<(u64, InodeAltKey), u64>,handles: BTreeMap<u64, Arc<Handle>>,next_node: u64,next_identity: u64,next_handle: u64,}-pub(crate) struct AggregateFs {- shares: Vec<Export>,+/// The export registry, keyed by export root, which doubles as the export+/// identity. Lock order is `registry` before `state`; neither lock spans+/// backend I/O.+struct Registry {+ exports: BTreeMap<u64, Arc<Export>>,+ /// Cleared by `destroy`; mutations refuse the dead session.+ alive: bool,+}++/// One guest namespace over the aggregate's independent per-share backends.+/// The mount-control socket reaches a live device through the process mount+/// registry (`virtio::fs::lookup_aggregate`) and drives registration here.+pub struct AggregateFs {+ registry: Mutex<Registry>,state: Mutex<State>,}@@ -116,6 +146,20 @@ fn errno(code: i32) -> io::Error {io::Error::from_raw_os_error(code)}+// Manual Debug: the registry and state hold backend descriptors and large+// maps that would make a derived dump unreadable; counts are what matters.+impl std::fmt::Debug for AggregateFs {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let (registry, state) = (self.registry.lock().unwrap(), self.state.lock().unwrap());+ f.debug_struct("AggregateFs")+ .field("exports", ®istry.exports.len())+ .field("alive", ®istry.alive)+ .field("nodes", &state.nodes.len())+ .field("handles", &state.handles.len())+ .finish()+ }+}+fn allocate(next: &mut u64) -> io::Result<u64> {let value = *next;*next = value.checked_add(1).ok_or_else(|| errno(libc::EOVERFLOW))?;@@ -162,53 +206,127 @@ fn entry_from_attr(inode: u64, attr: libc::stat64) -> Entry {}impl AggregateFs {- pub(crate) fn new(shares: Vec<Share>) -> io::Result<Self> {- let mut exports = Vec::with_capacity(shares.len());- let mut names = std::collections::BTreeSet::new();- for (index, share) in shares.into_iter().enumerate() {- let name = CString::new(share.name).map_err(|_| errno(libc::EINVAL))?;- component(&name, true)?;- if !names.insert(name.clone()) {- return Err(errno(libc::EINVAL));- }- exports.push(Export {- name,- root: index as u64 + 2,- backend: Arc::new(PassthroughFs::new(share.path)?),- read_only: share.read_only,- });- }- let first = exports.len() as u64 + 2;+ pub fn new(shares: Vec<Share>) -> io::Result<Self> {let fs = Self {- shares: exports,+ registry: Mutex::new(Registry {+ exports: BTreeMap::new(),+ alive: true,+ }),state: Mutex::new(State {- next_node: first,- next_identity: first,+ next_node: ROOT + 1,+ next_identity: ROOT + 1,next_handle: 1,..State::default()}),};+ for share in shares {+ fs.register(share)?;+ }fs.install_roots();Ok(fs)}+ /// Adds an export under `name`. The backend is constructed outside every+ /// lock so a slow source cannot stall device callbacks; the registry and+ /// state updates are short critical sections. Returns the export's root+ /// inode, which is also its registry key and its stable identity.+ pub(crate) fn register(&self, share: Share) -> io::Result<u64> {+ let backend = Arc::new(PassthroughFs::new(share.path)?);+ self.insert_export(share.name, backend, share.read_only)+ }++ /// Registers a backend over a directory descriptor delivered by the+ /// runtime. `from_dir_fd` validates its type; host permissions apply per operation.+ pub fn register_fd(&self, name: String, file: File, read_only: bool) -> io::Result<u64> {+ let backend = Arc::new(PassthroughFs::from_dir_fd(file)?);+ self.insert_export(name, backend, read_only)+ }++ fn insert_export(+ &self,+ name: String,+ backend: Arc<PassthroughFs>,+ read_only: bool,+ ) -> io::Result<u64> {+ let name = CString::new(name).map_err(|_| errno(libc::EINVAL))?;+ component(&name, true)?;+ let mut registry = self.registry.lock().unwrap();+ if !registry.alive {+ return Err(errno(libc::ENODEV));+ }+ if registry.exports.values().any(|export| export.name == name) {+ return Err(errno(libc::EEXIST));+ }+ let mut state = self.state.lock().unwrap();+ let root = allocate(&mut state.next_node)?;+ let identity = allocate(&mut state.next_identity)?;+ let export = Arc::new(Export {+ name,+ root,+ identity,+ backend,+ read_only,+ });+ state.local_ids.insert((root, ROOT), root);+ state.nodes.entry(root).or_insert_with(|| NodeRecord {+ node: Arc::new(Node {+ global: root,+ identity,+ export: export.clone(),+ local: ROOT,+ root: true,+ retired: AtomicBool::new(false),+ }),+ lookups: 0,+ opens: 0,+ });+ registry.exports.insert(root, export.clone());+ Ok(root)+ }++ /// Retires the export published under `name`. Only the name stops+ /// resolving: nodes, handles and in-flight requests keep their backend+ /// through their export Arc until their own references drop, and the+ /// export root becomes an ordinary reclaimable node.+ pub fn remove(&self, name: &str) -> io::Result<()> {+ let name = CString::new(name).map_err(|_| errno(libc::EINVAL))?;+ let mut registry = self.registry.lock().unwrap();+ if !registry.alive {+ return Err(errno(libc::ENODEV));+ }+ let root = registry+ .exports+ .values()+ .find(|export| export.name == name)+ .map(|export| export.root)+ .ok_or_else(|| errno(libc::ENOENT))?;+ registry.exports.remove(&root);+ let mut state = self.state.lock().unwrap();+ if let Some(record) = state.nodes.get_mut(&root) {+ record.node.retired.store(true, Ordering::Release);+ Self::collect_zero(&mut state, root);+ }+ Ok(())+ }+fn install_roots(&self) {+ let registry = self.registry.lock().unwrap();let mut state = self.state.lock().unwrap();- for (share, export) in self.shares.iter().enumerate() {- state.local_ids.insert((share, ROOT), export.root);+ for export in registry.exports.values() {+ state.local_ids.insert((export.root, ROOT), export.root);state.nodes.entry(export.root).or_insert_with(|| NodeRecord {node: Arc::new(Node {global: export.root,- identity: export.root,- share,+ identity: export.identity,+ export: export.clone(),local: ROOT,- backend: export.backend.clone(),root: true,+ retired: AtomicBool::new(false),}),- lookups: 1,+ lookups: 0,opens: 0,});}@@ -238,7 +356,7 @@ impl AggregateFs {}fn writable(&self, node: &Node) -> io::Result<()> {- if self.shares[node.share].read_only {+ if node.export.read_only {Err(errno(libc::EROFS))} else {Ok(())@@ -255,77 +373,74 @@ impl AggregateFs {Ok(node)}- fn map_entry(&self, share: usize, entry: Entry) -> io::Result<Entry> {+ fn map_entry(&self, export: &Arc<Export>, entry: Entry) -> io::Result<Entry> {let local = entry.inode;- let backend = &self.shares[share].backend;- let result = self.insert_entry(share, entry);+ let result = self.insert_entry(export, entry);if result.is_err() {- backend.forget(INTERNAL, local, 1);+ export.backend.forget(INTERNAL, local, 1);}result}// READDIRPLUS callbacks leave rollback ownership with the backend.- fn insert_entry(&self, share: usize, entry: Entry) -> io::Result<Entry> {+ fn insert_entry(&self, export: &Arc<Export>, entry: Entry) -> io::Result<Entry> {let local = entry.inode;- let backend = &self.shares[share].backend;- let key = (share, backend.identity(local)?);+ let key = (export.root, export.backend.identity(local)?);let mut state = self.state.lock().unwrap();- let (global, identity) = if let Some(global) = state.local_ids.get(&(share, local)).copied()- {- let record = state- .nodes- .get_mut(&global)- .ok_or_else(|| errno(libc::EBADF))?;- if !record.node.root {+ let (global, identity) =+ if let Some(global) = state.local_ids.get(&(export.root, local)).copied() {+ let record = state+ .nodes+ .get_mut(&global)+ .ok_or_else(|| errno(libc::EBADF))?;record.lookups = record.lookups.checked_add(1).ok_or_else(|| errno(libc::EOVERFLOW))?;- }- (global, record.node.identity)- } else {- let global = allocate(&mut state.next_node)?;- let identity = match state.identities.get(&key) {- Some(identity) => *identity,- None => {- let identity = allocate(&mut state.next_identity)?;- state.identities.insert(key, identity);- identity- }+ (global, record.node.identity)+ } else {+ let global = allocate(&mut state.next_node)?;+ let identity = match state.identities.get(&key) {+ Some(identity) => *identity,+ None => {+ let identity = allocate(&mut state.next_identity)?;+ state.identities.insert(key, identity);+ identity+ }+ };+ // retain is map-only: it reserves the in-flight object reference,+ // distinct from the guest lookup that produced this entry.+ export.backend.retain(local)?;+ state.local_ids.insert((export.root, local), global);+ state.nodes.insert(+ global,+ NodeRecord {+ node: Arc::new(Node {+ global,+ identity,+ export: export.clone(),+ local,+ root: false,+ retired: AtomicBool::new(false),+ }),+ lookups: 1,+ opens: 0,+ },+ );+ (global, identity)};- // retain is map-only: it reserves the in-flight object reference,- // distinct from the guest lookup that produced this entry.- backend.retain(local)?;- state.local_ids.insert((share, local), global);- state.nodes.insert(- global,- NodeRecord {- node: Arc::new(Node {- global,- identity,- share,- local,- backend: backend.clone(),- root: false,- }),- lookups: 1,- opens: 0,- },- );- (global, identity)- };Ok(normalize(entry, global, identity))}fn collect_zero(state: &mut State, inode: u64) -> Option<NodeRecord> {let record = state.nodes.get(&inode)?;- if record.node.root || record.lookups != 0 || record.opens != 0 {+ let pinned = record.node.root && !record.node.retired.load(Ordering::Acquire);+ if pinned || record.lookups != 0 || record.opens != 0 {return None;}state.local_ids- .remove(&(record.node.share, record.node.local));+ .remove(&(record.node.export.root, record.node.local));state.nodes.remove(&inode)}@@ -335,9 +450,6 @@ impl AggregateFs {let Some(record) = state.nodes.get_mut(&inode) else {return;};- if record.node.root {- return;- }let released = count.min(record.lookups);record.lookups -= released;let node = record.node.clone();@@ -345,7 +457,7 @@ impl AggregateFs {(node, released, removed)};if forward {- node.backend.forget(INTERNAL, node.local, released);+ node.export.backend.forget(INTERNAL, node.local, released);}drop(removed);}@@ -431,9 +543,11 @@ impl AggregateFs {self.writable(&node)?;}let (local, options) = if directory {- node.backend.opendir(ctx, node.local, flags)?+ node.export.backend.opendir(ctx, node.local, flags)?} else {- node.backend.open(ctx, node.local, kill_priv, flags)?+ node.export+ .backend+ .open(ctx, node.local, kill_priv, flags)?};let local = local.ok_or_else(|| errno(libc::EIO))?;let handle = self.add_handle(inode, Some(node), local, directory, flags)?;@@ -455,11 +569,12 @@ impl AggregateFs {continue;}let entry = if name == c"." {- let (mut attr, _) = node.backend.getattr(ctx, node.local, None)?;+ let (mut attr, _) = node.export.backend.getattr(ctx, node.local, None)?;attr.st_ino = node.identity;entry_from_attr(node.global, attr)} else {- entry_from_attr(ROOT, synthetic_attr(self.shares.len()))+ let count = self.registry.lock().unwrap().exports.len();+ entry_from_attr(ROOT, synthetic_attr(count))};let result = add(DirEntry {@@ -483,6 +598,7 @@ impl AggregateFs {handle: u64,size: u32,offset: u64,+ plus: bool,mut add: F,) -> io::Result<()>where@@ -492,9 +608,10 @@ impl AggregateFs {if size == 0 {return Ok(());}+ let count = self.registry.lock().unwrap().exports.len();for (name, cookie) in [(c".", 1), (c"..", 2)] {if offset < cookie {- let entry = entry_from_attr(ROOT, synthetic_attr(self.shares.len()));+ let entry = entry_from_attr(ROOT, synthetic_attr(count));if add(DirEntry {ino: ROOT,@@ -509,24 +626,48 @@ impl AggregateFs {}}}- let start = usize::try_from(offset.saturating_sub(2)).map_err(|_| errno(libc::EINVAL))?;- if start > self.shares.len() {- return Err(errno(libc::EINVAL));- }- for (index, share) in self.shares.iter().enumerate().skip(start) {- let (mut attr, _) = share.backend.getattr(ctx, ROOT, None)?;- attr.st_ino = share.root;- let entry = entry_from_attr(share.root, attr);- if add(- DirEntry {- ino: share.root,- offset: index as u64 + 3,- type_: libc::DT_DIR as u32,- name: share.name.to_bytes(),- },- entry,- )? == 0- {+ // Cookies are export roots plus one: strictly increasing, unique per+ // export and stable across removals, so a resumed stream neither+ // repeats nor skips exports that outlive it. New exports register with+ // higher roots and therefore sort after everything already streamed.+ let exports: Vec<Arc<Export>> = self+ .registry+ .lock()+ .unwrap()+ .exports+ .values()+ .filter(|export| export.root >= offset)+ .cloned()+ .collect();+ for export in &exports {+ if plus {+ let mut state = self.state.lock().unwrap();+ let Some(record) = state.nodes.get_mut(&export.root) else {+ continue;+ };+ record.lookups = record+ .lookups+ .checked_add(1)+ .ok_or_else(|| errno(libc::EOVERFLOW))?;+ }+ let result = (|| {+ let (mut attr, _) = export.backend.getattr(ctx, ROOT, None)?;+ attr.st_ino = export.identity;+ let entry = entry_from_attr(export.root, attr);+ add(+ DirEntry {+ ino: export.identity,+ offset: export.root + 1,+ type_: libc::DT_DIR as u32,+ name: export.name.to_bytes(),+ },+ entry,+ )+ })();+ if plus && !matches!(result, Ok(count) if count > 0) {+ self.forget_entry(export.root, 1, false);+ }+ if result? == 0 {break;}}@@ -540,14 +681,28 @@ impl FileSystem for AggregateFs {fn init(&self, capable: FsOptions) -> io::Result<FsOptions> {let mut options = capable;- for share in &self.shares {- options &= share.backend.init(capable)?;+ let exports: Vec<Arc<Export>> = self+ .registry+ .lock()+ .unwrap()+ .exports+ .values()+ .cloned()+ .collect();+ for export in &exports {+ options &= export.backend.init(capable)?;}+ self.registry.lock().unwrap().alive = true;self.install_roots();Ok(options & (FsOptions::DO_READDIRPLUS | FsOptions::READDIRPLUS_AUTO))}fn destroy(&self) {+ let exports = {+ let mut registry = self.registry.lock().unwrap();+ registry.alive = false;+ registry.exports.values().cloned().collect::<Vec<_>>()+ };let (handles, nodes) = {let mut state = self.state.lock().unwrap();state.local_ids.clear();@@ -556,8 +711,8 @@ impl FileSystem for AggregateFs {};drop(handles);drop(nodes);- for share in &self.shares {- share.backend.destroy();+ for export in &exports {+ export.backend.destroy();}}@@ -565,21 +720,44 @@ impl FileSystem for AggregateFs {component(name, false)?;if parent == ROOT {if matches!(name.to_bytes(), b"." | b"..") {- return Ok(entry_from_attr(ROOT, synthetic_attr(self.shares.len())));+ let count = self.registry.lock().unwrap().exports.len();+ return Ok(entry_from_attr(ROOT, synthetic_attr(count)));+ }+ let export = {+ let registry = self.registry.lock().unwrap();+ let export = registry+ .exports+ .values()+ .find(|export| export.name.as_c_str() == name)+ .cloned()+ .ok_or_else(|| errno(libc::ENOENT))?;+ let mut state = self.state.lock().unwrap();+ let record = state+ .nodes+ .get_mut(&export.root)+ .ok_or_else(|| errno(libc::EBADF))?;+ record.lookups = record+ .lookups+ .checked_add(1)+ .ok_or_else(|| errno(libc::EOVERFLOW))?;+ export+ };+ match export.backend.lookup(ctx, ROOT, c".") {+ Ok(found) => return Ok(normalize(found, export.root, export.identity)),+ Err(error) => {+ self.forget_entry(export.root, 1, false);+ return Err(error);+ }}- let (index, share) = self- .shares- .iter()- .enumerate()- .find(|(_, share)| share.name.as_c_str() == name)- .ok_or_else(|| errno(libc::ENOENT))?;- return self.map_entry(index, share.backend.lookup(ctx, ROOT, c".")?);}let node = self.node(parent)?;if name == c".." {return Err(errno(libc::EPERM));}- self.map_entry(node.share, node.backend.lookup(ctx, node.local, name)?)+ self.map_entry(+ &node.export,+ node.export.backend.lookup(ctx, node.local, name)?,+ )}fn forget(&self, _ctx: Context, inode: u64, count: u64) {@@ -596,14 +774,15 @@ impl FileSystem for AggregateFs {.map(|handle| self.handle(inode, handle, None)).transpose()?;if inode == ROOT {- return Ok((synthetic_attr(self.shares.len()), TIMEOUT));+ let count = self.registry.lock().unwrap().exports.len();+ return Ok((synthetic_attr(count), TIMEOUT));}let node = match held.as_ref().and_then(|handle| handle.node.clone()) {Some(node) => node,None => self.node(inode)?,};let local_handle = held.as_ref().map(|handle| handle.local);- let (mut attr, timeout) = node.backend.getattr(ctx, node.local, local_handle)?;+ let (mut attr, timeout) = node.export.backend.getattr(ctx, node.local, local_handle)?;attr.st_ino = node.identity;Ok((attr, timeout))}@@ -624,7 +803,7 @@ impl FileSystem for AggregateFs {let held = handle.map(|handle| self.handle(inode, handle, None)).transpose()?;- let (mut attr, timeout) = node.backend.setattr(+ let (mut attr, timeout) = node.export.backend.setattr(ctx,node.local,attr,@@ -680,16 +859,23 @@ impl FileSystem for AggregateFs {extensions: Extensions,) -> io::Result<(Entry, Option<u64>, OpenOptions)> {let node = self.mutation_parent(parent, name)?;- let (entry, local_handle, options) = node.backend.create(+ let (entry, local_handle, options) = node.export.backend.create(ctx, node.local, name, mode, kill_priv, flags, umask, extensions,)?;let local_inode = entry.inode;let local_handle = local_handle.ok_or_else(|| errno(libc::EIO))?;- let entry = match self.map_entry(node.share, entry) {+ let entry = match self.map_entry(&node.export, entry) {Ok(entry) => entry,Err(error) => {- node.backend- .release(ctx, local_inode, flags, local_handle, false, false, None)?;+ node.export.backend.release(+ ctx,+ local_inode,+ flags,+ local_handle,+ false,+ false,+ None,+ )?;return Err(error);}};@@ -715,8 +901,9 @@ impl FileSystem for AggregateFs {) -> io::Result<Entry> {let node = self.mutation_parent(parent, name)?;self.map_entry(- node.share,- node.backend+ &node.export,+ node.export+ .backend.mkdir(ctx, node.local, name, mode, umask, extensions)?,)}@@ -732,8 +919,9 @@ impl FileSystem for AggregateFs {) -> io::Result<Entry> {let node = self.mutation_parent(parent, name)?;self.map_entry(- node.share,- node.backend+ &node.export,+ node.export+ .backend.mknod(ctx, node.local, name, mode, rdev, umask, extensions)?,)}@@ -747,22 +935,23 @@ impl FileSystem for AggregateFs {) -> io::Result<Entry> {let node = self.mutation_parent(parent, name)?;self.map_entry(- node.share,- node.backend+ &node.export,+ node.export+ .backend.symlink(ctx, linkname, node.local, name, extensions)?,)}fn readlink(&self, ctx: Context, inode: u64) -> io::Result<Vec<u8>> {let node = self.node(inode)?;- node.backend.readlink(ctx, node.local)+ node.export.backend.readlink(ctx, node.local)}fn unlink(&self, ctx: Context, parent: u64, name: &CStr) -> io::Result<()> {let node = self.mutation_parent(parent, name)?;- node.backend.unlink(ctx, node.local, name)+ node.export.backend.unlink(ctx, node.local, name)}fn rmdir(&self, ctx: Context, parent: u64, name: &CStr) -> io::Result<()> {let node = self.mutation_parent(parent, name)?;- node.backend.rmdir(ctx, node.local, name)+ node.export.backend.rmdir(ctx, node.local, name)}fn rename(&self,@@ -780,12 +969,13 @@ impl FileSystem for AggregateFs {}let source = self.node(olddir)?;let target = self.node(newdir)?;- if source.share != target.share {+ if !Arc::ptr_eq(&source.export, &target.export) {return Err(errno(libc::EXDEV));}self.writable(&source)?;self.writable(&target)?;source+ .export.backend.rename(ctx, source.local, oldname, target.local, newname, flags)}@@ -796,13 +986,14 @@ impl FileSystem for AggregateFs {}let source = self.node(inode)?;let target = self.node(newparent)?;- if source.share != target.share {+ if !Arc::ptr_eq(&source.export, &target.export) {return Err(errno(libc::EXDEV));}self.writable(&target)?;self.map_entry(- source.share,+ &source.export,source+ .export.backend.link(ctx, source.local, target.local, newname)?,)@@ -821,7 +1012,7 @@ impl FileSystem for AggregateFs {) -> io::Result<usize> {let held = self.handle(inode, handle, Some(false))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;- node.backend.read(+ node.export.backend.read(ctx, node.local, held.local, writer, size, offset, lock_owner, flags,)}@@ -841,7 +1032,7 @@ impl FileSystem for AggregateFs {let held = self.handle(inode, handle, Some(false))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;self.writable(node)?;- node.backend.write(+ node.export.backend.write(ctx,node.local,held.local,@@ -857,19 +1048,25 @@ impl FileSystem for AggregateFs {fn flush(&self, ctx: Context, inode: u64, handle: u64, lock_owner: u64) -> io::Result<()> {let held = self.handle(inode, handle, Some(false))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;- node.backend.flush(ctx, node.local, held.local, lock_owner)+ node.export+ .backend+ .flush(ctx, node.local, held.local, lock_owner)}fn fsync(&self, ctx: Context, inode: u64, datasync: bool, handle: u64) -> io::Result<()> {let held = self.handle(inode, handle, Some(false))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;- node.backend.fsync(ctx, node.local, datasync, held.local)+ node.export+ .backend+ .fsync(ctx, node.local, datasync, held.local)}fn fsyncdir(&self, ctx: Context, inode: u64, datasync: bool, handle: u64) -> io::Result<()> {let held = self.handle(inode, handle, Some(true))?;let Some(node) = held.node.as_ref() else {return Ok(());};- node.backend.fsyncdir(ctx, node.local, datasync, held.local)+ node.export+ .backend+ .fsyncdir(ctx, node.local, datasync, held.local)}fn readdir<F>(@@ -885,14 +1082,14 @@ impl FileSystem for AggregateFs {F: FnMut(DirEntry) -> io::Result<usize>,{if inode == ROOT {- return self.root_directory(ctx, handle, size, offset, |dirent, _| add(dirent));+ return self.root_directory(ctx, handle, size, offset, false, |dirent, _| add(dirent));}let held = self.handle(inode, handle, Some(true))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;if size == 0 || !self.directory_dots(ctx, node, offset, |dirent, _| add(dirent))? {return Ok(());}- node.backend.readdir(+ node.export.backend.readdir(ctx,node.local,held.local,@@ -910,13 +1107,13 @@ impl FileSystem for AggregateFs {.offset.checked_add(2).ok_or_else(|| errno(libc::EOVERFLOW))?;- let found = match node.backend.lookup(ctx, node.local, name) {+ let found = match node.export.backend.lookup(ctx, node.local, name) {Ok(found) => found,// getdents buffered this name before a host-side removal.Err(error) if error.raw_os_error() == Some(libc::ENOENT) => return Ok(1),Err(error) => return Err(error),};- let entry = self.map_entry(node.share, found)?;+ let entry = self.map_entry(&node.export, found)?;let global = entry.inode;let result = add(DirEntry {ino: entry.attr.st_ino,@@ -942,14 +1139,14 @@ impl FileSystem for AggregateFs {F: FnMut(DirEntry, Entry) -> io::Result<usize>,{if inode == ROOT {- return self.root_directory(ctx, handle, size, offset, add);+ return self.root_directory(ctx, handle, size, offset, true, add);}let held = self.handle(inode, handle, Some(true))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;if size == 0 || !self.directory_dots(ctx, node, offset, &mut add)? {return Ok(());}- node.backend.readdirplus(+ node.export.backend.readdirplus(ctx,node.local,held.local,@@ -960,7 +1157,7 @@ impl FileSystem for AggregateFs {.offset.checked_add(2).ok_or_else(|| errno(libc::EOVERFLOW))?;- let entry = self.insert_entry(node.share, entry)?;+ let entry = self.insert_entry(&node.export, entry)?;let global = entry.inode;let result = add(DirEntry {@@ -995,7 +1192,7 @@ impl FileSystem for AggregateFs {if mask & libc::W_OK as u32 != 0 {self.writable(&node)?;}- node.backend.access(ctx, node.local, mask)+ node.export.backend.access(ctx, node.local, mask)}fn statfs(&self, ctx: Context, inode: u64) -> io::Result<libc::statvfs64> {@@ -1003,7 +1200,7 @@ impl FileSystem for AggregateFs {return Err(errno(libc::EOPNOTSUPP));}let node = self.node(inode)?;- node.backend.statfs(ctx, node.local)+ node.export.backend.statfs(ctx, node.local)}fn setxattr(&self,@@ -1018,7 +1215,9 @@ impl FileSystem for AggregateFs {}let node = self.node(inode)?;self.writable(&node)?;- node.backend.setxattr(ctx, node.local, name, value, flags)+ node.export+ .backend+ .setxattr(ctx, node.local, name, value, flags)}fn getxattr(&self,@@ -1031,14 +1230,14 @@ impl FileSystem for AggregateFs {return Err(errno(libc::EOPNOTSUPP));}let node = self.node(inode)?;- node.backend.getxattr(ctx, node.local, name, size)+ node.export.backend.getxattr(ctx, node.local, name, size)}fn listxattr(&self, ctx: Context, inode: u64, size: u32) -> io::Result<ListxattrReply> {if inode == ROOT {return Err(errno(libc::EOPNOTSUPP));}let node = self.node(inode)?;- node.backend.listxattr(ctx, node.local, size)+ node.export.backend.listxattr(ctx, node.local, size)}fn removexattr(&self, ctx: Context, inode: u64, name: &CStr) -> io::Result<()> {if inode == ROOT {@@ -1046,7 +1245,7 @@ impl FileSystem for AggregateFs {}let node = self.node(inode)?;self.writable(&node)?;- node.backend.removexattr(ctx, node.local, name)+ node.export.backend.removexattr(ctx, node.local, name)}fn fallocate(&self,@@ -1060,7 +1259,8 @@ impl FileSystem for AggregateFs {let held = self.handle(inode, handle, Some(false))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;self.writable(node)?;- node.backend+ node.export+ .backend.fallocate(ctx, node.local, held.local, mode, offset, length)}fn lseek(@@ -1073,7 +1273,8 @@ impl FileSystem for AggregateFs {) -> io::Result<u64> {let held = self.handle(inode, handle, Some(false))?;let node = held.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;- node.backend+ node.export+ .backend.lseek(ctx, node.local, held.local, offset, whence)}fn copyfilerange(@@ -1092,11 +1293,11 @@ impl FileSystem for AggregateFs {let target = self.handle(inode_out, handle_out, Some(false))?;let source_node = source.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;let target_node = target.node.as_ref().ok_or_else(|| errno(libc::EBADF))?;- if source_node.share != target_node.share {+ if !Arc::ptr_eq(&source_node.export, &target_node.export) {return Err(errno(libc::EXDEV));}self.writable(target_node)?;- source_node.backend.copyfilerange(+ source_node.export.backend.copyfilerange(ctx,source_node.local,source.local,diff --git a/src/vmm/src/virtio/fs/device.rs b/src/vmm/src/virtio/fs/device.rsindex 04e436c1f..287775f61 100644--- a/src/vmm/src/virtio/fs/device.rs+++ b/src/vmm/src/virtio/fs/device.rs@@ -2,6 +2,7 @@// SPDX-License-Identifier: Apache-2.0use std::io;+use std::sync::Arc;use super::{AggregateFs, Share, descriptor::request_buffers, server::Server};use crate::memory::GuestMemoryMmap;@@ -23,7 +24,7 @@ const SPEC: DeviceSpec = DeviceSpec {snapshot: SnapshotSupport::Unsupported,};-/// One immutable share registry and one FUSE session, independent of transport.+/// One dynamic share registry and one FUSE session, independent of transport.////// Reset releases the session's file handles and lookup references before the/// transport can replace guest RAM. It retains the export configuration.@@ -32,6 +33,7 @@ pub(crate) struct Fs {features: u64,server: Server<AggregateFs>,activation: Option<ActivationContext>,+ closed: bool,}impl Fs {@@ -50,8 +52,36 @@ impl Fs {features: 0,server: Server::new(AggregateFs::new(shares)?),activation: None,+ closed: false,})}++ /// The aggregate filesystem this device serves, shared with the+ /// process-wide mount registry for the control socket.+ pub(crate) fn filesystem(&self) -> Arc<AggregateFs> {+ self.server.filesystem()+ }++ fn close(&mut self) {+ if self.closed {+ return;+ }+ // Unpublish only this device's registration, then close its session+ // even when a control operation still holds a filesystem reference.+ let bytes = &self.config[..TAG_LEN];+ let len = bytes.iter().position(|byte| *byte == 0).unwrap_or(TAG_LEN);+ if let Ok(tag) = std::str::from_utf8(&bytes[..len]) {+ super::remove_aggregate(tag, &self.server.filesystem());+ }+ self.server.reset();+ self.closed = true;+ }+}++impl Drop for Fs {+ fn drop(&mut self) {+ self.close();+ }}impl VirtioDevice for Fs {@@ -109,6 +139,11 @@ impl VirtioDevice for Fs {Ok(())}+ fn quiesce(&mut self) -> Result<(), DeviceError> {+ self.close();+ Ok(())+ }+fn on_event(&mut self, event: DeviceEvent) -> Result<(), DeviceError> {let DeviceEvent::QueueKick(index) = event else {return Err(DeviceError::NeedsReset(diff --git a/src/vmm/src/virtio/fs/linux/passthrough.rs b/src/vmm/src/virtio/fs/linux/passthrough.rsindex b0c54ca82..083f21b1d 100644--- a/src/vmm/src/virtio/fs/linux/passthrough.rs+++ b/src/vmm/src/virtio/fs/linux/passthrough.rs@@ -52,6 +52,36 @@ fn openat(parent: i32, name: &CStr, flags: i32, mode: u32) -> io::Result<File> {Ok(unsafe { File::from_raw_fd(fd) })}+/// Resolves `name` strictly beneath `parent`: parent traversal and escape+/// symlinks (absolute targets or `..` hops beyond the parent) fail with+/// `EXDEV`. Guests pass a single validated component, but a hostile host+/// directory may contain symlinks, so every guest-driven walk goes through+/// this range limit.+pub(crate) fn openat_beneath(parent: i32, name: &CStr, flags: i32, mode: u32) -> io::Result<File> {+ // SAFETY: open_how is a plain integer struct and non-exhaustive, so it+ // cannot be built with a struct expression; zeroed padding is the valid+ // initializer the kernel expects.+ let mut how: libc::open_how = unsafe { mem::zeroed() };+ how.flags = (flags | libc::O_CLOEXEC) as u64;+ how.mode = mode as u64;+ how.resolve = libc::RESOLVE_BENEATH;+ // SAFETY: name is terminated and a successful descriptor is owned below.+ let fd = unsafe {+ libc::syscall(+ libc::SYS_openat2,+ parent,+ name.as_ptr(),+ &how,+ mem::size_of::<libc::open_how>(),+ )+ };+ if fd < 0 {+ return Err(io::Error::last_os_error());+ }+ // SAFETY: openat2 returned a new owned descriptor.+ Ok(unsafe { File::from_raw_fd(fd as i32) })+}+fn stat(file: &File) -> io::Result<libc::stat64> {let mut attr = MaybeUninit::uninit();// SAFETY: attr has room for stat64; file owns the descriptor during the call.@@ -249,7 +279,17 @@ impl PassthroughFs {libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW,0,)?;+ Self::from_dir_fd(file)+ }++ /// Builds a backend over a directory descriptor the runtime already holds.+ /// Symlink and non-directory descriptors are rejected. Host access rights+ /// are enforced by the kernel when each filesystem operation executes.+ pub(crate) fn from_dir_fd(file: File) -> io::Result<Self> {let (attr, mount) = statx(&file)?;+ if attr.st_mode & libc::S_IFMT != libc::S_IFDIR {+ return Err(errno(libc::ENOTDIR));+ }let fs = Self {root: Arc::new(InodeData {inode: ROOT,@@ -457,7 +497,7 @@ impl PassthroughFs {} else {name};- let file = openat(+ let file = openat_beneath(parent.file.as_raw_fd(),name,libc::O_PATH | libc::O_NOFOLLOW,@@ -832,7 +872,7 @@ impl FileSystem for PassthroughFs {let mode = mode & !umask & 0o7777;// O_EXCL pins a new regular file. Existing names are first opened with// O_PATH so CREATE cannot block on a FIFO or open a device or symlink.- let file = match openat(+ let file = match openat_beneath(parent.data.file.as_raw_fd(),name,flags | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW,@@ -847,7 +887,7 @@ impl FileSystem for PassthroughFs {Err(error)if error.raw_os_error() == Some(libc::EEXIST) && flags & libc::O_EXCL == 0 =>{- let existing = openat(+ let existing = openat_beneath(parent.data.file.as_raw_fd(),name,libc::O_PATH | libc::O_NOFOLLOW,@@ -897,7 +937,7 @@ impl FileSystem for PassthroughFs {let mode = mode & !umask & 0o7777;// SAFETY: the parent descriptor and component remain alive.cvt(unsafe { libc::mkdirat(parent.data.file.as_raw_fd(), name.as_ptr(), mode) })?;- let file = openat(+ let file = openat_beneath(parent.data.file.as_raw_fd(),name,libc::O_PATH | libc::O_NOFOLLOW | libc::O_DIRECTORY,@@ -936,7 +976,7 @@ impl FileSystem for PassthroughFs {0,)})?;- let file = openat(+ let file = openat_beneath(parent.data.file.as_raw_fd(),name,libc::O_PATH | libc::O_NOFOLLOW,diff --git a/src/vmm/src/virtio/fs/mod.rs b/src/vmm/src/virtio/fs/mod.rsindex 4ae16b70f..b9b78d329 100644--- a/src/vmm/src/virtio/fs/mod.rs+++ b/src/vmm/src/virtio/fs/mod.rs@@ -3,12 +3,12 @@//! In-process virtio-fs: a FUSE session over one priority and one request queue.//!-//! The immutable aggregate root exposes all shares through this one device.+//! The aggregate root exposes independently registered shares through one device.//! Host file I/O is synchronous. Under the shared executor a slow request also//! stalls other device callbacks. The VM registers this device through the common//! MMIO transport and worker runtime.-use std::sync::{Arc, Mutex};+use std::sync::{Arc, LazyLock, Mutex};use self::device::Fs;use super::{@@ -30,7 +30,55 @@ mod linux;mod multikey;pub(crate) mod server;-pub(crate) use aggregate::{AggregateFs, Share};+pub use aggregate::{AggregateFs, Share};++use std::collections::BTreeMap;++/// Live aggregate filesystems keyed by device tag. The shim process hosts+/// one VM; the mount-control server reaches the device through this registry+/// instead of threading device internals through the transport. The entry+/// appears when the device is built and is removed when the device stops or+/// drops. Lookups after teardown answer `ENODEV`.+static MOUNT_DEVICES: LazyLock<Mutex<BTreeMap<String, Arc<AggregateFs>>>> =+ LazyLock::new(|| Mutex::new(BTreeMap::new()));++fn mount_devices() -> &'static Mutex<BTreeMap<String, Arc<AggregateFs>>> {+ &MOUNT_DEVICES+}++/// The live aggregate filesystem for `tag`, or `ENODEV` if the tag is absent.+pub fn lookup_aggregate(tag: &str) -> std::io::Result<Arc<AggregateFs>> {+ mount_devices()+ .lock()+ .unwrap()+ .get(tag)+ .cloned()+ .ok_or_else(|| std::io::Error::from_raw_os_error(libc::ENODEV))+}++/// Publishes `filesystem` as the live device for `tag`. The VMM build path+/// calls this when the device enters the transport; tests use it to stand up+/// a control server against a real filesystem.+pub fn insert_aggregate(tag: &str, filesystem: Arc<AggregateFs>) {+ mount_devices()+ .lock()+ .unwrap()+ .insert(tag.to_string(), filesystem);+}++/// Removes the registration for `tag` when it still points at `filesystem`+/// and reports whether it did. Tearing down an older device must not+/// unregister a newer rebuild published under the same tag.+pub fn remove_aggregate(tag: &str, filesystem: &AggregateFs) -> bool {+ let mut devices = mount_devices().lock().unwrap();+ match devices.get(tag) {+ Some(live) if std::ptr::eq(live.as_ref(), filesystem) => {+ devices.remove(tag);+ true+ }+ _ => false,+ }+}/// Adds the configured exports behind a virtio-mmio transport in `slot`,/// run by the VM's workers.@@ -50,6 +98,7 @@ pub(crate) fn add_filesystem(}).collect();let filesystem = Fs::new(&config.tag, shares).map_err(Error::Filesystem)?;+ insert_aggregate(&config.tag, filesystem.filesystem());let device: Arc<Mutex<dyn VirtioDevice>> = Arc::new(Mutex::new(filesystem));mmio::add_device(chipset, ctx, "virtio-fs", slot, device)}diff --git a/src/vmm/src/virtio/fs/server.rs b/src/vmm/src/virtio/fs/server.rsindex 3a89dab5d..ff04bfa19 100644--- a/src/vmm/src/virtio/fs/server.rs+++ b/src/vmm/src/virtio/fs/server.rs@@ -11,6 +11,7 @@ use std::ffi::CStr;use std::fs::File;use std::io::{self, Read, Write};use std::mem::size_of;+use std::sync::Arc;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use vm_memory::ByteValued;@@ -83,7 +84,7 @@ impl io::Write for ZCWriter<'_> {}pub struct Server<F: FileSystem + Sync> {- fs: F,+ fs: Arc<F>,options: AtomicU64,initialized: AtomicBool,}@@ -91,12 +92,18 @@ pub struct Server<F: FileSystem + Sync> {impl<F: FileSystem + Sync> Server<F> {pub fn new(fs: F) -> Server<F> {Server {- fs,+ fs: Arc::new(fs),options: AtomicU64::new(FsOptions::empty().bits()),initialized: AtomicBool::new(false),}}+ /// A shared handle to the served filesystem. Host-side control paths use+ /// it to reach the device without crossing the worker runtime.+ pub fn filesystem(&self) -> Arc<F> {+ self.fs.clone()+ }+/// Clear negotiated protocol state and invalidate backend session resources.pub fn reset(&self) {self.options.store(0, Ordering::Relaxed);diff --git a/src/vmm/tests/virtio/fs_backend.rs b/src/vmm/tests/virtio/fs_backend.rsindex ad4d626cf..744c0e1c5 100644--- a/src/vmm/tests/virtio/fs_backend.rs+++ b/src/vmm/tests/virtio/fs_backend.rs@@ -17,7 +17,7 @@ use std::time::Duration;use crate::virtio::fs::filesystem::{Context, Extensions, FileSystem, FsOptions, SetattrValid, ZeroCopyReader, ZeroCopyWriter,};-use crate::virtio::fs::{AggregateFs, Share};+use crate::virtio::fs::{AggregateFs, Share, insert_aggregate, lookup_aggregate, remove_aggregate};static NEXT: AtomicU64 = AtomicU64::new(0);struct Directory(PathBuf);@@ -669,7 +669,7 @@ fn validates_share_names_and_preserves_symlink_contents_without_host_traversal()read_only: true,},]),- libc::EINVAL,+ libc::EEXIST,);let fs = dir.backend();let (rw, _, _) = roots(&fs);@@ -1146,3 +1146,400 @@ fn synthetic_root_xattr_queries_report_unsupported_not_invalid_inode() {libc::S_IFDIR);}++#[test]+fn registers_and_removes_exports_at_runtime() {+ let dir = Directory::new();+ let fs = dir.backend();++ // A directory no guest has seen becomes resolvable without a reset, and+ // its own read-only policy applies to it.+ let late = fs+ .register(Share {+ name: "late".into(),+ path: dir.0.clone(),+ read_only: true,+ })+ .unwrap();+ let found = fs.lookup(ctx(), 1, c"late").unwrap();+ assert_eq!(found.inode, late);+ error(+ fs.mkdir(ctx(), late, c"sub", 0o755, 0, Extensions::default()),+ libc::EROFS,+ );++ // Removal retires the name only: the seeded shares still resolve.+ fs.remove("late").unwrap();+ error(fs.lookup(ctx(), 1, c"late"), libc::ENOENT);+ error(fs.remove("late"), libc::ENOENT);+ fs.lookup(ctx(), 1, c"rw").unwrap();++ // The name is free again; the new export is a distinct identity with its+ // own policy.+ let again = fs+ .register(Share {+ name: "late".into(),+ path: dir.0.clone(),+ read_only: false,+ })+ .unwrap();+ assert_ne!(again, late);+ fs.mkdir(ctx(), again, c"sub", 0o755, 0, Extensions::default())+ .unwrap();+}++#[test]+fn rejects_duplicate_names_and_mutations_after_destroy() {+ let dir = Directory::new();+ let fs = dir.backend();+ error(+ fs.register(Share {+ name: "rw".into(),+ path: dir.0.clone(),+ read_only: false,+ }),+ libc::EEXIST,+ );+ fs.destroy();+ error(+ fs.register(Share {+ name: "fresh".into(),+ path: dir.0.clone(),+ read_only: false,+ }),+ libc::ENODEV,+ );+ error(fs.remove("rw"), libc::ENODEV);+}++#[test]+fn entries_expire_immediately_so_guest_caches_never_mask_deletions() {+ let dir = Directory::new();+ let fs = dir.backend();+ // Zero entry and attribute timeouts keep the guest kernel from caching+ // lookups: a removed export name resolves to ENOENT on the next lookup+ // instead of a stale dentry, and a re-registered name resolves to its+ // new identity. Verified against removal in+ // registers_and_removes_exports_at_runtime.+ let root = fs.lookup(ctx(), 1, c"rw").unwrap();+ assert_eq!(root.entry_timeout, std::time::Duration::ZERO);+ assert_eq!(root.attr_timeout, std::time::Duration::ZERO);+ let entry = fs.lookup(ctx(), root.inode, c"agents").unwrap_or_else(|_| {+ fs.create(+ ctx(),+ root.inode,+ c"agents",+ 0o600,+ false,+ libc::O_RDWR as u32,+ 0,+ Extensions::default(),+ )+ .unwrap()+ .0+ });+ assert_eq!(entry.entry_timeout, std::time::Duration::ZERO);+ assert_eq!(entry.attr_timeout, std::time::Duration::ZERO);+}++#[test]+fn removed_export_keeps_open_references_until_released() {+ let dir = Directory::new();+ fs::write(dir.0.join("data"), b"payload").unwrap();+ let fs = AggregateFs::new(vec![Share {+ name: "share".into(),+ path: dir.0.clone(),+ read_only: false,+ }])+ .unwrap();+ let root = fs.lookup(ctx(), 1, c"share").unwrap().inode;+ let entry = fs.lookup(ctx(), root, c"data").unwrap();+ let handle = open(&fs, entry.inode, libc::O_RDWR);+ let (dir_handle, _) = fs.opendir(ctx(), root, 0).unwrap();+ let dir_handle = dir_handle.unwrap();++ // The name stops resolving, while the open file and directory handles+ // keep serving their backend.+ fs.remove("share").unwrap();+ error(fs.lookup(ctx(), 1, c"share"), libc::ENOENT);+ assert_eq!(read(&fs, entry.inode, handle).unwrap(), b"payload");+ // The helper writes at offset 0: the byte lands in front of the payload,+ // proving the write reached the host file through the old handle.+ write(&fs, entry.inode, handle, b"!").unwrap();+ assert_eq!(fs::read(dir.0.join("data")).unwrap(), b"!ayload");+ let mut names = Vec::new();+ fs.readdir(ctx(), root, dir_handle, 4096, 0, |dirent| {+ names.push(dirent.name.to_vec());+ Ok(1)+ })+ .unwrap();+ assert!(names.contains(&b"data".to_vec()));++ // Releasing every reference reclaims the export: the inodes are no+ // longer addressable.+ fs.release(ctx(), entry.inode, 0, handle, false, false, None)+ .unwrap();+ fs.releasedir(ctx(), root, 0, dir_handle).unwrap();+ fs.forget(ctx(), entry.inode, 1);+ fs.forget(ctx(), root, 1);+ error(fs.getattr(ctx(), root, None), libc::EBADF);+ error(fs.getattr(ctx(), entry.inode, None), libc::EBADF);+}++#[test]+fn removed_export_keeps_root_lookups_without_open_handles() {+ let dir = Directory::new();+ fs::write(dir.0.join("data"), b"payload").unwrap();+ let fs = AggregateFs::new(vec![Share {+ name: "share".into(),+ path: dir.0.clone(),+ read_only: false,+ }])+ .unwrap();+ let root = fs.lookup(ctx(), 1, c"share").unwrap().inode;+ fs.lookup(ctx(), 1, c"share").unwrap();+ fs.forget(ctx(), root, 1);+ fs.remove("share").unwrap();+ error(fs.lookup(ctx(), 1, c"share"), libc::ENOENT);+ fs.getattr(ctx(), root, None).unwrap();+ let child = fs.lookup(ctx(), root, c"data").unwrap();+ fs.forget(ctx(), child.inode, 1);+ fs.forget(ctx(), root, 1);+ error(fs.getattr(ctx(), root, None), libc::EBADF);+}++#[test]+fn root_lookup_racing_removal_preserves_the_export_identity() {+ let dir = Directory::new();+ let fs = Arc::new(AggregateFs::new(Vec::new()).unwrap());+ let root = fs+ .register_fd("share".into(), File::open(&dir.0).unwrap(), false)+ .unwrap();+ let expected = fs.getattr(ctx(), root, None).unwrap().0.st_ino;+ let removing = fs.clone();+ super::linux_tests::before_next_statx(move || removing.remove("share").unwrap());+ let found = fs.lookup(ctx(), 1, c"share").unwrap();+ assert_eq!(found.inode, root);+ assert_eq!(found.attr.st_ino, expected);+ fs.getattr(ctx(), root, None).unwrap();+ fs.forget(ctx(), root, 1);+ error(fs.getattr(ctx(), root, None), libc::EBADF);+}++#[test]+fn root_directory_entries_retain_only_accepted_readdirplus_lookups() {+ for mode in 0..4 {+ let dir = Directory::new();+ let fs = AggregateFs::new(vec![Share {+ name: "share".into(),+ path: dir.0.clone(),+ read_only: false,+ }])+ .unwrap();+ let (handle, _) = fs.opendir(ctx(), 1, 0).unwrap();+ let mut root = 2;+ if mode == 0 {+ fs.readdir(ctx(), 1, handle.unwrap(), 4096, 2, |_| Ok(1))+ .unwrap();+ } else {+ let result = fs.readdirplus(ctx(), 1, handle.unwrap(), 4096, 2, |_, entry| {+ root = entry.inode;+ match mode {+ 1 => Ok(1),+ 2 => Ok(0),+ _ => Err(io::Error::from_raw_os_error(libc::EIO)),+ }+ });+ if mode == 3 {+ error(result, libc::EIO);+ } else {+ result.unwrap();+ }+ }+ fs.releasedir(ctx(), 1, 0, handle.unwrap()).unwrap();+ if mode == 0 {+ root = fs.lookup(ctx(), 1, c"share").unwrap().inode;+ fs.forget(ctx(), root, 1);+ }+ fs.remove("share").unwrap();+ if mode == 1 {+ fs.getattr(ctx(), root, None).unwrap();+ fs.forget(ctx(), root, 1);+ }+ error(fs.getattr(ctx(), root, None), libc::EBADF);+ }+}++#[test]+fn remount_replaces_identity_and_content_for_old_references() {+ let old_dir = Directory::new();+ let new_dir = Directory::new();+ fs::write(old_dir.0.join("marker"), b"old").unwrap();+ fs::write(new_dir.0.join("marker"), b"new").unwrap();+ let fs = AggregateFs::new(vec![Share {+ name: "vol".into(),+ path: old_dir.0.clone(),+ read_only: false,+ }])+ .unwrap();+ let root = fs.lookup(ctx(), 1, c"vol").unwrap().inode;+ let file = fs.lookup(ctx(), root, c"marker").unwrap();+ let handle = open(&fs, file.inode, libc::O_RDONLY);++ fs.remove("vol").unwrap();+ fs.register(Share {+ name: "vol".into(),+ path: new_dir.0.clone(),+ read_only: false,+ })+ .unwrap();++ // The surviving old reference still reads the old backend.+ assert_eq!(read(&fs, file.inode, handle).unwrap(), b"old");+ // The name now resolves to a new identity whose content differs.+ let fresh_root = fs.lookup(ctx(), 1, c"vol").unwrap().inode;+ assert_ne!(fresh_root, root);+ let fresh = fs.lookup(ctx(), fresh_root, c"marker").unwrap();+ assert_ne!(fresh.inode, file.inode);+ let fresh_handle = open(&fs, fresh.inode, libc::O_RDONLY);+ assert_eq!(read(&fs, fresh.inode, fresh_handle).unwrap(), b"new");+}++#[test]+fn register_fd_publishes_a_delivered_directory_descriptor() {+ if !super::linux_tests::in_unprivileged_child() {+ return;+ }+ let dir = Directory::new();+ fs::write(dir.0.join("note"), b"fd").unwrap();+ let fs = dir.backend();++ let delivered = File::open(&dir.0).unwrap();+ let root = fs.register_fd("late".into(), delivered, false).unwrap();+ let entry = fs.lookup(ctx(), root, c"note").unwrap();+ let handle = open(&fs, entry.inode, libc::O_RDONLY);+ assert_eq!(read(&fs, entry.inode, handle).unwrap(), b"fd");++ // A descriptor that is not a directory never becomes an export.+ let regular = File::create(dir.0.join("plain")).unwrap();+ error(fs.register_fd("bad".into(), regular, false), libc::ENOTDIR);+ error(fs.lookup(ctx(), 1, c"bad"), libc::ENOENT);++ // Directory mutation rights and existing-file write rights are independent.+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(dir.0.join("note"), fs::Permissions::from_mode(0o600)).unwrap();+ fs::set_permissions(&dir.0, fs::Permissions::from_mode(0o555)).unwrap();+ let root = fs+ .register_fd("strict".into(), File::open(&dir.0).unwrap(), false)+ .unwrap();+ let entry = fs.lookup(ctx(), root, c"note").unwrap();+ let handle = open(&fs, entry.inode, libc::O_RDWR);+ write(&fs, entry.inode, handle, b"ok").unwrap();+ assert_eq!(fs::read(dir.0.join("note")).unwrap(), b"ok");+ error(+ fs.create(+ ctx(),+ root,+ c"denied",+ 0o600,+ false,+ libc::O_RDWR as u32,+ 0,+ Extensions::default(),+ ),+ libc::EACCES,+ );+ fs::set_permissions(&dir.0, fs::Permissions::from_mode(0o700)).unwrap();+}++#[test]+fn runtime_export_roots_and_children_have_distinct_inode_identities() {+ let dir = Directory::new();+ fs::write(dir.0.join("child"), b"data").unwrap();+ let fs = AggregateFs::new(Vec::new()).unwrap();+ let first = fs+ .register_fd("first".into(), File::open(&dir.0).unwrap(), false)+ .unwrap();+ let root = fs.lookup(ctx(), 1, c"first").unwrap();+ let child = fs.lookup(ctx(), first, c"child").unwrap();+ let second = fs+ .register_fd("second".into(), File::open(&dir.0).unwrap(), false)+ .unwrap();+ let other = fs.getattr(ctx(), second, None).unwrap().0;+ assert_ne!(root.attr.st_ino, child.attr.st_ino);+ assert_ne!(root.attr.st_ino, other.st_ino);+ assert_ne!(child.attr.st_ino, other.st_ino);+}++/// Fds this process holds that resolve into `dir`.+fn fds_into(dir: &std::path::Path) -> usize {+ fs::read_dir("/proc/self/fd")+ .unwrap()+ .filter_map(|entry| fs::read_link(entry.ok()?.path()).ok())+ .filter(|target| target.starts_with(dir))+ .count()+}++fn teardown_share(path: &std::path::Path) -> Vec<Share> {+ vec![Share {+ name: "seed".into(),+ path: path.to_path_buf(),+ read_only: false,+ }]+}++#[test]+fn dropping_the_fs_device_unregisters_the_aggregate_and_closes_its_exports() {+ let dir = Directory::new();+ fs::write(dir.0.join("data"), b"payload").unwrap();+ let tag = "aggregate-device-teardown";+ let device = crate::virtio::fs::device::Fs::new(tag, teardown_share(&dir.0)).unwrap();+ insert_aggregate(tag, device.filesystem());+ lookup_aggregate(tag).unwrap();+ assert!(fds_into(&dir.0) >= 1);++ drop(device);+ error(lookup_aggregate(tag), libc::ENODEV);+ assert_eq!(fds_into(&dir.0), 0);+}++#[test]+fn cached_aggregate_handle_rejects_registration_after_device_drop() {+ let dir = Directory::new();+ let tag = "aggregate-cached-teardown";+ let device = crate::virtio::fs::device::Fs::new(tag, teardown_share(&dir.0)).unwrap();+ insert_aggregate(tag, device.filesystem());+ let cached = lookup_aggregate(tag).unwrap();+ drop(device);+ error(+ cached.register_fd("late".into(), File::open(&dir.0).unwrap(), false),+ libc::ENODEV,+ );+ error(cached.remove("seed"), libc::ENODEV);+ drop(cached);+ assert_eq!(fds_into(&dir.0), 0);+}++#[test]+fn aggregate_registry_teardown_is_scoped_to_the_registered_filesystem() {+ let dir = Directory::new();+ fs::write(dir.0.join("data"), b"payload").unwrap();+ let tag = "aggregate-registry-scoped-teardown";+ let filesystem = Arc::new(AggregateFs::new(teardown_share(&dir.0)).unwrap());+ insert_aggregate(tag, filesystem.clone());+ lookup_aggregate(tag).unwrap();+ assert!(fds_into(&dir.0) >= 1);++ // A foreign aggregate must not unregister the live entry, and the live+ // entry keeps answering until its own teardown removes it.+ let outsider = Arc::new(AggregateFs::new(teardown_share(&dir.0)).unwrap());+ assert!(!remove_aggregate(tag, &outsider));+ lookup_aggregate(tag).unwrap();+ drop(outsider);+ lookup_aggregate(tag).unwrap();++ assert!(remove_aggregate(tag, &filesystem));+ drop(filesystem);+ error(lookup_aggregate(tag), libc::ENODEV);+ assert_eq!(fds_into(&dir.0), 0);+}diff --git a/src/vmm/tests/virtio/fs_linux.rs b/src/vmm/tests/virtio/fs_linux.rsindex a8b1263e6..3f3b032a9 100644--- a/src/vmm/tests/virtio/fs_linux.rs+++ b/src/vmm/tests/virtio/fs_linux.rs@@ -5,7 +5,8 @@use std::ffi::{CStr, CString, OsString};use std::fs::{self, File};use std::io::{self, Cursor, Read, Write};-use std::os::unix::ffi::OsStringExt;+use std::os::fd::{AsRawFd, FromRawFd};+use std::os::unix::ffi::{OsStrExt, OsStringExt};use std::os::unix::fs::{FileExt, MetadataExt, PermissionsExt};use std::os::unix::net::UnixListener;use std::path::PathBuf;@@ -20,12 +21,17 @@ use crate::virtio::fs::filesystem::{Context, Entry, Extensions, FileSystem, FsOptions, GetxattrReply, ListxattrReply, OpenOptions,SetattrValid, ZeroCopyReader, ZeroCopyWriter,};-use crate::virtio::fs::linux::passthrough::PassthroughFs;+use crate::virtio::fs::linux::passthrough::{PassthroughFs, openat_beneath};static NEXT: AtomicU64 = AtomicU64::new(0);thread_local! {static OMIT_MOUNT_ID: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };+ static BEFORE_STATX: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };+}++pub(super) fn before_next_statx(callback: impl FnOnce() + 'static) {+ BEFORE_STATX.with(|hook| *hook.borrow_mut() = Some(Box::new(callback)));}// Interpose only in the test binary, preserving real host results except for a@@ -38,6 +44,13 @@ unsafe extern "C" fn host_statx(mask: libc::c_uint,out: *mut libc::statx,) -> libc::c_int {+ let hook = BEFORE_STATX+ .try_with(|hook| hook.borrow_mut().take())+ .ok()+ .flatten();+ if let Some(hook) = hook {+ hook();+ }// SAFETY: forward the libc ABI arguments unchanged to the Linux syscall.let result = unsafe { libc::syscall(libc::SYS_statx, dirfd, path, flags, mask, out) };if result == 0 && OMIT_MOUNT_ID.try_with(|omit| omit.get()).unwrap_or(false) {@@ -1001,8 +1014,8 @@ fn missing_statx_mount_identity_rejects_construction_and_lookup() {);}-fn in_unprivileged_xattr_child() -> bool {- const CHILD: &str = "BOXLITE_FS_XATTR_ACCESS_CHILD";+pub(super) fn in_unprivileged_child() -> bool {+ const CHILD: &str = "BOXLITE_FS_ACCESS_CHILD";if std::env::var_os(CHILD).is_none() {let name = std::thread::current().name().unwrap().to_owned();let status = std::process::Command::new(std::env::current_exe().unwrap())@@ -1029,7 +1042,7 @@ fn in_unprivileged_xattr_child() -> bool {#[test]fn xattr_writes_on_write_only_files_preserve_reads_directories_and_symlink_safety() {- if !in_unprivileged_xattr_child() {+ if !in_unprivileged_child() {return;}let directory = Directory::new();@@ -1078,7 +1091,7 @@ fn xattr_writes_on_write_only_files_preserve_reads_directories_and_symlink_safet#[test]fn xattr_writes_on_unreadable_directories_remain_bound_after_name_replacement() {- if !in_unprivileged_xattr_child() {+ if !in_unprivileged_child() {return;}let directory = Directory::new();@@ -1111,3 +1124,66 @@ fn xattr_writes_on_unreadable_directories_remain_bound_after_name_replacement()libc::ENODATA,);}++#[test]+fn directory_range_confines_walks_to_the_shared_subtree() {+ use std::os::unix::fs::symlink;++ let dir = Directory::new();+ fs::write(dir.0.join("plain"), b"inside").unwrap();+ symlink("/etc/passwd", dir.0.join("escape")).unwrap();+ symlink("plain", dir.0.join("within")).unwrap();+ let root = File::open(&dir.0).unwrap();+ let fd = root.as_raw_fd();+ let plain = &CString::new("plain").unwrap();+ let parent = &CString::new("..").unwrap();+ let escape = &CString::new("escape").unwrap();+ let within = &CString::new("within").unwrap();++ // Reads and writes beneath the directory succeed.+ let mut plain_file =+ openat_beneath(fd, plain, libc::O_RDWR, 0).expect("in-range open must succeed");+ plain_file.write_all(b"!").unwrap();+ // The single byte replaces the first character: the write landed on the+ // host file beneath the directory.+ assert_eq!(fs::read(dir.0.join("plain")).unwrap(), b"!nside");+ // Internal symlink targets still resolve while they stay beneath.+ let mut within_file =+ openat_beneath(fd, within, libc::O_RDONLY, 0).expect("internal symlink must resolve");+ let mut buf = String::new();+ within_file.read_to_string(&mut buf).unwrap();+ assert_eq!(buf, "!nside");+ // Parent traversal and escape symlinks are rejected outright.+ error(openat_beneath(fd, parent, libc::O_PATH, 0), libc::EXDEV);+ error(openat_beneath(fd, escape, libc::O_RDONLY, 0), libc::EXDEV);+}++#[test]+fn from_dir_fd_validates_type_and_defers_permissions_to_operations() {+ use std::os::unix::fs::PermissionsExt;++ if !in_unprivileged_child() {+ return;+ }+ let dir = Directory::new();+ let regular = File::create(dir.0.join("regular")).unwrap();+ error(PassthroughFs::from_dir_fd(regular), libc::ENOTDIR);++ let delivered = File::open(&dir.0).unwrap();+ let fs = PassthroughFs::from_dir_fd(delivered).unwrap();+ let entry = fs.lookup(ctx(), 1, c"regular").unwrap();+ assert!(entry.attr.st_mode & libc::S_IFMT == libc::S_IFREG);++ // O_PATH pins the directory without granting traversal rights.+ fs::set_permissions(&dir.0, fs::Permissions::from_mode(0o000)).unwrap();+ let path = CString::new(dir.0.as_os_str().as_bytes()).unwrap();+ // SAFETY: a plain O_PATH open of a NUL-terminated path we own.+ let fd = unsafe { libc::open(path.as_ptr(), libc::O_PATH) };+ assert!(fd >= 0);+ // SAFETY: open returned a fresh owned descriptor.+ let unreadable = unsafe { File::from_raw_fd(fd) };+ let backend = PassthroughFs::from_dir_fd(unreadable).unwrap();+ let denied = backend.lookup(ctx(), 1, c"regular");+ fs::set_permissions(&dir.0, fs::Permissions::from_mode(0o700)).unwrap();+ error(denied, libc::EACCES);+}