Skip to main content

hyprstream_vfs_server/
filesystem.rs

1//! `Namespace → FileSystem` **down-adapter** (native only).
2//!
3//! This is the inverse of FS-C's [`FuseFileSystemMount`](hyprstream_vfs::FuseFileSystemMount)
4//! up-adapter. Where the up-adapter exposes a `fuse_backend_rs` `FileSystem`
5//! (RAFS / OverlayFs / Passthrough) *as* a VFS [`Mount`], this adapter exposes a
6//! whole VFS [`Namespace`] *as* a `fuse_backend_rs`
7//! [`FileSystem`](fuse_backend_rs::api::filesystem::FileSystem) — so the
8//! namespace can be served over vhost-user-fs to a Cloud Hypervisor guest (see
9//! [`crate::server`]).
10//!
11//! ## Path model
12//!
13//! `FileSystem` is inode/handle addressed; the VFS is path addressed. The
14//! [`InodeTable`](crate::inode::InodeTable) owns the translation: inode `1`
15//! (`FUSE_ROOT_ID`) is the namespace root, every other inode is interned lazily
16//! on `lookup`/`create`/`mkdir` and reference counted so `forget` reclaims it.
17//! [`HandleTable`](crate::inode::HandleTable) holds the VFS [`Fid`] for each open
18//! file/dir.
19//!
20//! ## Routing
21//!
22//! A path resolves through [`Namespace::resolve_targets`] to the ordered mount
23//! targets (bind order) plus the components relative to the mount root. Read
24//! ops (`open`/`read`/`opendir`/`readdir`) drive the base [`Mount`] surface,
25//! trying each target in bind order until one succeeds — the same union /
26//! fallthrough policy the namespace's own `cat`/`ls` helpers use. Mutating ops
27//! (`create`/`unlink`/`mkdir`/`rmdir`/`rename`/`setattr`/`symlink`/`link`)
28//! require the writable [`FsMount`] capability, reached via
29//! [`Mount::as_fsmount`]; a target that is a plain `Mount` (synthetic, ctl,
30//! stream mounts) is **read-only** and such ops return `EROFS` — fail-closed,
31//! never a silent no-op. Paths the namespace spans only implicitly (intermediate
32//! directories, e.g. `/srv` when only `/srv/model` is mounted) are served as
33//! synthetic read-only directories.
34//!
35//! ## Subject threading
36//!
37//! Every VFS call carries the verified [`Subject`] the server was constructed
38//! with — the uniform Subject-per-call policy/audit boundary (#353/#319/#328)
39//! extended across the guest filesystem. The FUSE [`Context`] (host uid/gid) is
40//! *not* the identity; the `Subject` is.
41//!
42//! ## async → sync bridge
43//!
44//! `FileSystem` is synchronous; the VFS `Mount`/`FsMount` ops are `async`. We
45//! bridge with a tokio runtime [`Handle`], running each op on it via
46//! [`Handle::block_on`]. The server's vring threads are plain OS threads (not
47//! tokio workers), so blocking on a multi-thread runtime handle is safe and does
48//! not stall the async executor.
49//!
50//! ## Send + Sync
51//!
52//! Genuinely `Send + Sync`: all state is `Arc`/`Mutex`-guarded and the wrapped
53//! `Namespace` is `Send + Sync`. No wasm `unsafe impl Send` — the crate is
54//! native-only.
55
56use std::ffi::CStr;
57use std::io;
58use std::time::Duration;
59
60use fuse_backend_rs::abi::fuse_abi::CreateIn;
61use fuse_backend_rs::api::filesystem::{
62    Context, DirEntry as FuseDirEntry, Entry, FileSystem, FsOptions, GetxattrReply, ListxattrReply,
63    OpenOptions, SetattrValid, ZeroCopyReader, ZeroCopyWriter,
64};
65use tokio::runtime::Handle;
66
67use hyprstream_vfs::{
68    DirEntry, FsMount, MountError, MountTarget, Namespace, SetAttr, Subject, ORDWR, OWRITE,
69};
70
71use crate::inode::{HandleTable, InodeData, InodeTable, Kind, OpenFid, ROOT_INODE};
72
73/// Attribute / entry validity timeout handed to the guest kernel.
74const TTL: Duration = Duration::from_secs(1);
75/// Block size reported in `stat`.
76const BLOCK_SIZE: u32 = 512;
77
78/// Map a [`MountError`] to the `errno` the guest kernel expects.
79fn errno(err: &MountError) -> i32 {
80    match err {
81        MountError::NotFound(_) => libc::ENOENT,
82        MountError::PermissionDenied(_) => libc::EACCES,
83        MountError::NotDirectory(_) => libc::ENOTDIR,
84        MountError::IsDirectory(_) => libc::EISDIR,
85        MountError::InvalidArgument(_) => libc::EINVAL,
86        MountError::NotSupported(_) => libc::ENOSYS,
87        MountError::AlreadyExists(_) => libc::EEXIST,
88        MountError::Io(_) => libc::EIO,
89    }
90}
91
92fn io_err(err: &MountError) -> io::Error {
93    io::Error::from_raw_os_error(errno(err))
94}
95
96fn einval() -> io::Error {
97    io::Error::from_raw_os_error(libc::EINVAL)
98}
99
100fn erofs() -> io::Error {
101    io::Error::from_raw_os_error(libc::EROFS)
102}
103
104/// The down-adapter: a `fuse_backend_rs` [`FileSystem`] over a VFS [`Namespace`].
105pub struct VfsFileSystem {
106    ns: Namespace,
107    subject: Subject,
108    inodes: InodeTable,
109    handles: HandleTable,
110    rt: Handle,
111}
112
113impl VfsFileSystem {
114    /// Wrap `ns`, serving every op as `subject`, bridging async ops onto `rt`.
115    pub fn new(ns: Namespace, subject: Subject, rt: Handle) -> Self {
116        Self {
117            ns,
118            subject,
119            inodes: InodeTable::new(),
120            handles: HandleTable::new(),
121            rt,
122        }
123    }
124
125    /// Borrow the wrapped namespace (e.g. for FS-D to inspect mounts).
126    pub fn namespace(&self) -> &Namespace {
127        &self.ns
128    }
129
130    /// Run an async VFS future to completion on the adapter's runtime.
131    fn block<F: std::future::Future>(&self, fut: F) -> F::Output {
132        self.rt.block_on(fut)
133    }
134
135    /// The `/`-joined absolute path for an inode (for routing through the
136    /// namespace, which is string-prefix addressed at its public surface).
137    fn abs_path(components: &[String]) -> String {
138        if components.is_empty() {
139            "/".to_owned()
140        } else {
141            format!("/{}", components.join("/"))
142        }
143    }
144
145    /// Resolve `inode` → its [`InodeData`], or `ENOENT`.
146    fn inode_data(&self, inode: u64) -> io::Result<InodeData> {
147        self.inodes
148            .get(inode)
149            .ok_or_else(|| io::Error::from_raw_os_error(libc::ENOENT))
150    }
151
152    /// Resolve the child path components of `parent` + `name`.
153    fn child_components(&self, parent: u64, name: &CStr) -> io::Result<Vec<String>> {
154        let parent = self.inode_data(parent)?;
155        let name = name.to_str().map_err(|_| einval())?;
156        if name.is_empty() || name == "." || name.contains('/') {
157            return Err(einval());
158        }
159        let mut comps = parent.components.clone();
160        comps.push(name.to_owned());
161        Ok(comps)
162    }
163
164    /// Route a path to its mount targets (bind order) + mount-relative
165    /// components. Maps a namespace miss to `ENOENT`.
166    ///
167    /// The FUSE/vhost-user session loop is sync (fuse-backend-rs `Filesystem`
168    /// callbacks) and has no async frame per operation, so it cannot run the
169    /// revocation revalidation an armed PEP requires. This plane therefore
170    /// serves only dormant (PEP-less) namespaces; [`Namespace::resolve_targets_dormant`]
171    /// fails closed if an armed namespace is ever wired here.
172    fn route(&self, components: &[String]) -> io::Result<(Vec<MountTarget>, Vec<String>)> {
173        let path = Self::abs_path(components);
174        self.ns
175            .resolve_targets_dormant(&path, &self.subject)
176            .map_err(|_| io::Error::from_raw_os_error(libc::ENOENT))
177    }
178
179    /// Stat a path through the namespace, trying each target in bind order.
180    /// Returns the VFS [`hyprstream_vfs::Stat`] plus whether it is a directory.
181    fn stat_path(&self, components: &[String]) -> io::Result<(hyprstream_vfs::Stat, bool)> {
182        // Intermediate (implicitly-spanned) directories: no backing mount, but
183        // the namespace knows they exist as ancestors of real mounts.
184        let path = Self::abs_path(components);
185        if self.ns.intermediate_children(&path).is_some() {
186            return Ok((
187                hyprstream_vfs::Stat {
188                    qtype: 0x80,
189                    version: 0,
190                    path: 0,
191                    size: 0,
192                    name: components.last().cloned().unwrap_or_default(),
193                    mtime: 0,
194                },
195                true,
196            ));
197        }
198
199        let (targets, comps) = self.route(components)?;
200        // A path that resolves to a mount root (no components left after the
201        // prefix) is the mount point itself — always a directory. Don't require
202        // the backing mount to stat its own root.
203        if comps.is_empty() {
204            return Ok((
205                hyprstream_vfs::Stat {
206                    qtype: 0x80,
207                    version: 0,
208                    path: 0,
209                    size: 0,
210                    name: components.last().cloned().unwrap_or_default(),
211                    mtime: 0,
212                },
213                true,
214            ));
215        }
216        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
217        let mut last = MountError::NotFound(path.clone());
218        for mount in &targets {
219            let res = self.block(async {
220                let fid = mount.walk(&comp_refs, &self.subject).await?;
221                let st = mount.stat(&fid, &self.subject).await;
222                mount.clunk(fid, &self.subject).await;
223                st
224            });
225            match res {
226                Ok(st) => {
227                    let is_dir = st.qtype & 0x80 != 0;
228                    return Ok((st, is_dir));
229                }
230                Err(e) => last = e,
231            }
232        }
233        Err(io_err(&last))
234    }
235
236    /// Synthesise a `libc::stat64` for an inode from a VFS stat + kind.
237    fn fill_attr(inode: u64, st: &hyprstream_vfs::Stat, kind: Kind) -> libc::stat64 {
238        // SAFETY: `stat64` is plain old data; zeroing is a valid initial value.
239        let mut attr: libc::stat64 = unsafe { std::mem::zeroed() };
240        attr.st_ino = inode;
241        attr.st_size = st.size as i64;
242        // st_blksize is libc::blksize_t: i64 on x86_64 but i32 on aarch64 —
243        // cast to the field's own type so this compiles on both arches.
244        attr.st_blksize = BLOCK_SIZE as libc::blksize_t;
245        attr.st_blocks = st.size.div_ceil(BLOCK_SIZE as u64) as i64;
246        attr.st_nlink = 1;
247        let (typ, perm) = match kind {
248            Kind::Dir => (libc::S_IFDIR, 0o755),
249            Kind::File => (libc::S_IFREG, 0o644),
250            Kind::Symlink => (libc::S_IFLNK, 0o777),
251        };
252        attr.st_mode = typ | perm;
253        attr.st_mtime = st.mtime as i64;
254        attr.st_ctime = st.mtime as i64;
255        attr.st_atime = st.mtime as i64;
256        attr
257    }
258
259    /// Build a FUSE [`Entry`] for `inode`/`kind`/`stat`.
260    fn make_entry(&self, inode: u64, kind: Kind, st: &hyprstream_vfs::Stat) -> Entry {
261        Entry {
262            inode,
263            generation: 0,
264            attr: Self::fill_attr(inode, st, kind),
265            attr_flags: 0,
266            attr_timeout: TTL,
267            entry_timeout: TTL,
268        }
269    }
270
271    /// Resolve the writable [`FsMount`] for a path, or `EROFS` if no target at
272    /// the path is a full filesystem. Returns the mount plus mount-relative
273    /// components. (Mutations don't union: the first FsMount target wins.)
274    fn route_writable(&self, components: &[String]) -> io::Result<(MountTarget, Vec<String>)> {
275        let (targets, comps) = self.route(components)?;
276        for mount in targets {
277            if mount.as_fsmount().is_some() {
278                return Ok((mount, comps));
279            }
280        }
281        Err(erofs())
282    }
283}
284
285impl FileSystem for VfsFileSystem {
286    type Inode = u64;
287    type Handle = u64;
288
289    fn init(&self, _capable: FsOptions) -> io::Result<FsOptions> {
290        // We negotiate no special capabilities; the default option set is fine.
291        Ok(FsOptions::empty())
292    }
293
294    fn lookup(&self, _ctx: &Context, parent: Self::Inode, name: &CStr) -> io::Result<Entry> {
295        let components = self.child_components(parent, name)?;
296        let (st, is_dir) = self.stat_path(&components)?;
297        let kind = if is_dir { Kind::Dir } else { Kind::File };
298        let inode = self.inodes.intern(components, kind);
299        Ok(self.make_entry(inode, kind, &st))
300    }
301
302    fn forget(&self, _ctx: &Context, inode: Self::Inode, count: u64) {
303        self.inodes.forget(inode, count);
304    }
305
306    fn batch_forget(&self, _ctx: &Context, requests: Vec<(Self::Inode, u64)>) {
307        for (inode, count) in requests {
308            self.inodes.forget(inode, count);
309        }
310    }
311
312    fn getattr(
313        &self,
314        _ctx: &Context,
315        inode: Self::Inode,
316        _handle: Option<Self::Handle>,
317    ) -> io::Result<(libc::stat64, Duration)> {
318        let data = self.inode_data(inode)?;
319        if inode == ROOT_INODE {
320            let st = hyprstream_vfs::Stat {
321                qtype: 0x80,
322                version: 0,
323                path: 0,
324                size: 0,
325                name: String::new(),
326                mtime: 0,
327            };
328            return Ok((Self::fill_attr(inode, &st, Kind::Dir), TTL));
329        }
330        let (st, is_dir) = self.stat_path(&data.components)?;
331        let kind = if is_dir { Kind::Dir } else { data.kind };
332        Ok((Self::fill_attr(inode, &st, kind), TTL))
333    }
334
335    fn opendir(
336        &self,
337        _ctx: &Context,
338        inode: Self::Inode,
339        _flags: u32,
340    ) -> io::Result<(Option<Self::Handle>, OpenOptions)> {
341        let data = self.inode_data(inode)?;
342        // Root and intermediate directories have no backing mount fid; serve them
343        // synthetically (handle 0 ⇒ no stored fid).
344        let path = Self::abs_path(&data.components);
345        if inode == ROOT_INODE || self.ns.intermediate_children(&path).is_some() {
346            return Ok((Some(0), OpenOptions::empty()));
347        }
348        let (targets, comps) = self.route(&data.components)?;
349        // Mount-root directories are served synthetically (readdir merges via the
350        // namespace `ls`, which unions all targets); no backing dir fid needed.
351        if comps.is_empty() {
352            return Ok((Some(0), OpenOptions::empty()));
353        }
354        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
355        let mut last = MountError::NotFound(path);
356        for mount in &targets {
357            let res = self.block(async {
358                let mut fid = mount.walk(&comp_refs, &self.subject).await?;
359                mount.open(&mut fid, 0, &self.subject).await?;
360                Ok::<_, MountError>(fid)
361            });
362            match res {
363                Ok(fid) => {
364                    let handle = self.handles.insert(OpenFid {
365                        mount: mount.clone(),
366                        fid,
367                    });
368                    return Ok((Some(handle), OpenOptions::empty()));
369                }
370                Err(e) => last = e,
371            }
372        }
373        Err(io_err(&last))
374    }
375
376    fn readdir(
377        &self,
378        _ctx: &Context,
379        inode: Self::Inode,
380        _handle: Self::Handle,
381        _size: u32,
382        offset: u64,
383        add_entry: &mut dyn FnMut(FuseDirEntry) -> io::Result<usize>,
384    ) -> io::Result<()> {
385        let data = self.inode_data(inode)?;
386        let path = Self::abs_path(&data.components);
387        // Merge real mount entries with any synthetic (intermediate) children,
388        // matching the namespace's own union-readdir semantics.
389        let entries: Vec<DirEntry> = self
390            .block(self.ns.ls(&path, &self.subject))
391            .map_err(|_| io::Error::from_raw_os_error(libc::ENOENT))?;
392
393        // `.`/`..` first, then entries, honouring the offset cursor.
394        let mut all: Vec<(String, bool, u64)> = vec![
395            (".".to_owned(), true, inode),
396            ("..".to_owned(), true, ROOT_INODE),
397        ];
398        for e in entries {
399            // Intern child inodes so a subsequent lookup is stable.
400            let mut comps = data.components.clone();
401            comps.push(e.name.clone());
402            let kind = if e.is_dir { Kind::Dir } else { Kind::File };
403            let child = self.inodes.intern(comps, kind);
404            all.push((e.name, e.is_dir, child));
405        }
406
407        for (idx, (name, is_dir, ino)) in all.into_iter().enumerate().skip(offset as usize) {
408            let typ = if is_dir { libc::DT_DIR } else { libc::DT_REG } as u32;
409            let written = add_entry(FuseDirEntry {
410                ino,
411                offset: idx as u64 + 1,
412                type_: typ,
413                name: name.as_bytes(),
414            })?;
415            if written == 0 {
416                break;
417            }
418        }
419        Ok(())
420    }
421
422    fn releasedir(
423        &self,
424        _ctx: &Context,
425        _inode: Self::Inode,
426        _flags: u32,
427        handle: Self::Handle,
428    ) -> io::Result<()> {
429        if handle != 0 {
430            if let Some(open) = self.handles.remove(handle) {
431                self.block(open.mount.clunk(open.fid, &self.subject));
432            }
433        }
434        Ok(())
435    }
436
437    fn open(
438        &self,
439        _ctx: &Context,
440        inode: Self::Inode,
441        flags: u32,
442        _fuse_flags: u32,
443    ) -> io::Result<(Option<Self::Handle>, OpenOptions, Option<u32>)> {
444        let data = self.inode_data(inode)?;
445        let mode = match flags & libc::O_ACCMODE as u32 {
446            x if x == libc::O_WRONLY as u32 => OWRITE,
447            x if x == libc::O_RDWR as u32 => ORDWR,
448            _ => 0, // OREAD
449        };
450        let (targets, comps) = self.route(&data.components)?;
451        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
452        let mut last = MountError::NotFound(Self::abs_path(&data.components));
453        for mount in &targets {
454            // A write open against a read-only (non-FsMount) target fails closed.
455            if mode != 0 && mount.as_fsmount().is_none() {
456                last = MountError::PermissionDenied("read-only mount".into());
457                continue;
458            }
459            let res = self.block(async {
460                let mut fid = mount.walk(&comp_refs, &self.subject).await?;
461                mount.open(&mut fid, mode, &self.subject).await?;
462                Ok::<_, MountError>(fid)
463            });
464            match res {
465                Ok(fid) => {
466                    let handle = self.handles.insert(OpenFid {
467                        mount: mount.clone(),
468                        fid,
469                    });
470                    return Ok((Some(handle), OpenOptions::empty(), None));
471                }
472                Err(e) => last = e,
473            }
474        }
475        if mode != 0 {
476            Err(erofs())
477        } else {
478            Err(io_err(&last))
479        }
480    }
481
482    fn read(
483        &self,
484        _ctx: &Context,
485        _inode: Self::Inode,
486        handle: Self::Handle,
487        w: &mut dyn ZeroCopyWriter,
488        size: u32,
489        offset: u64,
490        _lock_owner: Option<u64>,
491        _flags: u32,
492    ) -> io::Result<usize> {
493        // Take the open fid out for the await, then return it.
494        let open = self.handles.take(handle).ok_or_else(einval)?;
495        let res = self.block(open.mount.read(&open.fid, offset, size, &self.subject));
496        self.handles.put(handle, open);
497        let data = res.map_err(|e| io_err(&e))?;
498        w.write_all(&data)?;
499        Ok(data.len())
500    }
501
502    fn write(
503        &self,
504        _ctx: &Context,
505        _inode: Self::Inode,
506        handle: Self::Handle,
507        r: &mut dyn ZeroCopyReader,
508        size: u32,
509        offset: u64,
510        _lock_owner: Option<u64>,
511        _delayed_write: bool,
512        _flags: u32,
513        _fuse_flags: u32,
514    ) -> io::Result<usize> {
515        // Stage the incoming bytes into a heap buffer (the VFS write API is
516        // buffer-based), then forward to the mount.
517        let mut buf = vec![0u8; size as usize];
518        let mut filled = 0;
519        while filled < buf.len() {
520            let n = r.read(&mut buf[filled..])?;
521            if n == 0 {
522                break;
523            }
524            filled += n;
525        }
526        buf.truncate(filled);
527
528        let open = self.handles.take(handle).ok_or_else(einval)?;
529        let res = self.block(open.mount.write(&open.fid, offset, &buf, &self.subject));
530        self.handles.put(handle, open);
531        let n = res.map_err(|e| io_err(&e))?;
532        Ok(n as usize)
533    }
534
535    fn release(
536        &self,
537        _ctx: &Context,
538        _inode: Self::Inode,
539        _flags: u32,
540        handle: Self::Handle,
541        _flush: bool,
542        _flock_release: bool,
543        _lock_owner: Option<u64>,
544    ) -> io::Result<()> {
545        if let Some(open) = self.handles.remove(handle) {
546            self.block(open.mount.clunk(open.fid, &self.subject));
547        }
548        Ok(())
549    }
550
551    fn create(
552        &self,
553        _ctx: &Context,
554        parent: Self::Inode,
555        name: &CStr,
556        args: CreateIn,
557    ) -> io::Result<(Entry, Option<Self::Handle>, OpenOptions, Option<u32>)> {
558        let components = self.child_components(parent, name)?;
559        let (mount, comps) = self.route_writable(&components)?;
560        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
561        let mode = args.mode & 0o7777;
562        // Create, then re-open for writing on the same mount.
563        let fid = self.block(async {
564            let fs = mount.as_fsmount().ok_or(erofs())?;
565            FsMount::create(fs, &comp_refs, mode, &self.subject)
566                .await
567                .map_err(|e| io_err(&e))?;
568            let mut fid = mount
569                .walk(&comp_refs, &self.subject)
570                .await
571                .map_err(|e| io_err(&e))?;
572            mount
573                .open(&mut fid, OWRITE, &self.subject)
574                .await
575                .map_err(|e| io_err(&e))?;
576            Ok::<_, io::Error>(fid)
577        })?;
578        let (st, _) = self.stat_path(&components)?;
579        let inode = self.inodes.intern(components, Kind::File);
580        let entry = self.make_entry(inode, Kind::File, &st);
581        let handle = self.handles.insert(OpenFid { mount, fid });
582        Ok((entry, Some(handle), OpenOptions::empty(), None))
583    }
584
585    fn unlink(&self, _ctx: &Context, parent: Self::Inode, name: &CStr) -> io::Result<()> {
586        let components = self.child_components(parent, name)?;
587        let (mount, comps) = self.route_writable(&components)?;
588        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
589        let r = self.block(async {
590            mount
591                .as_fsmount()
592                .ok_or(erofs())?
593                .unlink(&comp_refs, &self.subject)
594                .await
595                .map_err(|e| io_err(&e))
596        });
597        if r.is_ok() {
598            self.inodes.invalidate_path(&components);
599        }
600        r
601    }
602
603    fn mkdir(
604        &self,
605        _ctx: &Context,
606        parent: Self::Inode,
607        name: &CStr,
608        mode: u32,
609        _umask: u32,
610    ) -> io::Result<Entry> {
611        let components = self.child_components(parent, name)?;
612        let (mount, comps) = self.route_writable(&components)?;
613        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
614        self.block(async {
615            mount
616                .as_fsmount()
617                .ok_or(erofs())?
618                .mkdir(&comp_refs, mode & 0o7777, &self.subject)
619                .await
620                .map_err(|e| io_err(&e))
621        })?;
622        let (st, _) = self.stat_path(&components)?;
623        let inode = self.inodes.intern(components, Kind::Dir);
624        Ok(self.make_entry(inode, Kind::Dir, &st))
625    }
626
627    fn rmdir(&self, _ctx: &Context, parent: Self::Inode, name: &CStr) -> io::Result<()> {
628        let components = self.child_components(parent, name)?;
629        let (mount, comps) = self.route_writable(&components)?;
630        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
631        let r = self.block(async {
632            mount
633                .as_fsmount()
634                .ok_or(erofs())?
635                .rmdir(&comp_refs, &self.subject)
636                .await
637                .map_err(|e| io_err(&e))
638        });
639        if r.is_ok() {
640            self.inodes.invalidate_path(&components);
641        }
642        r
643    }
644
645    fn rename(
646        &self,
647        _ctx: &Context,
648        olddir: Self::Inode,
649        oldname: &CStr,
650        newdir: Self::Inode,
651        newname: &CStr,
652        _flags: u32,
653    ) -> io::Result<()> {
654        let from = self.child_components(olddir, oldname)?;
655        let to = self.child_components(newdir, newname)?;
656        // Rename across distinct mounts is not supported (no cross-mount copy);
657        // require both endpoints to resolve to the same writable mount.
658        let (from_targets, from_comps) = self.route(&from)?;
659        let (to_targets, to_comps) = self.route(&to)?;
660        let from_fs = from_targets.iter().find(|m| m.as_fsmount().is_some());
661        let to_fs = to_targets.iter().find(|m| m.as_fsmount().is_some());
662        let (Some(from_fs), Some(to_fs)) = (from_fs, to_fs) else {
663            return Err(erofs());
664        };
665        if !std::sync::Arc::ptr_eq(from_fs, to_fs) {
666            return Err(io::Error::from_raw_os_error(libc::EXDEV));
667        }
668        let from_refs: Vec<&str> = from_comps.iter().map(String::as_str).collect();
669        let to_refs: Vec<&str> = to_comps.iter().map(String::as_str).collect();
670        let res = self.block(async {
671            let fs = from_fs.as_fsmount().ok_or(erofs())?;
672            fs.rename(&from_refs, &to_refs, &self.subject)
673                .await
674                .map_err(|e| io_err(&e))
675        });
676        if res.is_ok() {
677            self.inodes.invalidate_path(&from);
678            self.inodes.invalidate_path(&to);
679        }
680        res
681    }
682
683    fn setattr(
684        &self,
685        _ctx: &Context,
686        inode: Self::Inode,
687        attr: libc::stat64,
688        _handle: Option<Self::Handle>,
689        valid: SetattrValid,
690    ) -> io::Result<(libc::stat64, Duration)> {
691        let data = self.inode_data(inode)?;
692        let set = SetAttr {
693            mode: valid
694                .contains(SetattrValid::MODE)
695                .then_some(attr.st_mode & 0o7777),
696            uid: valid.contains(SetattrValid::UID).then_some(attr.st_uid),
697            gid: valid.contains(SetattrValid::GID).then_some(attr.st_gid),
698            size: valid
699                .contains(SetattrValid::SIZE)
700                .then_some(attr.st_size as u64),
701            atime: valid
702                .contains(SetattrValid::ATIME)
703                .then_some(attr.st_atime as u64),
704            mtime: valid
705                .contains(SetattrValid::MTIME)
706                .then_some(attr.st_mtime as u64),
707        };
708        let (mount, comps) = self.route_writable(&data.components)?;
709        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
710        self.block(async {
711            mount
712                .as_fsmount()
713                .ok_or(erofs())?
714                .setattr(&comp_refs, &set, &self.subject)
715                .await
716                .map_err(|e| io_err(&e))
717        })?;
718        let (st, is_dir) = self.stat_path(&data.components)?;
719        let kind = if is_dir { Kind::Dir } else { data.kind };
720        Ok((Self::fill_attr(inode, &st, kind), TTL))
721    }
722
723    fn symlink(
724        &self,
725        _ctx: &Context,
726        linkname: &CStr,
727        parent: Self::Inode,
728        name: &CStr,
729    ) -> io::Result<Entry> {
730        let components = self.child_components(parent, name)?;
731        let target = linkname.to_str().map_err(|_| einval())?.to_owned();
732        let (mount, comps) = self.route_writable(&components)?;
733        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
734        self.block(async {
735            mount
736                .as_fsmount()
737                .ok_or(erofs())?
738                .symlink(&comp_refs, &target, &self.subject)
739                .await
740                .map_err(|e| io_err(&e))
741        })?;
742        let (st, _) = self.stat_path(&components)?;
743        let inode = self.inodes.intern(components, Kind::Symlink);
744        Ok(self.make_entry(inode, Kind::Symlink, &st))
745    }
746
747    fn readlink(&self, _ctx: &Context, inode: Self::Inode) -> io::Result<Vec<u8>> {
748        let data = self.inode_data(inode)?;
749        let (mount, comps) = self.route_writable(&data.components)?;
750        let comp_refs: Vec<&str> = comps.iter().map(String::as_str).collect();
751        let target = self.block(async {
752            mount
753                .as_fsmount()
754                .ok_or(erofs())?
755                .readlink(&comp_refs, &self.subject)
756                .await
757                .map_err(|e| io_err(&e))
758        })?;
759        Ok(target.into_bytes())
760    }
761
762    fn link(
763        &self,
764        _ctx: &Context,
765        inode: Self::Inode,
766        newparent: Self::Inode,
767        newname: &CStr,
768    ) -> io::Result<Entry> {
769        let existing = self.inode_data(inode)?.components;
770        let new_path = self.child_components(newparent, newname)?;
771        // Hard links must stay within one writable mount.
772        let (ex_targets, ex_comps) = self.route(&existing)?;
773        let (new_targets, new_comps) = self.route(&new_path)?;
774        let ex_fs = ex_targets.iter().find(|m| m.as_fsmount().is_some());
775        let new_fs = new_targets.iter().find(|m| m.as_fsmount().is_some());
776        let (Some(ex_fs), Some(new_fs)) = (ex_fs, new_fs) else {
777            return Err(erofs());
778        };
779        if !std::sync::Arc::ptr_eq(ex_fs, new_fs) {
780            return Err(io::Error::from_raw_os_error(libc::EXDEV));
781        }
782        let ex_refs: Vec<&str> = ex_comps.iter().map(String::as_str).collect();
783        let new_refs: Vec<&str> = new_comps.iter().map(String::as_str).collect();
784        self.block(async {
785            let fs = ex_fs.as_fsmount().ok_or(erofs())?;
786            fs.link(&ex_refs, &new_refs, &self.subject)
787                .await
788                .map_err(|e| io_err(&e))
789        })?;
790        let (st, _) = self.stat_path(&new_path)?;
791        let new_inode = self.inodes.intern(new_path, Kind::File);
792        Ok(self.make_entry(new_inode, Kind::File, &st))
793    }
794
795    fn access(&self, _ctx: &Context, _inode: Self::Inode, _mask: u32) -> io::Result<()> {
796        // Access control is enforced at the Subject/policy boundary, not via the
797        // guest's POSIX mode bits; grant and let the mount op fail-close.
798        Ok(())
799    }
800
801    fn getxattr(
802        &self,
803        _ctx: &Context,
804        _inode: Self::Inode,
805        _name: &CStr,
806        _size: u32,
807    ) -> io::Result<GetxattrReply> {
808        Err(io::Error::from_raw_os_error(libc::ENODATA))
809    }
810
811    fn listxattr(
812        &self,
813        _ctx: &Context,
814        _inode: Self::Inode,
815        _size: u32,
816    ) -> io::Result<ListxattrReply> {
817        Ok(ListxattrReply::Names(Vec::new()))
818    }
819}