Skip to main content

hyprstream_vfs_server/
inode.rs

1//! Inode and handle tables for the `Namespace → FileSystem` down-adapter.
2//!
3//! `fuse_backend_rs::FileSystem` is inode/handle addressed: the guest kernel
4//! refers to files by an opaque `u64` inode (returned from `lookup`) and to open
5//! files/dirs by an opaque `u64` handle (returned from `open`/`opendir`). The
6//! VFS [`Namespace`](hyprstream_vfs::Namespace), by contrast, is **path
7//! addressed** — every op takes a component slice rooted at `/`. The two tables
8//! here own that translation:
9//!
10//! - [`InodeTable`] maps each live inode to its absolute VFS path (the component
11//!   vector) plus a kind (file / dir / symlink). The FUSE root (`FUSE_ROOT_ID`,
12//!   `1`) is the namespace root `/`. Inodes are allocated lazily on `lookup` and
13//!   reference-counted so `forget` can reclaim them (matching the kernel's
14//!   lookup-count contract).
15//! - [`HandleTable`] maps each open handle to the VFS [`Fid`] obtained from
16//!   `Mount::walk` + `Mount::open`, so subsequent `read`/`write`/`readdir`/
17//!   `release` can reach the same open object.
18//!
19//! Both tables are plain `Mutex`-guarded maps — genuinely `Send + Sync`, no wasm
20//! `unsafe impl`. The whole crate is native-only.
21
22use std::collections::HashMap;
23
24use parking_lot::Mutex;
25
26/// The FUSE root inode (`FUSE_ROOT_ID`). Maps to the namespace root `/`.
27pub const ROOT_INODE: u64 = 1;
28
29/// The kind of object an inode refers to. Drives the `st_mode` we synthesise and
30/// whether an open goes through the dir or file path.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum Kind {
33    Dir,
34    File,
35    Symlink,
36}
37
38/// An inode's identity within the namespace: its absolute path components and
39/// kind. The path is stored as owned components (never a `/`-joined string) so
40/// it can be handed straight to the VFS `walk`/`FsMount` ops as a `&[&str]`.
41#[derive(Clone, Debug)]
42pub struct InodeData {
43    pub components: Vec<String>,
44    pub kind: Kind,
45    /// Lookup reference count (the kernel's `nlookup`). When it hits zero on
46    /// `forget`, the entry is evictable.
47    pub refcount: u64,
48}
49
50/// Inode allocation + path translation table.
51pub struct InodeTable {
52    /// inode → data.
53    by_inode: Mutex<HashMap<u64, InodeData>>,
54    /// `/`-joined path → inode, so repeated `lookup`s of the same path reuse the
55    /// inode (the kernel relies on a stable inode per path while referenced).
56    by_path: Mutex<HashMap<String, u64>>,
57    /// Next inode to hand out (root is 1, so we start at 2).
58    next: Mutex<u64>,
59}
60
61impl InodeTable {
62    /// Create a table pre-populated with the root inode mapped to `/`.
63    pub fn new() -> Self {
64        let mut by_inode = HashMap::new();
65        by_inode.insert(
66            ROOT_INODE,
67            InodeData {
68                components: Vec::new(),
69                kind: Kind::Dir,
70                // The root is never forgotten.
71                refcount: u64::MAX,
72            },
73        );
74        let mut by_path = HashMap::new();
75        by_path.insert(String::new(), ROOT_INODE);
76        Self {
77            by_inode: Mutex::new(by_inode),
78            by_path: Mutex::new(by_path),
79            next: Mutex::new(ROOT_INODE + 1),
80        }
81    }
82
83    fn key(components: &[String]) -> String {
84        components.join("/")
85    }
86
87    /// Look up the data for an inode (a clone, to avoid holding the lock).
88    pub fn get(&self, inode: u64) -> Option<InodeData> {
89        self.by_inode.lock().get(&inode).cloned()
90    }
91
92    /// Get-or-allocate an inode for `components`/`kind`, bumping its lookup
93    /// refcount. Returns the inode number. Used by `lookup`/`create`/`mkdir`.
94    pub fn intern(&self, components: Vec<String>, kind: Kind) -> u64 {
95        let key = Self::key(&components);
96        let mut by_path = self.by_path.lock();
97        let mut by_inode = self.by_inode.lock();
98        if let Some(&inode) = by_path.get(&key) {
99            if let Some(data) = by_inode.get_mut(&inode) {
100                data.refcount = data.refcount.saturating_add(1);
101                // A path can change kind (e.g. recreated as a different type);
102                // keep the latest observed kind.
103                data.kind = kind;
104            }
105            return inode;
106        }
107        let inode = {
108            let mut n = self.next.lock();
109            let i = *n;
110            *n += 1;
111            i
112        };
113        by_inode.insert(
114            inode,
115            InodeData {
116                components,
117                kind,
118                refcount: 1,
119            },
120        );
121        by_path.insert(key, inode);
122        inode
123    }
124
125    /// Drop `count` lookup references from `inode`; evict when the count reaches
126    /// zero (mirrors the FUSE `forget` contract). The root is never evicted.
127    pub fn forget(&self, inode: u64, count: u64) {
128        if inode == ROOT_INODE {
129            return;
130        }
131        let mut by_inode = self.by_inode.lock();
132        let evict = if let Some(data) = by_inode.get_mut(&inode) {
133            data.refcount = data.refcount.saturating_sub(count);
134            data.refcount == 0
135        } else {
136            false
137        };
138        if evict {
139            if let Some(data) = by_inode.remove(&inode) {
140                self.by_path.lock().remove(&Self::key(&data.components));
141            }
142        }
143    }
144
145    /// Forget a path's inode entirely (used after unlink/rmdir/rename so a stale
146    /// path no longer resolves to a live inode). No-op if not present.
147    pub fn invalidate_path(&self, components: &[String]) {
148        let key = Self::key(components);
149        if let Some(inode) = self.by_path.lock().remove(&key) {
150            self.by_inode.lock().remove(&inode);
151        }
152    }
153}
154
155impl Default for InodeTable {
156    fn default() -> Self {
157        Self::new()
158    }
159}
160
161/// An open object: the VFS [`Fid`](hyprstream_vfs::Fid) plus the mount that
162/// produced it. A `Fid` is opaque to the adapter and does not record its owning
163/// mount, so we keep the `Arc<dyn Mount>` alongside it; `read`/`write`/`clunk`
164/// route back to that exact mount.
165pub struct OpenFid {
166    pub mount: hyprstream_vfs::MountTarget,
167    pub fid: hyprstream_vfs::Fid,
168}
169
170/// Open-handle table mapping `u64` handles to live [`OpenFid`]s.
171///
172/// [`hyprstream_vfs::Fid`] is `Send + Sync` but not `Clone`; we own it here for
173/// the lifetime of the open file. Because the async VFS ops borrow the fid across
174/// an await, the adapter [`take`](Self::take)s the `OpenFid` out, awaits, then
175/// [`put`](Self::put)s it back under the same handle.
176pub struct HandleTable {
177    handles: Mutex<HashMap<u64, OpenFid>>,
178    next: Mutex<u64>,
179}
180
181impl HandleTable {
182    pub fn new() -> Self {
183        Self {
184            handles: Mutex::new(HashMap::new()),
185            next: Mutex::new(1),
186        }
187    }
188
189    /// Store an open fid + its mount, returning the handle id.
190    pub fn insert(&self, open: OpenFid) -> u64 {
191        let handle = {
192            let mut n = self.next.lock();
193            let h = *n;
194            *n += 1;
195            h
196        };
197        self.handles.lock().insert(handle, open);
198        handle
199    }
200
201    /// Remove and return the open fid for `handle` (on `release`/`releasedir`).
202    pub fn remove(&self, handle: u64) -> Option<OpenFid> {
203        self.handles.lock().remove(&handle)
204    }
205
206    /// Temporarily take the open fid out so an `async` op can borrow it across an
207    /// await without holding the table lock. Pair with [`Self::put`].
208    pub fn take(&self, handle: u64) -> Option<OpenFid> {
209        self.handles.lock().remove(&handle)
210    }
211
212    /// Return an open fid taken via [`Self::take`] under the same handle id.
213    pub fn put(&self, handle: u64, open: OpenFid) {
214        self.handles.lock().insert(handle, open);
215    }
216}
217
218impl Default for HandleTable {
219    fn default() -> Self {
220        Self::new()
221    }
222}