From 2033a2e6caac866760b96a5a46a452165396f37c Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 14:18:27 +0800 Subject: [PATCH 1/2] nfs: serve real `._*` Workspace files instead of hiding them With `refuse_apple_double` (the default), LOOKUP answered NFS3ERR_NOENT for every `._` name before asking the engine, while READDIR listed the real ones: a repository that contains `._foo` showed it in `ls` and then failed to open it (review finding #8, V-OV-3). A `._` name the Workspace view holds is now an ordinary Workspace file: - LOOKUP of a `._` name asks the view first and answers a companion only when the view has no such name, so LOOKUP and READDIR agree; GETATTR, READ, WRITE and SETATTR then reach the engine by serial as for any file. - CREATE of a `._` name the view holds is the ordinary CREATE of that file (UNCHECKED opens it, GUARDED/EXCLUSIVE answer EXIST); no companion is made, so nothing shadows it. The attributes a macOS client then stores there go into the Workspace file, as on any NFSv3 server. - REMOVE removes it, and RENAME may replace it; RENAME onto a `._` name the view lacks stays NFS3ERR_ACCES. - Names the view does not hold keep using the export-memory companions as before; a companion whose name the view gains later is shadowed by the real file. Cost: LOOKUP, CREATE, REMOVE and RENAME of a `._` name now make one engine LOOKUP (an observe visit) to ask the view, also for companions and absent names. The job-count test in tests/write.rs asserted zero owner jobs for a companion CREATE+WRITE+SETATTR+REMOVE and an absent `._` LOOKUP; that contract is what hid real files, so its exact expectation is now two and three observe visits with zero mutate visits (still exact, not loosened). Tests: new tests/apple_double_view.rs (a base with `._foo` and `d/._bar`: listed, LOOKUP+READ, CREATE GUARDED/UNCHECKED, WRITE, RENAME onto it, REMOVE, committed; a new companion still stays in memory and out of the Commit). Docs: kernel-routes/nfs.md AppleDouble section and LOOKUP rule, kernel-routes/README.md test table. Production LOC: 206,537 -> 206,585 (delta +48) core 40,988 -> 40,988 (0) engine 95,899 -> 95,947 (+48) layerfs-nfs +48 control 59,325 -> 59,325 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 343c59b2ca and the staged tree Co-Authored-By: Claude Opus 5.5 --- .../engine/kernel-routes/README.md | 1 + docs/architecture/engine/kernel-routes/nfs.md | 25 +++- engine/crates/layerfs-nfs/src/apple_double.rs | 54 +++++++-- engine/crates/layerfs-nfs/src/change.rs | 50 ++++++-- engine/crates/layerfs-nfs/src/kernel.rs | 19 +-- engine/crates/layerfs-nfs/src/names.rs | 4 +- .../layerfs-nfs/tests/apple_double_view.rs | 112 ++++++++++++++++++ engine/crates/layerfs-nfs/tests/write.rs | 18 +-- 8 files changed, 246 insertions(+), 37 deletions(-) create mode 100644 engine/crates/layerfs-nfs/tests/apple_double_view.rs diff --git a/docs/architecture/engine/kernel-routes/README.md b/docs/architecture/engine/kernel-routes/README.md index 938fabffaf..7fdec2fa85 100644 --- a/docs/architecture/engine/kernel-routes/README.md +++ b/docs/architecture/engine/kernel-routes/README.md @@ -188,6 +188,7 @@ stable media. | [`requests.rs`](../../../../engine/crates/layerfs-fuse/tests/requests.rs) | `cargo +1.85.1 test --locked -p layerfs-fuse --test requests` | any (no kernel) | A parked request resumes on its own thread and drain waits for it; a panic keeps its future and another mount stays usable | | [`protocol.rs`](../../../../engine/crates/layerfs-nfs/tests/protocol.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test protocol` | any (no network) | XDR round trips and bounds, fragment joining and `RECORD_LIMIT`, `AUTH_UNIX` headers, handles stable per mount and stale after it | | [`write.rs`](../../../../engine/crates/layerfs-nfs/tests/write.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test write` | any (in-process loopback export, no kernel mount) | Every changing NFS procedure; tickets released only after the reply; silly renames and AppleDouble names | +| [`apple_double_view.rs`](../../../../engine/crates/layerfs-nfs/tests/apple_double_view.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test apple_double_view` | any (in-process loopback export, no kernel mount) | A `._` file the Workspace holds is listed, read, written, replaced and removed as any other file and committed; a new companion still stays in export memory | Run each under a wall timeout of at most 120 s. The nightly lane runs each kernel binary alone in a container with `--device /dev/fuse --cap-add diff --git a/docs/architecture/engine/kernel-routes/nfs.md b/docs/architecture/engine/kernel-routes/nfs.md index ca370bb37d..07fb3e14f6 100644 --- a/docs/architecture/engine/kernel-routes/nfs.md +++ b/docs/architecture/engine/kernel-routes/nfs.md @@ -154,7 +154,7 @@ drawn once per export; it makes guessing costly and does not authenticate. | Rule | Source | | --- | --- | | One owner visit answers a LOOKUP: the job that resolves a name has already read the directory's own row, so the reply's `dir_attributes` cost no second visit | [`nfs.rs`](../../../../engine/crates/layerfs-nfs/src/nfs.rs), [`kernel.rs`](../../../../engine/crates/layerfs-nfs/src/kernel.rs), [`kernel_read.rs`](../../../../engine/crates/layerfs-workspace/src/operations/kernel_read.rs) | -| A LOOKUP that fails answers the directory's own fresh facts whenever the job that failed read its row, which is every name this export looks up: a name that binds nothing still read its parent's row in the same visit. `.`, `..`, a silly name, an AppleDouble companion and a refusal decided before any visit read no directory row and send no `dir_attributes`, so the client falls back to its own `actimeo`; RFC 1813 makes both fields optional. No LOOKUP answer repeats the export's last observation of the directory, which nothing ages. A failed LOOKUP's directory row is kept as the export's observation, as a successful one's is | [`nfs.rs`](../../../../engine/crates/layerfs-nfs/src/nfs.rs), [`kernel.rs`](../../../../engine/crates/layerfs-nfs/src/kernel.rs), [`kernel_read.rs`](../../../../engine/crates/layerfs-workspace/src/operations/kernel_read.rs) | +| A LOOKUP that fails answers the directory's own fresh facts whenever the job that failed read its row, which is every name this export looks up: a name that binds nothing still read its parent's row in the same visit. `.`, `..`, a silly name, an AppleDouble companion (whose LOOKUP asks the view first, and answers the companion only after the view had no such name) and a refusal decided before any visit send no `dir_attributes`, so the client falls back to its own `actimeo`; RFC 1813 makes both fields optional. No LOOKUP answer repeats the export's last observation of the directory, which nothing ages. A failed LOOKUP's directory row is kept as the export's observation, as a successful one's is | [`nfs.rs`](../../../../engine/crates/layerfs-nfs/src/nfs.rs), [`kernel.rs`](../../../../engine/crates/layerfs-nfs/src/kernel.rs), [`kernel_read.rs`](../../../../engine/crates/layerfs-workspace/src/operations/kernel_read.rs) | | `read.rs` holds what a read answers: the entry, its directory and its descriptors, and the refusal with its status (`NFS3ERR_STALE` for an engine `Stale`, else `NFS3ERR_IO`) and the directory row the job read | [`read.rs`](../../../../engine/crates/layerfs-nfs/src/read.rs) | | An export remembers the facts it last published or observed for a directory (LOOKUP, GETATTR, OPENDIR, a publishing change) and answers from them only where no job reads that directory: an AppleDouble companion's `wcc_data`, whose change never touches it. A directory listing is not such a place: its reply says only what its own window read | [`kernel.rs`](../../../../engine/crates/layerfs-nfs/src/kernel.rs), [`apple_double.rs`](../../../../engine/crates/layerfs-nfs/src/apple_double.rs) | @@ -180,14 +180,29 @@ drawn once per export; it makes guessing costly and does not authenticate. On NFSv3 the macOS client keeps extended attributes and resource forks in `._` files (at least one byte after `._`). With `refuse_apple_double`, a -regular `._` file lives in export state only (`Companions`, serials -`SERIALS` = 2^62 and above): LOOKUP, GETATTR, ACCESS, READ, WRITE, SETATTR, -COMMIT, REMOVE and RENAME to another `._` name are served there, READDIR -never lists it and the engine is never called. Any other kind is +regular `._` file the client creates under a name the Workspace view does not +hold lives in export state only (`Companions`, serials `SERIALS` = 2^62 and +above): LOOKUP, GETATTR, ACCESS, READ, WRITE, SETATTR, COMMIT, REMOVE and +RENAME to another `._` name are served there, READDIR never lists it and no +engine mutation is made for it. Any other new kind under a `._` name is `NFS3ERR_ACCES`. `cp`, `copyfile`, `ditto` and `tar` succeed while nothing reaches the Workspace, SQLite overlay or a Commit; everything is dropped with the export. +A `._` name the view holds (a file committed under that name, or made in the +view by another route) is an ordinary Workspace file, never hidden: READDIR +lists it, and LOOKUP, GETATTR, READ, WRITE, SETATTR, REMOVE and RENAME reach +the engine as for any other name, so the two agree. To decide, LOOKUP, CREATE, +REMOVE and RENAME of a `._` name ask the view first (one engine LOOKUP, also +for a name that turns out to be a companion's or absent); only a name the view +does not hold uses the companions. + +| Case | Answer | +| --- | --- | +| CREATE of a `._` name the view holds | The ordinary CREATE of that file: UNCHECKED opens it (applying a requested size), GUARDED and EXCLUSIVE answer `NFS3ERR_EXIST`. No companion is made, so nothing shadows it; the attributes a macOS client then stores there go into the Workspace file and a Commit captures them, as on any NFSv3 server | +| RENAME onto a `._` name the view holds | An ordinary RENAME that replaces it; onto a `._` name the view lacks it stays `NFS3ERR_ACCES` | +| A companion whose name the view gains later (an install, another route) | The real file answers that name; the companion is unreachable by it and goes with the export or orphan reclamation | + | Bound | Value | Over the bound | Source | | --- | --- | --- | --- | | `HELD` | 65,536 slotted companion entries | `Companions::admits` decides the bound in one place, before anything is committed: CREATE, and a WRITE, SETATTR or RENAME that needs a new slot, first reclaim the orphan slotted companions outside the companion lock, once, and then answer the whole operation `NFS3ERR_NOSPC` with the body, its length and its name as they were (CREATE also increments `names_refused` and logs at most once per 60 s per export). A call whose commit needs I/O in between (`Companions::reserve`) holds the slot from the decision, so the bound holds when calls race for the last one | [`apple_double.rs`](../../../../engine/crates/layerfs-nfs/src/apple_double.rs) | diff --git a/engine/crates/layerfs-nfs/src/apple_double.rs b/engine/crates/layerfs-nfs/src/apple_double.rs index ae9cd22731..bb5e9dadf5 100644 --- a/engine/crates/layerfs-nfs/src/apple_double.rs +++ b/engine/crates/layerfs-nfs/src/apple_double.rs @@ -7,15 +7,25 @@ //! WRITE, SETATTR, COMMIT, REMOVE, a LINK to another AppleDouble name and a //! RENAME to another AppleDouble name //! work on it, READDIR does not list it, and no mutation of it ever reaches -//! the engine, so the Workspace stays clean and no Commit can capture it. +//! the engine (a LOOKUP of its name in the view is the one engine call), so +//! the Workspace stays clean and no Commit can capture it. //! Everything is dropped when the export is released. //! -//! The tree is not consulted for such a name: while this mode is on, a -//! LOOKUP of a `._` name answers `NFS3ERR_NOENT` unless the export holds that -//! companion, which is what a READDIR of that directory already shows by not -//! listing them, so the two agree. Such a change also never touches the -//! directory it names, so its `wcc_data` answers both halves from the last -//! facts the export saw for it (see [`Kernel::directory_wcc`]). +//! Only a name the Workspace view does not hold is a companion's: a `._` file +//! that is really in the tree (committed, or made in the view by another +//! route) is an ordinary Workspace file, which READDIR lists. So a LOOKUP of +//! a `._` name asks the view first and answers the companion only when the +//! view has no such name ([`Kernel::lookup_apple_double`]), and LOOKUP and +//! READDIR agree. CREATE, REMOVE and RENAME of a `._` name ask the view the +//! same way: CREATE of a name the view holds is the ordinary CREATE of that +//! file (UNCHECKED opens it, GUARDED and EXCLUSIVE answer `NFS3ERR_EXIST`), +//! so no companion is made to shadow it, and the attributes a macOS client +//! then stores there go into the Workspace file, as on any NFSv3 server; a +//! RENAME may replace such a file. A companion whose name the view gains +//! later (an install, another route) is shadowed by the real file and stays +//! unreachable by that name. A companion change never touches the directory +//! it names, so its `wcc_data` answers both halves from the last facts the +//! export saw for it (see [`Kernel::directory_wcc`]). //! //! A companion created while the export knows its main file (`` in the //! same directory) belongs to that inode: any name of the inode reaches it, so @@ -330,6 +340,36 @@ impl Kernel { companions.use_serial(serial?); Some(stat) } + /// LOOKUP of a `._` name while companions are kept: the view answers + /// first, so a real Workspace file of that name (one READDIR lists) is + /// never hidden or shadowed, and only a name the view does not hold + /// answers the companion, if one is held, a companion answering with no + /// directory row. + pub(crate) fn lookup_apple_double( + &self, + parent: u64, + name: &[u8], + ) -> Result<(ViewStat, Option), crate::read::Refused> { + match self.lookup_view(parent, name) { + Err(refused) if refused.status == Status::NoEnt => { + match self.companion_named(parent, name) { + Some(stat) => Ok((stat, None)), + None => Err(refused), + } + } + answer => answer, + } + } + /// Whether the Workspace view holds `name` in `parent`: such a `._` name + /// is an ordinary Workspace file, never a companion's. A view that holds + /// it takes the export's one engine reference, as any LOOKUP does. + pub(crate) fn view_holds(&self, parent: u64, name: &[u8]) -> Result { + match self.lookup_view(parent, name) { + Ok(_) => Ok(true), + Err(refused) if refused.status == Status::NoEnt => Ok(false), + Err(refused) => Err(refused.status), + } + } /// CREATE of an already-held companion name: UNCHECKED applies its size, /// as an open with truncation would; GUARDED and EXCLUSIVE find it taken. fn companion_open( diff --git a/engine/crates/layerfs-nfs/src/change.rs b/engine/crates/layerfs-nfs/src/change.rs index 2456d43b53..142f841aa8 100644 --- a/engine/crates/layerfs-nfs/src/change.rs +++ b/engine/crates/layerfs-nfs/src/change.rs @@ -97,6 +97,13 @@ pub enum How { Exclusive([u8; 8]), } /// What a published result must carry for its reply to be composed. +/// The route of a name while `._` names are kept out (see [`Kernel::kept_name`]). +#[derive(Clone, Copy, Eq, PartialEq)] +enum Kept { + Ordinary, + Workspace, + Companion, +} #[derive(Clone, Copy)] enum Expect { Nothing, @@ -258,6 +265,19 @@ impl Kernel { } PathName::from_bytes(name).map_err(|_| Status::Inval) } + /// Which route a name takes while `._` names are kept out of the + /// Workspace: a `._` name the view holds is an ordinary Workspace file, + /// one it does not hold is a companion's (see `crate::apple_double`). + /// Only a `._` name asks the view. + fn kept_name(&self, parent: u64, name: &[u8]) -> Result { + if !(self.refuses_apple_double() && names::apple_double(name)) || name.len() > 255 { + return Ok(Kept::Ordinary); + } + Ok(match self.view_holds(parent, name)? { + true => Kept::Workspace, + false => Kept::Companion, + }) + } /// The entry a name binds now, or none. fn existing(&self, parent: u64, name: &[u8]) -> Result, Status> { match self.lookup(parent, name) { @@ -276,10 +296,14 @@ impl Kernel { how: How, tickets: &mut Tickets, ) -> Result<(ViewStat, Wcc), Status> { - if self.refuses_apple_double() && names::apple_double(name) && name.len() <= 255 { - return self.companion_create(parent, name, how, tickets); - } - let checked = self.checked(name, true)?; + // A `._` name the view holds is that Workspace file: its CREATE is the + // ordinary one (UNCHECKED opens it, GUARDED and EXCLUSIVE find it + // taken) and never makes a companion that would shadow it. + let checked = match self.kept_name(parent, name)? { + Kept::Companion => return self.companion_create(parent, name, how, tickets), + Kept::Workspace => PathName::from_bytes(name).map_err(|_| Status::Inval)?, + Kept::Ordinary => self.checked(name, true)?, + }; let key = (parent, name.to_vec()); if let How::Exclusive(verifier) = how { // A retransmitted EXCLUSIVE CREATE finds its own file. @@ -485,8 +509,10 @@ impl Kernel { } /// REMOVE of a non-directory name. pub fn remove(&self, parent: u64, name: &[u8], tickets: &mut Tickets) -> Result { - if let Some(wcc) = self.companion_remove(parent, name) { - return Ok(wcc); + if self.kept_name(parent, name)? == Kept::Companion { + if let Some(wcc) = self.companion_remove(parent, name) { + return Ok(wcc); + } } if self.silly_entry(parent, name).is_some() { self.drop_silly(parent, name); @@ -533,7 +559,11 @@ impl Kernel { new_name: &[u8], tickets: &mut Tickets, ) -> Result<[Wcc; 2], Status> { - if let Some(renamed) = self.companion_rename(from, name, to, new_name) { + let companion = self.kept_name(from, name)? == Kept::Companion; + if let Some(renamed) = companion + .then(|| self.companion_rename(from, name, to, new_name)) + .flatten() + { // The companion lives in the export alone: neither directory's own // facts change, so both halves of each answer from the last ones // this export saw (see `Kernel::directory_wcc`). @@ -566,7 +596,11 @@ impl Kernel { return Ok([wcc, destination]); } let source_name = self.checked(name, false)?; - let destination_name = self.checked(new_name, true)?; + // Replacing a `._` file the view holds is an ordinary RENAME. + let destination_name = match self.kept_name(to, new_name)? { + Kept::Workspace => PathName::from_bytes(new_name).map_err(|_| Status::Inval)?, + _ => self.checked(new_name, true)?, + }; if names::silly(new_name) { // The client renamed a file it still has open: only a regular // file keeps such a name, so this case reads the entry once. diff --git a/engine/crates/layerfs-nfs/src/kernel.rs b/engine/crates/layerfs-nfs/src/kernel.rs index 48c5c087bf..7f6973da60 100644 --- a/engine/crates/layerfs-nfs/src/kernel.rs +++ b/engine/crates/layerfs-nfs/src/kernel.rs @@ -475,15 +475,10 @@ impl Kernel { _ if name.len() > 255 => return Err(Refused::plain(Status::NameTooLong)), _ => {} } - // A companion lives in the export alone: no job read the directory. - if let Some(stat) = self.companion_named(parent, name) { - return Ok((stat, None)); - } + // A `._` name the view holds is the Workspace's; only one it does not + // hold may be a companion (see `crate::apple_double`). if self.refuses_apple_double() && crate::names::apple_double(name) { - if parent != self.root() && !self.table().parents.contains_key(&parent) { - return Err(Refused::plain(Status::NotDir)); - } - return Err(Refused::plain(Status::NoEnt)); + return self.lookup_apple_double(parent, name); } let silly = self.table().silly.get(&(parent, name.to_vec())).copied(); if let Some(serial) = silly { @@ -492,6 +487,14 @@ impl Kernel { .map(|stat| (stat, None)) .map_err(Refused::plain); } + self.lookup_view(parent, name) + } + /// LOOKUP of `name` in the Workspace view alone, asking the engine. + pub(crate) fn lookup_view( + &self, + parent: u64, + name: &[u8], + ) -> Result<(ViewStat, Option), Refused> { let path = PathName::from_bytes(name).map_err(|_| Refused::plain(Status::Inval))?; let lookup = KernelReadOperation::Lookup { parent, name: path }; let answer = self.observe(parent, None, lookup).inspect_err(|refused| { diff --git a/engine/crates/layerfs-nfs/src/names.rs b/engine/crates/layerfs-nfs/src/names.rs index 9237471c15..cf1ccf4bf9 100644 --- a/engine/crates/layerfs-nfs/src/names.rs +++ b/engine/crates/layerfs-nfs/src/names.rs @@ -16,7 +16,9 @@ //! attribute write (`copyfile`, `cp`, `std::fs::copy`, `ditto`, `tar`) //! succeeds and reads back for the export's life, and nothing reaches the //! Workspace. Any other kind under such a name (directory, symlink, link, -//! rename target) is refused with `NFS3ERR_ACCES`. +//! rename target) is refused with `NFS3ERR_ACCES`. A `._` name the +//! Workspace view already holds is not a companion: it is served, listed +//! and changed as any other Workspace file. //! //! The patterns are exact so that a user's own `.nfsrc` or `._config` is an //! ordinary name (the AppleDouble refusal is the one deliberate exception diff --git a/engine/crates/layerfs-nfs/tests/apple_double_view.rs b/engine/crates/layerfs-nfs/tests/apple_double_view.rs new file mode 100644 index 0000000000..6d4db1a835 --- /dev/null +++ b/engine/crates/layerfs-nfs/tests/apple_double_view.rs @@ -0,0 +1,112 @@ +//! A `._` name the Workspace view holds is an ordinary Workspace file while +//! the export keeps macOS AppleDouble companions out: READDIR lists it and +//! LOOKUP, READ, WRITE, CREATE, RENAME onto it and REMOVE reach it; only a +//! `._` name the view does not hold is a companion in export memory. +#[allow(dead_code)] +#[path = "support/client.rs"] +mod client; +#[allow(dead_code)] +#[path = "support/rig.rs"] +mod rig; +use client::{Client, How, Set, ACCES, EXIST, NOENT}; +use std::{fs, net::TcpListener, path::PathBuf, time::Duration}; + +const UID: u32 = 501; +const GID: u32 = 20; +/// The first serial of the export's own companions. +const COMPANIONS: u64 = 1 << 62; + +fn temp(label: &str) -> PathBuf { + std::env::temp_dir().join(format!("layerfs-nfs-adv{}-{label}", std::process::id())) +} + +#[test] +fn a_base_dot_underscore_file_is_listed_read_and_written_like_any_other() { + let base = temp("view"); + let tree = base.join("tree"); + drop(fs::remove_dir_all(&base)); + fs::create_dir_all(tree.join("d")).unwrap(); + fs::write(tree.join("foo"), b"main\n").unwrap(); + fs::write(tree.join("._foo"), b"committed AppleDouble\n").unwrap(); + fs::write(tree.join("d/._bar"), b"nested\n").unwrap(); + fs::write(tree.join("plain.txt"), b"plain\n").unwrap(); + fs::write(tree.join("other"), b"replacement\n").unwrap(); + let rig = rig::Rig::new(&tree, &base.join("rig"), Duration::from_secs(30)); + let server = rig.export(TcpListener::bind("127.0.0.1:0").unwrap(), UID, GID, false); + let mut c = Client::connect(server.local_addr(), UID, GID); + let root = c.mnt("/"); + + // READDIR and LOOKUP agree: the listed name opens, from the Workspace. + let (entries, _) = c.list(&root, 64 * 1024, true); + assert!(entries.iter().any(|entry| entry.name == b"._foo")); + let (real, attr) = c.lookup(&root, b"._foo").unwrap(); + assert!( + attr.fileid < COMPANIONS, + "a Workspace inode, not a companion" + ); + assert_eq!(attr.size, 22); + assert_eq!(c.read_all(&real, 4096), b"committed AppleDouble\n"); + let (d, _) = c.lookup(&root, b"d").unwrap(); + let (nested, _) = c.lookup(&d, b"._bar").unwrap(); + assert_eq!(c.read_all(&nested, 4096), b"nested\n"); + + // CREATE of a name the view holds is the ordinary CREATE of that file: + // GUARDED finds it taken, UNCHECKED opens it, and no companion shadows it. + let guarded = c.create(&root, b"._foo", How::Guarded(Set::default())); + assert_eq!(guarded.map(|_| ()), Err(EXIST)); + let opened = c + .create(&root, b"._foo", How::Unchecked(Set::default())) + .unwrap(); + assert_eq!( + (opened.handle.clone(), opened.attr.size), + (real.clone(), 22) + ); + assert_eq!(server.held().companions, 0); + + // WRITE reaches the Workspace file. + c.write(&real, 0, b"COMMITTED").unwrap(); + assert_eq!(c.read_all(&real, 4096), b"COMMITTED AppleDouble\n"); + + // A new companion of a file with no real `._` name behaves as before: + // export memory, never listed, never committed. + let companion = c.touch(&root, b"._plain.txt", 0o644).unwrap(); + assert!(companion.attr.fileid >= COMPANIONS); + c.write(&companion.handle, 0, b"xattr").unwrap(); + let (found, _) = c.lookup(&root, b"._plain.txt").unwrap(); + assert_eq!(found, companion.handle); + assert_eq!(server.held().companions, 1); + let (entries, _) = c.list(&root, 64 * 1024, true); + assert!(!entries.iter().any(|entry| entry.name == b"._plain.txt")); + // A new `._` name is still kept out of the Workspace: a file is not + // renamed onto one the view lacks, but replaces one the view holds. + let refused = c.rename(&root, b"plain.txt", &root, b"._new").map(|_| ()); + assert_eq!(refused, Err(ACCES)); + c.rename(&root, b"other", &d, b"._bar").unwrap(); + let (replaced, _) = c.lookup(&d, b"._bar").unwrap(); + assert_eq!(c.read_all(&replaced, 4096), b"replacement\n"); + // REMOVE of a name the view holds removes the Workspace file. + c.remove(&d, b"._bar").unwrap(); + assert_eq!(c.lookup(&d, b"._bar").map(|_| ()), Err(NOENT)); + + // The Commit holds the edited `._foo` and the removal, not the companion. + server.close_files(); + let done = rig.commit(); + assert!(done.history.is_some(), "{:?}", done.history); + let view = rig.view([79; 32]); + let viewer = rig.serve_view(TcpListener::bind("127.0.0.1:0").unwrap(), &view, UID, GID); + let mut v = Client::connect(viewer.local_addr(), UID, GID); + let view_root = v.mnt("/"); + let (handle, _) = v.lookup(&view_root, b"._foo").unwrap(); + assert_eq!(v.read_all(&handle, 4096), b"COMMITTED AppleDouble\n"); + assert_eq!(v.lookup(&view_root, b"._plain.txt").map(|_| ()), Err(NOENT)); + let (view_d, _) = v.lookup(&view_root, b"d").unwrap(); + assert_eq!(v.lookup(&view_d, b"._bar").map(|_| ()), Err(NOENT)); + drop(v); + let _released = viewer.stop(); + rig.close_view(view); + drop(c); + let released = server.stop(); + let (_, outstanding) = rig.stop(released); + assert_eq!(outstanding, 0); + drop(fs::remove_dir_all(&base)); +} diff --git a/engine/crates/layerfs-nfs/tests/write.rs b/engine/crates/layerfs-nfs/tests/write.rs index f1e444cfe3..2eb8d2f9bd 100644 --- a/engine/crates/layerfs-nfs/tests/write.rs +++ b/engine/crates/layerfs-nfs/tests/write.rs @@ -1715,10 +1715,12 @@ fn create_write_remove_and_apple_double_avoid_redundant_owner_jobs_and_orphans() ); // 4. AppleDouble companion changing lifecycle (CREATE, WRITE, SETATTR, - // REMOVE) issues 0 SQLite owner jobs (0 observe_visit, 0 mutate_visit), - // and LOOKUP of an absent companion issues none either: the export - // refuses the name before any visit, and the reply's directory - // attributes come from the facts it already published. + // REMOVE) never mutates the engine (0 mutate_visit). A `._` name the + // view holds is an ordinary Workspace file, so CREATE and REMOVE of a + // name ask the view once each (1 observe_visit, a LOOKUP that finds + // nothing) and WRITE and SETATTR of the companion serial ask nothing; + // a LOOKUP of an absent companion is that one LOOKUP too. The reply's + // directory attributes come from the facts the export already had. let before = counts.snapshot(); let ad = c.touch(&root, b"._single.txt", 0o644).unwrap(); // The directory's wcc_data is not a hole: a companion changes nothing in @@ -1752,14 +1754,14 @@ fn create_write_remove_and_apple_double_avoid_redundant_owner_jobs_and_orphans() ); assert_eq!( counts.snapshot(), - before, - "AppleDouble CREATE+WRITE+SETATTR+REMOVE must issue 0 engine owner jobs" + (before.0 + 2, before.1, before.2, before.3), + "AppleDouble CREATE+WRITE+SETATTR+REMOVE: 2 view LOOKUPs, 0 mutate_visit" ); assert_eq!(c.lookup(&root, b"._single.txt").map(|_| ()), Err(NOENT)); assert_eq!( counts.snapshot(), - before, - "an absent AppleDouble LOOKUP issues no owner job at all" + (before.0 + 3, before.1, before.2, before.3), + "an absent AppleDouble LOOKUP asks the view once and mutates nothing" ); // 5. REMOVE drops the last link and retires the synthetic kernel's file From a10feafb1d5d10e76b0e508737a0f27ca28c056e Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Mon, 23 Nov 2026 14:19:03 +0800 Subject: [PATCH 2/2] nfs: let a user chmod through the post-Commit refresh mark After a merged Commit the daemon marked every stale serial at once, then chmodded the paths one by one on a background thread; for up to 30 s any mode-only SETATTR on a marked serial was answered with the current attributes and changed nothing, without comparing the requested mode. So `chmod +x f` right after a Commit reported success and did nothing (review finding #9, V-OV-4). Now the mark suppresses only the refresh's own chmod: - `Server::refresh` returns (serial, path) and marks nothing. - The refresh thread lstats each path through the mount (skipping a symlink, a vanished path and a path that now names another inode), marks that serial with exactly the mode it is about to ask (`Refresher::arm`), then chmods to it. - `Kernel::refreshed` takes the mark only for a mode-only SETATTR asking the marked mode. A client SETATTR asking another mode is applied, and leaves the mark for the refresh chmod still on its way, which is then answered without a change, so the refresh never overwrites a newer user chmod. - `Refresher` holds a weak reference, so the thread never keeps a stopping export alive (unmount's `Arc::try_unwrap` stays unaffected), and stops once the export is gone. Residual: a client chmod to the very mode just marked, sent in the microseconds between the mark and the refresh's chmod, is answered unchanged; the refresh's chmod that follows applies that same mode. Documented, with the existing limits: the refresh is best effort, runs after the Commit reply and stops at 4,096 stale inodes. Tests: tests/refresh.rs now asserts the new contract. Its old assertion that a marked chmod to another mode (0o600 on a 0o644 file) is swallowed was the bug itself and is replaced: the refresh chmod asking the marked mode is answered unchanged; a user chmod to another mode inside the window is applied and the refresh chmod after it does not undo it (committed 0o700); a stopped export takes no mark. Docs: kernel-routes/nfs.md refresh section, kernel-routes/README.md. Production LOC: 206,585 -> 206,624 (delta +39) core 40,988 -> 40,988 (0) engine 95,947 -> 95,986 (+39) layerfs-daemon +5, layerfs-nfs +34 control 59,325 -> 59,325 (0) api 10,325 -> 10,325 (0) reference absent (retired R9c; last counted 65,417 at tree 498dd1917812) Method: tools/production_loc.py --detail on parent 2033a2e6ca and the staged tree Co-Authored-By: Claude Opus 5.5 --- .../engine/kernel-routes/README.md | 3 +- docs/architecture/engine/kernel-routes/nfs.md | 17 ++-- .../layerfs-daemon/src/control/export.rs | 29 ++++--- engine/crates/layerfs-nfs/src/kernel.rs | 4 +- engine/crates/layerfs-nfs/src/lib.rs | 2 +- engine/crates/layerfs-nfs/src/refresh.rs | 79 +++++++++++++------ engine/crates/layerfs-nfs/src/server.rs | 42 ++++++++-- engine/crates/layerfs-nfs/tests/refresh.rs | 54 +++++++++---- 8 files changed, 165 insertions(+), 65 deletions(-) diff --git a/docs/architecture/engine/kernel-routes/README.md b/docs/architecture/engine/kernel-routes/README.md index 7fdec2fa85..22df27a67d 100644 --- a/docs/architecture/engine/kernel-routes/README.md +++ b/docs/architecture/engine/kernel-routes/README.md @@ -132,7 +132,7 @@ so NFS calls charge nothing. | WRITE count | Full count or an error, never short | Short only after a later window failed; earlier windows stay published | [`coherence/pages.rs`](../../../../engine/crates/layerfs-fuse/src/coherence/pages.rs), [`change.rs`](../../../../engine/crates/layerfs-nfs/src/change.rs) | | Hard links | Aliases share one serial, so one kernel inode | `fileid` is the serial | [`link.rs`](../../../../engine/crates/layerfs-mount-ports/src/operations/link.rs), [`attributes.rs`](../../../../engine/crates/layerfs-nfs/src/attributes.rs) | | Ticket release | After the one reply attempt (fuser reports no send result) | After `write_record` returns | [`reply_order.rs`](../../../../engine/crates/layerfs-fuse/src/coherence/reply_order.rs), [`server.rs`](../../../../engine/crates/layerfs-nfs/src/server.rs) | -| After a Commit installs a root other than the one shown | `inval_inode` / `inval_entry` per stale serial or name before the answer | Mode-preserving SETATTR refresh through the client | [`invalidate.rs`](../../../../engine/crates/layerfs-daemon/src/control/invalidate.rs); [FUSE](fuse.md), [NFS](nfs.md) | +| After a Commit installs a root other than the one shown | `inval_inode` / `inval_entry` per stale serial or name before the answer | Mode-preserving SETATTR refresh through the client, after the answer and best effort (at most 4,096 inodes) | [`invalidate.rs`](../../../../engine/crates/layerfs-daemon/src/control/invalidate.rs); [FUSE](fuse.md), [NFS](nfs.md) | | Durability of a reply | `FLUSH`/`FSYNC`/`FSYNCDIR` answer `ENOSYS` once; the kernel then reports success and stops sending them | WRITE answers `FILE_SYNC`, meaning published; the daemon flushes the client before each Commit: the flush helper when set, else the export volume's own flush (`sync_volume_np(, SYNC_VOLUME_WAIT)` on macOS, `sync(2)` elsewhere); a failed flush refuses the Commit as `Failed` at `commit:flush` | [`flush.rs`](../../../../engine/crates/layerfs-mount-ports/src/operations/flush.rs), [`changing.rs`](../../../../engine/crates/layerfs-nfs/src/changing.rs) | An install of the Workspace's own captured root sends nothing: the tree the @@ -189,6 +189,7 @@ stable media. | [`protocol.rs`](../../../../engine/crates/layerfs-nfs/tests/protocol.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test protocol` | any (no network) | XDR round trips and bounds, fragment joining and `RECORD_LIMIT`, `AUTH_UNIX` headers, handles stable per mount and stale after it | | [`write.rs`](../../../../engine/crates/layerfs-nfs/tests/write.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test write` | any (in-process loopback export, no kernel mount) | Every changing NFS procedure; tickets released only after the reply; silly renames and AppleDouble names | | [`apple_double_view.rs`](../../../../engine/crates/layerfs-nfs/tests/apple_double_view.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test apple_double_view` | any (in-process loopback export, no kernel mount) | A `._` file the Workspace holds is listed, read, written, replaced and removed as any other file and committed; a new companion still stays in export memory | +| [`refresh.rs`](../../../../engine/crates/layerfs-nfs/tests/refresh.rs) | `cargo +1.85.1 test --locked -p layerfs-nfs --test refresh` | any (in-process loopback export, no kernel mount) | A refresh chmod changes nothing; a user chmod inside the mark window is applied and the refresh chmod after it does not undo it | Run each under a wall timeout of at most 120 s. The nightly lane runs each kernel binary alone in a container with `--device /dev/fuse --cap-add diff --git a/docs/architecture/engine/kernel-routes/nfs.md b/docs/architecture/engine/kernel-routes/nfs.md index 07fb3e14f6..b5d3d4b3f0 100644 --- a/docs/architecture/engine/kernel-routes/nfs.md +++ b/docs/architecture/engine/kernel-routes/nfs.md @@ -164,16 +164,23 @@ drawn once per export; it makes guessing costly and does not authenticate. Commit installed R' while the export showed R (R' != R) Server::installed(): close file and directory descriptors stale_after_install(R, R') -> serials (at most REFRESHED = 4096) - Server::refresh(serials): mark them, return their paths - thread layerfs-nfs-refresh: chmod(path, same mode) per path - client SETATTR -> marked and mode-only? answer current attrs, - change nothing -> new post-op attrs -> client drops its cache + Server::refresh(serials): (serial, path) of each the export knows + Commit reply sent; thread layerfs-nfs-refresh, per path in order: + lstat through the mount (skip a symlink, a vanished path, another inode) + Refresher::arm(serial, mode the client shows) -- one mark, that mode + chmod(path, that mode) + client SETATTR -> mode-only, marked, asking the marked mode? + answer current attrs, change nothing, take the mark + -> new post-op attrs -> client drops its cache + any other SETATTR (another mode included) -> applied as always ``` | Rule | Source | | --- | --- | -| A mark is taken by one mode-only SETATTR and ends after `MARK_LIFE` (30 s); a serial the client never saw is left out; symlinks and vanished paths are skipped | [`refresh.rs`](../../../../engine/crates/layerfs-nfs/src/refresh.rs), [`export.rs`](../../../../engine/crates/layerfs-daemon/src/control/export.rs) | +| One inode is marked right before its own refresh chmod, with the exact mode that chmod asks (the one the client shows through the mount point). A mark is taken by one mode-only SETATTR asking that mode and ends after `MARK_LIFE` (30 s); a serial the client never saw is left out; symlinks, vanished paths and paths that now name another inode are skipped; the thread stops once the export is gone or stopping | [`refresh.rs`](../../../../engine/crates/layerfs-nfs/src/refresh.rs), [`server.rs`](../../../../engine/crates/layerfs-nfs/src/server.rs), [`export.rs`](../../../../engine/crates/layerfs-daemon/src/control/export.rs) | | The refresh never writes into the Workspace and never reverts a mode the install changed | [`refresh.rs`](../../../../engine/crates/layerfs-nfs/src/refresh.rs) | +| The mark suppresses only the refresh's own chmod. A client SETATTR asking another mode is applied even on a marked inode, and the refresh chmod still on its way is then answered without a change, so it never overwrites the newer mode. The one request the export cannot tell from the refresh's is a client chmod to the very mode just marked, sent in the microseconds between the mark and the refresh's chmod: it is answered unchanged and the refresh's chmod that follows applies that same mode | [`refresh.rs`](../../../../engine/crates/layerfs-nfs/src/refresh.rs) | +| Best effort: the refresh runs after the Commit reply, so a client may still serve its cached attributes and listings for a moment after it; the walk stops at `REFRESHED` (4,096) stale inodes, and a failed walk, a failed chmod or one the client never sends leaves the rest to `actimeo` and close-to-open | [`export.rs`](../../../../engine/crates/layerfs-daemon/src/control/export.rs) | | `LAYERFS_NFS_REFRESH=0` leaves the client to `actimeo` and close-to-open | [`export.rs`](../../../../engine/crates/layerfs-daemon/src/control/export.rs) | ## AppleDouble files (`apple_double.rs`, `apple_double/edit.rs`, `apple_double/index.rs`, `apple_double/reclaim.rs`, `apple_double_codec.rs`, `apple_double_spill.rs`) diff --git a/engine/crates/layerfs-daemon/src/control/export.rs b/engine/crates/layerfs-daemon/src/control/export.rs index d4d3f7b262..3915a480fc 100644 --- a/engine/crates/layerfs-daemon/src/control/export.rs +++ b/engine/crates/layerfs-daemon/src/control/export.rs @@ -62,19 +62,27 @@ pub const REFRESHED: usize = 4096; pub const REFRESH: &str = "LAYERFS_NFS_REFRESH"; /// One mode-preserving chmod of each path below `root`, through the host's -/// NFS client; a symbolic link (chmod would follow it) and a path that is -/// gone are skipped. The export answers each without a change. -fn refresh(root: &std::path::Path, paths: &[PathBuf]) { +/// NFS client, in order and at most once each. A symbolic link (chmod would +/// follow it), a path that is gone and a path that now names another inode +/// than its serial are skipped. Each chmod asks the mode the client shows +/// and is marked with exactly that mode first, so the export answers it +/// without a change; a client chmod to another mode is still applied, and +/// stays (see `layerfs_nfs::refresh`). Stops when the export is gone. +fn refresh(root: &std::path::Path, refresher: &layerfs_nfs::Refresher, paths: &[(u64, PathBuf)]) { use std::os::unix::fs::{MetadataExt, PermissionsExt}; - for path in paths { + for (serial, path) in paths { let path = root.join(path); let Ok(metadata) = std::fs::symlink_metadata(&path) else { continue; }; - if !metadata.file_type().is_symlink() { - let mode = std::fs::Permissions::from_mode(metadata.mode() & 0o7777); - let _ = std::fs::set_permissions(&path, mode); + if metadata.file_type().is_symlink() || metadata.ino() != *serial { + continue; + } + let mode = metadata.mode() & 0o7777; + if !refresher.arm(*serial, mode) { + return; } + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)); } } /// How the host's NFS client mounts, flushes and unmounts an export. @@ -581,7 +589,9 @@ impl Service { /// the client may cache are refreshed through the mount point (see /// `layerfs_nfs::refresh`): a mode-preserving chmod of each, at most /// [`REFRESHED`], on a thread of its own after this returns, so the - /// Commit reply never waits on the client. False without an export. + /// Commit reply never waits on the client. Best effort: a walk that stops + /// at the bound, a chmod that fails or one the client never sends leaves + /// the rest to the client's own revalidation. False without an export. pub(super) fn installed_export( &self, token: WorkspaceToken, @@ -620,9 +630,10 @@ impl Service { let paths = server.refresh(stale); if !paths.is_empty() { let root = PathBuf::from(directory); + let refresher = server.refresher(); let _ = std::thread::Builder::new() .name("layerfs-nfs-refresh".into()) - .spawn(move || refresh(&root, &paths)); + .spawn(move || refresh(&root, &refresher, &paths)); } Ok(true) } diff --git a/engine/crates/layerfs-nfs/src/kernel.rs b/engine/crates/layerfs-nfs/src/kernel.rs index 7f6973da60..b851e4a9b4 100644 --- a/engine/crates/layerfs-nfs/src/kernel.rs +++ b/engine/crates/layerfs-nfs/src/kernel.rs @@ -121,8 +121,8 @@ pub(crate) struct Table { pub aliases: HashMap>, /// Serial -> last use, for the collection order. pub used: HashMap, - /// Serials marked for a cache refresh, and when (see [`crate::refresh`]). - pub refreshing: HashMap, + /// Serials marked for a cache refresh: the mode asked, and when. + pub refreshing: HashMap, /// Directory serial -> the facts last published or observed for it. A /// change of an AppleDouble companion names a directory but changes /// nothing in it, so its `wcc_data` answers from here (see diff --git a/engine/crates/layerfs-nfs/src/lib.rs b/engine/crates/layerfs-nfs/src/lib.rs index a33f6f6887..07076c8ed4 100644 --- a/engine/crates/layerfs-nfs/src/lib.rs +++ b/engine/crates/layerfs-nfs/src/lib.rs @@ -38,4 +38,4 @@ pub mod xdr; pub use kernel::Released; pub use nfs::TRANSFER_WINDOW; -pub use server::{Count, ExportConfig, Server}; +pub use server::{Count, ExportConfig, Refresher, Server}; diff --git a/engine/crates/layerfs-nfs/src/refresh.rs b/engine/crates/layerfs-nfs/src/refresh.rs index 32a7f1e071..d6ac60dd30 100644 --- a/engine/crates/layerfs-nfs/src/refresh.rs +++ b/engine/crates/layerfs-nfs/src/refresh.rs @@ -4,12 +4,23 @@ //! listings until `actimeo` or its close-to-open check. A SETATTR it sends //! itself is answered with fresh post-operation attributes, and a client //! that sees them changed drops what it cached for that inode. So the daemon -//! names the inodes an install made stale ([`Kernel::refresh`]) and changes -//! their mode to the value it already has through the mount point. The -//! export answers each such mode-only SETATTR on a marked inode with its -//! current attributes and changes nothing (the mark is taken once and ends -//! after [`MARK_LIFE`]), so the refresh never writes into the Workspace and -//! never reverts a mode the install changed. +//! names the inodes an install made stale ([`Kernel::refresh`]) and, one path +//! at a time, reads the mode the client shows through the mount point, marks +//! that inode with exactly that mode ([`Kernel::arm_refresh`]) and changes +//! the mode to it. The export answers a mode-only SETATTR on a marked inode +//! whose requested mode is the marked one with its current attributes and +//! changes nothing (the mark is taken once and ends after [`MARK_LIFE`]), so +//! the refresh never writes into the Workspace and never reverts a mode the +//! install changed (the client may still show the mode from before it). +//! +//! The mark suppresses only the refresh's own chmod. A client SETATTR asking +//! another mode is applied as always, even on a marked inode, and leaves the +//! mark for the refresh's chmod still on its way, which is then answered +//! without a change: it never overwrites the user's newer mode. The one +//! request the export cannot tell from the refresh's is a client chmod to +//! the very mode just marked, sent between the mark and the refresh's own +//! chmod (microseconds apart, one inode at a time): that one is answered +//! unchanged and the refresh's chmod that follows applies the same mode. use crate::{change::Sattr, kernel::Kernel}; use std::time::{Duration, Instant}; @@ -17,19 +28,18 @@ use std::time::{Duration, Instant}; pub const MARK_LIFE: Duration = Duration::from_secs(30); /// Directory depth one path is built to at most. const DEPTH: usize = 4096; +/// The permission bits a mark compares. +const PERMISSIONS: u32 = 0o7777; impl Kernel { - /// Marks each of `serials` this export handed out and still knows by - /// name, and returns their paths below the export root (empty for the - /// root itself), in the order given. A serial the client never saw has - /// nothing cached and is left out. - pub fn refresh(&self, serials: impl IntoIterator) -> Vec>> { + /// The paths below the export root (empty for the root itself) of each + /// of `serials` this export handed out and still knows by name, with the + /// serial, in the order given. A serial the client never saw has nothing + /// cached and is left out. Marks nothing: [`Kernel::arm_refresh`] marks + /// one inode right before its refresh chmod. + pub fn refresh(&self, serials: impl IntoIterator) -> Vec<(u64, Vec>)> { let root = self.root(); - let mut table = self.table(); - let now = Instant::now(); - table - .refreshing - .retain(|_, marked| now.duration_since(*marked) < MARK_LIFE); + let table = self.table(); let mut paths = Vec::new(); for serial in serials { let mut path = Vec::new(); @@ -49,17 +59,29 @@ impl Kernel { } if known { path.reverse(); - table.refreshing.insert(serial, now); - paths.push(path); + paths.push((serial, path)); } } paths } - /// Whether a SETATTR of `serial` is a pending refresh: mode only, on a - /// marked inode whose mark has not ended. Takes the mark. + /// Marks `serial` for the refresh chmod to `mode` about to be sent, and + /// drops the marks whose life ended. + pub fn arm_refresh(&self, serial: u64, mode: u32) { + let now = Instant::now(); + let mut table = self.table(); + table + .refreshing + .retain(|_, (_, marked)| now.duration_since(*marked) < MARK_LIFE); + table.refreshing.insert(serial, (mode & PERMISSIONS, now)); + } + /// Whether a SETATTR of `serial` is a pending refresh: mode only, asking + /// the marked mode, on an inode whose mark has not ended. Takes the mark; + /// a SETATTR asking another mode leaves it. pub(crate) fn refreshed(&self, serial: u64, sattr: &Sattr) -> bool { - let mode_only = sattr.mode.is_some() - && sattr.uid.is_none() + let Some(mode) = sattr.mode else { + return false; + }; + let mode_only = sattr.uid.is_none() && sattr.gid.is_none() && sattr.size.is_none() && sattr.mtime.is_none(); @@ -67,9 +89,16 @@ impl Kernel { return false; } let mut table = self.table(); - match table.refreshing.remove(&serial) { - Some(marked) => marked.elapsed() < MARK_LIFE, - None => false, + match table.refreshing.get(&serial).copied() { + Some((_, at)) if at.elapsed() >= MARK_LIFE => { + table.refreshing.remove(&serial); + false + } + Some((marked, _)) if marked == mode & PERMISSIONS => { + table.refreshing.remove(&serial); + true + } + _ => false, } } } diff --git a/engine/crates/layerfs-nfs/src/server.rs b/engine/crates/layerfs-nfs/src/server.rs index ab57eef018..3f20f781a4 100644 --- a/engine/crates/layerfs-nfs/src/server.rs +++ b/engine/crates/layerfs-nfs/src/server.rs @@ -127,6 +127,25 @@ impl Counters { } } +/// Marks a refresh chmod on the export it came from (see [`crate::refresh`]); +/// holds no reference that keeps a stopped export alive. +#[derive(Clone)] +pub struct Refresher(std::sync::Weak); +impl Refresher { + /// Marks `serial` for the refresh chmod to `mode` about to be sent; + /// false once the export is gone or stopping, when no chmod is due. + pub fn arm(&self, serial: u64, mode: u32) -> bool { + let Some(shared) = self.0.upgrade() else { + return false; + }; + if shared.stopping.load(Ordering::Acquire) { + return false; + } + shared.kernel.arm_refresh(serial, mode); + true + } +} + struct Shared { kernel: Kernel, /// The WRITE/COMMIT verifier: fresh for every export. @@ -207,19 +226,28 @@ impl Server { self.shared.kernel.close_directories(), ) } - /// After an install: marks the stale `serials` the client may cache and - /// returns their paths below the mount point, for the mode-preserving - /// SETATTR that makes the client drop its cache (see [`crate::refresh`]). - pub fn refresh(&self, serials: impl IntoIterator) -> Vec { + /// After an install: the paths below the mount point of the stale + /// `serials` the client may cache, each with its serial, for the + /// mode-preserving SETATTR that makes the client drop its cache (see + /// [`crate::refresh`]). Marks nothing: [`Refresher::arm`] does, per path. + pub fn refresh( + &self, + serials: impl IntoIterator, + ) -> Vec<(u64, std::path::PathBuf)> { use std::os::unix::ffi::OsStrExt; (self.shared.kernel.refresh(serials).into_iter()) - .map(|names| { - (names.iter()) + .map(|(serial, names)| { + let path = (names.iter()) .map(|name| std::ffi::OsStr::from_bytes(name)) - .collect() + .collect(); + (serial, path) }) .collect() } + /// A handle that marks refresh chmods without keeping the export alive. + pub fn refresher(&self) -> Refresher { + Refresher(Arc::downgrade(&self.shared)) + } /// The write verifier this export answers WRITE and COMMIT with. pub fn verifier(&self) -> [u8; 8] { self.shared.verifier diff --git a/engine/crates/layerfs-nfs/tests/refresh.rs b/engine/crates/layerfs-nfs/tests/refresh.rs index 7ff99c4d96..c3202c7095 100644 --- a/engine/crates/layerfs-nfs/tests/refresh.rs +++ b/engine/crates/layerfs-nfs/tests/refresh.rs @@ -1,7 +1,10 @@ -//! Cache refresh after an install (B): the inodes the daemon names are -//! marked and their paths returned; a mode-only SETATTR on a marked inode is -//! answered with its current attributes and changes nothing, once; every -//! other SETATTR still changes the inode; the Commit holds only real changes. +//! Cache refresh after an install (B): the daemon gets the paths of the +//! inodes it names, and marks one inode with the mode its refresh chmod asks +//! right before sending it. A mode-only SETATTR asking the marked mode is +//! answered with the current attributes and changes nothing, once; a client +//! SETATTR asking another mode is applied even while the inode is marked, +//! and the refresh chmod that follows does not undo it; every other SETATTR +//! still changes the inode; the Commit holds only real changes. #[allow(dead_code)] #[path = "support/client.rs"] mod client; @@ -25,7 +28,7 @@ fn temp(label: &str) -> PathBuf { } #[test] -fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { +fn a_refresh_chmod_changes_nothing_and_a_user_chmod_still_applies() { let source = temp("src"); let work = temp("work"); drop(fs::remove_dir_all(&source)); @@ -44,7 +47,8 @@ fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { let (a, a_attr) = client.lookup(&root, b"a").unwrap(); let (top, top_attr) = client.lookup(&root, b"top.txt").unwrap(); let root_id = client.getattr(&root).unwrap().fileid; - // Paths of the serials the client knows, the root's empty; an unknown serial is left out. + // Paths of the serials the client knows, the root's empty, each with its + // serial; an unknown serial is left out. Nothing is marked yet. let paths = server.refresh([ file_attr.fileid, a_attr.fileid, @@ -55,10 +59,10 @@ fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { assert_eq!( paths, vec![ - PathBuf::from("a/b/file"), - PathBuf::from("a"), - PathBuf::new(), - PathBuf::from("top.txt"), + (file_attr.fileid, PathBuf::from("a/b/file")), + (a_attr.fileid, PathBuf::from("a")), + (root_id, PathBuf::new()), + (top_attr.fileid, PathBuf::from("top.txt")), ] ); let mode = |set: Result| { @@ -69,14 +73,18 @@ fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { mode: Some(mode), ..Set::default() }; - // A marked inode: the mode-only SETATTR is answered, nothing changes. + let refresher = server.refresher(); + // An unmarked inode: a chmod to its own mode is an ordinary SETATTR. assert_eq!( - mode(client.setattr(&file, chmod(0o600), None)), + mode(client.setattr(&top, chmod(0o644), None)), Ok(Some(0o644)) ); + // The refresh chmod asks the mode the client still shows (0o600, from + // before an install that made it 0o644): answered, nothing reverts. + assert!(refresher.arm(file_attr.fileid, 0o600)); assert_eq!( - mode(client.setattr(&a, chmod(0o700), None)), - Ok(Some(0o755)) + mode(client.setattr(&file, chmod(0o600), None)), + Ok(Some(0o644)) ); assert_eq!(client.getattr(&file).unwrap().mode & 0o7777, 0o644); // The mark is taken once: the next chmod is real. @@ -84,7 +92,21 @@ fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { mode(client.setattr(&file, chmod(0o600), None)), Ok(Some(0o600)) ); + // A user chmod inside the mark window asks another mode: it is applied, + // and the refresh chmod that follows (asking the marked mode) is answered + // without a change, so it never undoes the user's newer mode. + assert!(refresher.arm(a_attr.fileid, 0o755)); + assert_eq!( + mode(client.setattr(&a, chmod(0o700), None)), + Ok(Some(0o700)) + ); + assert_eq!( + mode(client.setattr(&a, chmod(0o755), None)), + Ok(Some(0o700)) + ); + assert_eq!(client.getattr(&a).unwrap().mode & 0o7777, 0o700); // A SETATTR that is not mode-only is never taken for a refresh. + assert!(refresher.arm(top_attr.fileid, 0o640)); let truncate = Set { mode: Some(0o640), size: Some(0), @@ -101,7 +123,7 @@ fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { let view_root = reader.mnt("/"); let at = |reader: &mut Client, path: &str| reader.walk_to(&view_root, path).unwrap().1; assert_eq!(at(&mut reader, "a/b/file").mode & 0o7777, 0o600); - assert_eq!(at(&mut reader, "a").mode & 0o7777, 0o755); + assert_eq!(at(&mut reader, "a").mode & 0o7777, 0o700); let top_view = at(&mut reader, "top.txt"); assert_eq!((top_view.mode & 0o7777, top_view.size), (0o640, 0)); drop(reader); @@ -109,6 +131,8 @@ fn a_refresh_chmod_changes_nothing_and_other_setattrs_still_do() { rig.close_view(view); drop(client); let served = server.stop(); + // A stopped export takes no mark: the refresh thread stops. + assert!(!refresher.arm(file_attr.fileid, 0o600)); let (_, outstanding) = rig.stop(served); assert_eq!(outstanding, 0); for path in [&source, &work] {