This commit is contained in:
Antonio S. Musumeci 2026-09-25 00:48:35 -04:00
parent 515b0549ef
commit 54166afe08
15 changed files with 1984 additions and 65 deletions

View file

@ -50,6 +50,8 @@
#include "base_types.h"
#include <atomic>
#include <mutex>
#include <shared_mutex>
@ -105,8 +107,86 @@ public:
// Common case (plain pwrite on stable fd) only needs a shared lock
// since the kernel already serializes fd mutations. The danger is
// the fs::dup2() rebinding when moveonenospc activates. Writers
// take shared lock; move takes unique.
// take shared lock; move takes unique (lock_exclusive). Spliced
// reads (FUSE::read_buf) also take it shared, but only if that
// needs no waiting.
std::shared_mutex mutex;
// Threads waiting in lock_exclusive. FUSE::read_buf starts no splice
// while one waits: the rwlock prefers readers, so overlapping spliced
// reads could otherwise hold a mover off indefinitely.
std::atomic<int> exclusive_waiters{0};
// Lower bound on the branch file's size, used only by FUSE::read_buf
// to skip its end-of-file size check for reads ending inside this
// bound. Raised by that check, lowered by any short read (FUSE::read)
// or ftruncate and reset by fallocate through this handle. It may go
// stale when the file shrinks through another handle or outside
// mergerfs; the splice reply then hits EOF and falls back to
// FUSE::read, which returns the correct bytes and lowers the bound
// to where that read found the end (to 0 when it read nothing, as
// the end is then somewhere at or before its offset). 0 = unknown.
std::atomic<s64> size_floor{0};
// Whether FUSE::read_buf may offer fd for splicing: unknown until the
// first large read checks the branch filesystem (some serve splice
// from a page cache their reads bypass or revalidate), no once that
// check said so or the fd refused splice (its filesystem has no
// splice_read), after which reads go straight to the copy path.
// Decided once per fd binding; a filesystem refused by type is also
// remembered by device, so later handles on it are settled without
// repeating that check (see FUSE::read_buf).
enum class Splice : uint8_t { unknown, yes, no };
std::atomic<Splice> splice_state{Splice::unknown};
// Take mutex exclusively (moveonenospc), announced through
// exclusive_waiters so that no new spliced read starts meanwhile.
std::unique_lock<std::shared_mutex>
lock_exclusive()
{
// Counted out again even if locking throws, so a failed attempt
// cannot leave spliced reads on this handle declined for good.
struct Waiting
{
std::atomic<int> &count;
explicit Waiting(std::atomic<int> &count_)
: count(count_)
{
count.fetch_add(1,std::memory_order_relaxed);
}
~Waiting()
{
count.fetch_sub(1,std::memory_order_relaxed);
}
} waiting(exclusive_waiters);
return std::unique_lock<std::shared_mutex>(mutex);
}
void size_floor_lower(const s64 v_)
{
s64 cur = size_floor.load(std::memory_order_relaxed);
while((v_ < cur) &&
!size_floor.compare_exchange_weak(cur,v_,std::memory_order_relaxed))
;
}
// The file's size may have changed in a way size_floor_lower cannot
// express: call after the change. That narrows, but does not close,
// the window in which a size check that started before the change
// (and saw 0, the value stored here) installs the old size
// afterwards; like any stale floor that only costs a fallback.
void size_floor_reset()
{
size_floor.store(0,std::memory_order_relaxed);
}
// fd now refers to a different branch file (moveonenospc's dup2): a
// splice decision or size observed on the old one no longer applies.
void fd_rebound()
{
splice_state.store(Splice::unknown,std::memory_order_relaxed);
size_floor_reset();
}
};
inline

View file

@ -55,14 +55,23 @@ FUSE::fallocate(const fuse_req_ctx_t *ctx_,
off_t offset_,
off_t len_)
{
int rv;
FileInfo *fi;
fi = state.get_fi(ctx_,fh_);
if(not fi)
return -EBADF;
return ::_fallocate(fi->fd,
mode_,
offset_,
len_);
rv = ::_fallocate(fi->fd,
mode_,
offset_,
len_);
/* Reset read_buf's size floor. Defensive only: of the fallocate
modes only COLLAPSE_RANGE shrinks a file (PUNCH_HOLE requires
KEEP_SIZE), and the kernel's FUSE client forwards only KEEP_SIZE,
PUNCH_HOLE and ZERO_RANGE, so no request reaching here does. */
fi->size_floor_reset();
return rv;
}

View file

@ -50,11 +50,20 @@ FUSE::ftruncate(const fuse_req_ctx_t *ctx_,
cu64 fh_,
off_t size_)
{
int rv;
FileInfo *fi;
fi = state.get_fi(ctx_,fh_);
if(not fi)
return -EBADF;
return ::_ftruncate(fi->fd,size_);
rv = ::_ftruncate(fi->fd,size_);
/* A shrink through this handle would otherwise leave reads past the
new end on the EOF fallback; after a grow the old floor still
holds. */
if(rv == 0)
fi->size_floor_lower(size_);
return rv;
}

View file

@ -72,10 +72,19 @@ FUSE::read(const fuse_req_ctx_t *ctx_,
if(not fi)
return -EBADF;
if(fi->direct_io)
return ::_read_direct_io(fi->fd,buf_,size_,offset_);
const int rv = (fi->direct_io ?
::_read_direct_io(fi->fd,buf_,size_,offset_) :
::_read_cached(fi->fd,buf_,size_,offset_));
return ::_read_cached(fi->fd,buf_,size_,offset_);
/* A short read means end-of-file at offset+rv: keep read_buf's size
floor from claiming more (it is the splice reply's EOF fallback).
Nothing was read at all when rv is 0, so the file may end anywhere
at or before offset_ (it may have shrunk well below the offset
asked about): only 0 is then a bound that cannot be too high. */
if((rv >= 0) && ((size_t)rv < size_))
fi->size_floor_lower((rv > 0) ? ((s64)offset_ + rv) : 0);
return rv;
}
int

313
src/fuse_read_buf.cpp Normal file
View file

@ -0,0 +1,313 @@
/*
ISC License
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "fuse_read_buf.hpp"
#include "fileinfo.hpp"
#include "fs_fstat.hpp"
#include "fs_getfl.hpp"
#include "fs_statx.hpp"
#include "ioprio.hpp"
#include "state.hpp"
#include "fuse.h"
#include "boost/unordered/concurrent_flat_map.hpp"
#include <atomic>
#include <fcntl.h>
#include <shared_mutex>
#if defined(__linux__)
#include <sys/sysmacros.h>
#include <sys/vfs.h>
#endif
/* The branch file's type, size and device. A statx asking only for the
first two lets filesystems skip work a full fstat implies (NFS
flushes the file's dirty pages before reporting c/mtime; the device
is always reported); fstat covers builds and filesystems without
statx. */
static
int
_type_and_size(const int fd_,
mode_t *mode_,
s64 *size_,
dev_t *dev_)
{
int rv;
struct stat st;
#ifdef MERGERFS_SUPPORTED_STATX
struct fuse_statx stx;
const unsigned int want = (STATX_TYPE|STATX_SIZE);
rv = fs::statx(fd_,"",AT_EMPTY_PATH,want,&stx);
if((rv == 0) && ((stx.mask & want) == want))
{
*mode_ = stx.mode;
*size_ = (s64)stx.size;
*dev_ = makedev(stx.dev_major,stx.dev_minor);
return 0;
}
#endif
rv = fs::fstat(fd_,&st);
if(rv < 0)
return rv;
*mode_ = st.st_mode;
*size_ = st.st_size;
*dev_ = st.st_dev;
return 0;
}
/* Devices of branch filesystems _splice_coherent refused by type. The
type is a property of the superblock, not of the open file, and on
the network and FUSE filesystems it refuses fstatfs is a round trip
to their server, which the first large read of every opened file
would otherwise pay. Only refusals are remembered, so a device
number reused by another filesystem after an unmount can cost
splicing but never coherence. The value is unused. */
static boost::concurrent_flat_map<dev_t,bool> g_refused_devs;
/* Whether splicing from the branch fd returns what pread would, and is
worth doing. A filesystem that cannot be identified is refused too.
Not on FUSE, SMB/CIFS, NFS, Ceph, AFS, overlayfs or 9p
branches: their splice_read serves the branch inode's page cache
(filemap_splice_read) while their read path bypasses it or first
revalidates it (FUSE direct_io and auto_inval_data, SMB without a
read lease, NFS/Ceph/AFS/9p attribute/data caching, overlayfs's
copy-up), so a spliced reply could return stale data where the copy
path returns current data. Nor on an fd opened O_DIRECT, regardless
of filesystem: the kernel serves that splice by direct I/O into
freshly allocated pipe pages (as pread does, so nothing is stale),
which saves no copy over the copy path while adding syscalls, and a
misaligned request's EINVAL would look like a filesystem without
splice_read. A refusal by filesystem type is remembered for dev_ (the
fd's device, 0 if unknown) so later handles on that filesystem skip
the fstatfs. */
static
bool
_splice_coherent(const int fd_,
const dev_t dev_)
{
#if defined(__linux__)
constexpr u32 MAGIC_FUSE = 0x65735546; // fuse, fuseblk, virtiofs
constexpr u32 MAGIC_CIFS = 0xFF534D42;
constexpr u32 MAGIC_SMB2 = 0xFE534D42;
constexpr u32 MAGIC_NFS = 0x00006969;
constexpr u32 MAGIC_CEPH = 0x00C36400;
constexpr u32 MAGIC_AFS = 0x5346414F; // OpenAFS (/afs)
constexpr u32 MAGIC_KAFS = 0x6B414653; // in-kernel AFS client
constexpr u32 MAGIC_OVERLAYFS = 0x794C7630;
constexpr u32 MAGIC_V9FS = 0x01021997;
struct statfs st;
int rv;
if(::fstatfs(fd_,&st) < 0)
return false;
switch((u32)st.f_type)
{
case MAGIC_FUSE:
case MAGIC_CIFS:
case MAGIC_SMB2:
case MAGIC_NFS:
case MAGIC_CEPH:
case MAGIC_AFS:
case MAGIC_KAFS:
case MAGIC_OVERLAYFS:
case MAGIC_V9FS:
if(dev_ != 0)
g_refused_devs.emplace(dev_,true);
return false;
default:
break;
}
rv = fs::getfl(fd_);
if((rv >= 0) && (rv & O_DIRECT))
return false;
return true;
#else
(void)fd_;
(void)dev_;
return false;
#endif
}
/* Whether [offset, offset+size) lies inside [0, bound), computed
without overflow: offset+size itself can exceed INT64_MAX for reads
near the top of a huge sparse file. */
static
inline
bool
_window_inside(const off_t offset_,
const size_t size_,
const s64 bound_)
{
return ((offset_ >= 0) &&
(offset_ < bound_) &&
((u64)size_ <= (u64)(bound_ - offset_)));
}
/* Describe a large read as a region of the branch file so libfuse can
splice it into /dev/fuse without the data crossing userspace.
Returning a positive value declines, and libfuse calls FUSE::read.
The reply header, whose length is the region size, is staged before
any data, so only a read lying entirely within the file's reported
size is offered. A read crossing it declines rather than being
trimmed: some branches report a size that lags the data
(attribute-caching network or FUSE filesystems), and a trimmed reply
would end short where pread returns the rest. This also declines
non-regular files and files reporting size 0 (procfs) or 4096
(sysfs) while returning live content, which a splice past the
reported size would generate twice or block on. A file that shrinks
between the size check and the splice falls back to FUSE::read.
The size check is skipped when the window ends inside
fi->size_floor, a size already observed on this handle; a stale floor
only costs a fallback, whose short FUSE::read lowers it.
fi->mutex is held shared so moveonenospc's dup2 cannot rebind fd
while libfuse stages from it (see FileRegion::lock). It is never
waited for: a move holds it for a whole file copy, so the read
declines instead and the copy path serves it from the old fd. */
int
FUSE::read_buf(const fuse_req_ctx_t *ctx_,
const fuse_file_info_t *ffi_,
FileRegion *region_,
const size_t size_,
const off_t offset_)
{
FileInfo *fi;
FileInfo::Splice splice;
s64 floor;
dev_t dev = 0;
fi = state.get_fi(ctx_,ffi_->fh);
if(not fi)
return -EBADF;
if(fi->splice_state.load(std::memory_order_relaxed) == FileInfo::Splice::no)
return 1;
std::shared_lock<std::shared_mutex> lock(fi->mutex,std::try_to_lock);
if(not lock.owns_lock())
return 1;
/* Checked after the lock is held so a mover that started waiting
before try_to_lock succeeded is not joined by this splice. */
if(fi->exclusive_waiters.load(std::memory_order_relaxed) > 0)
return 1;
/* Read again under the lock: a move that completed before try_to_lock
rebound fd and reset this to unknown (fd_rebound), and the
once-per-binding check below must see that. */
splice = fi->splice_state.load(std::memory_order_relaxed);
if(splice == FileInfo::Splice::no)
return 1;
floor = fi->size_floor.load(std::memory_order_relaxed);
if(not ::_window_inside(offset_,size_,floor))
{
mode_t mode;
s64 fsize;
if((::_type_and_size(fi->fd,&mode,&fsize,&dev) < 0) ||
!S_ISREG(mode))
return 1;
/* On a filesystem already refused by type, settle this handle
now, even for a read that would decline below anyway (every
read of a file smaller than the request does), so its later
reads skip this statx. */
if((splice == FileInfo::Splice::unknown) && g_refused_devs.contains(dev))
{
fi->splice_state.compare_exchange_strong(splice,
FileInfo::Splice::no,
std::memory_order_relaxed);
return 1;
}
/* Only replace the floor this check started from: a short read
may have lowered it meanwhile, and that is newer than fsize. */
if(fsize > 0)
fi->size_floor.compare_exchange_strong(floor,fsize,
std::memory_order_relaxed);
if(not ::_window_inside(offset_,size_,fsize))
return 1;
}
/* Once per fd binding, for a read that could otherwise splice, and
under the lock so the answer is about the file fd refers to. A
concurrent rejection (read_buf_rejected) wins over this check. */
if(splice == FileInfo::Splice::unknown)
{
/* A filesystem that cannot be identified is not offered either,
and that is settled too: retrying would repeat the fstatfs,
possibly a server round trip, on every later large read. */
const FileInfo::Splice want = (::_splice_coherent(fi->fd,dev) ?
FileInfo::Splice::yes :
FileInfo::Splice::no);
/* On failure splice holds the concurrent decision, which wins. */
if(fi->splice_state.compare_exchange_strong(splice,want,
std::memory_order_relaxed))
splice = want;
if(splice != FileInfo::Splice::yes)
return 1;
}
/* ioprio is thread-persistent; without SetFrom the branch-file I/O
performed downstream of this handler (the kernel-side splice in
the reply path runs on this same worker thread) would inherit
whatever priority a previous request left behind. */
ioprio::SetFrom iop(ctx_->pid);
region_->fd = fi->fd;
region_->offset = offset_;
region_->size = size_;
region_->lock = std::move(lock);
return 0;
}
/* The branch fd refused splice (EINVAL on its first splice: its
filesystem has no splice_read). That will not change for this fd, so
stop offering it and let every later read go straight to FUSE::read.
O_DIRECT fds never get here: _splice_coherent refuses them. libfuse
calls this while the region's lock is still held, so fd is still the
one that refused. */
void
FUSE::read_buf_rejected(const fuse_req_ctx_t *ctx_,
const fuse_file_info_t *ffi_)
{
FileInfo *fi;
fi = state.get_fi(ctx_,ffi_->fh);
if(not fi)
return;
fi->splice_state.store(FileInfo::Splice::no,std::memory_order_relaxed);
}

35
src/fuse_read_buf.hpp Normal file
View file

@ -0,0 +1,35 @@
/*
ISC License
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include "fuse_io.hpp"
#include "fuse.h"
namespace FUSE
{
int read_buf(const fuse_req_ctx_t *ctx,
const fuse_file_info_t *ffi,
FileRegion *region,
const size_t size,
const off_t offset);
void read_buf_rejected(const fuse_req_ctx_t *ctx,
const fuse_file_info_t *ffi);
}

View file

@ -28,11 +28,13 @@
#include "fs_pwriten.hpp"
#include "ioprio.hpp"
#include "state.hpp"
#include "syslog.hpp"
#include "scope_guard/scope_guard.hpp"
#include "fuse.h"
#include <cstring>
#include <mutex>
#include <shared_mutex>
@ -45,6 +47,41 @@ _out_of_space(const ssize_t err_)
(err_ == -EDQUOT));
}
// moveonenospc: move the file to another branch and rebind fi_->fd to
// the copy. Called with fi_->mutex held exclusively. 0 or -errno.
static
int
_move_file(FileInfo *fi_)
{
int err;
int fd;
if(cfg.moveonenospc.enabled == false)
return -ENOSPC;
fd = fs::movefile_and_open_as_root(cfg.moveonenospc.policy,
cfg.branches,
fi_->branch.path,
fi_->fusepath,
fi_->fd);
if(fd < 0)
return fd;
err = fs::dup2(fd,fi_->fd);
{
const int close_err = fs::close(fd);
if(close_err < 0)
SysLog::warning("moveonenospc: closing the copy's fd after the move"
" failed: {}",strerror(-close_err));
}
if(err < 0)
return err;
fi_->fd_rebound();
return 0;
}
static
int
_move_and_pwrite(const char *buf_,
@ -53,23 +90,7 @@ _move_and_pwrite(const char *buf_,
FileInfo *fi_,
int err_)
{
int err;
ssize_t rv;
if(cfg.moveonenospc.enabled == false)
return err_;
rv = fs::movefile_and_open_as_root(cfg.moveonenospc.policy,
cfg.branches,
fi_->branch.path,
fi_->fusepath,
fi_->fd);
if(rv < 0)
return err_;
err = fs::dup2(rv,fi_->fd);
fs::close(rv);
if(err < 0)
if(::_move_file(fi_) < 0)
return err_;
return fs::pwrite(fi_->fd,buf_,count_,offset_);
@ -87,20 +108,7 @@ _move_and_pwriten(char const *buf_,
int err;
ssize_t rv;
if(cfg.moveonenospc.enabled == false)
return err_;
rv = fs::movefile_and_open_as_root(cfg.moveonenospc.policy,
cfg.branches,
fi_->branch.path,
fi_->fusepath,
fi_->fd);
if(rv < 0)
return err_;
err = fs::dup2(rv,fi_->fd);
fs::close(rv);
if(err < 0)
if(::_move_file(fi_) < 0)
return err_;
rv = fs::pwriten(fi_->fd,
@ -147,7 +155,11 @@ _write(const fuse_req_ctx_t *ctx_,
ssize_t rv;
if(fi->direct_io)
// A writeback (writepage) request must be written completely or
// fail: the kernel ignores a short count for it (see FUSE::write).
// So even on a direct_io handle it takes the looping path below,
// which also reaches moveonenospc when the branch fills mid-write.
if(fi->direct_io && !ffi_->writepage)
{
{
std::shared_lock<std::shared_mutex> slk(fi->mutex);
@ -157,7 +169,7 @@ _write(const fuse_req_ctx_t *ctx_,
if(not ::_out_of_space(rv))
return rv;
std::unique_lock<std::shared_mutex> ulk(fi->mutex);
std::unique_lock<std::shared_mutex> ulk = fi->lock_exclusive();
// Re-check under exclusive lock: another writer may have
// already moved the file and retired. If so the pwrite should
// now succeed without our own move call.
@ -181,7 +193,7 @@ _write(const fuse_req_ctx_t *ctx_,
if(err && not ::_out_of_space(err))
return err;
std::unique_lock<std::shared_mutex> ulk(fi->mutex);
std::unique_lock<std::shared_mutex> ulk = fi->lock_exclusive();
// Re-check under exclusive lock as another move may have
// already run.
written = fs::pwriten(fi->fd,buf_,count_,offset_,&err);
@ -202,8 +214,20 @@ FUSE::write(const fuse_req_ctx_t *ctx_,
off_t offset_)
{
ioprio::SetFrom iop(ctx_->pid);
int rv;
return ::_write(ctx_,ffi_,buf_,count_,offset_);
rv = ::_write(ctx_,ffi_,buf_,count_,offset_);
/* Writeback completion (FUSE_WRITE_CACHE) ignores a short reply's byte
count: Linux fuse_writepage_end consults only the error, so a short
nonnegative result would mark the unwritten tail clean and lose it.
_write already loops for these requests; a short count here means
a pwrite made no progress without an error, so report a failure.
Ordinary writes report their prefix. */
if(ffi_->writepage && (rv >= 0) && ((size_t)rv < count_))
return -EIO;
return rv;
}
int

View file

@ -63,6 +63,7 @@
#include "fuse_opendir.hpp"
#include "fuse_poll.hpp"
#include "fuse_read.hpp"
#include "fuse_read_buf.hpp"
#include "fuse_readdir.hpp"
#include "fuse_readdir_plus.hpp"
#include "fuse_readlink.hpp"
@ -126,6 +127,10 @@ _get_fuse_operations(struct fuse_operations &ops_,
ops_.opendir = FUSE::opendir;
ops_.poll = FUSE::poll;
ops_.read = (nullrw_ ? FUSE::read_null : FUSE::read);
/* Large reads are spliced from the branch file into /dev/fuse when
possible; nullrw has no branch data to splice. */
ops_.read_buf = (nullrw_ ? nullptr : FUSE::read_buf);
ops_.read_buf_rejected = (nullrw_ ? nullptr : FUSE::read_buf_rejected);
ops_.readdir = FUSE::readdir;
ops_.readdir_plus = FUSE::readdir_plus;
ops_.readlink = FUSE::readlink;