Skip to main content

Module fs_clone

Module fs_clone 

Source
Expand description

Filesystem-level copy-on-write helpers.

Heddle’s worktree materializer needs the storage win of pointing N worktrees at the same blob bytes (so checking out the same state to many sibling worktrees costs ~1× disk, not N×) without the mutation hazard that hardlinks bring. With hardlinks, an in-place write — chmod +w file && echo new > file, O_TRUNC, etc. — mutates the shared inode, corrupting every other worktree that points at the same blob.

Filesystem reflinks (a.k.a. CoW clones) solve this: the destination starts out sharing physical blocks with the source, but the first write to either side automatically forks the underlying allocation. The OS guarantees isolation even if an agent strips the read-only bit and overwrites the file in place.

Platform support:

  • macOS / APFS: clonefile(2) from <sys/clonefile.h>. True CoW.
  • Linux / btrfs / XFS-with-reflinks / ZFS: ioctl(dest_fd, FICLONE, src_fd).
  • Anywhere else (or when reflink isn’t supported by the underlying filesystem): caller falls back to a real copy.

The core try_reflink returns a ReflinkOutcome so the caller can tell three genuinely-different situations apart: a successful clone, a “this filesystem can’t reflink” verdict (batch-wide signal to stop trying), and a “the source vanished from under us” race (a per-blob fallback that must NOT poison the batch). Overloading the last two — as a bare Ok(false) did — makes one concurrently-pruned loose mirror needlessly disable reflinks for every remaining blob.

Enums§

ReflinkOutcome
The three outcomes of a reflink attempt, kept distinct so callers don’t conflate “filesystem can’t reflink” (a batch-wide property) with “this one source vanished mid-flight” (a per-blob race).

Functions§

clonefile_or_copy
Reflink if possible, otherwise fall back to a real copy. Returns the same Ok(true)/Ok(false) discriminator as try_reflinktrue when the OS gave us a CoW clone, false when we paid the full copy cost. Either way, on Ok the destination exists and has the source’s bytes.
filesystem_supports_reflink
Test whether the filesystem at parent_dir supports reflinks by trying one against a temp source/dest pair. Returns true on success. Useful for tests that want to soft-skip on filesystems without CoW support, and for any caller that wants a runtime capability check before asserting on reflink-specific properties.
try_reflink
Try a filesystem-level reflink (copy-on-write clone) from source to dest. On success the destination has its own inode and shares physical blocks with the source until either side is modified.